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

codexFileCitations.ts

63 lines2.2 KB

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;
17​
18function citationLabel(path: string): string {
19 const normalized = path.replaceAll("\\", "/").replace(/\/+$/, "");
20 return normalized.slice(normalized.lastIndexOf("/") + 1) || normalized || "File";
22​
23function markdownDestinationPath(path: string): string {
24 const destination = path.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3F");
25 // Only disambiguate rejected relative paths; recognized links keep workspace lookup behavior.
26 return parseMarkdownFileLink(destination) || /^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path)
27 ? destination
28 : `./${destination}`;
30​
31export function resolveCodexFileCitationLink(
32 attributes: CodexFileCitationAttributes | null | undefined,
33): CodexFileCitationLink | null {
34 const path = attributes?.path?.trim();
35 if (!path) return null;
36​
37 const lineRangeStart = positiveInteger(attributes?.line_range_start);
38 const destinationPath = markdownDestinationPath(path);
39 return {
40 path,
41 href: lineRangeStart === undefined ? destinationPath : `${destinationPath}#L${lineRangeStart}`,
42 label: citationLabel(path),
43 ...(lineRangeStart === undefined ? {} : { lineRangeStart }),
44 };
46​
47function markdownLabel(value: string): string {
48 return value.replace(/[\\[\]*_`<&]/g, "\\$&");
50​
51function markdownDestination(value: string): string {
52 return value
53 .replaceAll("\\", "%5C")
54 .replaceAll("&", "%26")
55 .replaceAll("<", "%3C")
56 .replaceAll(">", "%3E")
57 .replaceAll("\r", "%0D")
58 .replaceAll("\n", "%0A");
60​
61export function codexFileCitationMarkdown(citation: CodexFileCitationLink): string {
62 return `[${markdownLabel(citation.label)}](<${markdownDestination(citation.href)}>)`;