Open History to see the last commit
1import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "./path.ts";
2import {
3 type FilePathPosition,
4 formatFilePathPosition,
5 parseFileUrlHref,
6 resolvePathLinkTarget,
7 splitFilePathPosition,
8} from "./fileLinks.ts";
9
10const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
11
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}$/;
14
15const RELATIVE_FILE_NAME_PATTERN =
16 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
17
18const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
19
20const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
21
22const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
23
24const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
25
26const PATH_SEPARATOR_PATTERN = /[\\/]/;
27
28const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
29const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
30const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
31
32const POSIX_FILE_ROOT_PREFIXES = [
33 "/Users/",
34 "/home/",
35 "/tmp/",
36 "/var/",
37 "/etc/",
38 "/opt/",
39 "/mnt/",
40 "/Volumes/",
41 "/private/",
42 "/root/",
43 "/usr/",
44 "/bin/",
45 "/sbin/",
46 "/lib/",
47 "/lib64/",
48 "/srv/",
49 "/dev/",
50 "/proc/",
51 "/sys/",
52 "/run/",
53 "/boot/",
54 "/media/",
55 "/workspace/",
56 "/workspaces/",
57] as const;
58
59const EXTENSIONLESS_FILE_NAMES = new Set([
60 "Makefile",
61 "makefile",
62 "GNUmakefile",
63 "Dockerfile",
64 "Containerfile",
65 "Justfile",
66 "justfile",
67 "Rakefile",
68 "Gemfile",
69 "Procfile",
70 "Brewfile",
71 "Caddyfile",
72 "Vagrantfile",
73 "Jenkinsfile",
74 "Podfile",
75 "Fastfile",
76 "BUILD",
77 "WORKSPACE",
78 "LICENSE",
79 "LICENCE",
80 "COPYING",
81 "NOTICE",
82 "AUTHORS",
83 "CONTRIBUTORS",
84 "CHANGELOG",
85 "README",
86 "CODEOWNERS",
87]);
88
89const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
90
91const GENERIC_HOSTNAME_TLDS = new Set([
92 "com",
93 "net",
94 "org",
95 "io",
96 "dev",
97 "app",
98 "ai",
99 "co",
100 "edu",
101 "gov",
102 "mil",
103 "info",
104 "biz",
105 "xyz",
106 "me",
107 "tv",
108 "cc",
109 "gg",
110 "chat",
111 "cloud",
112 "site",
113 "online",
114 "tech",
115 "store",
116 "link",
117]);
118
119const COUNTRY_HOSTNAME_TLDS = new Set([
120 "uk",
121 "de",
122 "fr",
123 "nl",
124 "se",
125 "no",
126 "fi",
127 "dk",
128 "pl",
129 "ch",
130 "at",
131 "be",
132 "es",
133 "it",
134 "pt",
135 "eu",
136 "us",
137 "ca",
138 "au",
139 "nz",
140 "jp",
141 "kr",
142 "cn",
143 "br",
144 "ru",
145 "mx",
146 "ie",
147 "cz",
148 "tr",
149 "sg",
150 "hk",
151]);
152
153function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
154 if (segment.startsWith(".")) return false;
155 const lowered = segment.toLowerCase();
156 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
157 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
158 const labels = lowered.split(".");
159 const lastLabel = labels.at(-1);
160 if (labels.length < 2 || lastLabel === undefined) return false;
161 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
162 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
163}
164
165export function inlineCodeFilePathCandidate(codeText: string): string | null {
166 const trimmed = codeText.trim();
167 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
168
169 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
170 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
171 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
172
173 const hasExplicitPathShape =
174 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
175 candidate.startsWith("/") ||
176 isWindowsAbsolutePath(candidate);
177 if (!hasExplicitPathShape) {
178 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
179 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
180 if (looksLikeHostname(firstSegment, hasPosition)) return null;
181 const basename =
182 withoutPosition
183 .replace(/[/\\]+$/, "")
184 .split(/[\\/]/)
185 .at(-1) ?? "";
186 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
187 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
188 }
189 return candidate;
190}
191
192export function safeDecodeURIComponent(value: string): string {
193 try {
194 return decodeURIComponent(value);
195 } catch {
196 return value;
197 }
198}
199
200export function normalizeMarkdownLinkDestination(value: string): string {
201 const trimmed = value.trim();
202 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
203}
204
205export function splitMarkdownLinkSearchAndHash(value: string): {
206 readonly path: string;
207 readonly hash: string;
208} {
209 const hashIndex = value.indexOf("#");
210 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
211 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
212 const queryIndex = pathWithSearch.indexOf("?");
213 return {
214 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
215 hash,
216 };
217}
218
219export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
220 const destination = parseMarkdownFileLink(href);
221 if (!destination) return false;
222 const normalize = (path: string) =>
223 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
224 const labelPosition = splitFilePathPosition(label.trim());
225 if (
226 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
227 (labelPosition.column !== undefined && labelPosition.column !== destination.column)
228 ) {
229 return false;
230 }
231 let labelPath = normalize(labelPosition.path);
232 let destinationPath = normalize(destination.path);
233 if (labelPath.length === 0) return true;
234 if (isWindowsAbsolutePath(destination.path)) {
235 labelPath = labelPath.toLowerCase();
236 destinationPath = destinationPath.toLowerCase();
237 }
238 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
239}
240
241export function isRelativeFilePath(path: string): boolean {
242 return (
243 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
244 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
245 );
246}
247
248function looksLikePosixFilesystemPath(path: string): boolean {
249 if (!path.startsWith("/")) return false;
250 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
251 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
252 const basename = path.slice(path.lastIndexOf("/") + 1);
253 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
254}
255
256function looksLikeFilePath(path: string, authoredPath: string): boolean {
257 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
258 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
259 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
260 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
261}
262
263function hasExternalScheme(path: string): boolean {
264 if (isWindowsAbsolutePath(path)) return false;
265 const match = path.match(EXTERNAL_SCHEME_PATTERN);
266 if (!match) return false;
267 const rest = match[2] ?? "";
268 if (rest.startsWith("//")) return true;
269 return !POSITION_ONLY_PATTERN.test(rest);
270}
271
272export function parseMarkdownFileLink(href: string): FilePathPosition | null {
273 const normalized = normalizeMarkdownLinkDestination(href);
274 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
275 return null;
276 }
277
278 const source =
279 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
280 splitMarkdownLinkSearchAndHash(normalized);
281 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
282 const hash = safeDecodeURIComponent(source.hash.trim());
283 if (path.length === 0 || hasExternalScheme(path)) return null;
284
285 const position = splitFilePathPosition(path, hash);
286 return looksLikeFilePath(position.path, path) ? position : null;
287}
288
289const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
290
291const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
292
293export function extractInlineCodeSpans(text: string): string[] {
294 const spans: string[] = [];
295 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
296 for (let index = 0; index < segments.length; index += 2) {
297 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
298 const span = match[1]?.trim();
299 if (span) spans.push(span);
300 }
301 }
302 return spans;
303}
304
305function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
306 let runStart = -1;
307 let runEnd = -1;
308 return (start: number) => {
309 if (start >= runStart && start <= runEnd) return runEnd;
310 delimiter.lastIndex = start;
311 runStart = start;
312 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
313 return runEnd;
314 };
315}
316
317function markdownLinkTailScanner(markdown: string) {
318 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
319 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
320 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
321 return (start: number) => {
322 const end = whitespaceEnd(start);
323 if (markdown[end] === ")") return end + 1;
324 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
325 const quoteEnd = titleEnd(end + 1);
326 if (quoteEnd === markdown.length) return null;
327 const close = titleWhitespaceEnd(quoteEnd + 1);
328 return markdown[close] === ")" ? close + 1 : null;
329 };
330}
331
332function markdownLinkDestinationScanner(markdown: string) {
333 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
334 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
335 const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
336 // Separate caches keep each branch's searches moving forward even when an
337 // angle destination fails and falls back to an ordinary destination.
338 const angleTail = markdownLinkTailScanner(markdown);
339 const bareTail = markdownLinkTailScanner(markdown);
340 return (start: number) => {
341 if (markdown[start] !== "(") return null;
342 const hrefStart = whitespaceEnd(start + 1);
343 if (markdown[hrefStart] === "<") {
344 const hrefEnd = angleEnd(hrefStart + 1);
345 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
346 const end = angleTail(hrefEnd + 1);
347 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
348 }
349 }
350 const hrefEnd = bareEnd(hrefStart);
351 if (hrefEnd === hrefStart) return null;
352 const end = bareTail(hrefEnd);
353 return end === null ? null : { hrefStart, hrefEnd, end };
354 };
355}
356
357export function extractMarkdownLinkHrefs(markdown: string): string[] {
358 const hrefs: string[] = [];
359 const scanDestination = markdownLinkDestinationScanner(markdown);
360 let cursor = 0;
361 while (cursor < markdown.length) {
362 const labelStart = markdown.indexOf("[", cursor);
363 if (labelStart === -1) break;
364 const labelEnd = markdown.indexOf("]", labelStart + 1);
365 if (labelEnd === -1) break;
366
367 // Nested opening brackets share this closing bracket. On failure, skip the
368 // whole label instead of rescanning its suffix from each opening bracket.
369 cursor = labelEnd + 1;
370 const destination = scanDestination(cursor);
371 if (!destination) continue;
372 cursor = destination.end;
373 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
374 if (href) hrefs.push(href);
375 }
376 return hrefs;
377}
378
379export function resolveMarkdownFileLinkTarget(
380 href: string | undefined,
381 cwd?: string,
382 baseDir: string | undefined = cwd,
383): string | null {
384 if (!href) return null;
385 const target = parseMarkdownFileLink(href);
386 if (!target) return null;
387
388 const pathWithPosition = formatFilePathPosition(target);
389 if (!isRelativeFilePath(pathWithPosition)) return pathWithPosition;
390 if (!baseDir) return null;
391 return resolvePathLinkTarget(pathWithPosition, baseDir);
392}
393
394export function isWindowsDrivePathHref(href: string): boolean {
395 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
396}