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+){0,2})?$/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+){0,2}$/u;
26
27const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
28
29const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
30
31const POSITION_ONLY_PATTERN = /^\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 ) {
261 return false;
262 }
263 let labelPath = normalize(labelPosition.path);
264 let destinationPath = normalize(destination.path);
265 if (labelPath.length === 0) return true;
266 if (isWindowsAbsolutePath(destination.path)) {
267 labelPath = labelPath.toLowerCase();
268 destinationPath = destinationPath.toLowerCase();
269 }
270 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
271}
272
273export function isRelativeFilePath(path: string): boolean {
274 return (
275 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
276 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
277 );
278}
279
280function looksLikePosixFilesystemPath(path: string): boolean {
281 if (!path.startsWith("/")) return false;
282 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
283 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
284 const basename = path.slice(path.lastIndexOf("/") + 1);
285 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
286}
287
288function looksLikeFilePath(path: string, authoredPath: string): boolean {
289 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
290 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
291 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
292 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
293}
294
295function hasExternalScheme(path: string): boolean {
296 if (isWindowsAbsolutePath(path)) return false;
297 const match = path.match(EXTERNAL_SCHEME_PATTERN);
298 if (!match) return false;
299 const rest = match[2] ?? "";
300 if (rest.startsWith("//")) return true;
301 return !POSITION_ONLY_PATTERN.test(rest);
302}
303
304export function parseMarkdownFileLink(href: string): FilePathPosition | null {
305 const normalized = normalizeMarkdownLinkDestination(href);
306 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
307 return null;
308 }
309
310 const source =
311 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
312 splitMarkdownLinkSearchAndHash(normalized);
313 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
314 const hash = safeDecodeURIComponent(source.hash.trim());
315 if (path.length === 0 || hasExternalScheme(path)) return null;
316
317 const position = splitFilePathPosition(path, hash);
318 return looksLikeFilePath(position.path, path) ? position : null;
319}
320
321const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
322
323const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
324
325export function extractInlineCodeSpans(text: string): string[] {
326 const spans: string[] = [];
327 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
328 for (let index = 0; index < segments.length; index += 2) {
329 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
330 const span = match[1]?.trim();
331 if (span) spans.push(span);
332 }
333 }
334 return spans;
335}
336
337function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
338 let runStart = -1;
339 let runEnd = -1;
340 return (start: number) => {
341 if (start >= runStart && start <= runEnd) return runEnd;
342 delimiter.lastIndex = start;
343 runStart = start;
344 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
345 return runEnd;
346 };
347}
348
349function markdownLinkTailScanner(markdown: string) {
350 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
351 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
352 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
353 return (start: number) => {
354 const end = whitespaceEnd(start);
355 if (markdown[end] === ")") return end + 1;
356 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
357 const quoteEnd = titleEnd(end + 1);
358 if (quoteEnd === markdown.length) return null;
359 const close = titleWhitespaceEnd(quoteEnd + 1);
360 return markdown[close] === ")" ? close + 1 : null;
361 };
362}
363
364function markdownLinkDestinationScanner(markdown: string) {
365 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
366 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
367 const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
368 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
369 const angleTail = markdownLinkTailScanner(markdown);
370 const bareTail = markdownLinkTailScanner(markdown);
371 return (start: number) => {
372 if (markdown[start] !== "(") return null;
373 const hrefStart = whitespaceEnd(start + 1);
374 if (markdown[hrefStart] === "<") {
375 const hrefEnd = angleEnd(hrefStart + 1);
376 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
377 const end = angleTail(hrefEnd + 1);
378 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
379 }
380 }
381 const hrefEnd = bareEnd(hrefStart);
382 if (hrefEnd === hrefStart) return null;
383 const end = bareTail(hrefEnd);
384 return end === null ? null : { hrefStart, hrefEnd, end };
385 };
386}
387
388export function extractMarkdownLinkHrefs(markdown: string): string[] {
389 const hrefs: string[] = [];
390 const scanDestination = markdownLinkDestinationScanner(markdown);
391 let cursor = 0;
392 while (cursor < markdown.length) {
393 const labelStart = markdown.indexOf("[", cursor);
394 if (labelStart === -1) break;
395 const labelEnd = markdown.indexOf("]", labelStart + 1);
396 if (labelEnd === -1) break;
397
398 // Skip a failed label once; nested openings share its closing bracket.
399 cursor = labelEnd + 1;
400 const destination = scanDestination(cursor);
401 if (!destination) continue;
402 cursor = destination.end;
403 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
404 if (href) hrefs.push(href);
405 }
406 return hrefs;
407}
408
409export function resolveMarkdownFileLinkTarget(
410 href: string | undefined,
411 cwd?: string,
412 baseDir: string | undefined = cwd,
413): string | null {
414 if (!href) return null;
415 const target = parseMarkdownFileLink(href);
416 if (!target) return null;
417
418 const pathWithPosition = formatFilePathPosition(target);
419 if (!isRelativeFilePath(pathWithPosition)) {
420 // Opening a network path makes Windows sign in to its host with the user's
421 // NTLM credentials, so only the project's own share becomes a file link.
422 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
423 ? null
424 : pathWithPosition;
425 }
426 if (!baseDir) return null;
427 return resolvePathLinkTarget(pathWithPosition, baseDir);
428}
429
430export function isWindowsDrivePathHref(href: string): boolean {
431 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
432}