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

markdownPipeline.ts

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