Open History to see the last commit
1import {
2 isNetworkPath,
3 isWindowsAbsolutePath,
4 stripSlashPrefixedWindowsDrive,
5 workspaceRelativeFilePath,
6} from "./path.ts";
7import {
8 type FilePathPosition,
9 formatFilePathPosition,
10 parseFileUrlHref,
11 resolvePathLinkTarget,
12 splitFilePathPosition,
13} from "./fileLinks.ts";
14
15const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
16
17// Names may use any script (`線性代數/考試.pdf`) and routing punctuation (`posts.$id.tsx`,
18// `(group)/[id]/+page.svelte`, `@scope/pkg`). The final segment is optional so an explicit
19// folder link may end in `/` (`patches/`, `docs/My Folder/`). A bare name with no slash still fails.
20const RELATIVE_FILE_PATH_PATTERN =
21 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*\/)+(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?::\d+(?::\d+|-\d+)?)?)?$/u;
22
23// No `@` here: `me@example.com` is an address, not a file.
24const RELATIVE_FILE_NAME_PATTERN =
25 /^[\p{L}\p{M}\p{N}._$+()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+()[\]-]+)*\.[\p{L}\p{M}\p{N}_-]+(?::\d+(?::\d+|-\d+)?)?$/u;
26
27const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
28
29const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+|-\d+)?$/;
30
31const POSITION_ONLY_PATTERN = /^\d+(?::\d+|-\d+)?$/;
32
33const INLINE_CODE_WHITESPACE_PATTERN = /\s/;
34
35// Inline code with spaces is a file only when it is absolute and every word is a plain name:
36// `/Users/me/Mobile Documents/a - b.md` is, `/usr/bin/python3 -m venv .venv` (a flag) is not.
37// A space only in the last segment reads as a command (`/usr/local/bin/node server.js`), so it
38// must sit under a user root, and nothing after a bin folder counts.
39const SPACED_ABSOLUTE_PATH_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/])/;
40const SPACED_PATH_BODY_PATTERN =
41 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: (?!-+\p{L})[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?:[\\/]|$))+$/u;
42
43function isSpacedAbsoluteFilePath(text: string): boolean {
44 const root = SPACED_ABSOLUTE_PATH_ROOT_PATTERN.exec(text)?.[0];
45 if (root === undefined) return false;
46 const body = text.slice(root.length).replace(POSITION_SUFFIX_PATTERN, "");
47 if (!SPACED_PATH_BODY_PATTERN.test(body)) return false;
48 const firstSpace = body.indexOf(" ");
49 const foldersBeforeSpace = body.slice(0, firstSpace).split(PATH_SEPARATOR_PATTERN).slice(0, -1);
50 if (foldersBeforeSpace.some((folder) => folder === "bin" || folder === "sbin")) return false;
51 const spaceInFolder = PATH_SEPARATOR_PATTERN.test(body.slice(firstSpace));
52 if (!spaceInFolder && root === "/" && !/^(?:Users|home)[\\/]/.test(body)) return false;
53 if (PATH_SEPARATOR_PATTERN.test(body.at(-1) ?? "")) return true;
54 const basename = body.split(PATH_SEPARATOR_PATTERN).at(-1) ?? "";
55 return FILE_EXTENSION_PATTERN.test(basename) || EXTENSIONLESS_FILE_NAMES.has(basename);
56}
57
58const PATH_SEPARATOR_PATTERN = /[\\/]/;
59// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
60const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
61
62const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
63const ANY_FILE_EXTENSION_PATTERN = /\.[^./\\]+$/;
64const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
65const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
66
67const POSIX_FILE_ROOT_PREFIXES = [
68 "/Users/",
69 "/home/",
70 "/tmp/",
71 "/var/",
72 "/etc/",
73 "/opt/",
74 "/mnt/",
75 "/Volumes/",
76 "/private/",
77 "/root/",
78 "/usr/",
79 "/bin/",
80 "/sbin/",
81 "/lib/",
82 "/lib64/",
83 "/srv/",
84 "/dev/",
85 "/proc/",
86 "/sys/",
87 "/run/",
88 "/boot/",
89 "/media/",
90 "/workspace/",
91 "/workspaces/",
92] as const;
93
94export const EXTENSIONLESS_FILE_NAMES: ReadonlySet<string> = new Set([
95 "Makefile",
96 "makefile",
97 "GNUmakefile",
98 "Dockerfile",
99 "Containerfile",
100 "Justfile",
101 "justfile",
102 "Rakefile",
103 "Gemfile",
104 "Procfile",
105 "Brewfile",
106 "Caddyfile",
107 "Vagrantfile",
108 "Jenkinsfile",
109 "Podfile",
110 "Fastfile",
111 "BUILD",
112 "WORKSPACE",
113 "LICENSE",
114 "LICENCE",
115 "COPYING",
116 "NOTICE",
117 "AUTHORS",
118 "CONTRIBUTORS",
119 "CHANGELOG",
120 "README",
121 "CODEOWNERS",
122]);
123
124const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
125
126const GENERIC_HOSTNAME_TLDS = new Set([
127 "com",
128 "net",
129 "org",
130 "io",
131 "dev",
132 "app",
133 "ai",
134 "co",
135 "edu",
136 "gov",
137 "mil",
138 "info",
139 "biz",
140 "xyz",
141 "me",
142 "tv",
143 "gg",
144 "chat",
145 "cloud",
146 "site",
147 "online",
148 "tech",
149 "store",
150 "link",
151]);
152
153const COUNTRY_HOSTNAME_TLDS = new Set([
154 "uk",
155 "de",
156 "fr",
157 "nl",
158 "se",
159 "no",
160 "fi",
161 "dk",
162 "pl",
163 "ch",
164 "at",
165 "be",
166 "es",
167 "it",
168 "pt",
169 "eu",
170 "us",
171 "ca",
172 "au",
173 "nz",
174 "jp",
175 "kr",
176 "cn",
177 "br",
178 "ru",
179 "mx",
180 "ie",
181 "cz",
182 "tr",
183 "sg",
184 "hk",
185 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
186 "cc",
187]);
188
189function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
190 if (segment.startsWith(".")) return false;
191 const lowered = segment.toLowerCase();
192 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
193 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
194 const labels = lowered.split(".");
195 const lastLabel = labels.at(-1);
196 if (labels.length < 2 || lastLabel === undefined) return false;
197 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
198 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
199}
200
201export function inlineCodeFilePathCandidate(codeText: string): string | null {
202 const trimmed = codeText.trim();
203 if (trimmed.length === 0 || trimmed.includes("`")) return null;
204 if (INLINE_CODE_WHITESPACE_PATTERN.test(trimmed) && !isSpacedAbsoluteFilePath(trimmed)) {
205 return null;
206 }
207
208 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
209 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
210 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
211 if (ELIDED_PATH_SEGMENT_PATTERN.test(candidate.replace(POSITION_SUFFIX_PATTERN, ""))) return null;
212
213 const hasExplicitPathShape =
214 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
215 candidate.startsWith("/") ||
216 isWindowsAbsolutePath(candidate);
217 if (!hasExplicitPathShape) {
218 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
219 // Markdown destinations accept `patches/`. Inline code still needs a
220 // file-shaped final segment, so a trailing slash stays plain code.
221 if (withoutPosition.endsWith("/")) return null;
222 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
223 if (looksLikeHostname(firstSegment, hasPosition)) return null;
224 const basename =
225 withoutPosition
226 .replace(/[/\\]+$/, "")
227 .split(/[\\/]/)
228 .at(-1) ?? "";
229 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
230 if (!FILE_EXTENSION_PATTERN.test(basename)) {
231 if (!hasPosition) return EXTENSIONLESS_FILE_NAMES.has(basename) ? candidate : null;
232 // A `:line` suffix alone does not make `I/W217:220` a file reference.
233 if (
234 withoutPosition.includes("/") &&
235 !ANY_FILE_EXTENSION_PATTERN.test(basename) &&
236 !EXTENSIONLESS_FILE_NAMES.has(basename)
237 ) {
238 return null;
239 }
240 }
241 }
242 return candidate;
243}
244
245export function safeDecodeURIComponent(value: string): string {
246 try {
247 return decodeURIComponent(value);
248 } catch {
249 return value;
250 }
251}
252
253export function normalizeMarkdownLinkDestination(value: string): string {
254 const trimmed = value.trim();
255 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
256}
257
258export function splitMarkdownLinkSearchAndHash(value: string): {
259 readonly path: string;
260 readonly hash: string;
261} {
262 const hashIndex = value.indexOf("#");
263 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
264 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
265 const queryIndex = pathWithSearch.indexOf("?");
266 return {
267 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
268 hash,
269 };
270}
271
272/**
273 * The decoded path a markdown destination names on the host, before any workspace resolution, or
274 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
275 */
276export function markdownDestinationHostPath(source: string): string | null {
277 if (/^file:/i.test(source)) {
278 const target = parseFileUrlHref(source);
279 return target === null
280 ? null
281 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
282 }
283 return stripSlashPrefixedWindowsDrive(
284 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
285 );
286}
287
288export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
289 const destination = parseMarkdownFileLink(href);
290 if (!destination) return false;
291 const normalize = (path: string) =>
292 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
293 const labelPosition = splitFilePathPosition(label.trim());
294 if (
295 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
296 (labelPosition.column !== undefined && labelPosition.column !== destination.column) ||
297 (labelPosition.endLine !== undefined && labelPosition.endLine !== destination.endLine)
298 ) {
299 return false;
300 }
301 let labelPath = normalize(labelPosition.path);
302 let destinationPath = normalize(destination.path);
303 if (labelPath.length === 0) return true;
304 if (isWindowsAbsolutePath(destination.path)) {
305 labelPath = labelPath.toLowerCase();
306 destinationPath = destinationPath.toLowerCase();
307 }
308 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
309}
310
311export function isRelativeFilePath(path: string): boolean {
312 return (
313 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
314 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
315 );
316}
317
318function looksLikePosixFilesystemPath(path: string): boolean {
319 if (!path.startsWith("/")) return false;
320 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
321 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
322 const basename = path.slice(path.lastIndexOf("/") + 1);
323 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
324}
325
326function looksLikeFilePath(path: string, authoredPath: string): boolean {
327 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
328 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
329 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
330 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
331}
332
333function hasExternalScheme(path: string): boolean {
334 if (isWindowsAbsolutePath(path)) return false;
335 const match = path.match(EXTERNAL_SCHEME_PATTERN);
336 if (!match) return false;
337 const rest = match[2] ?? "";
338 if (rest.startsWith("//")) return true;
339 return !POSITION_ONLY_PATTERN.test(rest);
340}
341
342export function parseMarkdownFileLink(href: string): FilePathPosition | null {
343 const normalized = normalizeMarkdownLinkDestination(href);
344 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
345 return null;
346 }
347
348 const source =
349 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
350 splitMarkdownLinkSearchAndHash(normalized);
351 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
352 const hash = safeDecodeURIComponent(source.hash.trim());
353 if (path.length === 0 || hasExternalScheme(path)) return null;
354
355 const position = parseFilePathLink(path, hash);
356 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
357 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
358 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
359 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
360}
361
362function parseFilePathLink(path: string, hash: string): FilePathPosition | null {
363 const position = splitFilePathPosition(path, hash);
364 return !ELIDED_PATH_SEGMENT_PATTERN.test(position.path) && looksLikeFilePath(position.path, path)
365 ? position
366 : null;
367}
368
369const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
370
371const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
372
373export function extractInlineCodeSpans(text: string): string[] {
374 const spans: string[] = [];
375 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
376 for (let index = 0; index < segments.length; index += 2) {
377 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
378 const span = match[1]?.trim();
379 if (span) spans.push(span);
380 }
381 }
382 return spans;
383}
384
385function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
386 let runStart = -1;
387 let runEnd = -1;
388 return (start: number) => {
389 if (start >= runStart && start <= runEnd) return runEnd;
390 delimiter.lastIndex = start;
391 runStart = start;
392 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
393 return runEnd;
394 };
395}
396
397function markdownLinkTailScanner(markdown: string) {
398 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
399 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
400 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
401 return (start: number) => {
402 const end = whitespaceEnd(start);
403 if (markdown[end] === ")") return end + 1;
404 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
405 const quoteEnd = titleEnd(end + 1);
406 if (quoteEnd === markdown.length) return null;
407 const close = titleWhitespaceEnd(quoteEnd + 1);
408 return markdown[close] === ")" ? close + 1 : null;
409 };
410}
411
412// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
413// link's opening parenthesis while that parenthesis counts toward this depth.
414const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;
415
416function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
417 const delimiter = /[\s()\\]/g;
418 delimiter.lastIndex = start;
419 let depth = 0;
420 while (true) {
421 const index = delimiter.exec(markdown)?.index ?? markdown.length;
422 const char = markdown[index];
423 if (char === "\\") {
424 if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
425 } else if (char === "(") {
426 if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
427 depth += 1;
428 } else if (char === ")" && depth > 0) {
429 depth -= 1;
430 } else {
431 return depth === 0 ? index : null;
432 }
433 }
434}
435
436function markdownLinkDestinationScanner(markdown: string) {
437 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
438 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
439 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
440 const angleTail = markdownLinkTailScanner(markdown);
441 const bareTail = markdownLinkTailScanner(markdown);
442 return (start: number) => {
443 if (markdown[start] !== "(") return null;
444 const hrefStart = whitespaceEnd(start + 1);
445 if (markdown[hrefStart] === "<") {
446 const hrefEnd = angleEnd(hrefStart + 1);
447 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
448 const end = angleTail(hrefEnd + 1);
449 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
450 }
451 }
452 const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
453 if (hrefEnd === null || hrefEnd === hrefStart) return null;
454 const end = bareTail(hrefEnd);
455 return end === null ? null : { hrefStart, hrefEnd, end };
456 };
457}
458
459// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one.
460function unescapedLabelEnd(markdown: string, start: number): number {
461 let end = markdown.indexOf("]", start);
462 while (end !== -1) {
463 let backslashes = 0;
464 while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1;
465 if (backslashes % 2 === 0) return end;
466 end = markdown.indexOf("]", end + 1);
467 }
468 return -1;
469}
470
471export function extractMarkdownLinkHrefs(markdown: string): string[] {
472 const hrefs: string[] = [];
473 const scanDestination = markdownLinkDestinationScanner(markdown);
474 let cursor = 0;
475 while (cursor < markdown.length) {
476 const labelStart = markdown.indexOf("[", cursor);
477 if (labelStart === -1) break;
478 const labelEnd = unescapedLabelEnd(markdown, labelStart + 1);
479 if (labelEnd === -1) break;
480
481 // Skip a failed label once; nested openings share its closing bracket.
482 cursor = labelEnd + 1;
483 const destination = scanDestination(cursor);
484 if (!destination) continue;
485 cursor = destination.end;
486 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
487 if (href) hrefs.push(href);
488 }
489 return hrefs;
490}
491
492export function resolveMarkdownFileLinkTarget(
493 href: string | undefined,
494 cwd?: string,
495 baseDir: string | undefined = cwd,
496): string | null {
497 if (!href) return null;
498 const target = parseMarkdownFileLink(href);
499 if (!target) return null;
500
501 const pathWithPosition = formatFilePathPosition(target);
502 if (!isRelativeFilePath(pathWithPosition)) {
503 // Opening a network path makes Windows sign in to its host with the user's
504 // NTLM credentials, so only the project's own share becomes a file link.
505 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
506 ? null
507 : pathWithPosition;
508 }
509 if (!baseDir) return null;
510 return resolvePathLinkTarget(pathWithPosition, baseDir);
511}
512
513export function isWindowsDrivePathHref(href: string): boolean {
514 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
515}
516
517// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
518// and a file-shaped last segment.
519export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
520 const paths: Array<{ index: number; path: string }> = [];
521 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
522 const source = match[2]!;
523 let parentheses = 0;
524 let brackets = 0;
525 for (const character of source) {
526 if (character === "(") parentheses += 1;
527 if (character === ")") parentheses -= 1;
528 if (character === "[") brackets += 1;
529 if (character === "]") brackets -= 1;
530 }
531 let end = source.length;
532 while (end > 0) {
533 const character = source[end - 1]!;
534 if (character === ")" && parentheses < 0) parentheses += 1;
535 else if (character === "]" && brackets < 0) brackets += 1;
536 else if (!".,;!?:".includes(character)) break;
537 end -= 1;
538 }
539 const path = source.slice(0, end);
540 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
541 if (path.endsWith("/") && source.startsWith("...", end)) continue;
542 if (
543 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
544 !POSITION_SUFFIX_PATTERN.test(path)
545 )
546 continue;
547 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
548 const basename = path.slice(path.lastIndexOf("/") + 1);
549 if (
550 !POSITION_SUFFIX_PATTERN.test(path) &&
551 !FILE_EXTENSION_PATTERN.test(basename) &&
552 !EXTENSIONLESS_FILE_NAMES.has(basename)
553 )
554 continue;
555 if (!parseMarkdownFileLink(path)) continue;
556 paths.push({ index: match.index + match[1]!.length, path });
557 }
558 return paths;
559}