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

markdownPipeline.test.ts

348 lines14.6 KB

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