Open History to see the last commit
1import { parseMarkdownFileLink } from "./markdownLinks.ts";
2
3export interface CodexFileCitationLink {
4 readonly path: string;
5 readonly href: string;
6 readonly label: string;
7 readonly lineRangeStart?: number;
8}
9
10export type CodexFileCitationAttributes = Readonly<Record<string, string | null | undefined>>;
11
12function positiveInteger(value: string | null | undefined): number | undefined {
13 if (value === null || value === undefined || value.trim().length === 0) return undefined;
14 const parsed = Number(value);
15 return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
16}
17
18function citationLabel(path: string): string {
19 const normalized = path.replaceAll("\\", "/").replace(/\/+$/, "");
20 return normalized.slice(normalized.lastIndexOf("/") + 1) || normalized || "File";
21}
22
23const ABSOLUTE_OR_URI_PATH_PATTERN =
24 /^(?:[a-z]:[\\/]|[\\/]|[a-z][a-z\d+.-]*:\/\/|(?:file|sandbox):\/)/i;
25const COLON_BEFORE_SLASH_PATTERN = /^[^/]*:/;
26const FILE_URL_PATTERN = /^file:\//i;
27
28function decodeFileUrl(path: string): string | null {
29 if (!FILE_URL_PATTERN.test(path)) return null;
30 try {
31 return decodeURIComponent(path);
32 } catch {
33 return null;
34 }
35}
36
37function markdownDestinationPath(path: string, isEncoded: boolean): string {
38 // A file URL is already percent-encoded; escaping its `%` again would name a different file.
39 const destination = (isEncoded ? path : path.replaceAll("%", "%25"))
40 .replaceAll("#", "%23")
41 .replaceAll("?", "%3F")
42 .replace(/^\s+|\s+$/g, (whitespace) => encodeURIComponent(whitespace));
43 if (/^\/\/[^/\\]+[\\/][^/\\]/.test(path)) {
44 return `\\\\${destination.slice(2).replaceAll("/", "\\")}`;
45 }
46 if (ABSOLUTE_OR_URI_PATH_PATTERN.test(path)) return destination;
47 // Relative paths with a colon before the first slash look like URI schemes to HTML sanitizers.
48 return COLON_BEFORE_SLASH_PATTERN.test(path) || !parseMarkdownFileLink(destination)
49 ? `./${destination}`
50 : destination;
51}
52
53export function resolveCodexFileCitationLink(
54 attributes: CodexFileCitationAttributes | null | undefined,
55): CodexFileCitationLink | null {
56 const path = attributes?.path;
57 if (!path?.trim()) return null;
58
59 const lineRangeStart = positiveInteger(attributes?.line_range_start);
60 const decodedFileUrl = decodeFileUrl(path);
61 const destinationPath = markdownDestinationPath(path, decodedFileUrl !== null);
62 return {
63 path,
64 href: lineRangeStart === undefined ? destinationPath : `${destinationPath}#L${lineRangeStart}`,
65 label: citationLabel(decodedFileUrl ?? path),
66 ...(lineRangeStart === undefined ? {} : { lineRangeStart }),
67 };
68}
69
70function markdownLabel(value: string): string {
71 return value
72 .replace(/[\\[\]*_`~<&|$^]/g, "\\$&")
73 .replaceAll("\r", " ")
74 .replaceAll("\n", " ");
75}
76
77function markdownDestination(value: string): string {
78 return value
79 .replaceAll("\\", "%5C")
80 .replaceAll("&", "%26")
81 .replaceAll("<", "%3C")
82 .replaceAll(">", "%3E")
83 .replaceAll("|", "%7C")
84 .replaceAll("\r", "%0D")
85 .replaceAll("\n", "%0A");
86}
87
88export function codexFileCitationMarkdown(citation: CodexFileCitationLink): string {
89 return `[${markdownLabel(citation.label)}](<${markdownDestination(citation.href)}>)`;
90}