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

markdownPipeline.ts

573 lines22.0 KB

1import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
2import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
3import { type PluggableList, type Processor, type Transformer, unified } from "unified";
4import remarkParse from "remark-parse";
5import remarkRehype from "remark-rehype";
6import { find, html } from "property-information";
7import rehypeRaw from "rehype-raw";
8import rehypeSanitize from "rehype-sanitize";
9import remarkBreaks from "remark-breaks";
10import remarkGfm from "remark-gfm";
11import remarkCjkFriendly from "remark-cjk-friendly";
12import remarkCjkFriendlyGfmStrikethrough from "remark-cjk-friendly-gfm-strikethrough";
13import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
14import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
15import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
16import {
17 remarkEnableLeadingWhitespace,
18 remarkKeepLeadingWhitespace,
19} from "./markdownLeadingWhitespace.ts";
20import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts";
21import { absoluteFilePathMatches } from "./markdownLinks.ts";
22import { remarkEndAutolinksAtScriptPunctuation } from "./markdownScriptPunctuationAutolinks.ts";
23import { isWindowsAbsolutePath } from "./path.ts";
24import {
25 CHAT_MARKDOWN_SANITIZE_SCHEMA,
26 chatMarkdownImageSource,
27 rehypeNormalizeLocalFileLinks,
28 rehypePreserveImageSourceMeta,
29 type ChatMarkdownImageProperties,
30} from "./markdownHast.ts";
31​
32export { chatMarkdownImageSource, type ChatMarkdownImageProperties };
33​
34export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
35​
36type MarkdownImageHastNode = {
37 type?: string;
38 value?: string;
39 tagName?: string;
40 properties?: Record<string, unknown>;
41 children?: MarkdownImageHastNode[];
42};
43​
44// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
45const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
46​
47/**
48 * Follows raw anchors the way the browser will: a bare `<a>` that never closes stays text, and
49 * text inside any other open anchor already belongs to a link.
50 */
51function scanRawHtmlAnchors(rawType: "raw" | "html") {
52 return (tree: MarkdownImageHastNode) => {
53 const anchors: Array<MarkdownImageHastNode | null> = [];
54 const anchorAt = new Map<MarkdownImageHastNode, MarkdownImageHastNode | null>();
55 let rawTextTag: string | undefined;
56 const visit = (node: MarkdownImageHastNode) => {
57 if (node.type === rawType && typeof node.value === "string") {
58 const tags = new RegExp(RAW_HTML_TAG_PATTERN);
59 let offset = 0;
60 while (rawTextTag !== "plaintext") {
61 // Raw text ends at its closing tag even inside comment-looking text.
62 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
63 matcher.lastIndex = offset;
64 const match = matcher.exec(node.value);
65 if (!match) break;
66 const [tag] = match;
67 offset = matcher.lastIndex;
68 if (rawTextTag) {
69 rawTextTag = undefined;
70 continue;
71 }
72 if (tag.startsWith("<!--")) continue;
73 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
74 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
75 if (
76 opening &&
77 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
78 ) {
79 rawTextTag = opening;
80 } else if (opening === "a") {
81 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
82 } else if (closing === "a") {
83 anchors.pop();
84 }
85 }
86 } else if (rawType === "html" && node.type === "text" && (rawTextTag || anchors.length > 0)) {
87 anchorAt.set(node, rawTextTag || anchors.includes(null) ? null : anchors.at(-1)!);
88 }
89 // Like the linker, stay out of Markdown link labels: the browser closes raw anchors there.
90 if (rawType === "html" && (node.type === "link" || node.type === "linkReference")) return;
91 node.children?.forEach(visit);
92 };
93​
94 visit(tree);
95 const bare = new Set(anchors.filter((anchor) => anchor !== null));
96 return {
97 bare,
98 insideAnchor: (node: MarkdownImageHastNode) =>
99 anchorAt.has(node) && !bare.has(anchorAt.get(node)!),
100 };
101 };
103​
104function rehypePreserveBareAnchorPlaceholders() {
105 return (tree: MarkdownImageHastNode) => {
106 for (const anchor of scanRawHtmlAnchors("raw")(tree).bare) anchor.type = "text";
107 };
109​
110// CJK emphasis and strikethrough close next to CJK punctuation, as the web renderer's `cjk` option does.
111export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
112 remarkGfm,
113 remarkCjkFriendly,
114 remarkCjkFriendlyGfmStrikethrough,
115 remarkEndAutolinksAtScriptPunctuation,
116 remarkKeepAutolinkSuffixes,
117 remarkKeepWindowsPaths,
118 remarkGithubAlerts,
119 remarkKeepOrderedListNumbers,
120 remarkNormalizeListItemIndentation,
121 remarkLinkAbsoluteFilePaths,
122 remarkCodexDirectives,
123 remarkBreakAroundImageLines,
124 remarkPreserveCodeMeta,
125 remarkNormalizeLinksAndTagInlineCode,
126];
127​
128// Leading whitespace is kept only where each line renders as a line.
129export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
130 remarkGfm,
131 remarkCjkFriendly,
132 remarkCjkFriendlyGfmStrikethrough,
133 remarkEndAutolinksAtScriptPunctuation,
134 remarkKeepAutolinkSuffixes,
135 remarkKeepLeadingWhitespace,
136 remarkKeepWindowsPaths,
137 remarkGithubAlerts,
138 remarkKeepOrderedListNumbers,
139 remarkNormalizeListItemIndentation,
140 remarkLinkAbsoluteFilePaths,
141 remarkCodexDirectives,
142 remarkBreakAroundImageLines,
143 remarkBreaks,
144 remarkPreserveCodeMeta,
145 remarkNormalizeLinksAndTagInlineCode,
146];
147​
148// Users type paths like ~/a and (~/b, which GFM's single-tilde strikethrough hides as <del>.
149// Appended after the base list, this reconfigures its remark-gfm entry; ~~double~~ still strikes.
150// Users also indent lines with spaces, which CommonMark drops from a paragraph.
151export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [
152 [remarkGfm, { singleTilde: false }],
153 [remarkCjkFriendlyGfmStrikethrough, { singleTilde: false }],
154 remarkEnableLeadingWhitespace,
155];
156​
157// Start tags an HTML parser closes an open `<p>` for.
158const CLOSES_PARAGRAPH = new Set(
159 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
160 " ",
161 ),
162);
163const HEADING = /^h[1-6]$/;
164​
165interface HtmlScope {
166 readonly anchor: boolean;
167 readonly paragraph: boolean;
168 readonly heading: boolean;
170​
171/**
172 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
173 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
174 * drops `data`, both repeated here, and moves blank text that renders the same.
175 */
176function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
177 if (node.type === "raw") return true;
178 let inner = scope;
179 if (node.type === "element" && node.tagName) {
180 const { tagName } = node;
181 const heading = HEADING.test(tagName);
182 if (
183 (tagName === "a" && scope.anchor) ||
184 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
185 (heading && scope.heading)
186 ) {
187 return true;
188 }
189 inner = {
190 anchor: scope.anchor || tagName === "a",
191 paragraph: scope.paragraph || tagName === "p",
192 heading: scope.heading || heading,
193 };
194 const properties = node.properties ?? {};
195 for (const key of Object.keys(properties)) {
196 const value = properties[key];
197 const info = find(html, key);
198 if (
199 value === false ||
200 value === null ||
201 value === undefined ||
202 Number.isNaN(value) ||
203 (!value && info.boolean)
204 ) {
205 delete properties[key];
206 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
207 properties[key] = "";
208 }
209 }
210 delete (node as { data?: unknown }).data;
211 }
212 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
214​
215const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
216​
217/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
218function rehypeRawWhenPresent(this: Processor) {
219 const transform = rehypeRaw.call(this) as unknown as (
220 tree: MarkdownImageHastNode,
221 file: unknown,
222 ) => unknown;
223 return (tree: MarkdownImageHastNode, file: unknown) =>
224 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
226​
227export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
228 rehypePreserveBareAnchorPlaceholders,
229 rehypeRawWhenPresent,
230 rehypePreserveImageSourceMeta,
231 rehypeNormalizeLocalFileLinks,
232 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
233];
234​
235const isImageNode = (node: PhrasingContent | undefined): boolean =>
236 node?.type === "image" ||
237 node?.type === "imageReference" ||
238 ((node?.type === "link" || node?.type === "linkReference") &&
239 node.children.length === 1 &&
240 isImageNode(node.children[0]));
241const endsLine = (node: PhrasingContent | undefined) =>
242 node === undefined ||
243 node.type === "break" ||
244 (node.type === "text" && /(?:\r\n|\r|\n)[ \t]*$/.test(node.value));
245const startsLine = (node: PhrasingContent | undefined) =>
246 node === undefined ||
247 node.type === "break" ||
248 (node.type === "text" && /^[ \t]*(?:\r\n|\r|\n)/.test(node.value));
249​
250// A caption line ending in a screenshot reads as a figure, so the trailing images get a line.
251function trailingImagesStart(children: readonly PhrasingContent[]): number | undefined {
252 let start: number | undefined;
253 for (let index = children.length - 1; index >= 0; index--) {
254 const child = children[index]!;
255 if (isImageNode(child)) start = index;
256 else if (child.type !== "break" && !(child.type === "text" && !child.value.trim()))
257 return start;
258 }
259 return undefined;
261​
262function breakLinesAroundImages(paragraph: Paragraph) {
263 const children = paragraph.children;
264 if (!children.some(isImageNode)) return;
265 const ownsLine = (index: number) =>
266 isImageNode(children[index]) &&
267 endsLine(children[index - 1]) &&
268 startsLine(children[index + 1]);
269 const trailingStart = trailingImagesStart(children);
270 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
271 // Kept indentation after a line ending already sits on a line of its own.
272 const beforeTrailing =
273 index + 1 === trailingStart &&
274 !(child.type === "text" && !child.value.trim() && endsLine(children[index - 1]));
275 if (child.type !== "text") {
276 return beforeTrailing && child.type !== "break" ? [child, { type: "break" }] : [child];
277 }
278 const afterImage = ownsLine(index - 1);
279 const beforeImage = ownsLine(index + 1);
280 if (!afterImage && !beforeImage && !beforeTrailing) return [child];
281 const parts: PhrasingContent[] = [];
282 let value = child.value;
283 if (afterImage) {
284 value = value.replace(/^[ \t]*(?:\r\n|\r|\n)/, "");
285 parts.push({ type: "break" });
286 }
287 const breakAfter = (beforeImage && /(?:\r\n|\r|\n)[ \t]*$/.test(value)) || beforeTrailing;
288 if (breakAfter) value = value.replace(/[ \t]*(?:(?:\r\n|\r|\n)[ \t]*)?$/, "");
289 if (value) parts.push({ type: "text", value });
290 if (breakAfter) parts.push({ type: "break" });
291 return parts;
292 });
294​
295/**
296 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
297 * joins those lines into one paragraph, which puts the image inline beside its label. An
298 * image alone on its source line keeps that line; prose and inline badges still wrap.
299 */
300function remarkBreakAroundImageLines() {
301 return (tree: Root) => {
302 const visit = (node: Root | RootContent) => {
303 if (node.type === "paragraph") breakLinesAroundImages(node);
304 else if ("children" in node) node.children.forEach(visit);
305 };
306 visit(tree);
307 };
309​
310type MarkdownAstNode = {
311 type?: string;
312 meta?: unknown;
313 url?: string;
314 data?: {
315 hProperties?: Record<string, unknown>;
316 };
317 children?: MarkdownAstNode[];
318};
319​
320function remarkKeepAutolinkSuffixes(): Transformer<Root> {
321 return (tree, file) => {
322 const source = String(file);
323 const visit = (node: Root | RootContent) => {
324 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
325 for (let index = 0; index < node.children.length; index++) {
326 const child = node.children[index];
327 const next = node.children[index + 1];
328 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
329 const suffix = /^[_~]+/.exec(next.value)?.[0];
330 if (!suffix) continue;
331 const label = child.children.length === 1 ? child.children[0] : undefined;
332 if (label?.type !== "text") continue;
333 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
334 const start = child.position?.start.offset;
335 const end = child.position?.end.offset;
336 const bare =
337 !child.position ||
338 (start !== undefined &&
339 end !== undefined &&
340 source.slice(start, end) === label.value &&
341 source.slice(end, end + suffix.length) === suffix);
342 if (bare) {
343 child.url += suffix;
344 label.value += suffix;
345 next.value = next.value.slice(suffix.length);
346 if (child.position && end !== undefined) {
347 const boundary = {
348 ...child.position.end,
349 column: child.position.end.column + suffix.length,
350 offset: end + suffix.length,
351 };
352 child.position.end = boundary;
353 if (label.position) label.position.end = boundary;
354 if (next.position) next.position.start = boundary;
355 }
356 if (!next.value) node.children.splice(index + 1, 1);
357 }
358 }
359 if (child) visit(child);
360 }
361 };
362 visit(tree);
363 };
365function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
366 return (tree) => {
367 // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
368 const { insideAnchor } = scanRawHtmlAnchors("html")(tree);
369 const visit = (node: Root | RootContent) => {
370 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
371 node.children = node.children.flatMap((child): typeof node.children => {
372 if (child.type !== "text" || insideAnchor(child)) {
373 visit(child);
374 return [child];
375 }
376 const parts: PhrasingContent[] = [];
377 let offset = 0;
378 for (const { index, path } of absoluteFilePathMatches(child.value)) {
379 if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
380 parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
381 offset = index + path.length;
382 }
383 if (offset === 0) return [child];
384 if (offset < child.value.length)
385 parts.push({ type: "text", value: child.value.slice(offset) });
386 return parts;
387 });
388 };
389 visit(tree);
390 };
392​
393function remarkPreserveCodeMeta() {
394 return (tree: MarkdownAstNode) => {
395 const visit = (node: MarkdownAstNode) => {
396 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
397 node.data = {
398 ...node.data,
399 hProperties: {
400 ...node.data?.hProperties,
401 dataCodeMeta: node.meta.trim(),
402 },
403 };
404 }
405 node.children?.forEach(visit);
406 };
407​
408 visit(tree);
409 };
411​
412function remarkNormalizeLinksAndTagInlineCode() {
413 return (tree: MarkdownAstNode) => {
414 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
415 if ((node.type === "link" || node.type === "definition") && typeof node.url === "string") {
416 const path = node.url.replace(/%5C/gi, "\\");
417 if (/^[A-Za-z]:[\\/]/.test(path)) {
418 node.url = `file:///${path.replaceAll("\\", "/")}`;
419 }
420 }
421 if (node.type === "inlineCode" && !insideLink) {
422 node.data = {
423 ...node.data,
424 hProperties: {
425 ...node.data?.hProperties,
426 dataInlineCode: "",
427 },
428 };
429 }
430 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
431 node.children?.forEach((child) => visit(child, childInsideLink));
432 };
433​
434 visit(tree, false);
435 };
437​
438export function remarkAssistantInsights(this: Processor) {
439 return (tree: Root, file: { value: unknown }) => {
440 const text = String(file.value);
441 // Positions skip the one leading BOM the parser consumes; the reparse keeps it for that.
442 const bom = text.startsWith("\uFEFF") ? "\uFEFF" : "";
443 const source = text.slice(bom.length);
444 if (!source.includes("★ Insight")) return;
445 const protectedRanges: { start: number; end: number; code: boolean }[] = [];
446 const inspect = (node: RootContent | PhrasingContent) => {
447 const start = node.position?.start.offset;
448 const end = node.position?.end.offset;
449 if (start !== undefined && end !== undefined) {
450 const code =
451 node.type === "code" ||
452 node.type === "html" ||
453 (node.type === "inlineCode" && node.position?.start.line !== node.position?.end.line);
454 if (code || node.type === "list" || node.type === "blockquote")
455 protectedRanges.push({ start, end, code });
456 }
457 if ("children" in node) node.children.forEach(inspect);
458 };
459 tree.children.forEach(inspect);
460 const starts = new Set<number>();
461 const offsets: { original: number; rewritten: number; prefix: number }[] = [];
462 let indent: string | undefined;
463 let original = 0;
464 let rewritten = 0;
465 const lines = source.split(/(?<=\n)|(?<=\r)(?!\n)/u).map((line, index) => {
466 const value = line.replace(/[\r\n]+$/u, "");
467 const blocked = protectedRanges.some(
468 (range) =>
469 original >= range.start && original < range.end && (indent === undefined || range.code),
470 );
471 const opening =
472 indent === undefined && !blocked
473 ? /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u.exec(value)
474 : null;
475 const closing =
476 indent !== undefined && !blocked ? /^( {0,3})(`?)─{3,}\2[ \t]*$/u.exec(value) : null;
477 let prefix = 0;
478 let output = line;
479 if (opening) {
480 indent = opening[1] ?? "";
481 starts.add(index + 1);
482 output = ">" + line.slice(value.length);
483 } else if (closing && closing[1] === indent) {
484 indent = undefined;
485 output = line.slice(value.length);
486 } else if (indent !== undefined) {
487 prefix = 2;
488 output = "> " + line;
489 }
490 offsets.push({ original, rewritten, prefix });
491 original += line.length;
492 rewritten += output.length;
493 return output;
494 });
495 if (starts.size === 0) return;
496 const parsed = this.parse(bom + lines.join("")) as Root;
497 const restorePosition = (node: RootContent | PhrasingContent) => {
498 if (node.position) {
499 for (const point of [node.position.start, node.position.end]) {
500 const offset = offsets[point.line - 1];
501 if (!offset) continue;
502 point.column = Math.max(1, point.column - offset.prefix);
503 if (point.offset !== undefined)
504 point.offset += offset.original - offset.rewritten - offset.prefix;
505 }
506 }
507 if ("children" in node) node.children.forEach(restorePosition);
508 };
509 for (const node of parsed.children) {
510 if (node.type === "blockquote" && starts.has(node.position?.start.line ?? 0)) {
511 node.data = { ...node.data, hProperties: { dataAlert: "insight" } };
512 }
513 restorePosition(node);
514 }
515 tree.children = parsed.children;
516 };
518​
519const imageSourceProcessor = unified()
520 .use(remarkParse)
521 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
522 .use(remarkRehype, { allowDangerousHtml: true })
523 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
524​
525interface ImageSourceNode {
526 readonly type: string;
527 readonly tagName?: string;
528 readonly properties?: ChatMarkdownImageProperties;
529 readonly children?: ReadonlyArray<ImageSourceNode>;
531​
532/**
533 * Collect the fallback and every theme variant so images are available to all viewers.
534 */
535export function chatMarkdownImageSources(markdown: string): Array<string> {
536 const sources: Array<string> = [];
537 const visit = (node: ImageSourceNode) => {
538 if (node.type === "element" && node.tagName === "img") {
539 const properties = node.properties;
540 const fallback = chatMarkdownImageSource(properties);
541 if (fallback) sources.push(fallback.classifiedSrc);
542 for (const [theme, variant] of [
543 ["dark", properties?.dataDarkSrc],
544 ["light", properties?.dataLightSrc],
545 ] as const) {
546 if (typeof variant !== "string") continue;
547 const source = chatMarkdownImageSource(properties, theme);
548 if (source) sources.push(source.classifiedSrc);
549 }
550 }
551 node.children?.forEach(visit);
552 };
553 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
554 return sources;
556​
557const linkDestinationProcessor = unified().use(remarkParse).use(remarkKeepWindowsPaths);
558​
559// An angle destination cannot hold an unescaped `<` or `>`, or end on a lone backslash.
560const ANGLE_DESTINATION_CONTENT = /^(?:[^\\<>]|\\.)*$/;
561​
562/** Reads a destination from `extractMarkdownLinkHrefs` as the renderer's parser does. */
563export function decodeMarkdownLinkEscapes(href: string): string {
564 // Only the parser knows character references, so destinations that may have one go through it.
565 if (href.includes("&")) {
566 // The extractor drops angle brackets, and only that form keeps an unmatched `)` in the path.
567 const destination = ANGLE_DESTINATION_CONTENT.test(href) ? `<${href}>` : href;
568 const paragraph = linkDestinationProcessor.parse(`[](${destination})`).children[0];
569 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
570 if (link?.type === "link") return link.url;
571 }
572 return isWindowsAbsolutePath(href) ? href : href.replace(/\\([!-/:-@[-`{-~])/g, "$1");