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

markdownPipeline.ts

540 lines19.4 KB

1import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts";
2import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
3import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
4import { type PluggableList, type Processor, type Transformer, unified } from "unified";
5import remarkParse from "remark-parse";
6import remarkRehype from "remark-rehype";
7import { find, html } from "property-information";
8import rehypeRaw from "rehype-raw";
9import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
10import remarkBreaks from "remark-breaks";
11import remarkGfm from "remark-gfm";
12import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
13import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
14import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
15import {
16 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
17 remarkCodexDirectives,
18} from "./codexMarkdownDirectives.ts";
19import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
20import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
21​
22export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
23​
24type MarkdownImageHastNode = {
25 type?: string;
26 value?: string;
27 tagName?: string;
28 properties?: Record<string, unknown>;
29 children?: MarkdownImageHastNode[];
30};
31​
32function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
33 return (node.children ?? []).filter(
34 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
35 );
37​
38const STANDALONE_IMAGE_BLOCKS = new Set([
39 "p",
40 "div",
41 "li",
42 "td",
43 "th",
44 "figure",
45 "center",
46 "blockquote",
47]);
48​
49function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
50 const children = meaningfulHastChildren(node);
51 if (children.length !== 1) return undefined;
52 const only = children[0];
53 if (only?.type !== "element") return undefined;
54 if (only.tagName === "img") return only;
55 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
56 ? soleImageDescendant(only)
57 : undefined;
59​
60function markStandaloneImages(node: MarkdownImageHastNode) {
61 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
62 const image = soleImageDescendant(node);
63 if (image) image.properties = { ...image.properties, dataStandalone: true };
64 }
65 node.children?.forEach((child) => {
66 if (child.type === "element") markStandaloneImages(child);
67 });
69​
70function rehypePreserveBareAnchorPlaceholders() {
71 return (tree: MarkdownImageHastNode) => {
72 const anchors: Array<MarkdownImageHastNode | null> = [];
73 let rawTextTag: string | undefined;
74 const visit = (node: MarkdownImageHastNode) => {
75 if (node.type === "raw" && typeof node.value === "string") {
76 // Scan whole tags, attributes, and comments so embedded closing-anchor text cannot match a placeholder.
77 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
78 let offset = 0;
79 while (rawTextTag !== "plaintext") {
80 // Raw text ends at its closing tag even inside comment-looking text.
81 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
82 matcher.lastIndex = offset;
83 const match = matcher.exec(node.value);
84 if (!match) break;
85 const [tag] = match;
86 offset = matcher.lastIndex;
87 if (rawTextTag) {
88 rawTextTag = undefined;
89 continue;
90 }
91 if (tag.startsWith("<!--")) continue;
92 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
93 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
94 if (
95 opening &&
96 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
97 ) {
98 rawTextTag = opening;
99 } else if (opening === "a") {
100 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
101 } else if (closing === "a") {
102 anchors.pop();
103 }
104 }
105 }
106 node.children?.forEach(visit);
107 };
108​
109 visit(tree);
110 for (const anchor of anchors) {
111 if (anchor) anchor.type = "text";
112 }
113 };
115​
116const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
117​
118/**
119 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
120 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
121 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
122 */
123function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
124 if (!picture.children) return;
125 const image = picture.children.find((child) => child.tagName === "img");
126 for (const source of picture.children) {
127 if (source.tagName !== "source" || !image) continue;
128 const media = source.properties?.media;
129 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
130 const srcSet = source.properties?.srcSet;
131 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
132 // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
133 const url =
134 typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
135 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
136 // As in a browser, the first source that matches a scheme is the one shown.
137 if (scheme && url && image.properties?.[key] === undefined) {
138 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
139 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
140 image.properties = { ...image.properties, [key]: value };
141 }
142 }
143 picture.children = picture.children.filter((child) => child.tagName !== "source");
145​
146function rehypePreserveImageSourceMeta() {
147 return (tree: MarkdownImageHastNode) => {
148 const visit = (node: MarkdownImageHastNode) => {
149 const src = node.properties?.src;
150 const title = node.properties?.title;
151 if (node.type === "element" && node.tagName === "picture") {
152 moveColorSchemeSourcesToImage(node);
153 }
154 if (node.type === "element" && node.tagName === "img") {
155 node.properties = {
156 ...node.properties,
157 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
158 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
159 };
160 }
161 node.children?.forEach(visit);
162 };
163​
164 visit(tree);
165 markStandaloneImages(tree);
166 };
168​
169const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
170​
171// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first.
172function rehypeNormalizeLocalEditorLinks() {
173 return (tree: MarkdownImageHastNode) => {
174 const visit = (node: MarkdownImageHastNode) => {
175 const href = node.properties?.href;
176 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
177 try {
178 const url = new URL(href);
179 if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href };
180 } catch {
181 // Not an absolute URL; the sanitizer decides.
182 }
183 }
184 node.children?.forEach(visit);
185 };
186​
187 visit(tree);
188 };
190​
191const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
192 ...defaultSchema,
193 attributes: {
194 ...defaultSchema.attributes,
195 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
196 // Fence languages plus the two math classes the web chat's math plugin emits.
197 code: [
198 ["className", /^language-./, "math-inline", "math-display"],
199 "dataCodeMeta",
200 "dataInlineCode",
201 ],
202 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
203 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
204 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
205 img: [
206 ...(defaultSchema.attributes?.img ?? []),
207 "dataDarkSrc",
208 "dataLightSrc",
209 "dataLocalSrc",
210 "dataMarkdownTitle",
211 "dataStandalone",
212 ],
213 },
214 protocols: {
215 ...defaultSchema.protocols,
216 href: [
217 ...(defaultSchema.protocols?.href ?? []),
218 "file",
219 "t3-citation",
220 "t3-context",
221 THREAD_LINK_PROTOCOL,
222 // Scheme only: the renderer's URL transform checks the rest of the link shape.
223 ...LOCAL_FILE_LINK_SCHEMES,
224 ],
225 src: IMAGE_SRC_PROTOCOLS,
226 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
227 dataLightSrc: IMAGE_SRC_PROTOCOLS,
228 },
229} satisfies Parameters<typeof rehypeSanitize>[0];
230​
231export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
232 remarkGfm,
233 remarkKeepAutolinkSuffixes,
234 remarkKeepWindowsPaths,
235 remarkGithubAlerts,
236 remarkKeepOrderedListNumbers,
237 remarkNormalizeListItemIndentation,
238 remarkCodexDirectives,
239 remarkBreakAroundImageLines,
240 remarkPreserveCodeMeta,
241 remarkNormalizeLinksAndTagInlineCode,
242];
243​
244export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
245 remarkGfm,
246 remarkKeepAutolinkSuffixes,
247 remarkKeepWindowsPaths,
248 remarkGithubAlerts,
249 remarkKeepOrderedListNumbers,
250 remarkNormalizeListItemIndentation,
251 remarkCodexDirectives,
252 remarkBreakAroundImageLines,
253 remarkBreaks,
254 remarkPreserveCodeMeta,
255 remarkNormalizeLinksAndTagInlineCode,
256];
257​
258// Start tags an HTML parser closes an open `<p>` for.
259const CLOSES_PARAGRAPH = new Set(
260 "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(
261 " ",
262 ),
263);
264const HEADING = /^h[1-6]$/;
265​
266interface HtmlScope {
267 readonly anchor: boolean;
268 readonly paragraph: boolean;
269 readonly heading: boolean;
271​
272/**
273 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
274 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
275 * drops `data`, both repeated here, and moves blank text that renders the same.
276 */
277function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
278 if (node.type === "raw") return true;
279 let inner = scope;
280 if (node.type === "element" && node.tagName) {
281 const { tagName } = node;
282 const heading = HEADING.test(tagName);
283 if (
284 (tagName === "a" && scope.anchor) ||
285 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
286 (heading && scope.heading)
287 ) {
288 return true;
289 }
290 inner = {
291 anchor: scope.anchor || tagName === "a",
292 paragraph: scope.paragraph || tagName === "p",
293 heading: scope.heading || heading,
294 };
295 const properties = node.properties ?? {};
296 for (const key of Object.keys(properties)) {
297 const value = properties[key];
298 const info = find(html, key);
299 if (
300 value === false ||
301 value === null ||
302 value === undefined ||
303 Number.isNaN(value) ||
304 (!value && info.boolean)
305 ) {
306 delete properties[key];
307 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
308 properties[key] = "";
309 }
310 }
311 delete (node as { data?: unknown }).data;
312 }
313 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
315​
316const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
317​
318/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
319function rehypeRawWhenPresent(this: Processor) {
320 const transform = rehypeRaw.call(this) as unknown as (
321 tree: MarkdownImageHastNode,
322 file: unknown,
323 ) => unknown;
324 return (tree: MarkdownImageHastNode, file: unknown) =>
325 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
327​
328export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
329 rehypePreserveBareAnchorPlaceholders,
330 rehypeRawWhenPresent,
331 rehypePreserveImageSourceMeta,
332 rehypeNormalizeLocalEditorLinks,
333 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
334];
335​
336const isImageNode = (node: PhrasingContent | undefined): boolean =>
337 node?.type === "image" ||
338 node?.type === "imageReference" ||
339 ((node?.type === "link" || node?.type === "linkReference") &&
340 node.children.length === 1 &&
341 isImageNode(node.children[0]));
342const endsLine = (node: PhrasingContent | undefined) =>
343 node === undefined ||
344 node.type === "break" ||
345 (node.type === "text" && /\n[ \t]*$/.test(node.value));
346const startsLine = (node: PhrasingContent | undefined) =>
347 node === undefined ||
348 node.type === "break" ||
349 (node.type === "text" && /^[ \t]*\n/.test(node.value));
350​
351function breakLinesAroundImages(paragraph: Paragraph) {
352 const children = paragraph.children;
353 if (!children.some(isImageNode)) return;
354 const ownsLine = (index: number) =>
355 isImageNode(children[index]) &&
356 endsLine(children[index - 1]) &&
357 startsLine(children[index + 1]);
358 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
359 if (child.type !== "text") return [child];
360 const afterImage = ownsLine(index - 1);
361 const beforeImage = ownsLine(index + 1);
362 if (!afterImage && !beforeImage) return [child];
363 const parts: PhrasingContent[] = [];
364 let value = child.value;
365 if (afterImage) {
366 value = value.replace(/^[ \t]*\n/, "");
367 parts.push({ type: "break" });
368 }
369 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
370 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
371 if (value) parts.push({ type: "text", value });
372 if (breakAfter) parts.push({ type: "break" });
373 return parts;
374 });
376​
377/**
378 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
379 * joins those lines into one paragraph, which puts the image inline beside its label. An
380 * image alone on its source line keeps that line; prose and inline badges still wrap.
381 */
382function remarkBreakAroundImageLines() {
383 return (tree: Root) => {
384 const visit = (node: Root | RootContent) => {
385 if (node.type === "paragraph") breakLinesAroundImages(node);
386 else if ("children" in node) node.children.forEach(visit);
387 };
388 visit(tree);
389 };
391​
392type MarkdownAstNode = {
393 type?: string;
394 meta?: unknown;
395 url?: string;
396 data?: {
397 hProperties?: Record<string, unknown>;
398 };
399 children?: MarkdownAstNode[];
400};
401​
402function remarkKeepAutolinkSuffixes(): Transformer<Root> {
403 return (tree, file) => {
404 const source = String(file);
405 const visit = (node: Root | RootContent) => {
406 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
407 for (let index = 0; index < node.children.length; index++) {
408 const child = node.children[index];
409 const next = node.children[index + 1];
410 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
411 const suffix = /^[_~]+/.exec(next.value)?.[0];
412 if (!suffix) continue;
413 const label = child.children.length === 1 ? child.children[0] : undefined;
414 if (label?.type !== "text") continue;
415 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
416 const start = child.position?.start.offset;
417 const end = child.position?.end.offset;
418 const bare =
419 !child.position ||
420 (start !== undefined &&
421 end !== undefined &&
422 source.slice(start, end) === label.value &&
423 source.slice(end, end + suffix.length) === suffix);
424 if (bare) {
425 child.url += suffix;
426 label.value += suffix;
427 next.value = next.value.slice(suffix.length);
428 if (child.position && end !== undefined) {
429 const boundary = {
430 ...child.position.end,
431 column: child.position.end.column + suffix.length,
432 offset: end + suffix.length,
433 };
434 child.position.end = boundary;
435 if (label.position) label.position.end = boundary;
436 if (next.position) next.position.start = boundary;
437 }
438 if (!next.value) node.children.splice(index + 1, 1);
439 }
440 }
441 if (child) visit(child);
442 }
443 };
444 visit(tree);
445 };
447​
448function remarkPreserveCodeMeta() {
449 return (tree: MarkdownAstNode) => {
450 const visit = (node: MarkdownAstNode) => {
451 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
452 node.data = {
453 ...node.data,
454 hProperties: {
455 ...node.data?.hProperties,
456 dataCodeMeta: node.meta.trim(),
457 },
458 };
459 }
460 node.children?.forEach(visit);
461 };
462​
463 visit(tree);
464 };
466​
467function remarkNormalizeLinksAndTagInlineCode() {
468 return (tree: MarkdownAstNode) => {
469 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
470 if (
471 (node.type === "link" || node.type === "definition") &&
472 typeof node.url === "string" &&
473 /^[A-Za-z]:[\\/]/.test(node.url)
474 ) {
475 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
476 }
477 if (node.type === "inlineCode" && !insideLink) {
478 node.data = {
479 ...node.data,
480 hProperties: {
481 ...node.data?.hProperties,
482 dataInlineCode: "",
483 },
484 };
485 }
486 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
487 node.children?.forEach((child) => visit(child, childInsideLink));
488 };
489​
490 visit(tree, false);
491 };
493​
494export function shouldPreserveAssistantLineBreaks(text: string): boolean {
495 return /^★ Insight(?:\s|─)/mu.test(text);
497​
498const imageSourceProcessor = unified()
499 .use(remarkParse)
500 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
501 .use(remarkRehype, { allowDangerousHtml: true })
502 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
503​
504interface ImageSourceNode {
505 readonly type: string;
506 readonly tagName?: string;
507 readonly properties?: {
508 readonly src?: unknown;
509 readonly dataLocalSrc?: unknown;
510 readonly dataDarkSrc?: unknown;
511 readonly dataLightSrc?: unknown;
512 };
513 readonly children?: ReadonlyArray<ImageSourceNode>;
515​
516/**
517 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
518 * them. Code, comments, and plain links show no image, so they add none.
519 */
520export function chatMarkdownImageSources(markdown: string): Array<string> {
521 const sources: Array<string> = [];
522 const visit = (node: ImageSourceNode) => {
523 if (node.type === "element" && node.tagName === "img") {
524 const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
525 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
526 if (typeof dataLocalSrc === "string") {
527 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
528 } else if (typeof src === "string") {
529 sources.push(normalizeMarkdownLinkDestination(src));
530 }
531 // A `<picture>` shows one of these instead, by the viewer's theme.
532 for (const variant of [dataDarkSrc, dataLightSrc]) {
533 if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
534 }
535 }
536 node.children?.forEach(visit);
537 };
538 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
539 return sources;