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

markdownLinks.ts

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