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

markdown-links.ts

443 lines13.7 KB

1import { formatWorkspaceRelativePath } from "./filePathDisplay";
2import {
3 isTerminalLinkActivation,
4 resolvePathLinkTarget,
5 splitPathAndPosition,
6} from "./terminal-links";
7​
8const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
9const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
10const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
11const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
12const RELATIVE_FILE_PATH_PATTERN =
13 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
14const RELATIVE_FILE_NAME_PATTERN =
15 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
16const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
17const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
18// Standard OS and dev-container roots; deliberately excludes app-route-ish
19// prefixes like /app/ or /chat/ so SPA routes never read as files.
20const POSIX_FILE_ROOT_PREFIXES = [
21 "/Users/",
22 "/home/",
23 "/tmp/",
24 "/var/",
25 "/etc/",
26 "/opt/",
27 "/mnt/",
28 "/Volumes/",
29 "/private/",
30 "/root/",
31 "/usr/",
32 "/bin/",
33 "/sbin/",
34 "/lib/",
35 "/lib64/",
36 "/srv/",
37 "/dev/",
38 "/proc/",
39 "/sys/",
40 "/run/",
41 "/boot/",
42 "/media/",
43 "/workspace/",
44 "/workspaces/",
45] as const;
46const MARKDOWN_LINK_HREF_PATTERN =
47 /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;
48​
49export interface MarkdownFileLinkMeta {
50 filePath: string;
51 targetPath: string;
52 displayPath: string;
53 workspaceRelativePath: string | null;
54 basename: string;
55 line?: number;
56 column?: number;
58​
59export function extractMarkdownLinkHrefs(markdown: string): string[] {
60 const hrefs: string[] = [];
61 for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
62 const href = (match[1] ?? match[2])?.trim();
63 if (href) hrefs.push(href);
64 }
65 return hrefs;
67​
68export function shouldOpenMarkdownFileLinkInEditor(
69 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
70 platform?: string,
71): boolean {
72 return isTerminalLinkActivation(event, platform);
74​
75export function shouldOpenMarkdownFileLinkInBrowserByDefault(path: string): boolean {
76 return /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
78​
79function safeDecode(value: string): string {
80 try {
81 return decodeURIComponent(value);
82 } catch {
83 return value;
84 }
86​
87export function isWindowsDrivePathHref(href: string): boolean {
88 return WINDOWS_DRIVE_PATH_PATTERN.test(safeDecode(href));
90​
91function unwrapMarkdownLinkDestination(value: string): string {
92 return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
94​
95export function normalizeMarkdownLinkDestination(value: string): string {
96 return unwrapMarkdownLinkDestination(value.trim());
98​
99function stripSearchAndHash(value: string): { path: string; hash: string } {
100 const hashIndex = value.indexOf("#");
101 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
102 const rawHash = hashIndex >= 0 ? value.slice(hashIndex) : "";
103 const queryIndex = pathWithSearch.indexOf("?");
104 const path = queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch;
105 return { path, hash: rawHash };
107​
108function normalizeWindowsDrivePath(path: string): string {
109 return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
111​
112function parseFileUrlHref(
113 href: string,
114 options?: { readonly decodePath?: boolean },
115): { path: string; hash: string } | null {
116 try {
117 const parsed = new URL(href);
118 if (parsed.protocol.toLowerCase() !== "file:") return null;
119​
120 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
121 const rawPath = uncHostname
122 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
123 : parsed.pathname;
124 if (rawPath.length === 0) return null;
125​
126 // Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
127 const normalizedPath = normalizeWindowsDrivePath(rawPath);
128​
129 return {
130 path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
131 hash: parsed.hash,
132 };
133 } catch {
134 return null;
135 }
137​
138export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
139 if (!href) return null;
140 const normalizedHref = normalizeMarkdownLinkDestination(href);
141 const target = parseFileUrlHref(normalizedHref, { decodePath: false });
142 if (!target) return null;
143 return `${target.path}${target.hash}`;
145​
146function looksLikePosixFilesystemPath(path: string): boolean {
147 if (!path.startsWith("/")) return false;
148 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
149 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
150 const basename = path.slice(path.lastIndexOf("/") + 1);
151 return /\.[A-Za-z0-9_-]+$/.test(basename);
153​
154function appendLineColumnFromHash(path: string, hash: string): string {
155 if (!hash || POSITION_SUFFIX_PATTERN.test(path)) return path;
156 const match = hash.match(/^#L(\d+)(?:C(\d+))?$/i);
157 if (!match?.[1]) return path;
158 const line = match[1];
159 const column = match[2];
160 return `${path}:${line}${column ? `:${column}` : ""}`;
162​
163function isLikelyPathCandidate(path: string): boolean {
164 if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
165 if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
166 if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
167 return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
169​
170function isRelativePath(path: string): boolean {
171 return (
172 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
173 (!path.startsWith("/") &&
174 !WINDOWS_DRIVE_PATH_PATTERN.test(path) &&
175 !WINDOWS_UNC_PATH_PATTERN.test(path))
176 );
178​
179function hasExternalScheme(path: string): boolean {
180 const match = path.match(EXTERNAL_SCHEME_PATTERN);
181 if (!match) return false;
182 const rest = match[2] ?? "";
183 if (rest.startsWith("//")) return true;
184 return !POSITION_ONLY_PATTERN.test(rest);
186​
187export function resolveMarkdownFileLinkTarget(
188 href: string | undefined,
189 cwd?: string,
190): string | null {
191 if (!href) return null;
192 const rawHref = normalizeMarkdownLinkDestination(href);
193 if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
194​
195 const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
196 ? parseFileUrlHref(rawHref)
197 : null;
198 const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
199 const decodedPath = normalizeWindowsDrivePath(
200 fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim()),
201 );
202 const decodedHash = safeDecode(source.hash.trim());
203​
204 if (decodedPath.length === 0) return null;
205 if (
206 !WINDOWS_DRIVE_PATH_PATTERN.test(decodedPath) &&
207 !WINDOWS_UNC_PATH_PATTERN.test(decodedPath) &&
208 hasExternalScheme(decodedPath)
209 ) {
210 return null;
211 }
212​
213 if (!isLikelyPathCandidate(decodedPath)) return null;
214​
215 const pathWithPosition = appendLineColumnFromHash(decodedPath, decodedHash);
216 if (!isRelativePath(pathWithPosition)) {
217 return pathWithPosition;
218 }
219​
220 if (!cwd) return null;
221 return resolvePathLinkTarget(pathWithPosition, cwd);
223​
224const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
225const PATH_SEPARATOR_PATTERN = /[\\/]/;
226const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
227const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
228const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
229// Any `Name:digits` shape also matches `error:1`, `port:3000`, `TODO:12`, so
230// extensionless linking is limited to conventional filenames.
231const EXTENSIONLESS_FILE_NAMES = new Set([
232 "Makefile",
233 "makefile",
234 "GNUmakefile",
235 "Dockerfile",
236 "Containerfile",
237 "Justfile",
238 "justfile",
239 "Rakefile",
240 "Gemfile",
241 "Procfile",
242 "Brewfile",
243 "Caddyfile",
244 "Vagrantfile",
245 "Jenkinsfile",
246 "Podfile",
247 "Fastfile",
248 "BUILD",
249 "WORKSPACE",
250 "LICENSE",
251 "LICENCE",
252 "COPYING",
253 "NOTICE",
254 "AUTHORS",
255 "CONTRIBUTORS",
256 "CHANGELOG",
257 "README",
258 "CODEOWNERS",
259]);
260const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
261// Allowlists, not full public-suffix detection: treating every dotted first
262// segment as a host would swallow real paths like `conf.d/x.conf` or
263// `Makefile.in:12`. Extensions that double as filename suffixes (`sh`, `md`,
264// `ts`, `rs`, `in`, ...) are deliberately absent from both sets.
265const GENERIC_HOSTNAME_TLDS = new Set([
266 "com",
267 "net",
268 "org",
269 "io",
270 "dev",
271 "app",
272 "ai",
273 "co",
274 "edu",
275 "gov",
276 "mil",
277 "info",
278 "biz",
279 "xyz",
280 "me",
281 "tv",
282 "cc",
283 "gg",
284 "chat",
285 "cloud",
286 "site",
287 "online",
288 "tech",
289 "store",
290 "link",
291]);
292// Country codes collide with file extensions (`.pl` Perl, `.pt` PyTorch,
293// `.es` ES modules), so they only count as host evidence when the candidate
294// lacks a :line suffix — an explicit line reference marks a file and wins.
295const COUNTRY_HOSTNAME_TLDS = new Set([
296 "uk",
297 "de",
298 "fr",
299 "nl",
300 "se",
301 "no",
302 "fi",
303 "dk",
304 "pl",
305 "ch",
306 "at",
307 "be",
308 "es",
309 "it",
310 "pt",
311 "eu",
312 "us",
313 "ca",
314 "au",
315 "nz",
316 "jp",
317 "kr",
318 "cn",
319 "br",
320 "ru",
321 "mx",
322 "ie",
323 "cz",
324 "tr",
325 "sg",
326 "hk",
327]);
328​
329/** `127.0.0.1`, `localhost`, `example.com`, `1.2.3` — hosts and versions, not files. */
330function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
331 if (segment.startsWith(".")) return false;
332 const lowered = segment.toLowerCase();
333 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
334 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
335 const labels = lowered.split(".");
336 const lastLabel = labels[labels.length - 1];
337 if (labels.length < 2 || lastLabel === undefined) return false;
338 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
339 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
341​
342/**
343 * Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
344 * `origin/main`) rather than deliberate link destinations, so auto-linking
345 * them demands stronger path evidence than an explicit markdown link does:
346 * an unambiguous path prefix, a file extension, or a :line suffix.
347 */
348export function resolveInlineCodeFileLinkMeta(
349 codeText: string,
350 cwd?: string,
351): MarkdownFileLinkMeta | null {
352 const trimmed = codeText.trim();
353 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
354​
355 // Windows drive/UNC paths keep their backslashes; any other backslashes are
356 // relative Windows-style paths, which neither the shape checks nor the
357 // downstream resolver understand — normalize them to forward slashes.
358 const candidate =
359 WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
360 ? trimmed
361 : trimmed.replaceAll("\\", "/");
362​
363 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
364 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
365​
366 const hasExplicitPathShape =
367 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
368 candidate.startsWith("/") ||
369 WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
370 WINDOWS_UNC_PATH_PATTERN.test(candidate);
371 if (!hasExplicitPathShape) {
372 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
373 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
374 if (looksLikeHostname(firstSegment, hasPosition)) return null;
375 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basenameOfPath(withoutPosition))) {
376 return null;
377 }
378 }
379​
380 const resolved = resolveMarkdownFileLinkMeta(candidate, cwd);
381 if (resolved) return resolved;
382​
383 // `Makefile:12` — conventional extensionless names fail the generic
384 // markdown-link candidate patterns, but here the :line suffix already
385 // marked the span as a file reference.
386 if (
387 cwd &&
388 BARE_EXTENSIONLESS_POSITION_PATTERN.test(candidate) &&
389 EXTENSIONLESS_FILE_NAMES.has(candidate.replace(POSITION_SUFFIX_PATTERN, ""))
390 ) {
391 return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, cwd), cwd);
392 }
393 return null;
395​
396function basenameOfPath(path: string): string {
397 // A trailing separator is a valid way to write a directory, so trim it before
398 // taking the final segment. Without this the segment reads as empty and the
399 // chip renders with no label at all.
400 const trimmed = path.replace(/[/\\]+$/, "") || path;
401 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
402 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
404​
405function workspaceRelativePath(path: string, workspaceRoot: string | undefined): string | null {
406 if (!workspaceRoot) return null;
407 const normalizedPath = normalizeWindowsDrivePath(path.replaceAll("\\", "/"));
408 const normalizedRoot = normalizeWindowsDrivePath(workspaceRoot.replaceAll("\\", "/")).replace(
409 /\/+$/,
410 "",
411 );
412 const pathForCompare = normalizedPath.toLowerCase();
413 const rootForCompare = normalizedRoot.toLowerCase();
414 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
415 return normalizedPath.slice(normalizedRoot.length + 1);
417​
418export function resolveMarkdownFileLinkMeta(
419 href: string | undefined,
420 cwd?: string,
421): MarkdownFileLinkMeta | null {
422 const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
423 if (!targetPath) return null;
424 return buildFileLinkMetaFromTarget(targetPath, cwd);
426​
427function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
428 const { path, line, column } = splitPathAndPosition(targetPath);
429 const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
430 const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
431 const lineNumber = Number.isFinite(parsedLine) ? parsedLine : undefined;
432 const columnNumber = Number.isFinite(parsedColumn) ? parsedColumn : undefined;
433​
434 return {
435 filePath: path,
436 targetPath,
437 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
438 workspaceRelativePath: workspaceRelativePath(path, cwd),
439 basename: basenameOfPath(path),
440 ...(lineNumber !== undefined ? { line: lineNumber } : {}),
441 ...(columnNumber !== undefined ? { column: columnNumber } : {}),
442 };