Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownLinks.test.ts

597 lines24.7 KB

1import { workspaceRelativeFilePath } from "./path.ts";
2import { describe, expect, it } from "vite-plus/test";
3import { serializeComposerFileLink } from "./composerTrigger.ts";
4import {
5 extractInlineCodeSpans,
6 extractMarkdownLinkHrefs,
7 resolveMarkdownFileLink,
8 resolveMarkdownFileLinkTarget,
9} from "./markdownLinks.ts";
10​
11import {
12 inlineCodeFilePathCandidate,
13 isMarkdownFileLinkLabel,
14 parseMarkdownFileLink,
15 parseObsidianNavigationHref,
16} from "./markdownLinks.ts";
17​
18describe("parseObsidianNavigationHref", () => {
19 it.each([
20 "obsidian://open?vault=Example%20Vault",
21 "obsidian://open?vault=Example&file=notes%2FExample.md%23Overview&paneType=tab",
22 "obsidian://open?path=%2Ftmp%2FExample%20Vault%2FExample.md",
23 "obsidian://adv-uri?vault=Example&filepath=notes%2FExample.md&heading=Overview",
24 "obsidian://adv-uri?vault=Example&filepath=Example.md&block=example",
25 "obsidian://adv-uri?vault=Example&filename=Example&line=2&column=3&offset=4",
26 ])("preserves encoded navigation destinations in %s", (href) => {
27 expect(parseObsidianNavigationHref(href)).toBe(href);
28 });
29​
30 it("normalizes the scheme before Markdown sanitization", () => {
31 expect(parseObsidianNavigationHref("ObSiDiAn://open?vault=Example")).toBe(
32 "obsidian://open?vault=Example",
33 );
34 });
35​
36 it.each([
37 "not a URL",
38 "https://open?vault=Example",
39 "unknown://open?vault=Example",
40 "obsidian://new?vault=Example&file=Example",
41 "obsidian://daily?vault=Example",
42 "obsidian://open/other?vault=Example",
43 "obsidian://user:password@open?vault=Example",
44 "obsidian://open:123?vault=Example",
45 "obsidian://open?vault=Example#fragment",
46 "obsidian://open",
47 "obsidian://adv-uri?vault=Example",
48 "obsidian://adv-uri?filepath=",
49 "obsidian://open?vault=Example&vault=Other",
50 ...[
51 "data",
52 "mode",
53 "commandid",
54 "commandname",
55 "clipboard",
56 "append",
57 "prepend",
58 "x-success",
59 "uid",
60 ].map((key) => `obsidian://adv-uri?filepath=Example&${key}=value`),
61 ])("rejects unsupported actions, parameters and URL shapes in %s", (href) => {
62 expect(parseObsidianNavigationHref(href)).toBeNull();
63 });
64});
65​
66describe("isMarkdownFileLinkLabel", () => {
67 // regression: #15509 descriptive labels are not mistaken for the linked file name
68 it.each([
69 ["validates the input", "/repo/src/example.ts:12", false],
70 ["example.ts:12", "/repo/src/example.ts:12", true],
71 ["example.ts:99", "/repo/src/example.ts:12", false],
72 ["example.ts:12-20", "/repo/src/example.ts:12-20", true],
73 ["example.ts:12-20", "/repo/src/example.ts:12", false],
74 ["src/main.ts#L10-L20", "/repo/src/main.ts#L10-L20", true],
75 ["main.ts#L42C7", "/repo/src/main.ts:42:7", true],
76 ["src/main.ts#L10-L20", "/repo/src/main.ts#L10", false],
77 ["src/main.ts:10#L20", "/repo/src/main.ts:10", false],
78 ["C#/Program.cs#L10", "./C%23/Program.cs#L10", true],
79 ["src/main.ts#L10", "./src/main.ts%23L10", true],
80 ["draft.md ", "/tmp/draft.md%20", true],
81 [" draft.md ", "./%20draft.md%20%20", true],
82 [" draft.md ", "/tmp/draft.md", true],
83 ])("classifies %s for %s", (label, href, expected) => {
84 expect(isMarkdownFileLinkLabel(label, href)).toBe(expected);
85 });
86});
87​
88describe("inlineCodeFilePathCandidate", () => {
89 // regression: #13909 model ids in inline code do not become file chips
90 it.each([
91 ["src\\main.ts", "src/main.ts"],
92 ["allocator.cc:217", "allocator.cc:217"],
93 ["src/http.ts:42-64", "src/http.ts:42-64"],
94 ["http.ts:42-64", "http.ts:42-64"],
95 ["src/a.ts#section", null],
96 ["C#/a.cs#L10", null],
97 ["src/a.ts#L10-L20-extra", null],
98 [String.raw`C:\My Files\a.ts#section`, null],
99 ["origin/main", null],
100 ["z-ai/glm-5.3", null],
101 ["share/man/ls.1", "share/man/ls.1"],
102 ["docker/Dockerfile", "docker/Dockerfile"],
103 ["src/main.ts/", null],
104 ["./patches/", "./patches/"],
105 // regression: #30757 an agent's shortened path is not a file
106 ["/tmp/claude-1000/...", null],
107 ["/tmp/claude-1000/...:12", null],
108 ["/tmp/.../scratchpad/notes.md", null],
109 ["~/projects/…/notes.md", null],
110 ["src/.../main.ts", null],
111 // regression: #22181 a `:line` suffix does not make an extensionless basename a file
112 ["I/W217:220", null],
113 ["bin/run:12", null],
114 ["docs/README:12", "docs/README:12"],
115 ["./bin/run:12", "./bin/run:12"],
116 ["src/資料.備份:12", "src/資料.備份:12"],
117 ["src/foo.c++:12", "src/foo.c++:12"],
118 // regression: #37740 absolute paths with spaces are files, commands are not
119 ["/Users/me/Path Test/notes with spaces.md", "/Users/me/Path Test/notes with spaces.md"],
120 ["~/Library/Mobile Documents/notes.md", "~/Library/Mobile Documents/notes.md"],
121 [
122 "/Users/me/Library/CloudStorage/OneDrive-Org/Alex/Partners/Acme/Finance Use Cases/working/2026-11-16 message - draft.md",
123 "/Users/me/Library/CloudStorage/OneDrive-Org/Alex/Partners/Acme/Finance Use Cases/working/2026-11-16 message - draft.md",
124 ],
125 ["cd /tmp && ls", null],
126 ["/usr/bin/python3 -m venv .venv", null],
127 ["/usr/local/bin/node server.js", null],
128 ["/usr/bin/env python3 foo.py", null],
129 ["/opt/homebrew/bin/python3 manage.py", null],
130 ["/bin/echo hello world.txt", null],
131 ["~/bin/run tests.sh", null],
132 ["/Users/me/notes with spaces.md", "/Users/me/notes with spaces.md"],
133 [
134 "\\\\server\\share\\Project\\Guide Notes.md:10-20",
135 "\\\\server\\share\\Project\\Guide Notes.md:10-20",
136 ],
137 ["\\\\server\\Shared Docs\\Guide.md", "\\\\server\\Shared Docs\\Guide.md"],
138 // regression: #46241 consecutive spaces stay inside one path
139 [String.raw`C:\My Folder\notes.md#L10-L20`, String.raw`C:\My Folder\notes.md#L10-L20`],
140 [String.raw`\\server\Team Share\notes.md`, String.raw`\\server\Team Share\notes.md`],
141 ["/Users/me/Path Test/notes.md", "/Users/me/Path Test/notes.md"],
142 ["/Users/me/tool --fast notes.md", null],
143 ["\\\\server name\\share\\Guide Notes.md", null],
144 ["\\\\server\\Guide Notes.md", null],
145 ["~/Videos/clips/<thread-slug>/shot.png", null],
146 ["clips/<name>.mp4", null],
147 ])("distinguishes file paths from code and hostnames in %s", (source, candidate) => {
148 expect(inlineCodeFilePathCandidate(source)).toBe(candidate);
149 });
150​
151 it.each(["src/a.ts", String.raw`C:\My Files\a.ts`])(
152 "recognizes inline GitHub line ranges in %s like colon ranges",
153 (path) => {
154 const anchored = `${path}#L10-L20`;
155 expect(inlineCodeFilePathCandidate(anchored)).toBe(anchored);
156 expect(resolveMarkdownFileLink(anchored, "/work")).toEqual(
157 resolveMarkdownFileLink(`${path}:10-20`, "/work"),
158 );
159 expect(resolveMarkdownFileLink(anchored, "/work")).toMatchObject({
160 position: { line: 10, endLine: 20 },
161 });
162 },
163 );
164});
165​
166describe("parseMarkdownFileLink", () => {
167 it.each([
168 ["C:%5Crepo%5Cimage.png", "C:\\repo\\image.png"],
169 ["</D:/Programme/t3code/ChatMarkdown.tsx:1>", "D:/Programme/t3code/ChatMarkdown.tsx"],
170 ["file://localhost/home/me/notes.md", "/home/me/notes.md"],
171 ["app/routes/posts.$postId.tsx", "app/routes/posts.$postId.tsx"],
172 ["src/routes/+page.svelte", "src/routes/+page.svelte"],
173 ["app/(marketing)/page.tsx:12", "app/(marketing)/page.tsx"],
174 ["pages/posts/%5Bid%5D.tsx", "pages/posts/[id].tsx"],
175 ["+page.svelte", "+page.svelte"],
176 ["[id].tsx", "[id].tsx"],
177 ["/\\server\\share\\x.ts", "/\\server\\share\\x.ts"],
178 ])("recognizes %s as a file", (href, path) => {
179 expect(parseMarkdownFileLink(href)?.path).toBe(path);
180 });
181​
182 it.each([
183 "app/routes/posts.$postId.tsx",
184 "pages/posts/[id].tsx",
185 "docs/My File (draft).md",
186 "@scope/package.json",
187 "$postId.tsx",
188 ])("reads back the composer's link to %s", (path) => {
189 const destination = /\]\((.*)\)$/.exec(serializeComposerFileLink(path))?.[1];
190 expect(parseMarkdownFileLink(destination ?? "")?.path).toBe(path);
191 });
192​
193 // regression: #41223 names the parser rejects bare; the composer adds `./` to them
194 it.each([
195 "C#/Program.cs",
196 "docs/R&D/notes.md",
197 "docs/Bob's notes.md",
198 "docs/a,b.ts",
199 "docs/100%.md",
200 "docs/why?.md",
201 "icon@2x.png",
202 ])("resolves the composer's link to %s", (path) => {
203 const destination = /\]\((.*)\)$/.exec(serializeComposerFileLink(path))?.[1];
204 expect(resolveMarkdownFileLinkTarget(destination ?? "", "/workspace/project")).toBe(
205 `/workspace/project/${path}`,
206 );
207 });
208​
209 it.each([
210 "https://example.com/docs",
211 "/chat/settings#L3",
212 "TODO:12",
213 "patches",
214 "me@example.com",
215 "foo(bar)",
216 "$HOME",
217 "/tmp/claude-1000/...",
218 "/tmp/claude-1000/....:12",
219 "/tmp/claude-1000/%2E%2E%2E",
220 "\\foo.ts",
221 "sandbox://server/share/notes.txt",
222 "sandbox:/%2Fserver/share/notes.txt",
223 "sandbox:/%5Cserver/share/notes.txt",
224 "sandbox:/tmp/bad%00name.txt",
225 ])("does not treat %s as a file", (href) => {
226 expect(parseMarkdownFileLink(href)).toBeNull();
227 });
228​
229 it("resolves a sandbox link as an absolute host path, even outside the workspace", () => {
230 const href = "Sandbox:/Users/me/agent-output/example/brief%20%23final.txt#L3C2";
231 expect(parseMarkdownFileLink(href)).toEqual({
232 path: "/Users/me/agent-output/example/brief #final.txt",
233 line: 3,
234 column: 2,
235 });
236 expect(resolveMarkdownFileLinkTarget(href, "/Users/me/repo")).toBe(
237 "/Users/me/agent-output/example/brief #final.txt:3:2",
238 );
239 });
240​
241 it("recognizes a relative folder that ends in a slash", () => {
242 expect(parseMarkdownFileLink("patches/")).toEqual({ path: "patches/" });
243 expect(parseMarkdownFileLink("docs/My%20Folder/")?.path).toBe("docs/My Folder/");
244 });
245​
246 // regression: #16096 relative links with non-ASCII names open as files
247 it("recognizes relative paths with non-ASCII names", () => {
248 expect(parseMarkdownFileLink("pastexam/線性代數/exam_易志偉.pdf")?.path).toBe(
249 "pastexam/線性代數/exam_易志偉.pdf",
250 );
251 expect(parseMarkdownFileLink("Résumé%20final.pdf")?.path).toBe("Résumé final.pdf");
252 expect(parseMarkdownFileLink("資料.備份")?.path).toBe("資料.備份");
253 });
254​
255 it("accepts conventional extensionless names with or without a position", () => {
256 expect(parseMarkdownFileLink("Makefile")).toEqual({ path: "Makefile" });
257 expect(parseMarkdownFileLink("Dockerfile:8")).toEqual({ path: "Dockerfile", line: 8 });
258 expect(parseMarkdownFileLink("/srv/app/Makefile")).toEqual({ path: "/srv/app/Makefile" });
259 });
260​
261 it("reads line ranges and opens them at their first line", () => {
262 expect(parseMarkdownFileLink("/repo/src/http.ts:42-64")).toEqual({
263 path: "/repo/src/http.ts",
264 line: 42,
265 endLine: 64,
266 });
267 expect(parseMarkdownFileLink("/repo/src/http.ts#L42-L64")).toEqual({
268 path: "/repo/src/http.ts",
269 line: 42,
270 endLine: 64,
271 });
272 });
273​
274 it("reads positions from suffixes and line anchors", () => {
275 expect(parseMarkdownFileLink("/Users/julius/project/src/main.ts#L42C7")).toEqual({
276 path: "/Users/julius/project/src/main.ts",
277 line: 42,
278 column: 7,
279 });
280 expect(parseMarkdownFileLink("file://server/share/src/main.ts#L42C7")).toMatchObject({
281 path: "\\\\server\\share\\src\\main.ts",
282 line: 42,
283 column: 7,
284 });
285 });
286});
287​
288describe("workspaceRelativeFilePath", () => {
289 // regression: #12449 workspace root links resolve to "."
290 it.each([
291 ["/repo/project", "/repo/project", "."],
292 ["C:/", "c:/", "."],
293 ["/repo/project/a.ts", undefined, null],
294 ])("relates %s to %s", (path, workspaceRoot, relativePath) => {
295 expect(workspaceRelativeFilePath(path, workspaceRoot)).toBe(relativePath);
296 });
297});
298​
299describe("extractInlineCodeSpans", () => {
300 it.each([
301 ['[example](https://example.com "`/tmp/other/main.ts`")', ["/tmp/current/main.ts"]],
302 ["[`example`](https://example.com/`/tmp/other/main.ts`)", ["example", "/tmp/current/main.ts"]],
303 ])("ignores backticks in accepted link tails: %s", (link, spans) => {
304 expect(extractInlineCodeSpans(`${link} and \`/tmp/current/main.ts\``)).toEqual(spans);
305 });
306​
307 it.each([
308 ["``./a/shared.ts`` and `./b/shared.ts`", ["./a/shared.ts", "./b/shared.ts"]],
309 ["``a ` b`` and `./b/shared.ts`", ["a ` b", "./b/shared.ts"]],
310 ["``unclosed and `./b/shared.ts`", ["./b/shared.ts"]],
311 ["\\``./a/shared.ts` and `./b/shared.ts`", ["./a/shared.ts", "./b/shared.ts"]],
312 ["`a\\` and `./b/shared.ts`", ["a\\", "./b/shared.ts"]],
313 ["`unclosed\n`./b/shared.ts`", ["./b/shared.ts"]],
314 ])("matches complete backtick delimiter runs in %s", (markdown, spans) => {
315 expect(extractInlineCodeSpans(markdown)).toEqual(spans);
316 });
317​
318 it.each([
319 [
320 "Use `` ``` `` to open a fence, then edit `./a/shared.ts` and `./b/shared.ts`",
321 ["```", "./a/shared.ts", "./b/shared.ts"],
322 ],
323 ["```x``` then `./a/shared.ts`", ["x", "./a/shared.ts"]],
324 ["~~~\n`./a/shared.ts`\n~~~\n`./b/shared.ts`", ["./b/shared.ts"]],
325 ["````md\n```ts\n`./a/shared.ts`\n```\n````\n`./b/shared.ts`", ["./b/shared.ts"]],
326 ["```\n ```\n`./a/shared.ts`\n```\n`./b/shared.ts`", ["./b/shared.ts"]],
327 [
328 "```diff\n- ```\n```\nEdit `./a/shared.ts` and `./b/shared.ts`",
329 ["./a/shared.ts", "./b/shared.ts"],
330 ],
331 ["> ```\n> `./a/shared.ts`\nEdit `./b/shared.ts`", ["./b/shared.ts"]],
332 [
333 "- ~~~\n example\n\nEdit `./a/shared.ts` and `./b/shared.ts`",
334 ["./a/shared.ts", "./b/shared.ts"],
335 ],
336 ["Step\n2. ~~~\n `./a/shared.ts`", ["./a/shared.ts"]],
337 ["1. Step\n ```\r\n `./a/shared.ts`\r\n ```\r\n`./b/shared.ts`", ["./b/shared.ts"]],
338 [" ```\n `./a/shared.ts`\n ```\n\n`./b/shared.ts`", ["./b/shared.ts"]],
339 ["Example\n\n `src/a/index.ts`\n\nOpen `src/b/index.ts`", ["src/b/index.ts"]],
340 ["\r\t`src/a/index.ts`\r\rOpen `src/b/index.ts`", ["src/b/index.ts"]],
341 ["Example\n `src/a/index.ts`\n\n `src/b/index.ts`", ["src/a/index.ts"]],
342 ])("skips code spans inside code blocks in %j", (markdown, spans) => {
343 expect(extractInlineCodeSpans(markdown)).toEqual(spans);
344 });
345});
346​
347describe("extractMarkdownLinkHrefs", () => {
348 it.each(["\n\n", "\n \t\n", "\r\r"])(
349 "ends an unfinished label before a blank line %j after a backslash",
350 (breaks) => {
351 expect(
352 extractMarkdownLinkHrefs(
353 "Example [unfinished\\" + breaks + "](./old/a.ts)\n\nOpen [a.ts](./new/a.ts).",
354 ),
355 ).toEqual(["./new/a.ts"]);
356 },
357 );
358​
359 it.each([
360 ["[".repeat(32_000), []],
361 ["[a](<foo)bar> invalid [b](ok)", ["<foo", "ok"]],
362 ["[[[nested](src/main.ts) [unfinished", ["src/main.ts"]],
363 [
364 "[![a](a.png)](src/index.ts) [![b](b.png)](lib/index.ts)",
365 ["a.png", "src/index.ts", "b.png", "lib/index.ts"],
366 ],
367 [String.raw`[\![a](a.png)](src/index.ts) [label!](ok)`, ["a.png", "ok"]],
368 ["See [the [docs] guide](docs/guide.md) and [[1]](src/a.ts)", ["docs/guide.md", "src/a.ts"]],
369 ["[a [b](x) [c \\[d](y) [e\\]](z)", ["x", "y", "z"]],
370 ["[a [b]\n\nc](src/a.ts) [outer [inner]()](src/b.ts)", []],
371 ["[literal](\n\n./old/a.ts)\n\n[actual](./new/a.ts)", ["./new/a.ts"]],
372 ["[a]( \n \n<./old/a.ts>) [b](\n./new/a.ts)", ["./new/a.ts"]],
373 [`See ${serializeComposerFileLink("pages/posts/[id].tsx")} now`, ["pages/posts/%5Bid%5D.tsx"]],
374 ["[a](</tmp/one/a.ts >) [b]( /tmp/two/b.ts )", ["/tmp/one/a.ts ", "/tmp/two/b.ts"]],
375 ])("extracts links from incomplete and nested text", (markdown, hrefs) => {
376 expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
377 });
378​
379 it.each([
380 ["```md\n- [Setup](./a/README.md)\n```\n\nSee [README.md](./b/README.md)", ["./b/README.md"]],
381 ["Write `[Setup](./a/README.md)` as [README.md](./b/README.md)", ["./b/README.md"]],
382 ["[a `b](./a/README.md)` [c](./b/README.md)", ["./b/README.md"]],
383 ["[`code`](./a/README.md) and [x](<./b/a`b`.md>)", ["./a/README.md", "./b/a`b`.md"]],
384 ["`unclosed [a](./a/README.md)\n\nand` [b](./b/README.md)", ["./a/README.md", "./b/README.md"]],
385 ["~~~\n[a](./a/README.md)\n\n~~~\n[b](./b/README.md)", ["./b/README.md"]],
386 ["Type `` ``` `` then [a](./a/README.md)", ["./a/README.md"]],
387 ["\\``[a](./a/README.md)` [b](./b/README.md)", ["./b/README.md"]],
388 ["```\n```js\n[a](./a/README.md)\n```\n[b](./b/README.md)", ["./b/README.md"]],
389 ["- ```\n [a](./a/README.md)\n ```\n\n[b](./b/README.md)", ["./b/README.md"]],
390 ["> ```\n> [a](./a/README.md)\n> ```\n\n[b](./b/README.md)", ["./b/README.md"]],
391 ["- ```\n [a](./a/README.md)\n\n[b](./b/README.md)", ["./b/README.md"]],
392 ])("skips links inside code in %s", (markdown, hrefs) => {
393 expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
394 });
395​
396 it.each([
397 ["\t[a](src/a.ts)\r\n\r\n [b](src/b.ts)\r\n[c](src/c.ts)", ["src/c.ts"]],
398 ["- Item\n\n [a](src/a.ts)\n\n [b](src/b.ts)", ["src/b.ts"]],
399 ["> [a](src/a.ts)\n>\n> [b](src/b.ts)", ["src/b.ts"]],
400 ["Paragraph\n [a](src/a.ts)\n\n [b](src/b.ts)", ["src/a.ts"]],
401 [" [a](src/a.ts)\r\rOpen [b](src/b.ts)", ["src/b.ts"]],
402 ["Intro\r\r [a](src/a.ts)\r\nOpen [b](src/b.ts)", ["src/b.ts"]],
403 [
404 "[^n]: Intro\n\n [a](src/a.ts)\n\n [code](src/code.ts)\n\nSee [^n] and [b](src/b.ts)",
405 ["src/a.ts", "src/b.ts"],
406 ],
407 ["a | b\n-- | --\n [a](src/a.ts) | hi\n\n[b](src/b.ts)", ["src/b.ts"]],
408 ["a | b\n-- | --\nrow | row\n [a](src/a.ts) | hi\n\n[b](src/b.ts)", ["src/b.ts"]],
409 [
410 "- [code](src/code.ts)\n- [a](src/a.ts)\n- \t\t[b](src/b.ts)",
411 ["src/a.ts", "src/b.ts"],
412 ],
413 [
414 "- Example\n\n [a](src/a.ts)\n\n [code](src/code.ts)\n- [b](src/b.ts)",
415 ["src/a.ts", "src/b.ts"],
416 ],
417 [
418 "- [index.ts](src/a/index.ts) | heading\n -- | --\n\n[index.ts](src/b/index.ts)\n\n- [notes](src/notes.ts)",
419 ["src/b/index.ts", "src/notes.ts"],
420 ],
421 [
422 "- first\n\n - [index.ts](src/a/index.ts) | heading\n -- | --\n\n[index.ts](src/b/index.ts)",
423 ["src/b/index.ts"],
424 ],
425 [
426 "> - [index.ts](src/a/index.ts)\n> heading continuation\n> ===\n\n[index.ts](src/b/index.ts)",
427 ["src/b/index.ts"],
428 ],
429 [
430 "[^a\u00a0b]: Intro\n\n [index.ts](src/a/index.ts)\n\nSee [^a\u00a0b] and [index.ts](src/b/index.ts)",
431 ["src/a/index.ts", "src/b/index.ts"],
432 ],
433 ])("excludes indented code destinations in %j", (markdown, hrefs) => {
434 expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
435 });
436​
437 it.each([
438 [
439 String.raw`[one](<./a/doc\> final.ts>) [two](<./b/doc\> final.ts>)`,
440 [String.raw`./a/doc\> final.ts`, String.raw`./b/doc\> final.ts`],
441 ],
442 [
443 String.raw`[one](<./a/doc\\> "title") [two](<./b/doc\\> (title))`,
444 [String.raw`./a/doc\\`, String.raw`./b/doc\\`],
445 ],
446 [
447 String.raw`[bad](<./x/dir\> text) [one](<./a/doc\\\> final.ts> "title") [two](<./b/doc\< final.ts>)`,
448 [String.raw`./a/doc\\\> final.ts`, String.raw`./b/doc\< final.ts`],
449 ],
450 [
451 "[a](/x/app/(a)/page.tsx) [b](/x/app/(b)/page.tsx)",
452 ["/x/app/(a)/page.tsx", "/x/app/(b)/page.tsx"],
453 ],
454 ['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]],
455 ["[a.ts](a/a.ts (first)) [a.ts](b/a.ts (second))", ["a/a.ts", "b/a.ts"]],
456 [
457 String.raw`[a](<a/a.ts> (escaped \(first\) and \\)) [b](b/a.ts (second))`,
458 ["a/a.ts", "b/a.ts"],
459 ],
460 [
461 "[a](a.ts (nested (title))) [b](b.ts (missing close) [c](c.ts (blank\n\nline)) [d](ok)",
462 ["ok"],
463 ],
464 [`[a](a.ts "it's a title") [b](b.ts 'a "quoted" title') [c](ok)`, ["a.ts", "b.ts", "ok"]],
465 [`[a.ts](src/a.ts "say \\"hello\\"") [a.ts](lib/a.ts)`, ["src/a.ts", "lib/a.ts"]],
466 [`[a](a.ts 'it\\'s') [b](b.ts "ends in \\\\") [c](ok)`, ["a.ts", "b.ts", "ok"]],
467 [`[a](a.ts "unclosed \\") [b](b.ts)`, ["b.ts"]],
468 [`[a](a.ts "mixed') [b](b.ts)`, ["b.ts"]],
469 [`[a](a.ts "it's\n\n[b](lib/a.ts)")`, ["lib/a.ts"]],
470 ["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]],
471 ["[a](x\\)y) [b](x\\(y)", ["x\\)y", "x\\(y"]],
472 ["[a](unclosed(paren) [b](ok)", ["ok"]],
473 ["[a](" + "(".repeat(32) + "x" + ")".repeat(32) + ")", ["(".repeat(32) + "x" + ")".repeat(32)]],
474 ["[a](" + "(".repeat(33) + "x" + ")".repeat(33) + ") [b](ok)", ["ok"]],
475 ])("keeps balanced parentheses in a destination like the parser: %s", (markdown, hrefs) => {
476 expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
477 });
478​
479 it.each([
480 [
481 "[left](./left\u00a0folder/a.ts) and [right](./right/a.ts)",
482 ["./left\u00a0folder/a.ts", "./right/a.ts"],
483 ],
484 ["[a](./a.ts\f) [b](./b.ts\v) [c](ok)", ["ok"]],
485 [
486 "[left](./left/a.ts\u00a0) and [right](./right/a.ts\u00a0)",
487 ["./left/a.ts\u00a0", "./right/a.ts\u00a0"],
488 ],
489 ["[x](./a\0b.ts)", ["./a\0b.ts"]],
490 ])("ends bare destinations only at ASCII whitespace in %j", (markdown, hrefs) => {
491 expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs);
492 });
493});
494​
495describe("resolveMarkdownFileLinkTarget", () => {
496 it("resolves a relative folder with a trailing slash against cwd", () => {
497 expect(resolveMarkdownFileLinkTarget("patches/", "/repo/project")).toBe(
498 "/repo/project/patches/",
499 );
500 expect(resolveMarkdownFileLinkTarget("patches", "/repo/project")).toBeNull();
501 });
502​
503 // regression: #33625 backslash-separated relative links open the workspace file
504 it.each([
505 ["src/Example.cs", "C:\\repo\\src\\Example.cs"],
506 ["src\\Example.cs", "C:\\repo\\src\\Example.cs"],
507 ["src%5CExample.cs", "C:\\repo\\src\\Example.cs"],
508 ["src\\Example.cs:3", "C:\\repo\\src\\Example.cs:3"],
509 ])("resolves the relative link %s against a windows cwd", (href, target) => {
510 expect(resolveMarkdownFileLinkTarget(href, "C:\\repo")).toBe(target);
511 });
512​
513 it("keeps a backslash in a relative link that already names a file", () => {
514 expect(resolveMarkdownFileLinkTarget("./foo%5Cbar.ts", "/repo")).toBe("/repo/foo\\bar.ts");
515 });
516​
517 it("keeps a final nonbreaking space in the path, before a line anchor too", () => {
518 expect(resolveMarkdownFileLinkTarget("./a.ts\u00a0", "/repo")).toBe("/repo/a.ts\u00a0");
519 expect(resolveMarkdownFileLinkTarget("./a.ts\u00a0#L3", "/repo")).toBe("/repo/a.ts\u00a0:3");
520 });
521​
522 it("does not treat filename line references as external schemes", () => {
523 expect(resolveMarkdownFileLinkTarget("script.ts:10", "/Users/julius/project")).toBe(
524 "/Users/julius/project/script.ts:10",
525 );
526 });
527​
528 it("maps #L line anchors to editor line suffixes", () => {
529 expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(
530 "/Users/julius/project/src/main.ts:42:7",
531 );
532 });
533​
534 it("ignores external urls", () => {
535 expect(resolveMarkdownFileLinkTarget("https://example.com/docs")).toBeNull();
536 expect(resolveMarkdownFileLinkTarget("//cdn.example.com/clip.mp4", "/workspace")).toBeNull();
537 });
538​
539 it("does not double-decode file URLs", () => {
540 expect(resolveMarkdownFileLinkTarget("file:///Users/julius/project/file%2520name.md")).toBe(
541 "/Users/julius/project/file%20name.md",
542 );
543 });
544​
545 it("decodes escaped spaces in a file URL that also holds a literal percent", () => {
546 expect(
547 resolveMarkdownFileLink("file:///C:/My%20Folder/100%/notes.md#L10-L20", "C:/"),
548 ).toMatchObject({
549 targetPath: "C:/My Folder/100%/notes.md:10",
550 position: { path: "C:/My Folder/100%/notes.md", line: 10, endLine: 20 },
551 });
552 expect(resolveMarkdownFileLinkTarget("file:///tmp/My%20Folder/100%25%/a%2520b.md")).toBe(
553 "/tmp/My Folder/100%%/a%20b.md",
554 );
555 expect(resolveMarkdownFileLinkTarget("file:///tmp/100%/notes%FF.md#L10")).toBe(
556 "/tmp/100%/notes%FF.md:10",
557 );
558 });
559​
560 it("opens an explicit file URL to an extensionless file outside known roots", () => {
561 expect(resolveMarkdownFileLink("file:///nix/store/test/bin/tool#L10-L20")).toMatchObject({
562 targetPath: "/nix/store/test/bin/tool:10",
563 position: { path: "/nix/store/test/bin/tool", line: 10, endLine: 20 },
564 });
565 });
566​
567 it("links a network path only inside the project's share", () => {
568 const cwd = "\\\\server\\share";
569 expect(resolveMarkdownFileLinkTarget("file://server/share/workspace-image.svg", cwd)).toBe(
570 "\\\\server\\share\\workspace-image.svg",
571 );
572 // Opening these sent the Windows user's NTLM credentials to attacker.test.
573 for (const href of ["file://attacker.test/s/x.ts", "\\\\attacker.test\\s\\x.ts"]) {
574 expect(resolveMarkdownFileLinkTarget(href, cwd)).toBeNull();
575 }
576 });
577​
578 it("keeps an encoded final space in the absolute target", () => {
579 expect(resolveMarkdownFileLinkTarget("/tmp/repo/file.ts%20", "/tmp/repo")).toBe(
580 "/tmp/repo/file.ts ",
581 );
582 });
583​
584 it("normalizes slash-prefixed windows drive paths before resolving", () => {
585 expect(
586 resolveMarkdownFileLinkTarget(
587 "/D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69",
588 ),
589 ).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");
590 });
591​
592 it("decodes an encoded drive colon in a file uri before dropping its slash", () => {
593 expect(resolveMarkdownFileLinkTarget("file:///c%3A/Users/x/shot.png")).toBe(
594 "c:/Users/x/shot.png",
595 );
596 });
597});