Open History to see the last commit
1import { expect, it } from "vite-plus/test";
2import { type PluggableList, unified } from "unified";
3import rehypeRaw from "rehype-raw";
4import remarkParse from "remark-parse";
5import remarkRehype from "remark-rehype";
6import type { Root, RootContent } from "mdast";
7import {
8 CHAT_MARKDOWN_REHYPE_PLUGINS,
9 CHAT_MARKDOWN_REMARK_PLUGINS,
10 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
11 remarkEnableOrderedListNumbers,
12} from "./markdownPipeline.ts";
13
14it.each([
15 ["default", CHAT_MARKDOWN_REMARK_PLUGINS],
16 ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
17] as const)("preserves trailing underscores and tildes in bare URLs (%s)", (_, plugins) => {
18 const processor = unified().use(remarkParse).use(plugins);
19 const shape = (node: Root | RootContent): string => {
20 if (node.type === "text") return node.value;
21 if (node.type === "inlineCode") return `\`${node.value}\``;
22 if (node.type === "code") return `\`\`\`${node.value}\`\`\``;
23 const children = "children" in node ? node.children.map(shape).join("") : "";
24 if (node.type === "link") return `[${children}](${node.url})`;
25 if (node.type === "linkReference") return `[${children}][${node.identifier}]`;
26 if (node.type === "emphasis") return `*${children}*`;
27 if (node.type === "strong") return `**${children}**`;
28 if (node.type === "delete") return `~~${children}~~`;
29 return children;
30 };
31 const link = (url: string) => `[${url}](${/^www\./i.test(url) ? `http://${url}` : url})`;
32 for (const url of [
33 "https://x.com/dimasike_",
34 "http://example.com/name__",
35 "HTTPS://example.com/name_",
36 "https://example.com/a_(b)_",
37 "https://example.com/?name=value_",
38 "https://example.com/#section_",
39 "https://example.com/a_?name=value_#section_",
40 "https://example.com/name~",
41 "https://example.com/name~~",
42 "https://example.com/name_~",
43 "https://example.com/name~_",
44 "https://example.com/name__~~_",
45 "https://example.com/?name=value~",
46 "https://example.com/#section~",
47 "www.example.com/name_",
48 "www.example.com/name~_",
49 "WWW.example.com/name~~",
50 "https://example.com/name-",
51 "https://example.com/name/",
52 "https://example.com/name%5F",
53 "https://example.com/name%7E",
54 ]) {
55 for (const punctuation of ["", ".", ",", "!", "?", ":", ";", ")", "]", '"']) {
56 const markdown = `See ${url}${punctuation} next`;
57 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
58 `See ${link(url)}${punctuation} next`,
59 );
60 }
61 }
62 for (const [markdown, expected] of [
63 ["*https://x.com/dimasike_*", `*${link("https://x.com/dimasike_")}*`],
64 ["**https://x.com/dimasike_**", `**${link("https://x.com/dimasike_")}**`],
65 ["_https://x.com/dimasike_", `*${link("https://x.com/dimasike")}*`],
66 ["__https://x.com/dimasike__", `**${link("https://x.com/dimasike")}**`],
67 ["~~https://example.com/name_~~", `~~${link("https://example.com/name_")}~~`],
68 ["~~https://example.com/name~~", `~~${link("https://example.com/name")}~~`],
69 ["~https://example.com/name~", `~~${link("https://example.com/name")}~~`],
70 ["*https://example.com/name~*", `*${link("https://example.com/name~")}*`],
71 ["_https://example.com/name~_", `*${link("https://example.com/name~")}*`],
72 ["[test](https://example.com/name~)", "[test](https://example.com/name~)"],
73 ["[https://x.com/a](https://x.com/a)~_", `${link("https://x.com/a")}~_`],
74 ["<https://x.com/a>~_", `${link("https://x.com/a")}~_`],
75 ["[test][ref]~_\n\n[ref]: https://x.com/a~_", "[test][ref]~_"],
76 ["`https://example.com/name~_`", "`https://example.com/name~_`"],
77 ["```\nhttps://example.com/name~_\n```", "```https://example.com/name~_```"],
78 ["https\\://example.com/name~_", link("https://example.com/name~_")],
79 ["https://example.com/name. _~", `${link("https://example.com/name")}. _~`],
80 ["Mail person@example.com_", "Mail person@example.com_"],
81 ["Mail person@example.com ~_", "Mail [person@example.com](mailto:person@example.com) ~_"],
82 ["[test](https://x.com/dimasike_)", "[test](https://x.com/dimasike_)"],
83 ["[https://x.com/a](https://x.com/a)_", `${link("https://x.com/a")}_`],
84 ["<https://x.com/a>_", `${link("https://x.com/a")}_`],
85 ["[test][ref]_\n\n[ref]: https://x.com/a_", "[test][ref]_"],
86 ["`https://x.com/dimasike_`", "`https://x.com/dimasike_`"],
87 ["```\nhttps://x.com/dimasike_\n```", "```https://x.com/dimasike_```"],
88 ["https://x.com/a. _", `${link("https://x.com/a")}. _`],
89 ["https\\://x.com/dimasike_", link("https://x.com/dimasike_")],
90 ["https://x.com/a\\_", link("https://x.com/a\\_")],
91 ["https://x.com/a_", `${link("https://x.com/a_")};`],
92 [
93 "https://x.com/a_ https://x.com/b_",
94 `${link("https://x.com/a_")} ${link("https://x.com/b_")}`,
95 ],
96 ] as const) {
97 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
98 expected,
99 );
100 }
101 for (const url of ["https://x.com/dimasike_", "www.example.com/name~_"]) {
102 const markdown = `${url}, next`;
103 const boundary = { line: 1, column: url.length + 1, offset: url.length };
104 expect(processor.runSync(processor.parse(markdown), markdown)).toMatchObject({
105 children: [
106 {
107 children: [
108 {
109 type: "link",
110 url: /^www\./i.test(url) ? `http://${url}` : url,
111 position: { end: boundary },
112 children: [{ type: "text", value: url, position: { end: boundary } }],
113 },
114 { type: "text", value: ", next", position: { start: boundary } },
115 ],
116 },
117 ],
118 });
119 }
120});
121
122it("preserves in-app thread links through the shared Markdown sanitizer", () => {
123 const processor = unified()
124 .use(remarkParse)
125 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
126 .use(remarkRehype, { allowDangerousHtml: true })
127 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
128 const tree = processor.runSync(
129 processor.parse(
130 '[Open thread](t3-thread://v1/thread)\n\n<t3-thread://v2/environment/thread:a%3A1>\n\n<a href="javascript:alert(1)">Unsafe</a>',
131 ),
132 );
133 expect(tree.children[0]).toMatchObject({
134 tagName: "p",
135 children: [
136 {
137 tagName: "a",
138 properties: { href: "t3-thread://v1/thread" },
139 children: [{ type: "text", value: "Open thread" }],
140 },
141 ],
142 });
143 expect(tree.children[2]).toMatchObject({
144 tagName: "p",
145 children: [
146 {
147 tagName: "a",
148 properties: { href: "t3-thread://v2/environment/thread:a%3A1" },
149 children: [{ type: "text", value: "t3-thread://v2/environment/thread:a%3A1" }],
150 },
151 ],
152 });
153 expect(JSON.stringify(tree)).not.toContain("javascript:");
154});
155
156it("builds the tree rehype-raw builds for markdown without HTML", () => {
157 type Node = {
158 type: string;
159 tagName?: string;
160 value?: string;
161 position?: unknown;
162 data?: unknown;
163 children?: Node[];
164 };
165 // What the round trip changes that renders the same; see `needsHtmlParser`.
166 const comparable = (node: Node): Node => {
167 const { position, children, data, ...rest } = node;
168 const result: Node =
169 node.type === "text" || node.type === "root" ? rest : { ...rest, position, data };
170 if (!children) return result;
171 const merged: Node[] = [];
172 for (const child of children.map(comparable)) {
173 const last = merged.at(-1);
174 if (child.type === "text" && last?.type === "text") last.value += child.value ?? "";
175 else merged.push(child);
176 }
177 // Blank text inside a table moves in front of it; the JSX runtime drops it in tables.
178 const inTable = /^(?:table|thead|tbody|tfoot|tr)$/.test(node.tagName ?? "");
179 result.children = merged.filter(
180 (child, index) =>
181 child.type !== "text" ||
182 child.value?.trim() ||
183 !(inTable || merged[index + 1]?.tagName === "table"),
184 );
185 return result;
186 };
187 const tree = (rehypePlugins: typeof CHAT_MARKDOWN_REHYPE_PLUGINS, markdown: string) => {
188 const processor = unified()
189 .use(remarkParse)
190 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
191 .use(remarkRehype, { allowDangerousHtml: true })
192 .use(rehypePlugins);
193 return comparable(processor.runSync(processor.parse(markdown)) as Node);
194 };
195 const [first, , ...rest] = CHAT_MARKDOWN_REHYPE_PLUGINS;
196 const withRaw = [first!, rehypeRaw, ...rest];
197 for (const markdown of [
198 "- [ ] open\n- [x] done\n\nNote[^1]\n\n[^1]: The note.",
199 "| a | b |\n| :- | -: |\n| `c` |  |\n\n```ts title=x\nconst a = 1;\n```",
200 // The HTML parser moves the footnote's link out of the label's link.
201 "[note[^x]](https://example.com)\n\n[^x]: text",
202 "**a** **b**\r\n> - | a |\r\n> | - |\r\n> | b |\r\n\n-\tx\n\n y",
203 ]) {
204 expect(tree(CHAT_MARKDOWN_REHYPE_PLUGINS, markdown)).toEqual(tree(withRaw, markdown));
205 }
206});
207
208it("keeps local editor file links but not other schemes through the shared Markdown sanitizer", () => {
209 const processor = unified()
210 .use(remarkParse)
211 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
212 .use(remarkRehype, { allowDangerousHtml: true })
213 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
214 const tree = processor.runSync(
215 processor.parse(
216 [
217 "[cursor](cursor://file/Users/me/repo/file.md:3)",
218 "[code](vscode://file/Users/me/repo/file.md:3:7)",
219 "[insiders](vscode-insiders://file/Users/me/repo/file.md)",
220 "[unknown](foo://file/Users/me/repo/file.md)",
221 "[zed](zed://file/Users/me/repo/file.md)",
222 ].join(" "),
223 ),
224 );
225 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
226 const hrefs = ((tree.children[0] as Node).children ?? [])
227 .filter((node) => node.tagName === "a")
228 .map((node) => node.properties?.href);
229 expect(hrefs).toEqual([
230 "cursor://file/Users/me/repo/file.md:3",
231 "vscode://file/Users/me/repo/file.md:3:7",
232 "vscode-insiders://file/Users/me/repo/file.md",
233 undefined,
234 undefined,
235 ]);
236});
237
238it("keeps mixed-case local editor file links by lowercasing the scheme before sanitizing", () => {
239 const processor = unified()
240 .use(remarkParse)
241 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
242 .use(remarkRehype, { allowDangerousHtml: true })
243 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
244 const tree = processor.runSync(
245 processor.parse(
246 [
247 "[upper](VSCODE://file/Users/me/repo/file.md:3:7)",
248 "[mixed](Cursor://file/Users/me/repo/file.md:3)",
249 "[other](FOO://file/Users/me/repo/file.md)",
250 ].join(" "),
251 ),
252 );
253 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
254 const hrefs = ((tree.children[0] as Node).children ?? [])
255 .filter((node) => node.tagName === "a")
256 .map((node) => node.properties?.href);
257 expect(hrefs).toEqual([
258 "vscode://file/Users/me/repo/file.md:3:7",
259 "cursor://file/Users/me/repo/file.md:3",
260 undefined,
261 ]);
262});
263
264it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {
265 const processor = unified()
266 .use(remarkParse)
267 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
268 .use(remarkRehype, { allowDangerousHtml: true })
269 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
270 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
271 const text = (node: Node): string =>
272 node.type === "text"
273 ? (node.value ?? "")
274 : node.tagName === "code"
275 ? `<code>${(node.children ?? []).map(text).join("")}</code>`
276 : (node.children ?? []).map(text).join("");
277 const render = (markdown: string) => text(processor.runSync(processor.parse(markdown)) as Node);
278
279 expect(
280 render(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`),
281 ).toBe(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`);
282 expect(render(String.raw`Escaped C:\\Users\\me`)).toBe(String.raw`Escaped C:\\Users\\me`);
283 expect(render(String.raw`See C:\x and \*this\* and Note:\*that\*.`)).toBe(
284 String.raw`See C:\x and *this* and Note:*that*.`,
285 );
286 expect(render(String.raw`${"`"}C:\me\.t3${"`"} and C:\me\.t3`)).toBe(
287 String.raw`<code>C:\me\.t3</code> and C:\me\.t3`,
288 );
289});
290
291it("keeps an image on its own line under a label but leaves inline images inline", () => {
292 const processor = unified()
293 .use(remarkParse)
294 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
295 .use(remarkRehype, { allowDangerousHtml: true })
296 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
297 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
298 const shape = (node: Node): string =>
299 node.type === "text"
300 ? (node.value ?? "")
301 : node.tagName === "br" || node.tagName === "img"
302 ? `<${node.tagName}>`
303 : (node.children ?? []).map(shape).join("");
304 const render = (markdown: string) => shape(processor.runSync(processor.parse(markdown)) as Node);
305
306 expect(
307 render("**Palette**\n\n**Hero** (dark)\n"),
308 ).toBe("Palette<br>\n<img><br>\nHero (dark)<br>\n<img>");
309 expect(render("Built [](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
310 expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
311});
312
313it("keeps the number written on each ordered list item only when enabled", () => {
314 type Node = { tagName?: string; properties?: { value?: unknown }; children?: Node[] };
315 const values = (node: Node): unknown[] => [
316 ...(node.tagName === "li" ? [node.properties?.value] : []),
317 ...(node.children ?? []).flatMap(values),
318 ];
319 const renderer = (plugins: PluggableList) => {
320 const processor = unified()
321 .use(remarkParse)
322 .use(plugins)
323 .use(remarkRehype, { allowDangerousHtml: true });
324 return (markdown: string) =>
325 values(processor.runSync(processor.parse(markdown), markdown) as Node);
326 };
327 const render = renderer([
328 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
329 remarkEnableOrderedListNumbers,
330 ]);
331
332 expect(render("3. first\n5. second\n6. third")).toEqual([undefined, "5", undefined]);
333 expect(render("1. one\n1. one again")).toEqual([undefined, "1"]);
334 expect(render("> 1. quoted\n> 4. skipped")).toEqual([undefined, "4"]);
335 expect(render("1. outer\n 1. nested\n 7. jump\n9. back")).toEqual([
336 undefined,
337 undefined,
338 "7",
339 "9",
340 ]);
341 expect(render("1. one\n2. two\n- bullet")).toEqual([undefined, undefined, undefined]);
342 expect(render("- first block\n\n 3. first\n 5. second")).toEqual([
343 undefined,
344 undefined,
345 "5",
346 ]);
347 expect(
348 renderer(CHAT_MARKDOWN_REMARK_PLUGINS)(
349 "3. first\n5. second\n\n- first block\n\n 3. first\n 5. second",
350 ),
351 ).toEqual([undefined, undefined, undefined, undefined, undefined]);
352});
353
354it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
355 const processor = unified()
356 .use(remarkParse)
357 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
358 .use(remarkRehype, { allowDangerousHtml: true })
359 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
360 type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
361 const tags = (node: Node): string[] => [
362 ...(node.tagName ? [node.tagName] : []),
363 ...(node.children ?? []).flatMap(tags),
364 ];
365 const images = (node: Node): Node[] =>
366 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
367 const tree = processor.runSync(
368 processor.parse(
369 [
370 "<picture>",
371 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/dark@2x.webp 2x">',
372 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',
373 ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
374 ' <img src="docs/light.webp" alt="Studio">',
375 "</picture>",
376 "",
377 '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
378 "",
379 String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,
380 ].join("\n"),
381 ),
382 ) as Node;
383
384 expect(tags(tree)).toEqual(["picture", "img", "p", "picture", "img", "p", "picture", "img"]);
385 expect(images(tree).map((image) => image.properties)).toEqual([
386 { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp" },
387 { src: "docs/dark.webp" },
388 { dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },
389 ]);
390});