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 = /^[^/]*:/;
26
27function markdownDestinationPath(path: string): string {
28 const destination = path
29 .replaceAll("%", "%25")
30 .replaceAll("#", "%23")
31 .replaceAll("?", "%3F")
32 .replace(/^\s+|\s+$/g, (whitespace) => encodeURIComponent(whitespace));
33 if (/^\/\/[^/\\]+[\\/][^/\\]/.test(path)) {
34 return `\\\\${destination.slice(2).replaceAll("/", "\\")}`;
35 }
36 if (ABSOLUTE_OR_URI_PATH_PATTERN.test(path)) return destination;
37 // Relative paths with a colon before the first slash look like URI schemes to HTML sanitizers.
38 return COLON_BEFORE_SLASH_PATTERN.test(path) || !parseMarkdownFileLink(destination)
39 ? `./${destination}`
40 : destination;
41}
42
43export function resolveCodexFileCitationLink(
44 attributes: CodexFileCitationAttributes | null | undefined,
45): CodexFileCitationLink | null {
46 const path = attributes?.path;
47 if (!path?.trim()) return null;
48
49 const lineRangeStart = positiveInteger(attributes?.line_range_start);
50 const destinationPath = markdownDestinationPath(path);
51 return {
52 path,
53 href: lineRangeStart === undefined ? destinationPath : `${destinationPath}#L${lineRangeStart}`,
54 label: citationLabel(path),
55 ...(lineRangeStart === undefined ? {} : { lineRangeStart }),
56 };
57}
58
59function markdownLabel(value: string): string {
60 return value.replace(/[\\[\]*_`~<&|]/g, "\\$&");
61}
62
63function markdownDestination(value: string): string {
64 return value
65 .replaceAll("\\", "%5C")
66 .replaceAll("&", "%26")
67 .replaceAll("<", "%3C")
68 .replaceAll(">", "%3E")
69 .replaceAll("|", "%7C")
70 .replaceAll("\r", "%0D")
71 .replaceAll("\n", "%0A");
72}
73
74export function codexFileCitationMarkdown(citation: CodexFileCitationLink): string {
75 return `[${markdownLabel(citation.label)}](<${markdownDestination(citation.href)}>)`;
76}