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_DISQUALIFIER_PATTERN = /[\s`]/;
34
35const PATH_SEPARATOR_PATTERN = /[\\/]/;
36// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
37const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
38
39const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
40const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
41const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
42
43const POSIX_FILE_ROOT_PREFIXES = [
44 "/Users/",
45 "/home/",
46 "/tmp/",
47 "/var/",
48 "/etc/",
49 "/opt/",
50 "/mnt/",
51 "/Volumes/",
52 "/private/",
53 "/root/",
54 "/usr/",
55 "/bin/",
56 "/sbin/",
57 "/lib/",
58 "/lib64/",
59 "/srv/",
60 "/dev/",
61 "/proc/",
62 "/sys/",
63 "/run/",
64 "/boot/",
65 "/media/",
66 "/workspace/",
67 "/workspaces/",
68] as const;
69
70const EXTENSIONLESS_FILE_NAMES = new Set([
71 "Makefile",
72 "makefile",
73 "GNUmakefile",
74 "Dockerfile",
75 "Containerfile",
76 "Justfile",
77 "justfile",
78 "Rakefile",
79 "Gemfile",
80 "Procfile",
81 "Brewfile",
82 "Caddyfile",
83 "Vagrantfile",
84 "Jenkinsfile",
85 "Podfile",
86 "Fastfile",
87 "BUILD",
88 "WORKSPACE",
89 "LICENSE",
90 "LICENCE",
91 "COPYING",
92 "NOTICE",
93 "AUTHORS",
94 "CONTRIBUTORS",
95 "CHANGELOG",
96 "README",
97 "CODEOWNERS",
98]);
99
100const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
101
102const GENERIC_HOSTNAME_TLDS = new Set([
103 "com",
104 "net",
105 "org",
106 "io",
107 "dev",
108 "app",
109 "ai",
110 "co",
111 "edu",
112 "gov",
113 "mil",
114 "info",
115 "biz",
116 "xyz",
117 "me",
118 "tv",
119 "gg",
120 "chat",
121 "cloud",
122 "site",
123 "online",
124 "tech",
125 "store",
126 "link",
127]);
128
129const COUNTRY_HOSTNAME_TLDS = new Set([
130 "uk",
131 "de",
132 "fr",
133 "nl",
134 "se",
135 "no",
136 "fi",
137 "dk",
138 "pl",
139 "ch",
140 "at",
141 "be",
142 "es",
143 "it",
144 "pt",
145 "eu",
146 "us",
147 "ca",
148 "au",
149 "nz",
150 "jp",
151 "kr",
152 "cn",
153 "br",
154 "ru",
155 "mx",
156 "ie",
157 "cz",
158 "tr",
159 "sg",
160 "hk",
161 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
162 "cc",
163]);
164
165function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
166 if (segment.startsWith(".")) return false;
167 const lowered = segment.toLowerCase();
168 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
169 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
170 const labels = lowered.split(".");
171 const lastLabel = labels.at(-1);
172 if (labels.length < 2 || lastLabel === undefined) return false;
173 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
174 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
175}
176
177export function inlineCodeFilePathCandidate(codeText: string): string | null {
178 const trimmed = codeText.trim();
179 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
180
181 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
182 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
183 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
184 if (ELIDED_PATH_SEGMENT_PATTERN.test(candidate.replace(POSITION_SUFFIX_PATTERN, ""))) return null;
185
186 const hasExplicitPathShape =
187 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
188 candidate.startsWith("/") ||
189 isWindowsAbsolutePath(candidate);
190 if (!hasExplicitPathShape) {
191 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
192 // Markdown destinations accept `patches/`. Inline code still needs a
193 // file-shaped final segment, so a trailing slash stays plain code.
194 if (withoutPosition.endsWith("/")) return null;
195 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
196 if (looksLikeHostname(firstSegment, hasPosition)) return null;
197 const basename =
198 withoutPosition
199 .replace(/[/\\]+$/, "")
200 .split(/[\\/]/)
201 .at(-1) ?? "";
202 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
203 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
204 }
205 return candidate;
206}
207
208export function safeDecodeURIComponent(value: string): string {
209 try {
210 return decodeURIComponent(value);
211 } catch {
212 return value;
213 }
214}
215
216export function normalizeMarkdownLinkDestination(value: string): string {
217 const trimmed = value.trim();
218 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
219}
220
221export function splitMarkdownLinkSearchAndHash(value: string): {
222 readonly path: string;
223 readonly hash: string;
224} {
225 const hashIndex = value.indexOf("#");
226 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
227 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
228 const queryIndex = pathWithSearch.indexOf("?");
229 return {
230 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
231 hash,
232 };
233}
234
235/**
236 * The decoded path a markdown destination names on the host, before any workspace resolution, or
237 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
238 */
239export function markdownDestinationHostPath(source: string): string | null {
240 if (/^file:/i.test(source)) {
241 const target = parseFileUrlHref(source);
242 return target === null
243 ? null
244 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
245 }
246 return stripSlashPrefixedWindowsDrive(
247 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
248 );
249}
250
251export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
252 const destination = parseMarkdownFileLink(href);
253 if (!destination) return false;
254 const normalize = (path: string) =>
255 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
256 const labelPosition = splitFilePathPosition(label.trim());
257 if (
258 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
259 (labelPosition.column !== undefined && labelPosition.column !== destination.column) ||
260 (labelPosition.endLine !== undefined && labelPosition.endLine !== destination.endLine)
261 ) {
262 return false;
263 }
264 let labelPath = normalize(labelPosition.path);
265 let destinationPath = normalize(destination.path);
266 if (labelPath.length === 0) return true;
267 if (isWindowsAbsolutePath(destination.path)) {
268 labelPath = labelPath.toLowerCase();
269 destinationPath = destinationPath.toLowerCase();
270 }
271 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
272}
273
274export function isRelativeFilePath(path: string): boolean {
275 return (
276 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
277 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
278 );
279}
280
281function looksLikePosixFilesystemPath(path: string): boolean {
282 if (!path.startsWith("/")) return false;
283 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
284 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
285 const basename = path.slice(path.lastIndexOf("/") + 1);
286 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
287}
288
289function looksLikeFilePath(path: string, authoredPath: string): boolean {
290 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
291 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
292 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
293 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
294}
295
296function hasExternalScheme(path: string): boolean {
297 if (isWindowsAbsolutePath(path)) return false;
298 const match = path.match(EXTERNAL_SCHEME_PATTERN);
299 if (!match) return false;
300 const rest = match[2] ?? "";
301 if (rest.startsWith("//")) return true;
302 return !POSITION_ONLY_PATTERN.test(rest);
303}
304
305export function parseMarkdownFileLink(href: string): FilePathPosition | null {
306 const normalized = normalizeMarkdownLinkDestination(href);
307 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
308 return null;
309 }
310
311 const source =
312 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
313 splitMarkdownLinkSearchAndHash(normalized);
314 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
315 const hash = safeDecodeURIComponent(source.hash.trim());
316 if (path.length === 0 || hasExternalScheme(path)) return null;
317
318 const position = parseFilePathLink(path, hash);
319 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
320 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
321 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
322 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
323}
324
325function parseFilePathLink(path: string, hash: string): FilePathPosition | null {
326 const position = splitFilePathPosition(path, hash);
327 return looksLikeFilePath(position.path, path) ? position : null;
328}
329
330const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
331
332const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
333
334export function extractInlineCodeSpans(text: string): string[] {
335 const spans: string[] = [];
336 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
337 for (let index = 0; index < segments.length; index += 2) {
338 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
339 const span = match[1]?.trim();
340 if (span) spans.push(span);
341 }
342 }
343 return spans;
344}
345
346function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
347 let runStart = -1;
348 let runEnd = -1;
349 return (start: number) => {
350 if (start >= runStart && start <= runEnd) return runEnd;
351 delimiter.lastIndex = start;
352 runStart = start;
353 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
354 return runEnd;
355 };
356}
357
358function markdownLinkTailScanner(markdown: string) {
359 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
360 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
361 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
362 return (start: number) => {
363 const end = whitespaceEnd(start);
364 if (markdown[end] === ")") return end + 1;
365 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
366 const quoteEnd = titleEnd(end + 1);
367 if (quoteEnd === markdown.length) return null;
368 const close = titleWhitespaceEnd(quoteEnd + 1);
369 return markdown[close] === ")" ? close + 1 : null;
370 };
371}
372
373function markdownLinkDestinationScanner(markdown: string) {
374 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
375 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
376 const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
377 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
378 const angleTail = markdownLinkTailScanner(markdown);
379 const bareTail = markdownLinkTailScanner(markdown);
380 return (start: number) => {
381 if (markdown[start] !== "(") return null;
382 const hrefStart = whitespaceEnd(start + 1);
383 if (markdown[hrefStart] === "<") {
384 const hrefEnd = angleEnd(hrefStart + 1);
385 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
386 const end = angleTail(hrefEnd + 1);
387 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
388 }
389 }
390 const hrefEnd = bareEnd(hrefStart);
391 if (hrefEnd === hrefStart) return null;
392 const end = bareTail(hrefEnd);
393 return end === null ? null : { hrefStart, hrefEnd, end };
394 };
395}
396
397export function extractMarkdownLinkHrefs(markdown: string): string[] {
398 const hrefs: string[] = [];
399 const scanDestination = markdownLinkDestinationScanner(markdown);
400 let cursor = 0;
401 while (cursor < markdown.length) {
402 const labelStart = markdown.indexOf("[", cursor);
403 if (labelStart === -1) break;
404 const labelEnd = markdown.indexOf("]", labelStart + 1);
405 if (labelEnd === -1) break;
406
407 // Skip a failed label once; nested openings share its closing bracket.
408 cursor = labelEnd + 1;
409 const destination = scanDestination(cursor);
410 if (!destination) continue;
411 cursor = destination.end;
412 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
413 if (href) hrefs.push(href);
414 }
415 return hrefs;
416}
417
418export function resolveMarkdownFileLinkTarget(
419 href: string | undefined,
420 cwd?: string,
421 baseDir: string | undefined = cwd,
422): string | null {
423 if (!href) return null;
424 const target = parseMarkdownFileLink(href);
425 if (!target) return null;
426
427 const pathWithPosition = formatFilePathPosition(target);
428 if (!isRelativeFilePath(pathWithPosition)) {
429 // Opening a network path makes Windows sign in to its host with the user's
430 // NTLM credentials, so only the project's own share becomes a file link.
431 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
432 ? null
433 : pathWithPosition;
434 }
435 if (!baseDir) return null;
436 return resolvePathLinkTarget(pathWithPosition, baseDir);
437}
438
439export function isWindowsDrivePathHref(href: string): boolean {
440 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
441}