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

markdownPipeline.ts

293 lines10.0 KB

1import type { Processor } from "unified";
2import { isWindowsAbsolutePath } from "./path.ts";
3import type { PluggableList } from "unified";
4import rehypeRaw from "rehype-raw";
5import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
6import remarkBreaks from "remark-breaks";
7import remarkGfm from "remark-gfm";
8import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
9import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
10import {
11 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
12 remarkCodexDirectives,
13} from "./codexMarkdownDirectives.ts";
14import { isWindowsDrivePathHref } from "./markdownLinks.ts";
15import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
16​
17type MarkdownImageHastNode = {
18 type?: string;
19 value?: string;
20 tagName?: string;
21 properties?: Record<string, unknown>;
22 children?: MarkdownImageHastNode[];
23};
24​
25function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
26 return (node.children ?? []).filter(
27 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
28 );
30​
31/**
32 * An image that is the only content of its block (optionally wrapped in a
33 * link) is almost always a screenshot or figure, so it gets a reserved slot
34 * while it loads. Images mixed with text or other images — badge rows, icons
35 * in a sentence — stay inline at their natural size, since a placeholder taller
36 * than the image would move the page more than the image itself does.
37 */
38/** Containers whose sole child image reads as a figure rather than part of a sentence. */
39const STANDALONE_IMAGE_BLOCKS = new Set([
40 "p",
41 "div",
42 "li",
43 "td",
44 "th",
45 "figure",
46 "center",
47 "blockquote",
48]);
49​
50function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
51 const children = meaningfulHastChildren(node);
52 if (children.length !== 1) return undefined;
53 const only = children[0];
54 if (only?.type !== "element") return undefined;
55 if (only.tagName === "img") return only;
56 // A link, emphasis, or similar inline wrapper around the image still counts
57 // as long as nothing else shares the block.
58 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
59 ? soleImageDescendant(only)
60 : undefined;
62​
63function markStandaloneImages(node: MarkdownImageHastNode) {
64 // A raw `<img>` on its own line reaches the root without a paragraph.
65 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
66 const image = soleImageDescendant(node);
67 if (image) image.properties = { ...image.properties, dataStandalone: true };
68 }
69 node.children?.forEach((child) => {
70 if (child.type === "element") markStandaloneImages(child);
71 });
73​
74/** Keep unmatched inline `<A>` placeholders from opening an HTML link over later blocks. */
75function rehypePreserveBareAnchorPlaceholders() {
76 return (tree: MarkdownImageHastNode) => {
77 const anchors: Array<MarkdownImageHastNode | null> = [];
78 let rawTextTag: string | undefined;
79 const visit = (node: MarkdownImageHastNode) => {
80 if (node.type === "raw" && typeof node.value === "string") {
81 // Raw blocks can contain several tags. Consume whole tags, quoted attributes,
82 // and comments so text resembling a closing anchor cannot pair a placeholder.
83 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
84 let offset = 0;
85 while (rawTextTag !== "plaintext") {
86 // Raw text ends at its closing tag even inside comment-looking text.
87 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
88 matcher.lastIndex = offset;
89 const match = matcher.exec(node.value);
90 if (!match) break;
91 const [tag] = match;
92 offset = matcher.lastIndex;
93 if (rawTextTag) {
94 rawTextTag = undefined;
95 continue;
96 }
97 if (tag.startsWith("<!--")) continue;
98 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
99 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
100 if (
101 opening &&
102 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
103 ) {
104 rawTextTag = opening;
105 } else if (opening === "a") {
106 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
107 } else if (closing === "a") {
108 anchors.pop();
109 }
110 }
111 }
112 node.children?.forEach(visit);
113 };
114​
115 visit(tree);
116 for (const anchor of anchors) {
117 if (anchor) anchor.type = "text";
118 }
119 };
121​
122/** Carries authored image source metadata through the sanitizer to the image renderer. */
123function rehypePreserveImageSourceMeta() {
124 return (tree: MarkdownImageHastNode) => {
125 const visit = (node: MarkdownImageHastNode) => {
126 const src = node.properties?.src;
127 const title = node.properties?.title;
128 if (node.type === "element" && node.tagName === "img") {
129 node.properties = {
130 ...node.properties,
131 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
132 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
133 };
134 }
135 node.children?.forEach(visit);
136 };
137​
138 visit(tree);
139 markStandaloneImages(tree);
140 };
142​
143const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
144 ...defaultSchema,
145 attributes: {
146 ...defaultSchema.attributes,
147 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
148 code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
149 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
150 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
151 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
152 img: [
153 ...(defaultSchema.attributes?.img ?? []),
154 "dataLocalSrc",
155 "dataMarkdownTitle",
156 "dataStandalone",
157 ],
158 },
159 protocols: {
160 ...defaultSchema.protocols,
161 href: [
162 ...(defaultSchema.protocols?.href ?? []),
163 "file",
164 "t3-citation",
165 "t3-context",
166 THREAD_LINK_PROTOCOL,
167 ],
168 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
169 },
170} satisfies Parameters<typeof rehypeSanitize>[0];
171​
172export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
173 remarkGfm,
174 remarkKeepWindowsPathDestinations,
175 remarkGithubAlerts,
176 remarkNormalizeListItemIndentation,
177 remarkCodexDirectives,
178 remarkPreserveCodeMeta,
179 remarkNormalizeLinksAndTagInlineCode,
180];
181​
182export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
183 remarkGfm,
184 remarkKeepWindowsPathDestinations,
185 remarkGithubAlerts,
186 remarkNormalizeListItemIndentation,
187 remarkCodexDirectives,
188 remarkBreaks,
189 remarkPreserveCodeMeta,
190 remarkNormalizeLinksAndTagInlineCode,
191];
192​
193export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
194 rehypePreserveBareAnchorPlaceholders,
195 rehypeRaw,
196 rehypePreserveImageSourceMeta,
197 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
198];
199​
200type MarkdownAstNode = {
201 type?: string;
202 meta?: unknown;
203 url?: string;
204 data?: {
205 hProperties?: Record<string, unknown>;
206 };
207 children?: MarkdownAstNode[];
208};
209​
210function remarkPreserveCodeMeta() {
211 return (tree: MarkdownAstNode) => {
212 const visit = (node: MarkdownAstNode) => {
213 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
214 node.data = {
215 ...node.data,
216 hProperties: {
217 ...node.data?.hProperties,
218 dataCodeMeta: node.meta.trim(),
219 },
220 };
221 }
222 node.children?.forEach(visit);
223 };
224​
225 visit(tree);
226 };
228​
229/**
230 * Preserve Windows drive links as allowed `file:` URLs before sanitization.
231 * The same traversal tags inline code while it can still be distinguished
232 * from fenced code. Code inside links stays untagged to avoid nested anchors.
233 */
234function remarkNormalizeLinksAndTagInlineCode() {
235 return (tree: MarkdownAstNode) => {
236 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
237 if (
238 (node.type === "link" || node.type === "definition") &&
239 typeof node.url === "string" &&
240 /^[A-Za-z]:[\\/]/.test(node.url)
241 ) {
242 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
243 }
244 if (node.type === "inlineCode" && !insideLink) {
245 node.data = {
246 ...node.data,
247 hProperties: {
248 ...node.data?.hProperties,
249 dataInlineCode: "",
250 },
251 };
252 }
253 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
254 node.children?.forEach((child) => visit(child, childInsideLink));
255 };
256​
257 visit(tree, false);
258 };
260​
261interface DestinationCompileContext {
262 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
263 resume(): string;
264 sliceSerialize(token: unknown): string;
266​
267function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
268 const decoded = this.resume();
269 const authored = this.sliceSerialize(token);
270 const node = this.stack.at(-1);
271 // Character references still need decoding, so those destinations keep the parsed URL.
272 if (node)
273 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
275​
276/**
277 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape, even in a link
278 * destination. Every backslash in a Windows path is a separator, so link, image, and
279 * definition destinations that are Windows paths keep the text as written.
280 */
281function remarkKeepWindowsPathDestinations(this: Processor) {
282 const data = this.data();
283 (data.fromMarkdownExtensions ??= []).push({
284 exit: {
285 resourceDestinationString: keepWindowsPathDestination,
286 definitionDestinationString: keepWindowsPathDestination,
287 },
288 });
290​
291export function shouldPreserveAssistantLineBreaks(text: string): boolean {
292 return /^★ Insight(?:\s|─)/mu.test(text);