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

markdownLinks.ts

350 lines10.9 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+)+$/;
18const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
19// Standard OS and dev-container roots; deliberately excludes app-route-ish
20// prefixes like /app/ or /chat/ so SPA routes never read as files.
21const POSIX_FILE_ROOT_PREFIXES = [
22 "/Users/",
23 "/home/",
24 "/tmp/",
25 "/var/",
26 "/etc/",
27 "/opt/",
28 "/mnt/",
29 "/Volumes/",
30 "/private/",
31 "/root/",
32 "/usr/",
33 "/bin/",
34 "/sbin/",
35 "/lib/",
36 "/lib64/",
37 "/srv/",
38 "/dev/",
39 "/proc/",
40 "/sys/",
41 "/run/",
42 "/boot/",
43 "/media/",
44 "/workspace/",
45 "/workspaces/",
46] as const;
47// `Name:digits` also matches `error:1`, `port:3000`, and `TODO:12`.
48const EXTENSIONLESS_FILE_NAMES = new Set([
49 "Makefile",
50 "makefile",
51 "GNUmakefile",
52 "Dockerfile",
53 "Containerfile",
54 "Justfile",
55 "justfile",
56 "Rakefile",
57 "Gemfile",
58 "Procfile",
59 "Brewfile",
60 "Caddyfile",
61 "Vagrantfile",
62 "Jenkinsfile",
63 "Podfile",
64 "Fastfile",
65 "BUILD",
66 "WORKSPACE",
67 "LICENSE",
68 "LICENCE",
69 "COPYING",
70 "NOTICE",
71 "AUTHORS",
72 "CONTRIBUTORS",
73 "CHANGELOG",
74 "README",
75 "CODEOWNERS",
76]);
77const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
78// These allowlists avoid classifying dotted directories such as `conf.d/`
79// or filenames such as `Makefile.in:12` as hosts.
80const GENERIC_HOSTNAME_TLDS = new Set([
81 "com",
82 "net",
83 "org",
84 "io",
85 "dev",
86 "app",
87 "ai",
88 "co",
89 "edu",
90 "gov",
91 "mil",
92 "info",
93 "biz",
94 "xyz",
95 "me",
96 "tv",
97 "cc",
98 "gg",
99 "chat",
100 "cloud",
101 "site",
102 "online",
103 "tech",
104 "store",
105 "link",
106]);
107// Country codes also name file extensions. A :line suffix makes `.pl`
108// and `.pt` files more likely than hostnames.
109const COUNTRY_HOSTNAME_TLDS = new Set([
110 "uk",
111 "de",
112 "fr",
113 "nl",
114 "se",
115 "no",
116 "fi",
117 "dk",
118 "pl",
119 "ch",
120 "at",
121 "be",
122 "es",
123 "it",
124 "pt",
125 "eu",
126 "us",
127 "ca",
128 "au",
129 "nz",
130 "jp",
131 "kr",
132 "cn",
133 "br",
134 "ru",
135 "mx",
136 "ie",
137 "cz",
138 "tr",
139 "sg",
140 "hk",
141]);
142​
143function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
144 if (segment.startsWith(".")) return false;
145 const lowered = segment.toLowerCase();
146 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
147 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
148 const labels = lowered.split(".");
149 const lastLabel = labels.at(-1);
150 if (labels.length < 2 || lastLabel === undefined) return false;
151 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
152 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
154​
155/** Recognizes conventional extensionless filenames with an explicit line position. */
156export function isConventionalFilePosition(path: string): boolean {
157 return (
158 BARE_EXTENSIONLESS_POSITION_PATTERN.test(path) &&
159 EXTENSIONLESS_FILE_NAMES.has(path.replace(POSITION_SUFFIX_PATTERN, ""))
160 );
162​
163/**
164 * Picks path-shaped inline code for the client's markdown file-link resolver.
165 * It does not resolve paths or turn plain prose and fenced code into links.
166 */
167export function inlineCodeFilePathCandidate(codeText: string): string | null {
168 const trimmed = codeText.trim();
169 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
170​
171 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
172 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
173 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
174​
175 const hasExplicitPathShape =
176 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
177 candidate.startsWith("/") ||
178 isWindowsAbsolutePath(candidate);
179 if (!hasExplicitPathShape) {
180 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
181 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
182 if (looksLikeHostname(firstSegment, hasPosition)) return null;
183 const basename =
184 withoutPosition
185 .replace(/[/\\]+$/, "")
186 .split(/[\\/]/)
187 .at(-1) ?? "";
188 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
189 }
190 return candidate;
192​
193export function safeDecodeURIComponent(value: string): string {
194 try {
195 return decodeURIComponent(value);
196 } catch {
197 return value;
198 }
200​
201export function normalizeMarkdownLinkDestination(value: string): string {
202 const trimmed = value.trim();
203 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
205​
206/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
207export function stripSlashPrefixedWindowsDrive(path: string): string {
208 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
210​
211export function splitMarkdownLinkSearchAndHash(value: string): {
212 readonly path: string;
213 readonly hash: string;
214} {
215 const hashIndex = value.indexOf("#");
216 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
217 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
218 const queryIndex = pathWithSearch.indexOf("?");
219 return {
220 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
221 hash,
222 };
224​
225/**
226 * Turns a `file:` URL into a host path, still percent-encoded so callers that
227 * decode every destination in one place do not decode file URLs twice. A
228 * non-localhost authority becomes a UNC share.
229 */
230export function parseFileUrlHref(
231 href: string,
232): { readonly path: string; readonly hash: string } | null {
233 try {
234 const parsed = new URL(href);
235 if (parsed.protocol.toLowerCase() !== "file:") return null;
236​
237 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
238 const path = uncHostname
239 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
240 : parsed.pathname;
241 if (path.length === 0) return null;
242 return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };
243 } catch {
244 return null;
245 }
247​
248export interface FilePathPosition {
249 readonly path: string;
250 readonly line?: number;
251 readonly column?: number;
253​
254export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {
255 const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);
256 const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);
257 if (!match?.[1]) return { path };
258​
259 const line = Number.parseInt(match[1], 10);
260 const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
261 return {
262 path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,
263 ...(line > 0 ? { line } : {}),
264 ...(column !== undefined && column > 0 ? { column } : {}),
265 };
267​
268export function formatFilePathPosition(position: FilePathPosition): string {
269 if (!position.line) return position.path;
270 return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;
272​
273export function isRelativeFilePath(path: string): boolean {
274 return (
275 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
276 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
277 );
279​
280function looksLikePosixFilesystemPath(path: string): boolean {
281 if (!path.startsWith("/")) return false;
282 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
283 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
284 const basename = path.slice(path.lastIndexOf("/") + 1);
285 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
287​
288/**
289 * Decides whether a decoded link destination is a file path rather than a route
290 * or prose. Only a `:line` suffix the author wrote counts as evidence; a `#L`
291 * anchor never turns `/chat/settings` into a file.
292 */
293function looksLikeFilePath(path: string, authoredPath: string): boolean {
294 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
295 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
296 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
297 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
299​
300function hasExternalScheme(path: string): boolean {
301 if (isWindowsAbsolutePath(path)) return false;
302 const match = path.match(EXTERNAL_SCHEME_PATTERN);
303 if (!match) return false;
304 const rest = match[2] ?? "";
305 if (rest.startsWith("//")) return true;
306 return !POSITION_ONLY_PATTERN.test(rest);
308​
309export function parseMarkdownFileLink(href: string): FilePathPosition | null {
310 const normalized = normalizeMarkdownLinkDestination(href);
311 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
312 return null;
313 }
314​
315 const source =
316 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
317 splitMarkdownLinkSearchAndHash(normalized);
318 // A percent-encoded drive colon (`/c%3A/`) only becomes strippable once decoded.
319 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
320 const hash = safeDecodeURIComponent(source.hash.trim());
321 if (path.length === 0 || hasExternalScheme(path)) return null;
322​
323 const position = splitFilePathPosition(path, hash);
324 return looksLikeFilePath(position.path, path) ? position : null;
326​
327export function fileBasename(path: string): string {
328 // A trailing separator is a valid way to write a directory. Trim it before
329 // taking the final segment so the label is never empty.
330 const trimmed = path.replace(/[/\\]+$/, "");
331 if (trimmed.length === 0) return path;
332 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
333 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
335​
336export function workspaceRelativeFilePath(
337 path: string,
338 workspaceRoot: string | null | undefined,
339): string | null {
340 if (!workspaceRoot) return null;
341 const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"));
342 const normalizedRoot = stripSlashPrefixedWindowsDrive(
343 workspaceRoot.replaceAll("\\", "/"),
344 ).replace(/\/+$/, "");
345 const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));
346 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
347 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
348 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
349 return normalizedPath.slice(normalizedRoot.length + 1);