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

markdownLinks.ts

341 lines10.6 KB

1import { isWindowsAbsolutePath } from "@t3tools/shared/path";
2​
3const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
4const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
5const RELATIVE_FILE_PATH_PATTERN =
6 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
7const RELATIVE_FILE_NAME_PATTERN =
8 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
9const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
10const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
11const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+))?$/;
12const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+))?$/i;
13const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
14const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
15const PATH_SEPARATOR_PATTERN = /[\\/]/;
16const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
17const NUMERIC_DOTTED_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;
46// `Name:digits` also matches `error:1`, `port:3000`, and `TODO:12`.
47const EXTENSIONLESS_FILE_NAMES = new Set([
48 "Makefile",
49 "makefile",
50 "GNUmakefile",
51 "Dockerfile",
52 "Containerfile",
53 "Justfile",
54 "justfile",
55 "Rakefile",
56 "Gemfile",
57 "Procfile",
58 "Brewfile",
59 "Caddyfile",
60 "Vagrantfile",
61 "Jenkinsfile",
62 "Podfile",
63 "Fastfile",
64 "BUILD",
65 "WORKSPACE",
66 "LICENSE",
67 "LICENCE",
68 "COPYING",
69 "NOTICE",
70 "AUTHORS",
71 "CONTRIBUTORS",
72 "CHANGELOG",
73 "README",
74 "CODEOWNERS",
75]);
76const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
77// These allowlists avoid classifying dotted directories such as `conf.d/`
78// or filenames such as `Makefile.in:12` as hosts.
79const GENERIC_HOSTNAME_TLDS = new Set([
80 "com",
81 "net",
82 "org",
83 "io",
84 "dev",
85 "app",
86 "ai",
87 "co",
88 "edu",
89 "gov",
90 "mil",
91 "info",
92 "biz",
93 "xyz",
94 "me",
95 "tv",
96 "cc",
97 "gg",
98 "chat",
99 "cloud",
100 "site",
101 "online",
102 "tech",
103 "store",
104 "link",
105]);
106// Country codes also name file extensions. A :line suffix makes `.pl`
107// and `.pt` files more likely than hostnames.
108const COUNTRY_HOSTNAME_TLDS = new Set([
109 "uk",
110 "de",
111 "fr",
112 "nl",
113 "se",
114 "no",
115 "fi",
116 "dk",
117 "pl",
118 "ch",
119 "at",
120 "be",
121 "es",
122 "it",
123 "pt",
124 "eu",
125 "us",
126 "ca",
127 "au",
128 "nz",
129 "jp",
130 "kr",
131 "cn",
132 "br",
133 "ru",
134 "mx",
135 "ie",
136 "cz",
137 "tr",
138 "sg",
139 "hk",
140]);
141​
142function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
143 if (segment.startsWith(".")) return false;
144 const lowered = segment.toLowerCase();
145 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
146 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
147 const labels = lowered.split(".");
148 const lastLabel = labels.at(-1);
149 if (labels.length < 2 || lastLabel === undefined) return false;
150 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
151 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
153​
154/**
155 * Picks path-shaped inline code for the client's markdown file-link resolver.
156 * It does not resolve paths or turn plain prose and fenced code into links.
157 */
158export function inlineCodeFilePathCandidate(codeText: string): string | null {
159 const trimmed = codeText.trim();
160 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
161​
162 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
163 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
164 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
165​
166 const hasExplicitPathShape =
167 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
168 candidate.startsWith("/") ||
169 isWindowsAbsolutePath(candidate);
170 if (!hasExplicitPathShape) {
171 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
172 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
173 if (looksLikeHostname(firstSegment, hasPosition)) return null;
174 const basename =
175 withoutPosition
176 .replace(/[/\\]+$/, "")
177 .split(/[\\/]/)
178 .at(-1) ?? "";
179 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
180 }
181 return candidate;
183​
184export function safeDecodeURIComponent(value: string): string {
185 try {
186 return decodeURIComponent(value);
187 } catch {
188 return value;
189 }
191​
192export function normalizeMarkdownLinkDestination(value: string): string {
193 const trimmed = value.trim();
194 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
196​
197/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
198export function stripSlashPrefixedWindowsDrive(path: string): string {
199 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
201​
202export function splitMarkdownLinkSearchAndHash(value: string): {
203 readonly path: string;
204 readonly hash: string;
205} {
206 const hashIndex = value.indexOf("#");
207 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
208 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
209 const queryIndex = pathWithSearch.indexOf("?");
210 return {
211 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
212 hash,
213 };
215​
216/**
217 * Turns a `file:` URL into a host path, still percent-encoded so callers that
218 * decode every destination in one place do not decode file URLs twice. A
219 * non-localhost authority becomes a UNC share.
220 */
221export function parseFileUrlHref(
222 href: string,
223): { readonly path: string; readonly hash: string } | null {
224 try {
225 const parsed = new URL(href);
226 if (parsed.protocol.toLowerCase() !== "file:") return null;
227​
228 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
229 const path = uncHostname
230 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
231 : parsed.pathname;
232 if (path.length === 0) return null;
233 return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };
234 } catch {
235 return null;
236 }
238​
239export interface FilePathPosition {
240 readonly path: string;
241 readonly line?: number;
242 readonly column?: number;
244​
245export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {
246 const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);
247 const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);
248 if (!match?.[1]) return { path };
249​
250 const line = Number.parseInt(match[1], 10);
251 const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
252 return {
253 path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,
254 ...(line > 0 ? { line } : {}),
255 ...(column !== undefined && column > 0 ? { column } : {}),
256 };
258​
259export function formatFilePathPosition(position: FilePathPosition): string {
260 if (!position.line) return position.path;
261 return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;
263​
264export function isRelativeFilePath(path: string): boolean {
265 return (
266 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
267 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
268 );
270​
271function looksLikePosixFilesystemPath(path: string): boolean {
272 if (!path.startsWith("/")) return false;
273 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
274 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
275 const basename = path.slice(path.lastIndexOf("/") + 1);
276 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
278​
279/**
280 * Decides whether a decoded link destination is a file path rather than a route
281 * or prose. Only a `:line` suffix the author wrote counts as evidence; a `#L`
282 * anchor never turns `/chat/settings` into a file.
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 // A percent-encoded drive colon (`/c%3A/`) only becomes strippable once decoded.
310 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
311 const hash = safeDecodeURIComponent(source.hash.trim());
312 if (path.length === 0 || hasExternalScheme(path)) return null;
313​
314 const position = splitFilePathPosition(path, hash);
315 return looksLikeFilePath(position.path, path) ? position : null;
317​
318export function fileBasename(path: string): string {
319 // A trailing separator is a valid way to write a directory. Trim it before
320 // taking the final segment so the label is never empty.
321 const trimmed = path.replace(/[/\\]+$/, "");
322 if (trimmed.length === 0) return path;
323 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
324 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
326​
327export function workspaceRelativeFilePath(
328 path: string,
329 workspaceRoot: string | null | undefined,
330): string | null {
331 if (!workspaceRoot) return null;
332 const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"));
333 const normalizedRoot = stripSlashPrefixedWindowsDrive(
334 workspaceRoot.replaceAll("\\", "/"),
335 ).replace(/\/+$/, "");
336 const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));
337 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
338 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
339 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
340 return normalizedPath.slice(normalizedRoot.length + 1);