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