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

markdownLinks.ts

401 lines10.9 KB

1import type { MARKDOWN_FILE_ICON_SOURCES } from "./markdownFileIcons.generated";
2​
3const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
4const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
5const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
6const RELATIVE_FILE_PATH_PATTERN =
7 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
8const RELATIVE_FILE_NAME_PATTERN =
9 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
10const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
11const POSIX_FILE_ROOT_PREFIXES = [
12 "/Users/",
13 "/home/",
14 "/tmp/",
15 "/var/",
16 "/etc/",
17 "/opt/",
18 "/mnt/",
19 "/Volumes/",
20 "/private/",
21 "/root/",
22] as const;
23​
24export type MarkdownLinkPresentation =
25 | {
26 readonly kind: "external";
27 readonly href: string;
28 readonly host: string;
29 }
30 | {
31 readonly kind: "file";
32 readonly href: string;
33 readonly icon: MarkdownFileIcon;
34 readonly label: string;
35 readonly path: string;
36 readonly line?: number;
37 readonly column?: number;
38 }
39 | {
40 readonly kind: "link";
41 readonly href: string | null;
42 };
43​
44export type MarkdownFileIcon = keyof typeof MARKDOWN_FILE_ICON_SOURCES;
45​
46const FILE_ICON_BY_NAME: Readonly<Record<string, MarkdownFileIcon>> = {
47 ".babelrc": "babel",
48 ".babelrc.json": "babel",
49 ".bash_profile": "bash",
50 ".bashrc": "bash",
51 ".browserslistrc": "browserslist",
52 ".dockerignore": "docker",
53 ".eslintignore": "eslint",
54 ".eslintrc": "eslint",
55 ".eslintrc.cjs": "eslint",
56 ".eslintrc.js": "eslint",
57 ".eslintrc.json": "eslint",
58 ".eslintrc.yaml": "eslint",
59 ".eslintrc.yml": "eslint",
60 ".gitattributes": "git",
61 ".gitignore": "git",
62 ".gitkeep": "git",
63 ".gitmodules": "git",
64 ".oxlintrc.json": "oxc",
65 ".postcssrc": "postcss",
66 ".postcssrc.json": "postcss",
67 ".postcssrc.yaml": "postcss",
68 ".postcssrc.yml": "postcss",
69 ".prettierignore": "prettier",
70 ".prettierrc": "prettier",
71 ".prettierrc.json": "prettier",
72 ".prettierrc.cjs": "prettier",
73 ".prettierrc.js": "prettier",
74 ".prettierrc.mjs": "prettier",
75 ".prettierrc.toml": "prettier",
76 ".prettierrc.yaml": "prettier",
77 ".prettierrc.yml": "prettier",
78 ".stylelintignore": "stylelint",
79 ".stylelintrc": "stylelint",
80 ".stylelintrc.cjs": "stylelint",
81 ".stylelintrc.js": "stylelint",
82 ".stylelintrc.json": "stylelint",
83 ".stylelintrc.mjs": "stylelint",
84 ".stylelintrc.yaml": "stylelint",
85 ".stylelintrc.yml": "stylelint",
86 ".terraform.lock.hcl": "terraform",
87 ".zprofile": "bash",
88 ".zshenv": "bash",
89 ".zshrc": "bash",
90 "agents.md": "agents",
91 "babel.config.js": "babel",
92 "babel.config.cjs": "babel",
93 "babel.config.json": "babel",
94 "babel.config.mjs": "babel",
95 "biome.json": "biome",
96 "biome.jsonc": "biome",
97 "bun.lock": "bun",
98 "bun.lockb": "bun",
99 "bunfig.toml": "bun",
100 "claude.md": "claude",
101 "compose.yaml": "docker",
102 "compose.yml": "docker",
103 "docker-compose.yaml": "docker",
104 "docker-compose.yml": "docker",
105 "docker-compose.override.yml": "docker",
106 dockerfile: "docker",
107 "eslint.config.js": "eslint",
108 "eslint.config.cjs": "eslint",
109 "eslint.config.mjs": "eslint",
110 "eslint.config.mts": "eslint",
111 "eslint.config.ts": "eslint",
112 gemfile: "ruby",
113 "next.config.js": "nextjs",
114 "next.config.mjs": "nextjs",
115 "next.config.mts": "nextjs",
116 "next.config.ts": "nextjs",
117 "package.json": "package",
118 "pnpm-lock.yaml": "pnpm",
119 "pnpm-workspace.yaml": "pnpm",
120 "postcss.config.js": "postcss",
121 "postcss.config.cjs": "postcss",
122 "postcss.config.mjs": "postcss",
123 "postcss.config.ts": "postcss",
124 "prettier.config.js": "prettier",
125 "prettier.config.cjs": "prettier",
126 "prettier.config.mjs": "prettier",
127 rakefile: "ruby",
128 "readme.md": "readme",
129 "stylelint.config.js": "stylelint",
130 "stylelint.config.cjs": "stylelint",
131 "stylelint.config.mjs": "stylelint",
132 "svgo.config.js": "svgo",
133 "svgo.config.cjs": "svgo",
134 "svgo.config.mjs": "svgo",
135 "svgo.config.ts": "svgo",
136 "tailwind.config.js": "tailwind",
137 "tailwind.config.cjs": "tailwind",
138 "tailwind.config.mjs": "tailwind",
139 "tailwind.config.ts": "tailwind",
140 "tsconfig.json": "tsconfig",
141 "vite.config.js": "vite",
142 "vite.config.mjs": "vite",
143 "vite.config.mts": "vite",
144 "vite.config.ts": "vite",
145 "webpack.config.js": "webpack",
146 "webpack.config.babel.js": "webpack",
147 "webpack.config.cjs": "webpack",
148 "webpack.config.mjs": "webpack",
149 "webpack.config.ts": "webpack",
150};
151​
152const FILE_ICON_BY_EXTENSION: Readonly<Record<string, MarkdownFileIcon>> = {
153 "7z": "zip",
154 astro: "astro",
155 avif: "image",
156 "code-workspace": "vscode",
157 bash: "bash",
158 bmp: "image",
159 bz2: "zip",
160 c: "c",
161 cc: "cpp",
162 cpp: "cpp",
163 cxx: "cpp",
164 css: "css",
165 csv: "table",
166 cts: "typescript",
167 db: "database",
168 env: "text",
169 "env.development": "text",
170 "env.local": "text",
171 "env.production": "text",
172 eot: "font",
173 erb: "ruby",
174 fish: "bash",
175 gif: "image",
176 go: "go",
177 gql: "graphql",
178 graphql: "graphql",
179 gz: "zip",
180 h: "c",
181 hh: "cpp",
182 hpp: "cpp",
183 hxx: "cpp",
184 htm: "html",
185 html: "html",
186 ico: "image",
187 icns: "image",
188 ini: "text",
189 inl: "cpp",
190 jar: "zip",
191 jpeg: "image",
192 jpg: "image",
193 js: "javascript",
194 jsx: "react",
195 json: "json",
196 jsonc: "json",
197 less: "css",
198 md: "markdown",
199 mdx: "markdown",
200 "mdx.tsx": "markdown",
201 mjs: "javascript",
202 mts: "typescript",
203 png: "image",
204 postcss: "css",
205 py: "python",
206 pyi: "python",
207 pyw: "python",
208 pyx: "python",
209 rake: "ruby",
210 rar: "zip",
211 rb: "ruby",
212 rs: "rust",
213 sass: "sass",
214 scss: "sass",
215 sh: "bash",
216 sql: "database",
217 sqlite: "database",
218 sqlite3: "database",
219 svelte: "svelte",
220 svg: "svg",
221 swift: "swift",
222 tar: "zip",
223 tf: "terraform",
224 tfstate: "terraform",
225 tfvars: "terraform",
226 tgz: "zip",
227 ts: "typescript",
228 tsv: "table",
229 tsx: "react",
230 txt: "text",
231 woff: "font",
232 woff2: "font",
233 vue: "vue",
234 wasm: "wasm",
235 webp: "image",
236 yml: "yml",
237 yaml: "yml",
238 zig: "zig",
239 zip: "zip",
240 zsh: "bash",
241};
242​
243function safeDecode(value: string): string {
244 try {
245 return decodeURIComponent(value);
246 } catch {
247 return value;
248 }
250​
251function normalizeDestination(value: string): string {
252 const trimmed = value.trim();
253 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
255​
256function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
257 try {
258 const parsed = new URL(href);
259 if (parsed.protocol.toLowerCase() !== "file:") {
260 return null;
261 }
262 const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
263 ? parsed.pathname.slice(1)
264 : parsed.pathname;
265 return { path, hash: parsed.hash };
266 } catch {
267 return null;
268 }
270​
271function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
272 const hashIndex = value.indexOf("#");
273 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
274 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
275 const queryIndex = pathWithSearch.indexOf("?");
276 return {
277 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
278 hash,
279 };
281​
282function splitFilePosition(
283 path: string,
284 hash: string,
285): { readonly path: string; readonly line?: number; readonly column?: number } {
286 const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
287 const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
288 const match = suffixMatch ?? hashMatch;
289 if (!match?.[1]) {
290 return { path };
291 }
292​
293 const line = Number.parseInt(match[1], 10);
294 const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
295 const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
296 return {
297 path: pathWithoutPosition,
298 ...(line > 0 ? { line } : {}),
299 ...(column !== undefined && column > 0 ? { column } : {}),
300 };
302​
303function looksLikePosixFilesystemPath(path: string): boolean {
304 if (!path.startsWith("/")) {
305 return false;
306 }
307 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) {
308 return true;
309 }
310 if (POSITION_SUFFIX_PATTERN.test(path)) {
311 return true;
312 }
313 const basename = path.slice(path.lastIndexOf("/") + 1);
314 return /\.[A-Za-z0-9_-]+$/.test(basename);
316​
317function looksLikeFilePath(value: string): boolean {
318 if (WINDOWS_DRIVE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value)) {
319 return true;
320 }
321 if (RELATIVE_PATH_PREFIX_PATTERN.test(value)) {
322 return true;
323 }
324 if (value.startsWith("/")) {
325 return looksLikePosixFilesystemPath(value);
326 }
327 if (FILE_ICON_BY_NAME[value.replace(POSITION_SUFFIX_PATTERN, "").toLowerCase()]) {
328 return true;
329 }
330 return RELATIVE_FILE_PATH_PATTERN.test(value) || RELATIVE_FILE_NAME_PATTERN.test(value);
332​
333function fileLabel(value: string): string {
334 const normalized = value.replaceAll("\\", "/");
335 const basename = normalized.slice(normalized.lastIndexOf("/") + 1);
336 return basename || normalized;
338​
339export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
340 const basename = fileLabel(value).replace(POSITION_SUFFIX_PATTERN, "").toLowerCase();
341 const exactIcon = FILE_ICON_BY_NAME[basename];
342 if (exactIcon) return exactIcon;
343 if (basename.startsWith("tsconfig.") && basename.endsWith(".json")) {
344 return "tsconfig";
345 }
346 const segments = basename.split(".");
347 for (let index = 1; index < segments.length; index += 1) {
348 const icon = FILE_ICON_BY_EXTENSION[segments.slice(index).join(".")];
349 if (icon) return icon;
350 }
351 return "default";
353​
354export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresentation {
355 const normalized = normalizeDestination(href);
356 try {
357 const parsed = new URL(normalized);
358 if (parsed.protocol === "http:" || parsed.protocol === "https:") {
359 return {
360 kind: "external",
361 href: parsed.toString(),
362 host: parsed.hostname,
363 };
364 }
365 } catch {
366 // Relative paths and non-URL link destinations are handled below.
367 }
368​
369 const source = normalized.toLowerCase().startsWith("file:")
370 ? fileUrlTarget(normalized)
371 : stripSearchAndHash(normalized);
372 const decodedSource = source
373 ? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
374 : null;
375 const fileTarget = decodedSource
376 ? splitFilePosition(decodedSource.path, decodedSource.hash)
377 : null;
378 const targetWithPosition = fileTarget
379 ? `${fileTarget.path}${
380 fileTarget.line
381 ? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
382 : ""
383 }`
384 : null;
385 if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
386 return {
387 kind: "file",
388 href: normalized,
389 icon: resolveMarkdownFileIcon(fileTarget.path),
390 label: fileLabel(targetWithPosition),
391 path: fileTarget.path,
392 ...(fileTarget.line ? { line: fileTarget.line } : {}),
393 ...(fileTarget.column ? { column: fileTarget.column } : {}),
394 };
395 }
396​
397 return {
398 kind: "link",
399 href: /^(?:mailto|tel):/i.test(normalized) ? normalized : null,
400 };