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

codexMarkdownDirectives.ts

397 lines12.8 KB

1import { directiveFromMarkdown } from "mdast-util-directive";
2import { directive } from "micromark-extension-directive";
3import {
4 markdownLineEnding,
5 unicodePunctuation,
6 unicodeWhitespace,
7} from "micromark-util-character";
8import type { Construct, Extension, Tokenizer } from "micromark-util-types";
9import remarkParse from "remark-parse";
10import { unified, type Processor } from "unified";
11​
12import {
13 codexArtifactTemplatePresentationLabel,
14 resolveCodexArtifactTemplate,
15 type CodexArtifactTemplate,
16} from "./codexArtifactTemplates.ts";
17import { codexFileCitationMarkdown, resolveCodexFileCitationLink } from "./codexFileCitations.ts";
18​
19const COLON = 58;
20const DASH = 45;
21const UNDERSCORE = 95;
22const CODEX_FILE_CITATION_NAME = "codex-file-citation";
23const CODEX_FOLLOW_UP_NAME = "codex-followup";
24const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template";
25​
26interface MarkdownPosition {
27 readonly start: { readonly offset?: number };
28 readonly end: { readonly offset?: number };
30​
31interface MarkdownAstNode {
32 type?: string;
33 name?: string;
34 value?: string;
35 url?: string;
36 attributes?: Readonly<Record<string, string | null>>;
37 position?: MarkdownPosition;
38 data?: {
39 codexArtifactTemplate?: CodexArtifactTemplate;
40 codexFileCitationMarkdown?: string;
41 codexFollowUp?: true;
42 hName?: string;
43 hProperties?: Record<string, unknown>;
44 };
45 children?: MarkdownAstNode[];
47​
48interface MarkdownFile {
49 readonly value: unknown;
51​
52export type CodexArtifactTemplateMarkdownSegment =
53 | { readonly kind: "markdown"; readonly markdown: string; readonly sourceOffset: number }
54 | {
55 readonly kind: "artifact-template";
56 readonly sourceOffset: number;
57 readonly template: CodexArtifactTemplate;
58 };
59​
60function asConstruct(value: Construct | Construct[] | undefined, label: string): Construct {
61 const construct = Array.isArray(value) ? value[0] : value;
62 if (!construct) throw new Error(`Missing ${label} directive construct`);
63 return construct;
65​
66function directiveNameEnds(code: number | null): boolean {
67 return (
68 code === null ||
69 markdownLineEnding(code) ||
70 unicodeWhitespace(code) ||
71 (unicodePunctuation(code) && code !== DASH && code !== UNDERSCORE)
72 );
74​
75function directiveNameGate(markerCount: number, name: string): Construct {
76 const tokenize: Tokenizer = (effects, ok, nok) => {
77 let markerIndex = 0;
78 let nameIndex = 0;
79​
80 return marker;
81​
82 function marker(code: number | null) {
83 if (code !== COLON) return nok(code);
84 if (markerIndex === 0) effects.enter("data");
85 effects.consume(code);
86 markerIndex += 1;
87 return markerIndex === markerCount ? nameCharacter : marker;
88 }
89​
90 function nameCharacter(code: number | null) {
91 if (code !== name.charCodeAt(nameIndex)) return nok(code);
92 effects.consume(code);
93 nameIndex += 1;
94 return nameIndex === name.length ? afterName : nameCharacter;
95 }
96​
97 function afterName(code: number | null) {
98 effects.exit("data");
99 return directiveNameEnds(code) ? ok(code) : nok(code);
100 }
101 };
102​
103 return { partial: true, tokenize };
105​
106function restrictedDirective(construct: Construct, markerCount: number, name: string): Construct {
107 const gate = directiveNameGate(markerCount, name);
108 return {
109 ...construct,
110 tokenize(effects, ok, nok) {
111 return effects.check(gate, construct.tokenize.call(this, effects, ok, nok), nok);
112 },
113 };
115​
116function codexDirectiveSyntax(): Extension {
117 const genericSyntax = directive();
118 const textDirective = asConstruct(genericSyntax.text?.[COLON], CODEX_FILE_CITATION_NAME);
119 const flowDirectives = genericSyntax.flow?.[COLON];
120 const leafDirective = Array.isArray(flowDirectives)
121 ? flowDirectives.find((construct) => construct.concrete !== true)
122 : flowDirectives;
123 if (!leafDirective)
124 throw new Error(`Missing ${CODEX_ARTIFACT_TEMPLATE_NAME} directive construct`);
125​
126 return {
127 text: {
128 [COLON]: [
129 restrictedDirective(textDirective, 1, CODEX_FILE_CITATION_NAME),
130 restrictedDirective(textDirective, 1, CODEX_FOLLOW_UP_NAME),
131 ],
132 },
133 flow: {
134 [COLON]: restrictedDirective(leafDirective, 2, CODEX_ARTIFACT_TEMPLATE_NAME),
135 },
136 };
138​
139const CODEX_DIRECTIVE_SYNTAX = codexDirectiveSyntax();
140const CODEX_DIRECTIVE_FROM_MARKDOWN = directiveFromMarkdown();
141​
142function sourceForNode(node: MarkdownAstNode, source: string): string {
143 const start = node.position?.start.offset;
144 const end = node.position?.end.offset;
145 return start === undefined || end === undefined ? "" : source.slice(start, end);
147​
148function textContent(node: MarkdownAstNode): string {
149 return node.value ?? (node.children ?? []).map(textContent).join("");
151​
152function sourceForDirective(node: MarkdownAstNode, source: string, marker: ":" | "::"): string {
153 const prefix = `${marker}${node.name ?? ""}`;
154 const slicedSource = sourceForNode(node, source);
155 if (slicedSource.startsWith(prefix)) return slicedSource;
156​
157 const label = node.children?.length ? `[${textContent(node)}]` : "";
158 const attributes = Object.entries(node.attributes ?? {}).map(([name, value]) =>
159 value === null ? name : `${name}=${JSON.stringify(value)}`,
160 );
161 return `${prefix}${label}${attributes.length === 0 ? "" : `{${attributes.join(" ")}}`}`;
163​
164function restoreTextDirective(node: MarkdownAstNode, source: string): void {
165 node.type = "text";
166 node.value = sourceForDirective(node, source, ":");
167 delete node.name;
168 delete node.attributes;
169 delete node.url;
170 delete node.data;
171 delete node.children;
173​
174function restoreLeafDirective(node: MarkdownAstNode, source: string): void {
175 const value = sourceForDirective(node, source, "::");
176 node.type = "paragraph";
177 node.children = [
178 { type: "text", value, ...(node.position === undefined ? {} : { position: node.position }) },
179 ];
180 delete node.name;
181 delete node.attributes;
182 delete node.value;
183 delete node.url;
184 delete node.data;
186​
187function renderFileCitation(node: MarkdownAstNode, source: string, insideLink: boolean): void {
188 const citation = resolveCodexFileCitationLink(node.attributes);
189 if (!citation || insideLink) {
190 restoreTextDirective(node, source);
191 return;
192 }
193​
194 node.type = "link";
195 node.url = citation.href;
196 node.children = [{ type: "text", value: citation.label }];
197 node.data = { codexFileCitationMarkdown: codexFileCitationMarkdown(citation) };
198 delete node.name;
199 delete node.attributes;
200 delete node.value;
202​
203function renderFollowUp(node: MarkdownAstNode, source: string): void {
204 if (!node.attributes?.prompt?.trim() || !textContent(node).trim()) {
205 restoreTextDirective(node, source);
206 return;
207 }
208​
209 node.data = { codexFollowUp: true, hName: "span" };
210 delete node.name;
211 delete node.attributes;
213​
214function renderArtifactTemplate(node: MarkdownAstNode, source: string): void {
215 const template = resolveCodexArtifactTemplate(node.attributes);
216 if (!template) {
217 restoreLeafDirective(node, source);
218 return;
219 }
220​
221 node.type = "paragraph";
222 node.children = [];
223 node.data = {
224 codexArtifactTemplate: template,
225 hName: "div",
226 hProperties: {
227 dataCodexArtifactTemplate: "true",
228 dataArtifactKind: template.artifactKind,
229 dataDisplayName: template.displayName,
230 ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
231 dataSkillDirectory: template.skillDirectory,
232 dataSkillName: template.skillName,
233 },
234 };
235 delete node.name;
236 delete node.attributes;
237 delete node.value;
238 delete node.url;
240​
241function transformCodexDirectives(node: MarkdownAstNode, source: string, insideLink = false): void {
242 if (node.type === "textDirective" && node.name === CODEX_FILE_CITATION_NAME) {
243 renderFileCitation(node, source, insideLink);
244 return;
245 }
246 if (node.type === "textDirective" && node.name === CODEX_FOLLOW_UP_NAME) {
247 renderFollowUp(node, source);
248 }
249 if (node.type === "leafDirective" && node.name === CODEX_ARTIFACT_TEMPLATE_NAME) {
250 renderArtifactTemplate(node, source);
251 return;
252 }
253​
254 const childrenInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
255 for (const child of node.children ?? []) {
256 transformCodexDirectives(child, source, childrenInsideLink);
257 }
259​
260function attachCodexDirectives(this: Processor) {
261 const data = this.data();
262 const micromarkExtensions = data.micromarkExtensions ?? (data.micromarkExtensions = []);
263 const fromMarkdownExtensions = data.fromMarkdownExtensions ?? (data.fromMarkdownExtensions = []);
264 micromarkExtensions.push(CODEX_DIRECTIVE_SYNTAX);
265 fromMarkdownExtensions.push(CODEX_DIRECTIVE_FROM_MARKDOWN);
266​
267 return (tree: unknown, file: MarkdownFile) => {
268 transformCodexDirectives(tree as MarkdownAstNode, String(file.value));
269 };
271​
272export const remarkCodexDirectives = attachCodexDirectives;
273​
274const directiveParser = unified().use(remarkParse).use(remarkCodexDirectives).freeze();
275​
276function parseCodexMarkdown(markdown: string): MarkdownAstNode {
277 return directiveParser.runSync(directiveParser.parse(markdown), {
278 value: markdown,
279 }) as MarkdownAstNode;
281​
282interface DirectiveMatch {
283 readonly start: number;
284 readonly end: number;
285 readonly markdown?: string;
286 readonly template?: CodexArtifactTemplate;
287 readonly labelRange?: readonly [start: number, end: number];
289​
290function collectDirectiveMatches(node: MarkdownAstNode, matches: DirectiveMatch[]): void {
291 const start = node.position?.start.offset;
292 const end = node.position?.end.offset;
293 if (start !== undefined && end !== undefined) {
294 if (node.data?.codexFileCitationMarkdown !== undefined) {
295 matches.push({ start, end, markdown: node.data.codexFileCitationMarkdown });
296 return;
297 }
298 if (node.data?.codexArtifactTemplate !== undefined) {
299 matches.push({ start, end, template: node.data.codexArtifactTemplate });
300 return;
301 }
302 const labelStart = node.children?.[0]?.position?.start.offset;
303 const labelEnd = node.children?.at(-1)?.position?.end.offset;
304 if (node.data?.codexFollowUp && labelStart !== undefined && labelEnd !== undefined) {
305 matches.push({ start, end, labelRange: [labelStart, labelEnd] });
306 return;
307 }
308 }
309 for (const child of node.children ?? []) collectDirectiveMatches(child, matches);
311​
312function renderDirectiveMatches(
313 markdown: string,
314 replacementFor: (match: DirectiveMatch) => string | undefined,
315): string {
316 const matches: DirectiveMatch[] = [];
317 collectDirectiveMatches(parseCodexMarkdown(markdown), matches);
318 let rendered = markdown;
319 for (const match of matches.sort((left, right) => right.start - left.start)) {
320 const replacement = match.labelRange
321 ? markdown.slice(...match.labelRange)
322 : replacementFor(match);
323 if (replacement !== undefined) {
324 rendered = rendered.slice(0, match.start) + replacement + rendered.slice(match.end);
325 }
326 }
327 return rendered;
329​
330export function renderCodexInlineDirectivesAsMarkdown(markdown: string): string {
331 if (
332 !markdown.includes(`:${CODEX_FILE_CITATION_NAME}`) &&
333 !markdown.includes(`:${CODEX_FOLLOW_UP_NAME}`)
334 ) {
335 return markdown;
336 }
337​
338 return renderDirectiveMatches(markdown, (match) => match.markdown);
340​
341export function renderCodexDirectivesForCopy(markdown: string): string {
342 if (
343 !markdown.includes(`:${CODEX_FILE_CITATION_NAME}`) &&
344 !markdown.includes(`:${CODEX_FOLLOW_UP_NAME}`) &&
345 !markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)
346 ) {
347 return markdown;
348 }
349​
350 return renderDirectiveMatches(markdown, (match) => {
351 if (match.markdown !== undefined) return match.markdown;
352 if (match.template === undefined) return undefined;
353 return `${match.template.displayName} (${codexArtifactTemplatePresentationLabel(match.template.artifactKind)})`;
354 });
356​
357export function splitCodexArtifactTemplateMarkdown(
358 markdown: string,
359): ReadonlyArray<CodexArtifactTemplateMarkdownSegment> {
360 if (!markdown.includes(`::${CODEX_ARTIFACT_TEMPLATE_NAME}`)) {
361 return [{ kind: "markdown", markdown, sourceOffset: 0 }];
362 }
363​
364 const matches: DirectiveMatch[] = [];
365 collectDirectiveMatches(parseCodexMarkdown(markdown), matches);
366 const templates = matches
367 .filter(
368 (match): match is DirectiveMatch & { readonly template: CodexArtifactTemplate } =>
369 match.template !== undefined,
370 )
371 .sort((left, right) => left.start - right.start);
372 if (templates.length === 0) {
373 return [{ kind: "markdown", markdown, sourceOffset: 0 }];
374 }
375​
376 const segments: CodexArtifactTemplateMarkdownSegment[] = [];
377 let cursor = 0;
378 for (const match of templates) {
379 if (match.start > cursor) {
380 segments.push({
381 kind: "markdown",
382 markdown: markdown.slice(cursor, match.start),
383 sourceOffset: cursor,
384 });
385 }
386 segments.push({
387 kind: "artifact-template",
388 sourceOffset: match.start,
389 template: match.template,
390 });
391 cursor = match.end;
392 }
393 if (cursor < markdown.length) {
394 segments.push({ kind: "markdown", markdown: markdown.slice(cursor), sourceOffset: cursor });
395 }
396 return segments;