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

markdownPipeline.ts

358 lines12.0 KB

1import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast";
2import type { Processor } from "unified";
3import { isWindowsAbsolutePath } from "./path.ts";
4import type { PluggableList } from "unified";
5import rehypeRaw from "rehype-raw";
6import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
7import remarkBreaks from "remark-breaks";
8import remarkGfm from "remark-gfm";
9import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
10import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
11import {
12 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
13 remarkCodexDirectives,
14} from "./codexMarkdownDirectives.ts";
15import { isWindowsDrivePathHref } from "./markdownLinks.ts";
16import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
17​
18type MarkdownImageHastNode = {
19 type?: string;
20 value?: string;
21 tagName?: string;
22 properties?: Record<string, unknown>;
23 children?: MarkdownImageHastNode[];
24};
25​
26function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
27 return (node.children ?? []).filter(
28 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
29 );
31​
32const STANDALONE_IMAGE_BLOCKS = new Set([
33 "p",
34 "div",
35 "li",
36 "td",
37 "th",
38 "figure",
39 "center",
40 "blockquote",
41]);
42​
43function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
44 const children = meaningfulHastChildren(node);
45 if (children.length !== 1) return undefined;
46 const only = children[0];
47 if (only?.type !== "element") return undefined;
48 if (only.tagName === "img") return only;
49 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
50 ? soleImageDescendant(only)
51 : undefined;
53​
54function markStandaloneImages(node: MarkdownImageHastNode) {
55 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
56 const image = soleImageDescendant(node);
57 if (image) image.properties = { ...image.properties, dataStandalone: true };
58 }
59 node.children?.forEach((child) => {
60 if (child.type === "element") markStandaloneImages(child);
61 });
63​
64function rehypePreserveBareAnchorPlaceholders() {
65 return (tree: MarkdownImageHastNode) => {
66 const anchors: Array<MarkdownImageHastNode | null> = [];
67 let rawTextTag: string | undefined;
68 const visit = (node: MarkdownImageHastNode) => {
69 if (node.type === "raw" && typeof node.value === "string") {
70 // Raw blocks can contain several tags. Consume whole tags, quoted attributes,
71 // and comments so text resembling a closing anchor cannot pair 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​
306interface DestinationCompileContext {
307 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
308 resume(): string;
309 sliceSerialize(token: unknown): string;
311​
312function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
313 const decoded = this.resume();
314 const authored = this.sliceSerialize(token);
315 const node = this.stack.at(-1);
316 // Character references still need decoding, so those destinations keep the parsed URL.
317 if (node)
318 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
320​
321// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
322const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
323​
324interface EscapeCompileContext {
325 readonly stack: ReadonlyArray<{
326 readonly type: string;
327 children?: Array<{ type: string; value?: string }>;
328 }>;
330​
331function keepWindowsPathEscape(this: EscapeCompileContext) {
332 const text = this.stack.at(-1)?.children?.at(-1);
333 if (text?.type !== "text" || text.value === undefined) return;
334 const before = text.value.slice(0, -1);
335 if (UNFINISHED_DRIVE_PATH.test(before)) text.value = `${before}\\${text.value.slice(-1)}`;
337​
338/**
339 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape. Every backslash in a
340 * Windows path is a separator, so link, image, and definition destinations that are
341 * Windows paths keep the text as written, and so do escapes inside drive paths in prose.
342 * Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
343 * `C:\x and \*this\*` must still read `*this*`.
344 */
345function remarkKeepWindowsPaths(this: Processor) {
346 const data = this.data();
347 (data.fromMarkdownExtensions ??= []).push({
348 exit: {
349 resourceDestinationString: keepWindowsPathDestination,
350 definitionDestinationString: keepWindowsPathDestination,
351 characterEscape: keepWindowsPathEscape,
352 },
353 });
355​
356export function shouldPreserveAssistantLineBreaks(text: string): boolean {
357 return /^★ Insight(?:\s|─)/mu.test(text);