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