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) return null;
523 const end = bareTail(hrefEnd);
524 return end === null ? null : { hrefStart, hrefEnd, end };
525 };
526}
527
528// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them
529// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels.
530export function extractMarkdownLinkHrefs(markdown: string): string[] {
531 const hrefs: string[] = [];
532 const scanDestination = markdownLinkDestinationScanner(markdown);
533 const bracket = /[[\]\\]|\n[ \t\r]*\n/g;
534 let openBrackets = 0;
535 for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) {
536 if (match[0] === "\\") {
537 bracket.lastIndex = match.index + 2;
538 } else if (match[0].startsWith("\n")) {
539 openBrackets = 0;
540 } else if (match[0] === "[") {
541 openBrackets += 1;
542 } else if (openBrackets > 0) {
543 openBrackets -= 1;
544 const destination = scanDestination(match.index + 1);
545 if (!destination) continue;
546 // A link cannot contain a link, so the brackets still open around it become text.
547 openBrackets = 0;
548 bracket.lastIndex = destination.end;
549 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
550 if (href) hrefs.push(href);
551 }
552 }
553 return hrefs;
554}
555
556export function resolveMarkdownFileLinkTarget(
557 href: string | undefined,
558 cwd?: string,
559 baseDir: string | undefined = cwd,
560): string | null {
561 return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
562}
563
564/** Resolves the displayed position and the editor target, which opens at the start line. */
565export function resolveMarkdownFileLink(
566 href: string | undefined,
567 cwd?: string,
568 baseDir: string | undefined = cwd,
569): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
570 const source = href ? parseMarkdownFileLink(href) : null;
571 if (!source) return null;
572
573 const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
574 if (!targetPath) return null;
575 return {
576 sourcePath: source.path,
577 targetPath,
578 position: {
579 ...splitFilePathPosition(targetPath),
580 ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
581 },
582 };
583}
584
585function resolveParsedFileLinkTarget(
586 target: FilePathPosition,
587 cwd: string | undefined,
588 baseDir: string | undefined,
589): string | null {
590 const pathWithPosition = formatFilePathPosition(target);
591 if (!isRelativeFilePath(pathWithPosition)) {
592 // Opening a network path makes Windows sign in to its host with the user's
593 // NTLM credentials, so only the project's own share becomes a file link.
594 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
595 ? null
596 : pathWithPosition;
597 }
598 if (!baseDir) return null;
599 return resolvePathLinkTarget(pathWithPosition, baseDir);
600}
601
602export function isWindowsDrivePathHref(href: string): boolean {
603 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
604}
605
606// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
607// and a file-shaped last segment.
608export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
609 const paths: Array<{ index: number; path: string }> = [];
610 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
611 const source = match[2]!;
612 let parentheses = 0;
613 let brackets = 0;
614 for (const character of source) {
615 if (character === "(") parentheses += 1;
616 if (character === ")") parentheses -= 1;
617 if (character === "[") brackets += 1;
618 if (character === "]") brackets -= 1;
619 }
620 let end = source.length;
621 while (end > 0) {
622 const character = source[end - 1]!;
623 if (character === ")" && parentheses < 0) parentheses += 1;
624 else if (character === "]" && brackets < 0) brackets += 1;
625 else if (!".,;!?:".includes(character)) break;
626 end -= 1;
627 }
628 const path = source.slice(0, end);
629 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
630 if (path.endsWith("/") && source.startsWith("...", end)) continue;
631 if (
632 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
633 !POSITION_SUFFIX_PATTERN.test(path)
634 )
635 continue;
636 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
637 const basename = path.slice(path.lastIndexOf("/") + 1);
638 if (
639 !POSITION_SUFFIX_PATTERN.test(path) &&
640 !FILE_EXTENSION_PATTERN.test(basename) &&
641 !EXTENSIONLESS_FILE_NAMES.has(basename)
642 )
643 continue;
644 if (!parseMarkdownFileLink(path)) continue;
645 paths.push({ index: match.index + match[1]!.length, path });
646 }
647 return paths;
648}
649
650// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
651export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;