Open History to see the last commit
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 );
29}
30
31const STANDALONE_IMAGE_BLOCKS = new Set([
32 "p",
33 "div",
34 "li",
35 "td",
36 "th",
37 "figure",
38 "center",
39 "blockquote",
40]);
41
42function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
43 const children = meaningfulHastChildren(node);
44 if (children.length !== 1) return undefined;
45 const only = children[0];
46 if (only?.type !== "element") return undefined;
47 if (only.tagName === "img") return only;
48 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
49 ? soleImageDescendant(only)
50 : undefined;
51}
52
53function markStandaloneImages(node: MarkdownImageHastNode) {
54 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
55 const image = soleImageDescendant(node);
56 if (image) image.properties = { ...image.properties, dataStandalone: true };
57 }
58 node.children?.forEach((child) => {
59 if (child.type === "element") markStandaloneImages(child);
60 });
61}
62
63function rehypePreserveBareAnchorPlaceholders() {
64 return (tree: MarkdownImageHastNode) => {
65 const anchors: Array<MarkdownImageHastNode | null> = [];
66 let rawTextTag: string | undefined;
67 const visit = (node: MarkdownImageHastNode) => {
68 if (node.type === "raw" && typeof node.value === "string") {
69 // Raw blocks can contain several tags. Consume whole tags, quoted attributes,
70 // and comments so text resembling a closing anchor cannot pair a placeholder.
71 const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
72 let offset = 0;
73 while (rawTextTag !== "plaintext") {
74 // Raw text ends at its closing tag even inside comment-looking text.
75 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
76 matcher.lastIndex = offset;
77 const match = matcher.exec(node.value);
78 if (!match) break;
79 const [tag] = match;
80 offset = matcher.lastIndex;
81 if (rawTextTag) {
82 rawTextTag = undefined;
83 continue;
84 }
85 if (tag.startsWith("<!--")) continue;
86 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
87 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
88 if (
89 opening &&
90 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
91 ) {
92 rawTextTag = opening;
93 } else if (opening === "a") {
94 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
95 } else if (closing === "a") {
96 anchors.pop();
97 }
98 }
99 }
100 node.children?.forEach(visit);
101 };
102
103 visit(tree);
104 for (const anchor of anchors) {
105 if (anchor) anchor.type = "text";
106 }
107 };
108}
109
110function rehypePreserveImageSourceMeta() {
111 return (tree: MarkdownImageHastNode) => {
112 const visit = (node: MarkdownImageHastNode) => {
113 const src = node.properties?.src;
114 const title = node.properties?.title;
115 if (node.type === "element" && node.tagName === "img") {
116 node.properties = {
117 ...node.properties,
118 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
119 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
120 };
121 }
122 node.children?.forEach(visit);
123 };
124
125 visit(tree);
126 markStandaloneImages(tree);
127 };
128}
129
130const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
131 ...defaultSchema,
132 attributes: {
133 ...defaultSchema.attributes,
134 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
135 code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
136 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
137 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
138 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
139 img: [
140 ...(defaultSchema.attributes?.img ?? []),
141 "dataLocalSrc",
142 "dataMarkdownTitle",
143 "dataStandalone",
144 ],
145 },
146 protocols: {
147 ...defaultSchema.protocols,
148 href: [
149 ...(defaultSchema.protocols?.href ?? []),
150 "file",
151 "t3-citation",
152 "t3-context",
153 THREAD_LINK_PROTOCOL,
154 ],
155 src: [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"],
156 },
157} satisfies Parameters<typeof rehypeSanitize>[0];
158
159export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
160 remarkGfm,
161 remarkKeepWindowsPathDestinations,
162 remarkGithubAlerts,
163 remarkNormalizeListItemIndentation,
164 remarkCodexDirectives,
165 remarkPreserveCodeMeta,
166 remarkNormalizeLinksAndTagInlineCode,
167];
168
169export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
170 remarkGfm,
171 remarkKeepWindowsPathDestinations,
172 remarkGithubAlerts,
173 remarkNormalizeListItemIndentation,
174 remarkCodexDirectives,
175 remarkBreaks,
176 remarkPreserveCodeMeta,
177 remarkNormalizeLinksAndTagInlineCode,
178];
179
180export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
181 rehypePreserveBareAnchorPlaceholders,
182 rehypeRaw,
183 rehypePreserveImageSourceMeta,
184 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
185];
186
187type MarkdownAstNode = {
188 type?: string;
189 meta?: unknown;
190 url?: string;
191 data?: {
192 hProperties?: Record<string, unknown>;
193 };
194 children?: MarkdownAstNode[];
195};
196
197function remarkPreserveCodeMeta() {
198 return (tree: MarkdownAstNode) => {
199 const visit = (node: MarkdownAstNode) => {
200 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
201 node.data = {
202 ...node.data,
203 hProperties: {
204 ...node.data?.hProperties,
205 dataCodeMeta: node.meta.trim(),
206 },
207 };
208 }
209 node.children?.forEach(visit);
210 };
211
212 visit(tree);
213 };
214}
215
216function remarkNormalizeLinksAndTagInlineCode() {
217 return (tree: MarkdownAstNode) => {
218 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
219 if (
220 (node.type === "link" || node.type === "definition") &&
221 typeof node.url === "string" &&
222 /^[A-Za-z]:[\\/]/.test(node.url)
223 ) {
224 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
225 }
226 if (node.type === "inlineCode" && !insideLink) {
227 node.data = {
228 ...node.data,
229 hProperties: {
230 ...node.data?.hProperties,
231 dataInlineCode: "",
232 },
233 };
234 }
235 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
236 node.children?.forEach((child) => visit(child, childInsideLink));
237 };
238
239 visit(tree, false);
240 };
241}
242
243interface DestinationCompileContext {
244 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
245 resume(): string;
246 sliceSerialize(token: unknown): string;
247}
248
249function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
250 const decoded = this.resume();
251 const authored = this.sliceSerialize(token);
252 const node = this.stack.at(-1);
253 // Character references still need decoding, so those destinations keep the parsed URL.
254 if (node)
255 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
256}
257
258/**
259 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape, even in a link
260 * destination. Every backslash in a Windows path is a separator, so link, image, and
261 * definition destinations that are Windows paths keep the text as written.
262 */
263function remarkKeepWindowsPathDestinations(this: Processor) {
264 const data = this.data();
265 (data.fromMarkdownExtensions ??= []).push({
266 exit: {
267 resourceDestinationString: keepWindowsPathDestination,
268 definitionDestinationString: keepWindowsPathDestination,
269 },
270 });
271}
272
273export function shouldPreserveAssistantLineBreaks(text: string): boolean {
274 return /^★ Insight(?:\s|─)/mu.test(text);
275}