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

markdownPipeline.ts

343 lines11.5 KB

1import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
2import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
3import { type PluggableList, unified } from "unified";
4import remarkParse from "remark-parse";
5import remarkRehype from "remark-rehype";
6import rehypeRaw from "rehype-raw";
7import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
8import remarkBreaks from "remark-breaks";
9import remarkGfm from "remark-gfm";
10import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
11import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
12import {
13 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
14 remarkCodexDirectives,
15} from "./codexMarkdownDirectives.ts";
16import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
17import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
18​
19type MarkdownImageHastNode = {
20 type?: string;
21 value?: string;
22 tagName?: string;
23 properties?: Record<string, unknown>;
24 children?: MarkdownImageHastNode[];
25};
26​
27function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
28 return (node.children ?? []).filter(
29 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
30 );
32​
33const STANDALONE_IMAGE_BLOCKS = new Set([
34 "p",
35 "div",
36 "li",
37 "td",
38 "th",
39 "figure",
40 "center",
41 "blockquote",
42]);
43​
44function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
45 const children = meaningfulHastChildren(node);
46 if (children.length !== 1) return undefined;
47 const only = children[0];
48 if (only?.type !== "element") return undefined;
49 if (only.tagName === "img") return only;
50 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
51 ? soleImageDescendant(only)
52 : undefined;
54​
55function markStandaloneImages(node: MarkdownImageHastNode) {
56 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
57 const image = soleImageDescendant(node);
58 if (image) image.properties = { ...image.properties, dataStandalone: true };
59 }
60 node.children?.forEach((child) => {
61 if (child.type === "element") markStandaloneImages(child);
62 });
64​
65function rehypePreserveBareAnchorPlaceholders() {
66 return (tree: MarkdownImageHastNode) => {
67 const anchors: Array<MarkdownImageHastNode | null> = [];
68 let rawTextTag: string | undefined;
69 const visit = (node: MarkdownImageHastNode) => {
70 if (node.type === "raw" && typeof node.value === "string") {
71 // Scan whole tags, attributes, and comments so embedded closing-anchor text cannot match a placeholder.
72 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
73 let offset = 0;
74 while (rawTextTag !== "plaintext") {
75 // Raw text ends at its closing tag even inside comment-looking text.
76 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
77 matcher.lastIndex = offset;
78 const match = matcher.exec(node.value);
79 if (!match) break;
80 const [tag] = match;
81 offset = matcher.lastIndex;
82 if (rawTextTag) {
83 rawTextTag = undefined;
84 continue;
85 }
86 if (tag.startsWith("<!--")) continue;
87 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
88 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
89 if (
90 opening &&
91 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
92 ) {
93 rawTextTag = opening;
94 } else if (opening === "a") {
95 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
96 } else if (closing === "a") {
97 anchors.pop();
98 }
99 }
100 }
101 node.children?.forEach(visit);
102 };
103​
104 visit(tree);
105 for (const anchor of anchors) {
106 if (anchor) anchor.type = "text";
107 }
108 };
110​
111function rehypePreserveImageSourceMeta() {
112 return (tree: MarkdownImageHastNode) => {
113 const visit = (node: MarkdownImageHastNode) => {
114 const src = node.properties?.src;
115 const title = node.properties?.title;
116 if (node.type === "element" && node.tagName === "img") {
117 node.properties = {
118 ...node.properties,
119 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
120 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
121 };
122 }
123 node.children?.forEach(visit);
124 };
125​
126 visit(tree);
127 markStandaloneImages(tree);
128 };
130​
131const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
132 ...defaultSchema,
133 attributes: {
134 ...defaultSchema.attributes,
135 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
136 // Fence languages plus the two math classes the web chat's math plugin emits.
137 code: [
138 ["className", /^language-./, "math-inline", "math-display"],
139 "dataCodeMeta",
140 "dataInlineCode",
141 ],
142 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
143 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
144 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
145 img: [
146 ...(defaultSchema.attributes?.img ?? []),
147 "dataLocalSrc",
148 "dataMarkdownTitle",
149 "dataStandalone",
150 ],
151 },
152 protocols: {
153 ...defaultSchema.protocols,
154 href: [
155 ...(defaultSchema.protocols?.href ?? []),
156 "file",
157 "t3-citation",
158 "t3-context",
159 THREAD_LINK_PROTOCOL,
160 ],
161 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
162 },
163} satisfies Parameters<typeof rehypeSanitize>[0];
164​
165export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
166 remarkGfm,
167 remarkKeepWindowsPaths,
168 remarkGithubAlerts,
169 remarkNormalizeListItemIndentation,
170 remarkCodexDirectives,
171 remarkBreakAroundImageLines,
172 remarkPreserveCodeMeta,
173 remarkNormalizeLinksAndTagInlineCode,
174];
175​
176export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
177 remarkGfm,
178 remarkKeepWindowsPaths,
179 remarkGithubAlerts,
180 remarkNormalizeListItemIndentation,
181 remarkCodexDirectives,
182 remarkBreakAroundImageLines,
183 remarkBreaks,
184 remarkPreserveCodeMeta,
185 remarkNormalizeLinksAndTagInlineCode,
186];
187​
188export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
189 rehypePreserveBareAnchorPlaceholders,
190 rehypeRaw,
191 rehypePreserveImageSourceMeta,
192 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
193];
194​
195const isImageNode = (node: PhrasingContent | undefined): boolean =>
196 node?.type === "image" ||
197 node?.type === "imageReference" ||
198 ((node?.type === "link" || node?.type === "linkReference") &&
199 node.children.length === 1 &&
200 isImageNode(node.children[0]));
201const endsLine = (node: PhrasingContent | undefined) =>
202 node === undefined ||
203 node.type === "break" ||
204 (node.type === "text" && /\n[ \t]*$/.test(node.value));
205const startsLine = (node: PhrasingContent | undefined) =>
206 node === undefined ||
207 node.type === "break" ||
208 (node.type === "text" && /^[ \t]*\n/.test(node.value));
209​
210function breakLinesAroundImages(paragraph: Paragraph) {
211 const children = paragraph.children;
212 const ownsLine = (index: number) =>
213 isImageNode(children[index]) &&
214 endsLine(children[index - 1]) &&
215 startsLine(children[index + 1]);
216 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
217 if (child.type !== "text") return [child];
218 const afterImage = ownsLine(index - 1);
219 const beforeImage = ownsLine(index + 1);
220 if (!afterImage && !beforeImage) return [child];
221 const parts: PhrasingContent[] = [];
222 let value = child.value;
223 if (afterImage) {
224 value = value.replace(/^[ \t]*\n/, "");
225 parts.push({ type: "break" });
226 }
227 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
228 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
229 if (value) parts.push({ type: "text", value });
230 if (breakAfter) parts.push({ type: "break" });
231 return parts;
232 });
234​
235/**
236 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
237 * joins those lines into one paragraph, which puts the image inline beside its label. An
238 * image alone on its source line keeps that line; prose and inline badges still wrap.
239 */
240function remarkBreakAroundImageLines() {
241 return (tree: Root) => {
242 const visit = (node: Root | RootContent) => {
243 if (node.type === "paragraph") breakLinesAroundImages(node);
244 else if ("children" in node) node.children.forEach(visit);
245 };
246 visit(tree);
247 };
249​
250type MarkdownAstNode = {
251 type?: string;
252 meta?: unknown;
253 url?: string;
254 data?: {
255 hProperties?: Record<string, unknown>;
256 };
257 children?: MarkdownAstNode[];
258};
259​
260function remarkPreserveCodeMeta() {
261 return (tree: MarkdownAstNode) => {
262 const visit = (node: MarkdownAstNode) => {
263 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
264 node.data = {
265 ...node.data,
266 hProperties: {
267 ...node.data?.hProperties,
268 dataCodeMeta: node.meta.trim(),
269 },
270 };
271 }
272 node.children?.forEach(visit);
273 };
274​
275 visit(tree);
276 };
278​
279function remarkNormalizeLinksAndTagInlineCode() {
280 return (tree: MarkdownAstNode) => {
281 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
282 if (
283 (node.type === "link" || node.type === "definition") &&
284 typeof node.url === "string" &&
285 /^[A-Za-z]:[\\/]/.test(node.url)
286 ) {
287 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
288 }
289 if (node.type === "inlineCode" && !insideLink) {
290 node.data = {
291 ...node.data,
292 hProperties: {
293 ...node.data?.hProperties,
294 dataInlineCode: "",
295 },
296 };
297 }
298 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
299 node.children?.forEach((child) => visit(child, childInsideLink));
300 };
301​
302 visit(tree, false);
303 };
305​
306export function shouldPreserveAssistantLineBreaks(text: string): boolean {
307 return /^★ Insight(?:\s|─)/mu.test(text);
309​
310const imageSourceProcessor = unified()
311 .use(remarkParse)
312 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
313 .use(remarkRehype, { allowDangerousHtml: true })
314 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
315​
316interface ImageSourceNode {
317 readonly type: string;
318 readonly tagName?: string;
319 readonly properties?: { readonly src?: unknown; readonly dataLocalSrc?: unknown };
320 readonly children?: ReadonlyArray<ImageSourceNode>;
322​
323/**
324 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
325 * them. Code, comments, and plain links show no image, so they add none.
326 */
327export function chatMarkdownImageSources(markdown: string): Array<string> {
328 const sources: Array<string> = [];
329 const visit = (node: ImageSourceNode) => {
330 if (node.type === "element" && node.tagName === "img") {
331 const { src, dataLocalSrc } = node.properties ?? {};
332 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
333 if (typeof dataLocalSrc === "string") {
334 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
335 } else if (typeof src === "string") {
336 sources.push(normalizeMarkdownLinkDestination(src));
337 }
338 }
339 node.children?.forEach(visit);
340 };
341 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
342 return sources;