Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownLinks.ts

1,122 lines41.3 KB

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 HASH_POSITION_PATTERN = /#L\d+(?:C\d+|-L?\d+)?$/i;
33​
34const INLINE_CODE_POSITION_PATTERN = /(?::\d+(?::\d+|-\d+)?|#L\d+(?:C\d+|-L?\d+)?)$/i;
35​
36const POSITION_ONLY_PATTERN = /^\d+(?::\d+|-\d+)?$/;
37​
38const INLINE_CODE_WHITESPACE_PATTERN = /\s/;
39​
40// Inline code with spaces is a file only when it is absolute and every word is a plain name:
41// `/Users/me/Mobile Documents/a - b.md` is, `/usr/bin/python3 -m venv .venv` (a flag) is not.
42// A space only in the last segment reads as a command (`/usr/local/bin/node server.js`), so it
43// must sit under a user root, and nothing after a bin folder counts.
44const SPACED_ABSOLUTE_PATH_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/]|\\\\)/;
45const SPACED_PATH_BODY_PATTERN =
46 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +(?!-+\p{L})[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?:[\\/]|$))+$/u;
47​
48function isSpacedAbsoluteFilePath(text: string): boolean {
49 const root = SPACED_ABSOLUTE_PATH_ROOT_PATTERN.exec(text)?.[0];
50 if (root === undefined) return false;
51 const body = text.slice(root.length).replace(INLINE_CODE_POSITION_PATTERN, "");
52 if (!SPACED_PATH_BODY_PATTERN.test(body)) return false;
53 const firstSpace = body.indexOf(" ");
54 const foldersBeforeSpace = body.slice(0, firstSpace).split(PATH_SEPARATOR_PATTERN).slice(0, -1);
55 if (foldersBeforeSpace.some((folder) => folder === "bin" || folder === "sbin")) return false;
56 const spaceInFolder = PATH_SEPARATOR_PATTERN.test(body.slice(firstSpace));
57 if (root === "\\\\" && foldersBeforeSpace.length < (spaceInFolder ? 1 : 2)) return false;
58 if (!spaceInFolder && root === "/" && !/^(?:Users|home)[\\/]/.test(body)) return false;
59 if (PATH_SEPARATOR_PATTERN.test(body.at(-1) ?? "")) return true;
60 const basename = body.split(PATH_SEPARATOR_PATTERN).at(-1) ?? "";
61 return FILE_EXTENSION_PATTERN.test(basename) || EXTENSIONLESS_FILE_NAMES.has(basename);
63​
64const PATH_SEPARATOR_PATTERN = /[\\/]/;
65// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
66const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
67​
68const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
69const ANY_FILE_EXTENSION_PATTERN = /\.[^./\\]+$/;
70const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
71const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
72​
73const POSIX_FILE_ROOT_PREFIXES = [
74 "/Users/",
75 "/home/",
76 "/tmp/",
77 "/var/",
78 "/etc/",
79 "/opt/",
80 "/mnt/",
81 "/Volumes/",
82 "/private/",
83 "/root/",
84 "/usr/",
85 "/bin/",
86 "/sbin/",
87 "/lib/",
88 "/lib64/",
89 "/srv/",
90 "/dev/",
91 "/proc/",
92 "/sys/",
93 "/run/",
94 "/boot/",
95 "/media/",
96 "/workspace/",
97 "/workspaces/",
98] as const;
99​
100export const EXTENSIONLESS_FILE_NAMES: ReadonlySet<string> = new Set([
101 "Makefile",
102 "makefile",
103 "GNUmakefile",
104 "Dockerfile",
105 "Containerfile",
106 "Justfile",
107 "justfile",
108 "Rakefile",
109 "Gemfile",
110 "Procfile",
111 "Brewfile",
112 "Caddyfile",
113 "Vagrantfile",
114 "Jenkinsfile",
115 "Podfile",
116 "Fastfile",
117 "BUILD",
118 "WORKSPACE",
119 "LICENSE",
120 "LICENCE",
121 "COPYING",
122 "NOTICE",
123 "AUTHORS",
124 "CONTRIBUTORS",
125 "CHANGELOG",
126 "README",
127 "CODEOWNERS",
128]);
129​
130const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
131​
132const GENERIC_HOSTNAME_TLDS = new Set([
133 "com",
134 "net",
135 "org",
136 "io",
137 "dev",
138 "app",
139 "ai",
140 "co",
141 "edu",
142 "gov",
143 "mil",
144 "info",
145 "biz",
146 "xyz",
147 "me",
148 "tv",
149 "gg",
150 "chat",
151 "cloud",
152 "site",
153 "online",
154 "tech",
155 "store",
156 "link",
157]);
158​
159const COUNTRY_HOSTNAME_TLDS = new Set([
160 "uk",
161 "de",
162 "fr",
163 "nl",
164 "se",
165 "no",
166 "fi",
167 "dk",
168 "pl",
169 "ch",
170 "at",
171 "be",
172 "es",
173 "it",
174 "pt",
175 "eu",
176 "us",
177 "ca",
178 "au",
179 "nz",
180 "jp",
181 "kr",
182 "cn",
183 "br",
184 "ru",
185 "mx",
186 "ie",
187 "cz",
188 "tr",
189 "sg",
190 "hk",
191 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
192 "cc",
193]);
194​
195function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
196 if (segment.startsWith(".")) return false;
197 const lowered = segment.toLowerCase();
198 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
199 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
200 const labels = lowered.split(".");
201 const lastLabel = labels.at(-1);
202 if (labels.length < 2 || lastLabel === undefined) return false;
203 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
204 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
206​
207export function inlineCodeFilePathCandidate(codeText: string): string | null {
208 const trimmed = codeText.trim();
209 if (trimmed.length === 0 || trimmed.includes("`") || /[<>]/.test(trimmed)) return null;
210 if (INLINE_CODE_WHITESPACE_PATTERN.test(trimmed) && !isSpacedAbsoluteFilePath(trimmed)) {
211 return null;
212 }
213​
214 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
215 const position = INLINE_CODE_POSITION_PATTERN.exec(candidate)?.[0];
216 const hasPosition = position !== undefined;
217 const withoutPosition = candidate.replace(INLINE_CODE_POSITION_PATTERN, "");
218 // Resolvers split at the first `#`, so a `#L` anchor only works on a path without another `#`.
219 if (position?.startsWith("#") && withoutPosition.includes("#")) return null;
220 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
221 if (ELIDED_PATH_SEGMENT_PATTERN.test(withoutPosition)) return null;
222​
223 const hasExplicitPathShape =
224 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
225 candidate.startsWith("/") ||
226 isWindowsAbsolutePath(candidate);
227 if (!hasExplicitPathShape) {
228 // Markdown destinations accept `patches/`. Inline code still needs a
229 // file-shaped final segment, so a trailing slash stays plain code.
230 if (withoutPosition.endsWith("/")) return null;
231 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
232 if (looksLikeHostname(firstSegment, hasPosition)) return null;
233 const basename =
234 withoutPosition
235 .replace(/[/\\]+$/, "")
236 .split(/[\\/]/)
237 .at(-1) ?? "";
238 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
239 if (!FILE_EXTENSION_PATTERN.test(basename)) {
240 if (!hasPosition) return EXTENSIONLESS_FILE_NAMES.has(basename) ? candidate : null;
241 // A `:line` suffix alone does not make `I/W217:220` a file reference.
242 if (
243 withoutPosition.includes("/") &&
244 !ANY_FILE_EXTENSION_PATTERN.test(basename) &&
245 !EXTENSIONLESS_FILE_NAMES.has(basename)
246 ) {
247 return null;
248 }
249 }
250 }
251 return candidate;
253​
254export function safeDecodeURIComponent(value: string): string {
255 try {
256 return decodeURIComponent(value);
257 } catch {
258 return value;
259 }
261​
262// Markdown whitespace is ASCII, so a path may end in U+00A0. A `$` regex would be quadratic.
263function trimAscii(value: string): string {
264 let end = value.length;
265 while (/[ \t\r\n]/.test(value[end - 1] ?? "")) end--;
266 return value.slice(0, end).replace(/^[ \t\r\n]+/, "");
268​
269// An angle destination may start or end in whitespace, which later trimming would drop, so encode it
270// as the renderer does once decoded. Words encodes what `encodeURI` does except `%`; micromark also
271// escapes a `%` that two alphanumerics do not follow.
272export function encodeMarkdownLinkBoundaryWhitespace(url: string, strayPercent: boolean): string {
273 if (!/^[ \t]|[ \t]$/.test(url)) return url;
274 const escaped = strayPercent ? url.replace(/%(?![\dA-Za-z]{2})/g, "%25") : url;
275 const wellFormed = escaped.replace(/\p{Cs}/gu, "\uFFFD");
276 return wellFormed
277 .split("%")
278 .map((part) => encodeURI(part))
279 .join("%");
281​
282export function normalizeMarkdownLinkDestination(value: string): string {
283 const trimmed = trimAscii(value);
284 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
286​
287export function splitMarkdownLinkSearchAndHash(value: string): {
288 readonly path: string;
289 readonly hash: string;
290} {
291 const hashIndex = value.indexOf("#");
292 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
293 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
294 const queryIndex = pathWithSearch.indexOf("?");
295 return {
296 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
297 hash,
298 };
300​
301/**
302 * The decoded path a markdown destination names on the host, before any workspace resolution, or
303 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
304 */
305export function markdownDestinationHostPath(source: string): string | null {
306 if (/^file:/i.test(source)) {
307 const target = parseFileUrlHref(source);
308 return target === null
309 ? null
310 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
311 }
312 return stripSlashPrefixedWindowsDrive(
313 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
314 );
316​
317const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
318const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
319​
320export type MarkdownImageSource =
321 | { readonly _tag: "Direct"; readonly uri: string }
322 | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true }
323 | { readonly _tag: "Blocked" };
324​
325// A POSIX filename may contain a backslash, so only Windows roots treat it as a separator.
326function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
327 if (!isWindowsAbsolutePath(workspaceRoot)) {
328 return `${workspaceRoot.replace(/\/+$/, "")}/${relativePath.replace(/^\/+/, "")}`;
329 }
330 const root = workspaceRoot.replace(/[\\/]+$/, "");
331 return `${root}\\${relativePath.replace(/[\\/]/g, "\\").replace(/^\\+/, "")}`;
333​
334/** Rendering is not a click, so a network path loads only from the project's own share. */
335function hostFileSource(
336 path: string,
337 workspaceRoot: string | null | undefined,
338): MarkdownImageSource {
339 return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
340 ? { _tag: "Blocked" }
341 : { _tag: "WorkspaceFile", path };
343​
344/**
345 * Filesystem paths belong to the environment host and must never reach a
346 * browser or native image component without first becoming a signed asset URL.
347 */
348export function classifyMarkdownImageSource(
349 value: string | null | undefined,
350 workspaceRoot?: string | null,
351): MarkdownImageSource {
352 if (value === null || value === undefined) return { _tag: "Blocked" };
353​
354 const source = normalizeMarkdownLinkDestination(value);
355 if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
356 return { _tag: "Blocked" };
357 }
358 if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
359 return { _tag: "Direct", uri: source };
360 }
361​
362 const path = markdownDestinationHostPath(source);
363 if (path === null) return { _tag: "Blocked" };
364 if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);
365 if (path.length === 0) return { _tag: "Blocked" };
366 if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
367 return hostFileSource(path, workspaceRoot);
368 }
369 if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
370 return { _tag: "Blocked" };
371 }
372 if (!workspaceRoot) return { _tag: "Blocked" };
373​
374 return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true };
376​
377export function shouldRenderMarkdownImageAsFileLink(
378 source: MarkdownImageSource,
379 mediaKind: ReturnType<typeof mediaKindFromPath>,
380): boolean {
381 return source._tag === "WorkspaceFile" && mediaKind === null;
383​
384export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
385 const destination = parseMarkdownFileLink(href);
386 if (!destination) return false;
387 const normalize = (path: string) =>
388 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
389 const trimmed = label.trim();
390 const isWindowsDestination = isWindowsAbsolutePath(destination.path);
391 const destinationPath = isWindowsDestination
392 ? normalize(destination.path).toLowerCase()
393 : normalize(destination.path);
394 const matchesLabelPosition = (labelPosition: FilePathPosition): boolean => {
395 if (
396 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
397 (labelPosition.column !== undefined && labelPosition.column !== destination.column) ||
398 (labelPosition.endLine !== undefined && labelPosition.endLine !== destination.endLine)
399 ) {
400 return false;
401 }
402 let labelPath = normalize(labelPosition.path);
403 if (labelPath.length === 0) return true;
404 if (isWindowsDestination) {
405 labelPath = labelPath.toLowerCase();
406 }
407 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
408 };
409 const hashIndex = trimmed.lastIndexOf("#");
410 if (hashIndex >= 0) {
411 const path = trimmed.slice(0, hashIndex);
412 const anchored = splitFilePathPosition(path, trimmed.slice(hashIndex));
413 // A `:line` suffix before the hash wins in splitFilePathPosition; only a position from the anchor counts here.
414 if (anchored.line !== undefined && anchored.path === path && matchesLabelPosition(anchored)) {
415 return true;
416 }
417 }
418 return (
419 matchesLabelPosition(splitFilePathPosition(trimmed)) ||
420 (trimmed.length > 0 && matchesLabelPosition(splitFilePathPosition(label)))
421 );
423​
424export function isRelativeFilePath(path: string): boolean {
425 return (
426 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
427 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
428 );
430​
431function looksLikePosixFilesystemPath(path: string): boolean {
432 if (!path.startsWith("/")) return false;
433 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
434 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
435 const basename = path.slice(path.lastIndexOf("/") + 1);
436 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename.trimEnd());
438​
439function looksLikeFilePath(path: string, authoredPath: string): boolean {
440 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
441 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
442 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
443 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
445​
446function hasExternalScheme(path: string): boolean {
447 if (isWindowsAbsolutePath(path)) return false;
448 const match = path.match(EXTERNAL_SCHEME_PATTERN);
449 if (!match) return false;
450 const rest = match[2] ?? "";
451 if (rest.startsWith("//")) return true;
452 return !POSITION_ONLY_PATTERN.test(rest);
454​
455export function parseMarkdownSandboxFileLink(href: string): FilePathPosition | null {
456 const prefix = /^sandbox:(?=\/|[A-Za-z]:[\\/])/i.exec(href);
457 if (!prefix) return null;
458​
459 const source = splitMarkdownLinkSearchAndHash(href.slice(prefix[0].length));
460 const path = safeDecodeURIComponent(source.path);
461 // A sandbox URI names a local file on the thread host, never a network share.
462 if (path.length < 2 || isNetworkPath(path) || path.includes("\0") || /[\t\r\n]/.test(path)) {
463 return null;
464 }
465 const position = splitFilePathPosition(
466 stripSlashPrefixedWindowsDrive(path),
467 safeDecodeURIComponent(source.hash),
468 );
469 return ELIDED_PATH_SEGMENT_PATTERN.test(position.path) ? null : position;
471​
472export function parseMarkdownFileLink(href: string): FilePathPosition | null {
473 const normalized = normalizeMarkdownLinkDestination(href);
474 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
475 return null;
476 }
477​
478 const sandboxFile = parseMarkdownSandboxFileLink(normalized);
479 if (sandboxFile) return sandboxFile;
480​
481 const fileUrl = normalized.toLowerCase().startsWith("file:")
482 ? parseFileUrlHref(normalized)
483 : null;
484 const source = fileUrl ?? splitMarkdownLinkSearchAndHash(normalized);
485 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(trimAscii(source.path)));
486 const hash = safeDecodeURIComponent(trimAscii(source.hash));
487 if (path.length === 0 || hasExternalScheme(path)) return null;
488​
489 const position = parseFilePathLink(path, hash, fileUrl !== null);
490 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
491 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
492 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
493 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
495​
496function parseFilePathLink(path: string, hash: string, isFileUrl = false): FilePathPosition | null {
497 const position = splitFilePathPosition(path, hash);
498 return !ELIDED_PATH_SEGMENT_PATTERN.test(position.path) &&
499 (isFileUrl || looksLikeFilePath(position.path, path))
500 ? position
501 : null;
503​
504const BACKTICK_RUN_PATTERN = /`+/g;
505​
506function collectLineCodeSpans(line: string, spans: string[]) {
507 const runs = line.includes("`") ? [...line.matchAll(BACKTICK_RUN_PATTERN)] : [];
508 if (runs.length < 2) return;
509 const runsByLength = new Map<number, number[]>();
510 for (const [i, run] of runs.entries()) {
511 const indexes = runsByLength.get(run[0].length);
512 if (indexes) indexes.push(i);
513 else runsByLength.set(run[0].length, [i]);
514 }
515 const cursorByLength = new Map<number, number>();
516 let textStart = 0;
517 for (let i = 0; i < runs.length; i += 1) {
518 const run = runs[i]!;
519 let backslashes = 0;
520 while (run.index - backslashes > textStart && line[run.index - backslashes - 1] === "\\") {
521 backslashes += 1;
522 }
523 // An escaped backtick is literal outside code spans; only closers keep backslashes literal.
524 const length = run[0].length - (backslashes % 2);
525 const candidates = runsByLength.get(length) ?? [];
526 let cursor = cursorByLength.get(length) ?? 0;
527 while (cursor < candidates.length && candidates[cursor]! <= i) cursor += 1;
528 cursorByLength.set(length, cursor);
529 const close = candidates[cursor];
530 if (length === 0 || close === undefined) continue;
531 const span = line.slice(run.index + run[0].length, runs[close]!.index).trim();
532 if (span) spans.push(span);
533 i = close;
534 textStart = runs[close]!.index + runs[close]![0].length;
535 }
537​
538// A backtick fence's info string cannot contain a backtick: "```a```" is a code span.
539const FENCE_OPENER_PATTERN = /^(`{3,}(?![^`]*`)|~{3,})/;
540const FENCE_CLOSER_PATTERN = /^(`{3,}|~{3,}) *$/;
541const LIST_MARKER_PATTERN = /^(?:[-+*]|(\d{1,9})[.)])( +|$)/;
542const THEMATIC_BREAK_PATTERN = /^([-*_]) *(?:\1 *){2,}$/;
543const ATX_HEADING_PATTERN = /^#{1,6}(?: |$)/;
544const SETEXT_UNDERLINE_PATTERN = /^(?:=+|-+) *$/;
545// What ends a paragraph, so a line starting with one is never its lazy continuation.
546const PARAGRAPH_INTERRUPTION_PATTERN =
547 /^(?:>|`{3,}(?![^`]*`)|~{3,}|(?:[-+*]|\d{1,9}[.)])(?: |$)|#{1,6}(?: |$)|([-*_]) *(?:\1 *){2,}$)/;
548​
549const FOOTNOTE_DEFINITION_PATTERN = /^\[\^(?:\\[\\[\]]|\\(?![\\[\]])|[^ \t\r\n\\[\]]){1,999}\]: */;
550const TABLE_DELIMITER_PATTERN = /^\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/;
551​
552const BLOCKQUOTE = 0;
553// A recovered list block continues within the original code block's four-column prefix.
554const RECOVERED_LIST_CODE = -4;
555​
556function tableColumnCount(row: string): number {
557 const trimmed = row.trimEnd();
558 let columns = 1;
559 for (const match of trimmed.matchAll(/\\[\\|]|\|/g)) {
560 if (match[0] === "|" && match.index > 0 && match.index < trimmed.length - 1) columns += 1;
561 }
562 return columns;
564​
565function isTableDelimiter(header: string, line: string): boolean {
566 return (
567 header.trimEnd() !== "|" &&
568 /[|:]/.test(line) &&
569 TABLE_DELIMITER_PATTERN.test(line) &&
570 tableColumnCount(line) === tableColumnCount(header)
571 );
573​
574function expandMarkdownLine(line: string): string {
575 const source = line.endsWith("\r") ? line.slice(0, -1) : line;
576 if (!source.includes("\t")) return source;
577 let column = 0;
578 return source.replace(/\t|[^\t]+/g, (part) => {
579 const expanded = part === "\t" ? " ".repeat(4 - (column % 4)) : part;
580 column += expanded.length;
581 return expanded;
582 });
584​
585function markdownIndent(source: string, position: number): number {
586 let indent = 0;
587 while (source[position + indent] === " ") indent += 1;
588 return indent;
590​
591function blockquoteContentStart(source: string, marker: number): number {
592 return marker + (source[marker + 1] === " " ? 2 : 1);
594​
595function matchMarkdownContainers(
596 source: string,
597 containers: readonly number[],
598 blankEndsItemAt = -1,
599) {
600 let position = 0;
601 let matched = 0;
602 for (const container of containers) {
603 const indent = markdownIndent(source, position);
604 const first = source[position + indent];
605 if (container === BLOCKQUOTE) {
606 if (indent > 3 || first !== ">") break;
607 position = blockquoteContentStart(source, position + indent);
608 } else if (first === undefined) {
609 if (matched === blankEndsItemAt) break;
610 } else if (indent >= Math.abs(container)) {
611 position += Math.abs(container);
612 } else {
613 break;
614 }
615 matched += 1;
616 }
617 return { position, matched };
619​
620// List recovery prefixes the first line as prose. A table delimiter or a setext underline
621// can still turn that first block into a table or heading, which the renderer leaves literal.
622function recoveredListStartsWithParagraph(
623 lines: readonly string[],
624 index: number,
625 header: string,
626 containers: readonly number[],
627): boolean {
628 for (let next = index + 1; next < lines.length; next += 1) {
629 const source = expandMarkdownLine(lines[next]!);
630 const { position, matched } = matchMarkdownContainers(source, containers);
631 if (matched < containers.length) break;
632 const indent = markdownIndent(source, position);
633 const content = source.slice(position + indent);
634 if (!content || indent < 4) break;
635 if (indent >= 8) continue;
636 if (SETEXT_UNDERLINE_PATTERN.test(content)) return false;
637 if (PARAGRAPH_INTERRUPTION_PATTERN.test(content) || FOOTNOTE_DEFINITION_PATTERN.test(content)) {
638 break;
639 }
640 if (next === index + 1 && isTableDelimiter(`x ${header}`, content)) return false;
641 }
642 return true;
644​
645// Normalize lone CR without changing offsets or splitting CRLF into two line endings.
646function normalizeLoneCarriageReturns(text: string): string {
647 return text.replace(/\r(?!\n)/g, "\n");
649​
650export function extractInlineCodeSpans(text: string): string[] {
651 if (!text.includes("`")) return [];
652 const markdown = normalizeLoneCarriageReturns(text);
653 let masked = "";
654 let copied = 0;
655 if (markdown.includes("](")) {
656 visitLinkTails(markdown, (_href, start, end) => {
657 masked += markdown.slice(copied, start) + markdown.slice(start, end).replaceAll("`", " ");
658 copied = end;
659 });
660 }
661 const spans: string[] = [];
662 const inlineMarkdown = copied > 0 ? masked + markdown.slice(copied) : undefined;
663 visitMarkdownLines(markdown, (line, start, code) => {
664 if (code) return;
665 collectLineCodeSpans(inlineMarkdown?.slice(start, start + line.length) ?? line, spans);
666 });
667 return spans;
669​
670/**
671 * Visits text and code lines. Blockquotes and list items are tracked line by line as
672 * CommonMark nests them, because a fence closes only at its own container's indentation and ends
673 * with that container. A full parse would be exact but costs about 100x this scan, which runs on
674 * every streamed chunk.
675 */
676function visitMarkdownLines(
677 text: string,
678 visit: (line: string, start: number, code: boolean, heading?: boolean) => void,
679) {
680 // Open containers, outermost first: blockquotes, indented content, and recovered list code.
681 const containers: number[] = [];
682 let fence: { marker: string; indented: boolean } | null = null;
683 // Whether the previous line left a paragraph open, and whether indented code is still open:
684 // micromark lets neither be interrupted by an empty list item or one not numbered 1.
685 let paragraph = false;
686 let indentedCode = false;
687 // A table has a header candidate until its delimiter row opens the body.
688 let table: { depth: number; header?: string } | undefined;
689 // Depth of an item that has only its marker so far; a blank line next ends it.
690 let emptyItemDepth = 0;
691 let lineStart = 0;
692 const lines = text.split("\n");
693 for (const [index, line] of lines.entries()) {
694 const previousTable = table;
695 table = undefined;
696 const start = lineStart;
697 lineStart += line.length + 1;
698 const source = expandMarkdownLine(line);
699 const containerCount = containers.length;
700 const prefix = matchMarkdownContainers(source, containers, emptyItemDepth - 1);
701 const { matched } = prefix;
702 let { position } = prefix;
703 emptyItemDepth = 0;
704 let indent = 0;
705 let content = "";
706 const readIndent = () => {
707 indent = markdownIndent(source, position);
708 content = source.slice(position + indent);
709 };
710 readIndent();
711​
712 if (fence) {
713 if (matched === containers.length) {
714 if (content === "") continue;
715 // A fence written inside indented code ends with that code.
716 if (!fence.indented || indent >= 4) {
717 visit(line, start, true);
718 const closer = FENCE_CLOSER_PATTERN.exec(content)?.[1];
719 if (
720 closer?.startsWith(fence.marker[0]!) &&
721 closer.length >= fence.marker.length &&
722 (fence.indented || indent <= 3)
723 ) {
724 fence = null;
725 paragraph = false;
726 }
727 continue;
728 }
729 }
730 fence = null;
731 paragraph = false;
732 }
733​
734 if (matched < containers.length) {
735 if (
736 paragraph &&
737 content !== "" &&
738 containers.lastIndexOf(RECOVERED_LIST_CODE) < matched &&
739 (indent >= 4 ||
740 (!PARAGRAPH_INTERRUPTION_PATTERN.test(content) &&
741 !FOOTNOTE_DEFINITION_PATTERN.test(content)))
742 ) {
743 visit(line, start, false);
744 continue;
745 }
746 containers.length = matched;
747 paragraph = false;
748 indentedCode = false;
749 }
750 // micromark decides this once per line, and not at all on a line that closed a container.
751 const interrupts = paragraph || indentedCode;
752 const closedContainer = matched < containerCount;
753​
754 for (;;) {
755 if (content === "") {
756 paragraph = false;
757 break;
758 }
759 const opener = FENCE_OPENER_PATTERN.exec(content)?.[1];
760 if (indent >= 4) {
761 if (!paragraph && !closedContainer) indentedCode = true;
762 // Inside a paragraph an indented line is text, where only a backtick run opens code (a span).
763 if (opener && (!paragraph || opener[0] === "`")) {
764 fence = { marker: opener, indented: true };
765 visit(line, start, true);
766 } else {
767 visit(line, start, !paragraph);
768 }
769 break;
770 }
771 indentedCode = false;
772 if (opener) {
773 fence = { marker: opener, indented: false };
774 visit(line, start, true);
775 break;
776 }
777 if (content[0] === ">") {
778 containers.push(BLOCKQUOTE);
779 position = blockquoteContentStart(source, position + indent);
780 paragraph = false;
781 readIndent();
782 continue;
783 }
784 if (THEMATIC_BREAK_PATTERN.test(content)) {
785 paragraph = false;
786 break;
787 }
788 const footnote = FOOTNOTE_DEFINITION_PATTERN.exec(content);
789 if (footnote) {
790 containers.push(4);
791 position += indent + footnote[0].length;
792 paragraph = false;
793 readIndent();
794 continue;
795 }
796 const item = LIST_MARKER_PATTERN.exec(content);
797 const emptyItem = item?.[0].length === content.length;
798 // Only a non-empty item, numbered 1 if ordered, starts a list in the middle of a block.
799 if (
800 item &&
801 !(interrupts && (emptyItem || (item[1] !== undefined && Number(item[1]) !== 1)))
802 ) {
803 const padding = item[2]!.length;
804 const width = item[0].length - padding + (emptyItem || padding > 4 ? 1 : padding);
805 containers.push(indent + width);
806 if (emptyItem) emptyItemDepth = containers.length;
807 position += indent + width;
808 paragraph = false;
809 readIndent();
810 // The renderer recovers same-line indented list code with whitespace left in its value.
811 if (
812 !emptyItem &&
813 padding > 5 &&
814 recoveredListStartsWithParagraph(lines, index, content, containers)
815 ) {
816 containers.push(RECOVERED_LIST_CODE);
817 visit(line, start, false);
818 paragraph = true;
819 break;
820 }
821 continue;
822 }
823 const heading = ATX_HEADING_PATTERN.test(content);
824 visit(line, start, false, heading);
825 if (heading || (paragraph && SETEXT_UNDERLINE_PATTERN.test(content))) {
826 paragraph = false;
827 } else if (
828 previousTable?.depth === containers.length &&
829 !closedContainer &&
830 (previousTable.header === undefined || isTableDelimiter(previousTable.header, content))
831 ) {
832 table = { depth: containers.length };
833 paragraph = false;
834 } else {
835 table = { depth: containers.length, header: content };
836 paragraph = true;
837 }
838 break;
839 }
840 }
842​
843function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
844 let runStart = -1;
845 let runEnd = -1;
846 return (start: number) => {
847 if (start >= runStart && start <= runEnd) return runEnd;
848 delimiter.lastIndex = start;
849 runStart = start;
850 let match = delimiter.exec(markdown);
851 while (match?.[0].length === 2 && match[0][0] === "\\") match = delimiter.exec(markdown);
852 runEnd = match?.index ?? markdown.length;
853 return runEnd;
854 };
856​
857function markdownLinkTailScanner(markdown: string) {
858 // A blank line ends the paragraph, so no part of a link's tail runs past one.
859 const whitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
860 // Escape pairs (`\"`, `\\`) match so the finder can skip them.
861 const doubleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\"]|"|\n[ \t\r]*\n/g);
862 const singleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\']|'|\n[ \t\r]*\n/g);
863 const parenthesisEnd = markdownRunEndFinder(markdown, /\\[\\()]|[()]|\n[ \t\r]*\n/g);
864 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
865 return (start: number) => {
866 const end = whitespaceEnd(start);
867 const quote = markdown[end];
868 if (quote === ")") return end + 1;
869 if (end === start || (quote !== '"' && quote !== "'" && quote !== "(")) return null;
870 const titleEnd =
871 quote === '"' ? doubleQuoteEnd : quote === "'" ? singleQuoteEnd : parenthesisEnd;
872 const quoteEnd = titleEnd(end + 1);
873 if (markdown[quoteEnd] !== (quote === "(" ? ")" : quote)) return null;
874 const close = titleWhitespaceEnd(quoteEnd + 1);
875 return markdown[close] === ")" ? close + 1 : null;
876 };
878​
879// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
880// link's opening parenthesis while that parenthesis counts toward this depth.
881const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;
882​
883function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
884 // Destinations end at ASCII spaces and controls but not NUL, which micromark reads as U+FFFD.
885 const delimiter = /[\x01-\x20\x7f()\\]/g;
886 delimiter.lastIndex = start;
887 let depth = 0;
888 while (true) {
889 const index = delimiter.exec(markdown)?.index ?? markdown.length;
890 const char = markdown[index];
891 if (char === "\\") {
892 if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
893 } else if (char === "(") {
894 if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
895 depth += 1;
896 } else if (char === ")" && depth > 0) {
897 depth -= 1;
898 } else {
899 return depth === 0 ? index : null;
900 }
901 }
903​
904export function markdownLinkDestinationScanner(markdown: string) {
905 const whitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
906 const angleEnd = markdownRunEndFinder(markdown, /\\[\\<>]|[<>\r\n]/g);
907 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
908 const angleTail = markdownLinkTailScanner(markdown);
909 const bareTail = markdownLinkTailScanner(markdown);
910 return (start: number) => {
911 if (markdown[start] !== "(") return null;
912 const hrefStart = whitespaceEnd(start + 1);
913 if (markdown[hrefStart] === "<") {
914 const hrefEnd = angleEnd(hrefStart + 1);
915 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
916 const end = angleTail(hrefEnd + 1);
917 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
918 }
919 }
920 const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
921 if (hrefEnd === null) return null;
922 const end = bareTail(hrefEnd);
923 return end === null ? null : { hrefStart, hrefEnd, end };
924 };
926​
927// Code blocks keep their offsets; heading edges end inline labels and code spans.
928function linkScanSource(text: string) {
929 const boundaries: number[] = [];
930 if (!/ {4}|\t|```|~~~|#/.test(text)) return { markdown: text, boundaries };
931 let blanked = "";
932 let copied = 0;
933 visitMarkdownLines(text, (line, start, code, heading) => {
934 if (heading) boundaries.push(start, start + line.length);
935 if (!code) return;
936 blanked += text.slice(copied, start) + line.replace(/[^\r]/g, " ");
937 copied = start + line.length;
938 });
939 return { markdown: blanked + text.slice(copied), boundaries };
941​
942// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them
943// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels.
944function visitLinkTails(
945 text: string,
946 visit: (href: string, from: number, to: number, imageStart?: number) => void,
947) {
948 const { markdown, boundaries } = linkScanSource(text);
949 const scanDestination = markdownLinkDestinationScanner(markdown);
950 const paragraphEnd = markdownRunEndFinder(markdown, /\n[ \t\r]*\n/g);
951 // A code span closes at the next run of as many backticks in its paragraph.
952 const closersByLength = new Map<number, { ends: number[]; next: number }>();
953 for (const run of markdown.matchAll(/`+/g)) {
954 const closers = closersByLength.get(run[0].length) ?? { ends: [], next: 0 };
955 closers.ends.push(run.index + run[0].length);
956 closersByLength.set(run[0].length, closers);
957 }
958 // Only punctuation forms an escape pair. A newline still starts a paragraph break.
959 const bracket = /\\[!-/:-@[-`{-~]|!\[|[[\]]|`+|\n[ \t\r]*\n/g;
960 const openers: Array<number | { imageStart: number }> = [];
961 let generation = 0;
962 let boundaryIndex = 0;
963 for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) {
964 while ((boundaries[boundaryIndex] ?? Infinity) <= match.index) {
965 openers.length = 0;
966 boundaryIndex++;
967 }
968 const nextBoundary = boundaries[boundaryIndex] ?? markdown.length;
969 if (match[0].startsWith("\\")) continue;
970 if (match[0].startsWith("`")) {
971 const length = match[0].length;
972 const closers = closersByLength.get(length) ?? { ends: [], next: 0 };
973 while ((closers.ends[closers.next] ?? Infinity) - length < bracket.lastIndex) closers.next++;
974 const end = closers.ends[closers.next];
975 if (
976 end !== undefined &&
977 end <= nextBoundary &&
978 end - length <= paragraphEnd(bracket.lastIndex)
979 ) {
980 bracket.lastIndex = end;
981 }
982 } else if (match[0].startsWith("\n")) {
983 openers.length = 0;
984 } else if (match[0].endsWith("[")) {
985 openers.push(match[0] === "![" ? { imageStart: match.index } : generation);
986 } else if (openers.length > 0) {
987 const opener = openers.pop()!;
988 const imageStart = typeof opener === "number" ? undefined : opener.imageStart;
989 if (imageStart === undefined && opener !== generation) continue;
990 const destination = scanDestination(match.index + 1);
991 if (!destination || destination.end > nextBoundary) continue;
992 // Deactivate older links without dropping enclosing image labels.
993 if (imageStart === undefined) generation++;
994 bracket.lastIndex = destination.end;
995 const href = markdown.slice(destination.hrefStart, destination.hrefEnd);
996 visit(href, match.index + 1, destination.end, imageStart);
997 }
998 }
1000​
1001export function extractMarkdownLinkHrefs(text: string): string[] {
1002 const hrefs: Array<{ href: string; offset: number }> = [];
1003 visitLinkTails(normalizeLoneCarriageReturns(text), (href, from, _to, imageStart) => {
1004 if (imageStart !== undefined) {
1005 while ((hrefs.at(-1)?.offset ?? -Infinity) > imageStart) hrefs.pop();
1007 if (href) hrefs.push({ href, offset: from });
1008 });
1009 return hrefs.map(({ href }) => href);
1011​
1012export function resolveMarkdownFileLinkTarget(
1013 href: string | undefined,
1014 cwd?: string,
1015 baseDir: string | undefined = cwd,
1016): string | null {
1017 return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
1019​
1020/** Resolves the displayed position and the editor target, which opens at the start line. */
1021export function resolveMarkdownFileLink(
1022 href: string | undefined,
1023 cwd?: string,
1024 baseDir: string | undefined = cwd,
1025): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
1026 const source = href ? parseMarkdownFileLink(href) : null;
1027 if (!source) return null;
1028​
1029 const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
1030 if (!targetPath) return null;
1031 return {
1032 sourcePath: source.path,
1033 targetPath,
1034 position: {
1035 ...splitFilePathPosition(targetPath),
1036 ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
1037 },
1038 };
1040​
1041function resolveParsedFileLinkTarget(
1042 target: FilePathPosition,
1043 cwd: string | undefined,
1044 baseDir: string | undefined,
1045): string | null {
1046 const pathWithPosition = formatFilePathPosition(target);
1047 if (!isRelativeFilePath(pathWithPosition)) {
1048 // Opening a network path makes Windows sign in to its host with the user's
1049 // NTLM credentials, so only the project's own share becomes a file link.
1050 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
1051 ? null
1052 : pathWithPosition;
1054 if (!baseDir) return null;
1055 return resolvePathLinkTarget(pathWithPosition, baseDir);
1057​
1058export function isWindowsDrivePathHref(href: string): boolean {
1059 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
1061​
1062// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms,
1063// plus the Arabic-script comma, semicolon, question mark, and full stop.
1064export const SCRIPT_PUNCTUATION = /(?=[ -〿＀-￯،؛؟۔])[\p{P}\p{S}]/u;
1065​
1066/** Where ASCII text runs into such a mark, or -1. Unicode before it may make the mark part of the text. */
1067export function scriptPunctuationAfterAscii(text: string): number {
1068 const index = text.search(/[^!-~]/u);
1069 return index > 0 && SCRIPT_PUNCTUATION.test(text.charAt(index)) ? index : -1;
1071​
1072// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
1073// and a file-shaped last segment.
1074export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
1075 const paths: Array<{ index: number; path: string }> = [];
1076 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
1077 const cut = scriptPunctuationAfterAscii(match[2]!);
1078 const source = cut > 0 ? match[2]!.slice(0, cut) : match[2]!;
1079 let parentheses = 0;
1080 let brackets = 0;
1081 for (const character of source) {
1082 if (character === "(") parentheses += 1;
1083 if (character === ")") parentheses -= 1;
1084 if (character === "[") brackets += 1;
1085 if (character === "]") brackets -= 1;
1087 let end = source.length;
1088 while (end > 0) {
1089 const character = source[end - 1]!;
1090 if (character === ")" && parentheses < 0) parentheses += 1;
1091 else if (character === "]" && brackets < 0) brackets += 1;
1092 else if (!".,;!?:".includes(character)) break;
1093 end -= 1;
1095 const path = source.slice(0, end);
1096 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
1097 if (path.endsWith("/") && source.startsWith("...", end)) continue;
1098 if (
1099 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
1100 !POSITION_SUFFIX_PATTERN.test(path)
1102 continue;
1103 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
1104 const hashPosition = HASH_POSITION_PATTERN.exec(path)?.[0];
1105 const filePath = hashPosition ? path.slice(0, -hashPosition.length) : path;
1106 const basename = filePath.slice(filePath.lastIndexOf("/") + 1);
1107 if (
1108 !POSITION_SUFFIX_PATTERN.test(path) &&
1109 !FILE_EXTENSION_PATTERN.test(basename) &&
1110 !EXTENSIONLESS_FILE_NAMES.has(basename)
1112 continue;
1113 if (hashPosition && /[?#]/.test(filePath)) continue;
1114 const parsed = parseMarkdownFileLink(path);
1115 if (!parsed || (hashPosition && parsed.line === undefined)) continue;
1116 paths.push({ index: match.index + match[1]!.length, path });
1118 return paths;
1120​
1121// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
1122export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;