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

markdownLinks.ts

428 lines13.0 KB

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