Open History to see the last commit
1import type { Processor } from "unified";
2import { isWindowsAbsolutePath } from "./path.ts";
3import type { Pluggable, PluggableList } from "unified";
4import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
5import remarkBreaks from "remark-breaks";
6import remarkGfm from "remark-gfm";
7import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
8import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
9import {
10 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
11 remarkCodexDirectives,
12} from "./codexMarkdownDirectives.ts";
13import { isWindowsDrivePathHref } from "./markdownLinks.ts";
14import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
15
16type MarkdownImageHastNode = {
17 type?: string;
18 value?: string;
19 tagName?: string;
20 properties?: Record<string, unknown>;
21 children?: MarkdownImageHastNode[];
22};
23
24function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
25 return (node.children ?? []).filter(
26 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
27 );
28}
29
30const STANDALONE_IMAGE_BLOCKS = new Set([
31 "p",
32 "div",
33 "li",
34 "td",
35 "th",
36 "figure",
37 "center",
38 "blockquote",
39]);
40
41function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
42 const children = meaningfulHastChildren(node);
43 if (children.length !== 1) return undefined;
44 const only = children[0];
45 if (only?.type !== "element") return undefined;
46 if (only.tagName === "img") return only;
47 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
48 ? soleImageDescendant(only)
49 : undefined;
50}
51
52function markStandaloneImages(node: MarkdownImageHastNode) {
53 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
54 const image = soleImageDescendant(node);
55 if (image) image.properties = { ...image.properties, dataStandalone: true };
56 }
57 node.children?.forEach((child) => {
58 if (child.type === "element") markStandaloneImages(child);
59 });
60}
61
62function rehypePreserveBareAnchorPlaceholders() {
63 return (tree: MarkdownImageHastNode) => {
64 const anchors: Array<MarkdownImageHastNode | null> = [];
65 let rawTextTag: string | undefined;
66 const visit = (node: MarkdownImageHastNode) => {
67 if (node.type === "raw" && typeof node.value === "string") {
68 // Raw blocks can contain several tags. Consume whole tags, quoted attributes,
69 // and comments so text resembling a closing anchor cannot pair a placeholder.
70 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
71 let offset = 0;
72 while (rawTextTag !== "plaintext") {
73 // Raw text ends at its closing tag even inside comment-looking text.
74 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
75 matcher.lastIndex = offset;
76 const match = matcher.exec(node.value);
77 if (!match) break;
78 const [tag] = match;
79 offset = matcher.lastIndex;
80 if (rawTextTag) {
81 rawTextTag = undefined;
82 continue;
83 }
84 if (tag.startsWith("<!--")) continue;
85 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
86 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
87 if (
88 opening &&
89 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
90 ) {
91 rawTextTag = opening;
92 } else if (opening === "a") {
93 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
94 } else if (closing === "a") {
95 anchors.pop();
96 }
97 }
98 }
99 node.children?.forEach(visit);
100 };
101
102 visit(tree);
103 for (const anchor of anchors) {
104 if (anchor) anchor.type = "text";
105 }
106 };
107}
108
109function rehypePreserveImageSourceMeta() {
110 return (tree: MarkdownImageHastNode) => {
111 const visit = (node: MarkdownImageHastNode) => {
112 const src = node.properties?.src;
113 const title = node.properties?.title;
114 if (node.type === "element" && node.tagName === "img") {
115 node.properties = {
116 ...node.properties,
117 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
118 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
119 };
120 }
121 node.children?.forEach(visit);
122 };
123
124 visit(tree);
125 markStandaloneImages(tree);
126 };
127}
128
129const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
130 ...defaultSchema,
131 attributes: {
132 ...defaultSchema.attributes,
133 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
134 code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
135 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
136 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
137 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
138 img: [
139 ...(defaultSchema.attributes?.img ?? []),
140 "dataLocalSrc",
141 "dataMarkdownTitle",
142 "dataStandalone",
143 ],
144 },
145 protocols: {
146 ...defaultSchema.protocols,
147 href: [
148 ...(defaultSchema.protocols?.href ?? []),
149 "file",
150 "t3-citation",
151 "t3-context",
152 THREAD_LINK_PROTOCOL,
153 ],
154 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
155 },
156} satisfies Parameters<typeof rehypeSanitize>[0];
157
158export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
159 remarkGfm,
160 remarkKeepWindowsPaths,
161 remarkGithubAlerts,
162 remarkNormalizeListItemIndentation,
163 remarkCodexDirectives,
164 remarkPreserveCodeMeta,
165 remarkNormalizeLinksAndTagInlineCode,
166];
167
168export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
169 remarkGfm,
170 remarkKeepWindowsPaths,
171 remarkGithubAlerts,
172 remarkNormalizeListItemIndentation,
173 remarkCodexDirectives,
174 remarkBreaks,
175 remarkPreserveCodeMeta,
176 remarkNormalizeLinksAndTagInlineCode,
177];
178
179/**
180 * The chat rehype pipeline, parsing raw HTML only when given rehype-raw. The web
181 * client loads it once a message has a tag, so parse5 stays out of its startup;
182 * a static import anywhere in this module would pull it back into that chunk.
183 */
184export function chatMarkdownRehypePlugins(rawHtml: Pluggable | null): PluggableList {
185 return [
186 rehypePreserveBareAnchorPlaceholders,
187 ...(rawHtml ? [rawHtml] : []),
188 rehypePreserveImageSourceMeta,
189 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
190 ];
191}
192
193let rehypeRaw: Pluggable | undefined;
194let rehypeRawPromise: Promise<Pluggable> | undefined;
195
196/**
197 * Loads rehype-raw for clients that keep parse5 out of their startup bundle. A failed
198 * load stays cached: browsers cache a failed dynamic import, so a retry cannot succeed.
199 */
200export function loadRehypeRaw(): Promise<Pluggable> {
201 rehypeRawPromise ??= import("rehype-raw").then((module) => (rehypeRaw = module.default));
202 return rehypeRawPromise;
203}
204
205/** rehype-raw once {@link loadRehypeRaw} has resolved, for synchronous renders. */
206export const loadedRehypeRaw = (): Pluggable | undefined => rehypeRaw;
207
208/** Raw HTML always starts with `<` and a letter, `/`, `!` or `?`; anything else parses the same without rehype-raw. */
209export function markdownMayContainRawHtml(markdown: string): boolean {
210 return /<[A-Za-z/!?]/.test(markdown);
211}
212
213type MarkdownAstNode = {
214 type?: string;
215 meta?: unknown;
216 url?: string;
217 data?: {
218 hProperties?: Record<string, unknown>;
219 };
220 children?: MarkdownAstNode[];
221};
222
223function remarkPreserveCodeMeta() {
224 return (tree: MarkdownAstNode) => {
225 const visit = (node: MarkdownAstNode) => {
226 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
227 node.data = {
228 ...node.data,
229 hProperties: {
230 ...node.data?.hProperties,
231 dataCodeMeta: node.meta.trim(),
232 },
233 };
234 }
235 node.children?.forEach(visit);
236 };
237
238 visit(tree);
239 };
240}
241
242function remarkNormalizeLinksAndTagInlineCode() {
243 return (tree: MarkdownAstNode) => {
244 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
245 if (
246 (node.type === "link" || node.type === "definition") &&
247 typeof node.url === "string" &&
248 /^[A-Za-z]:[\\/]/.test(node.url)
249 ) {
250 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
251 }
252 if (node.type === "inlineCode" && !insideLink) {
253 node.data = {
254 ...node.data,
255 hProperties: {
256 ...node.data?.hProperties,
257 dataInlineCode: "",
258 },
259 };
260 }
261 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
262 node.children?.forEach((child) => visit(child, childInsideLink));
263 };
264
265 visit(tree, false);
266 };
267}
268
269interface DestinationCompileContext {
270 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
271 resume(): string;
272 sliceSerialize(token: unknown): string;
273}
274
275function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
276 const decoded = this.resume();
277 const authored = this.sliceSerialize(token);
278 const node = this.stack.at(-1);
279 // Character references still need decoding, so those destinations keep the parsed URL.
280 if (node)
281 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
282}
283
284// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
285const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
286
287interface EscapeCompileContext {
288 readonly stack: ReadonlyArray<{
289 readonly type: string;
290 children?: Array<{ type: string; value?: string }>;
291 }>;
292}
293
294function keepWindowsPathEscape(this: EscapeCompileContext) {
295 const text = this.stack.at(-1)?.children?.at(-1);
296 if (text?.type !== "text" || text.value === undefined) return;
297 const before = text.value.slice(0, -1);
298 if (UNFINISHED_DRIVE_PATH.test(before)) text.value = `${before}\\${text.value.slice(-1)}`;
299}
300
301/**
302 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape. Every backslash in a
303 * Windows path is a separator, so link, image, and definition destinations that are
304 * Windows paths keep the text as written, and so do escapes inside drive paths in prose.
305 * Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
306 * `C:\x and \*this\*` must still read `*this*`.
307 */
308export function remarkKeepWindowsPaths(this: Processor) {
309 const data = this.data();
310 (data.fromMarkdownExtensions ??= []).push({
311 exit: {
312 resourceDestinationString: keepWindowsPathDestination,
313 definitionDestinationString: keepWindowsPathDestination,
314 characterEscape: keepWindowsPathEscape,
315 },
316 });
317}
318
319export function shouldPreserveAssistantLineBreaks(text: string): boolean {
320 return /^★ Insight(?:\s|─)/mu.test(text);
321}