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

markdownHtml.test.ts

499 lines20.7 KB

1import { describe, expect, it } from "vite-plus/test";
2import { renderCodexInlineDirectivesAsMarkdown } from "@t3tools/shared/codexMarkdownDirectives";
3import {
4 markdownForNativeParsing,
5 markdownForNativeRendering,
6 markdownHtmlContent,
7 markdownWithHtml,
8 markdownWithFileEmbeds,
9 parseMarkdownDocument,
10 type MarkdownNode,
11} from "./markdownDocument";
12import { markdownImageSources } from "./markdownImageSources";
13import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia";
14import { resolveMarkdownLinkPresentation } from "./markdownLinks";
15import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
16import { EnvironmentId, ThreadId } from "@t3tools/contracts";
17import { parseEnrichedMarkdown as parseMarkdown } from "./parseEnrichedMarkdown.test-support";
18​
19describe("HTML in native Markdown", () => {
20 it.each([
21 [":codex-followup[# Draft]", ["# Draft"]],
22 ["Intro<br>:codex-followup[# Draft]", ["Intro", "# Draft"]],
23 [":codex-followup[ ## Draft]", ["## Draft"]],
24 ])("keeps a Codex follow-up hash literal in %j", async (directive, expectedText) => {
25 const source = `${directive}{prompt="Draft it"}`;
26 const markdown = renderCodexInlineDirectivesAsMarkdown(source);
27 for (const native of [
28 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
29 markdownForNativeParsing(markdown),
30 ]) {
31 const tree = await parseMarkdown(native);
32 expect(tree.children?.map(({ type }) => type)).toEqual(["Paragraph"]);
33 expect(
34 tree.children?.[0]?.children
35 ?.filter(({ type }) => type === "Text")
36 .map(({ content }) => content),
37 ).toEqual(expectedText);
38 }
39 });
40​
41 it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => {
42 expect(
43 markdownHtmlContent(
44 '<img width="900" alt="Before > after [settings]" src="https://example.com/before.png?a=1&amp;b=2" />',
45 ),
46 ).toBe("![Before > after \\[settings\\]](<https://example.com/before.png?a=1\\&b=2>)");
47 expect(
48 markdownHtmlContent(
49 "<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
50 ),
51 ).toBe("[![Review](<https://example.com/banner.svg>)](<https://example.com>)");
52 });
53​
54 it.each(["\r\n", "\r"])("strips HTML destination line endings (%j)", (lineEnding) => {
55 const link = `<a href="https://example.com/${lineEnding}foo">link</a>`;
56 const image = `<img src="https://example.com/${lineEnding}foo.png" alt="pic">`;
57​
58 expect(markdownWithHtml(link)).toBe("[link](<https://example.com/foo>)");
59 expect(markdownWithHtml(image)).toBe("![pic](<https://example.com/foo.png>)");
60 expect(parseMarkdownDocument(link).children).toMatchObject([
61 { type: "paragraph", children: [{ type: "link", url: "https://example.com/foo" }] },
62 ]);
63 });
64​
65 it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
66 const markdown =
67 '<img alt="&amp;lt;" src="https://example.com/shot.png?label=&amp;lt;&amp;sig=a%26b">';
68 expect(markdownWithHtml(markdown)).toBe(
69 "![\\&lt;](<https://example.com/shot.png?label=\\&lt;\\&sig=a%26b>)",
70 );
71 expect(markdownImageSources(markdown)).toEqual([
72 "https://example.com/shot.png?label=&lt;&sig=a%26b",
73 ]);
74 const paragraph = parseMarkdownDocument(markdown).children[0];
75 expect(paragraph?.type).toBe("paragraph");
76 if (paragraph?.type === "paragraph")
77 expect(paragraph.children[0]).toMatchObject({ type: "image", alt: "&lt;" });
78 });
79​
80 it("ignores code delimiters in HTML attributes and comments when collecting screenshots", () => {
81 const markdown =
82 '<details data-example="`">\n<summary>Proof</summary>\n<img src="https://example.com/shot.png" alt="Screenshot">\n<!-- ` -->\n</details>';
83 expect(markdownHtmlContent(markdown)).toContain(
84 "![Screenshot](<https://example.com/shot.png>)",
85 );
86 expect(markdownImageSources(markdown)).toEqual(["https://example.com/shot.png"]);
87 expect(markdownWithHtml(markdown)).not.toContain("<img");
88 });
89​
90 it("removes bot metadata and details wrappers while keeping the content", () => {
91 const markdown =
92 "<!-- generated bot metadata -->\n<details>\n<summary>Walkthrough</summary>\n\n## Changes\n\nText\n\n</details>";
93 const result = markdownWithHtml(markdown);
94 expect(result).not.toContain("<!--");
95 expect(result).not.toContain("<details>");
96 expect(result).toContain("**Walkthrough**");
97 expect(result).toContain("## Changes");
98 expect(parseMarkdownDocument(markdown).children.some((node) => node.type === "html")).toBe(
99 false,
100 );
101 });
102​
103 it("collects HTML and Markdown screenshots while leaving inline and fenced code literal", () => {
104 const markdown =
105 '```html\n<img src="literal.png">\n```\n\nUse `<img src="inline.png">` here.\n\n<img src="one.png">\n\n![Two](two.png)\n\n<img src="one.png">';
106 expect(markdownImageSources(markdown)).toEqual(["one.png", "two.png"]);
107 const result = markdownWithHtml(markdown);
108 expect(result).toContain('```html\n<img src="literal.png">\n```');
109 expect(result).toContain('`<img src="inline.png">`');
110 });
111​
112 it("treats an unclosed fence in an HTML block as code through the end", () => {
113 // Sized so the quadratic rescan cannot finish within the test timeout.
114 const fences = Array.from({ length: 40_000 }, () => "```x y").join("\n");
115 const markdown = `<details>\n<img src="before.png">\n${fences}\n<img src="after.png">\n</details>`;
116 const result = markdownHtmlContent(markdown);
117 expect(result).toContain("![](<before.png>)");
118 expect(result).not.toContain("<details>");
119 expect(result).toContain('<img src="after.png">\n</details>');
120 });
121​
122 it("keeps <br> line breaks in a table cell without breaking the row", () => {
123 const markdown =
124 "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |\n| • One<br/>• Two<BR />**Three** | `<br>` |";
125 // md4c decodes the reference to a newline in the cell's text, as remark does.
126 expect(markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX)).toContain(
127 "| • One&#10;• Two&#10;**Three** | `<br>` |",
128 );
129 const table = parseMarkdownDocument(markdown).children[0];
130 expect(table?.type).toBe("table");
131 if (table?.type !== "table") return;
132 expect(table.children).toHaveLength(3);
133 expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2]);
134 expect(table.children[1]?.children[1]?.children).toMatchObject([
135 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
136 { type: "text", value: "\n" },
137 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
138 ]);
139 expect(table.children[2]?.children).toMatchObject([
140 { children: [{ value: "• One\n• Two\n" }, { type: "strong" }] },
141 { children: [{ type: "inlineCode", value: "<br>" }] },
142 ]);
143 });
144​
145 it.each([
146 "one<p>two</p>",
147 "one<div>two</div>",
148 "one<summary>two</summary>",
149 "<p>one</p><p>two</p>",
150 ])("keeps a table row intact when a cell contains block HTML: %s", async (cell) => {
151 const native = await parseMarkdown(
152 markdownForNativeRendering(
153 `| A | B |\n| - | - |\n| ${cell} | x |`,
154 ENRICHED_INLINE_FILE_LINK_REGEX,
155 ),
156 );
157 const text = (node: { content?: string; children?: unknown[] }): string =>
158 (node.content ?? "") +
159 (node.children ?? []).map((child) => text(child as typeof node)).join("");
160 expect(native.children).toHaveLength(1);
161 expect(native.children?.[0]?.children?.[1]?.children?.[0]?.children?.map(text)).toEqual([
162 expect.stringMatching(/one\s*two/),
163 "x",
164 ]);
165 });
166​
167 it("keeps a table row intact when an anchor href contains a pipe", () => {
168 const document = parseMarkdownDocument(
169 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1&#124;2'>Open</a> | done |",
170 );
171 const table = document.children[0];
172 expect(table?.type).toBe("table");
173 if (table?.type !== "table") return;
174 expect(table.children[1]?.children).toMatchObject([
175 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
176 { children: [{ value: "done" }] },
177 ]);
178 });
179​
180 it("keeps anchor text unlinked for unsafe hrefs", () => {
181 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
182 });
183​
184 it("keeps anchor labels and escaped bangs intact across nested formatting and table cells", () => {
185 const markdown =
186 '> **!<a href="https://x.test">[one]</a>** and <span>tail</span>\n\n| A |\n| - |\n| !<a href="https://x.test">x[y]</a><br><img src="x.png"> |';
187 expect(markdownWithHtml(markdown)).toBe(
188 "> **\\![\\[one\\]](<https://x.test>)** and tail\n\n| A |\n| - |\n| \\![x\\[y\\]](<https://x.test>)&#10;![](<x.png>) |",
189 );
190 expect(
191 markdownWithHtml(
192 String.raw`Before \!<a href="https://x.test">escaped</a> \\!<a href="mailto:a@b">even</a>`,
193 ),
194 ).toBe(String.raw`Before \![escaped](<https://x.test>) \\\![even](<mailto:a@b>)`);
195 });
196​
197 it("converts separated HTML without changing code examples or an unfinished tag", () => {
198 const literal = '`<br>`\n\n```html\n<img src="literal.png">\n```\n\n<broken';
199 expect(markdownWithHtml(literal)).toBe(literal);
200 const rows = Array.from(
201 { length: 100 },
202 (_, index) => `row ${index} <span>text</span><br>!<a href="https://x.test/${index}">go</a>`,
203 );
204 const expected = Array.from(
205 { length: 100 },
206 (_, index) => `row ${index} text \n\\![go](<https://x.test/${index}>)`,
207 );
208 expect(markdownWithHtml(rows.join("\n\n") + "\n\n" + literal)).toBe(
209 expected.join("\n\n") + "\n\n" + literal,
210 );
211 });
212});
213​
214describe("file embeds in native thread and file Markdown", () => {
215 const input = {
216 environmentId: EnvironmentId.make("environment-1"),
217 threadId: ThreadId.make("thread-1"),
218 workspaceRoot: "/repo",
219 };
220 const assets = (markdown: string) => {
221 const result: MarkdownNode[] = [];
222 const visit = (node: MarkdownNode) => {
223 if (node.type === "link" || node.type === "image") result.push(node);
224 if ("children" in node) node.children.forEach(visit);
225 };
226 visit(parseMarkdownDocument(markdown));
227 return result;
228 };
229​
230 it.each([
231 [
232 "[![sheet](./report.csv)](https://example.com/download)",
233 "report.csv",
234 "https://example.com/download",
235 ],
236 ["[![report](./report.pdf)](./report.pdf)", "report.pdf", "./report.pdf"],
237 [
238 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
239 "report.csv",
240 "https://example.com/download",
241 ],
242 ])("keeps the enclosing link for %s", async (source, filename, target) => {
243 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
244 markdownFileEmbedLabel(href, input, standalone),
245 );
246 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
247 {
248 type: "Paragraph",
249 children: [
250 {
251 type: "Link",
252 attributes: { url: target },
253 children: [{ type: "Text", content: filename }],
254 },
255 ],
256 },
257 ]);
258 });
259​
260 it.each(["f", "F", "File Label", "file label"])(
261 "uses the first reference definition for %s",
262 async (identifier) => {
263 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
264 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
265 markdownFileEmbedLabel(href, input, standalone),
266 );
267 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
268 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
269 {
270 type: "Paragraph",
271 children: [
272 {
273 type: "Link",
274 attributes: { url: "./report.csv" },
275 children: [{ type: "Text", content: "report.csv" }],
276 },
277 ],
278 },
279 ]);
280 expect((await parseMarkdown(source)).children).toMatchObject([
281 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
282 ]);
283 },
284 );
285​
286 it.each([
287 "report.csv",
288 "report.tsv",
289 "report.pdf",
290 "report.docx",
291 "report.xlsx",
292 "report.pptx",
293 "report.unknown",
294 "main.tf",
295 "schema.prisma",
296 "index.astro",
297 "main.zig",
298 "Containerfile",
299 "sound.mp3",
300 "clip.mp4",
301 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
302 for (const href of [
303 `./${name}`,
304 `/tmp/${name}`,
305 `file:///tmp/${name}`,
306 `https://cdn.example.com/${name}?signature=a%2fb`,
307 ]) {
308 if (name === "Containerfile" && href.startsWith("https:")) continue;
309 for (const source of [
310 `download: ![sheet](<${href}>)`,
311 `- ![sheet](<${href}>)`,
312 `| file |\n| --- |\n| ![sheet](<${href}>) |`,
313 `download: ![sheet][file]\n\n[file]: <${href}>`,
314 `download: <img src="${href}" alt="sheet">`,
315 ]) {
316 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
317 markdownFileEmbedLabel(url, input, standalone),
318 );
319 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
320 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
321 else
322 expect(assets(converted.markdown)).toMatchObject([
323 { type: "link", url: href, children: [{ type: "text", value: name }] },
324 ]);
325 expect(converted.fileHrefs.has(href)).toBe(!image);
326 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
327 if (
328 !href.startsWith("https:") &&
329 !name.endsWith(".pdf") &&
330 !name.endsWith(".mp3") &&
331 !name.endsWith(".mp4")
332 ) {
333 expect(preview?.kind).toBe("file");
334 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
335 }
336 }
337 }
338 });
339​
340 it("gives each image on its own line its own native paragraph", async () => {
341 const images =
342 "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]";
343 const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`;
344 const paragraphs = (
345 await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX))
346 ).children?.map((block) => block.children?.map((child) => child.type).join(" "));
347 expect(paragraphs).toEqual([
348 "Text",
349 "Image",
350 "Image",
351 "Image",
352 "Image",
353 "Image",
354 "Image",
355 "Text",
356 ]);
357 expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe(
358 "![a](./a.png)\r\n\r\n![b](./b.png)",
359 );
360 expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe(
361 "![a](./a.png)\r\r![b](./b.png)",
362 );
363 expect(
364 markdownForNativeParsing(
365 "**Dialog** (native) ![a](./a.png)\n\n**Label**\n![b](./b.png)\nBuilt ![ci](./ci.svg) ok\n\nCI [![ci](./ci.svg)](https://ci)",
366 ),
367 ).toBe(
368 "**Dialog** (native)\n\n![a](./a.png)\n\n**Label**\n\n![b](./b.png)\n\nBuilt ![ci](./ci.svg) ok\n\nCI [![ci](./ci.svg)](https://ci)",
369 );
370 });
371​
372 it("retains standalone audio players and image/video embeds in threads", () => {
373 const source =
374 "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)";
375 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
376 markdownFileEmbedLabel(href, input, standalone),
377 );
378 expect(converted.markdown).toBe(source);
379 expect(converted.fileHrefs.size).toBe(0);
380 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
381 });
382​
383 it("uses audio filenames in file previews and draft workspaces", () => {
384 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
385 const converted = markdownWithFileEmbeds("![sound](./sound.mp3)", (href) =>
386 markdownFileEmbedLabel(href, draft, false),
387 );
388 expect(assets(converted.markdown)).toMatchObject([
389 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
390 ]);
391 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
392 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
393 });
394 });
395​
396 it("keeps captured images on the image path and documents on filename links", () => {
397 const captured = { ...input, captured: true };
398 const converted = markdownWithFileEmbeds(
399 "![photo](./photo.png)\n\n![clip](./clip.mp4)\n\n![sheet](./report.csv)",
400 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
401 );
402 expect(assets(converted.markdown)).toMatchObject([
403 { type: "image", url: "./photo.png" },
404 { type: "image", url: "./clip.mp4" },
405 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
406 ]);
407 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
408 });
409​
410 it("preserves table structure and filename punctuation", () => {
411 const source = "| file |\n| --- |\n| ![sheet](./report%5B1%5D%26%7C.csv) |";
412 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
413 markdownFileEmbedLabel(href, input, standalone),
414 );
415 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
416 expect(assets(converted.markdown)).toMatchObject([
417 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
418 ]);
419 });
420​
421 it("keeps authored positions, signed URLs, and code examples literal", () => {
422 const href = "https://cdn.example.com/report%23one%2520.csv?name=&lt;&signature=a%2fb";
423 const source = `![report](<${href.replaceAll("&", "\\&")}>)\n\n![source](./main.tf#L42C3)\n\n\`![sheet](./literal.csv)\`\n\n\`\`\`md\n![sheet](./fenced.csv)\n\`\`\``;
424 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
425 markdownFileEmbedLabel(url, input, standalone),
426 );
427 expect(assets(converted.markdown)).toMatchObject([
428 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
429 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
430 ]);
431 expect(converted.markdown).toContain("`![sheet](./literal.csv)`");
432 expect(converted.markdown).toContain("```md\n![sheet](./fenced.csv)\n```");
433 expect(converted.fileHrefs.has(href)).toBe(true);
434 });
435});
436​
437describe("Windows paths in native Markdown", () => {
438 // regression: #23722 Markdown escapes ate the separator before `.t3` and `_build`
439 it("keeps backslashes in Windows image and link destinations", async () => {
440 const image = String.raw`C:\work\.t3\_build\shot.png`;
441 const link = String.raw`\\server\share\.t3\notes.md`;
442 const ampLeaf = String.raw`C:\work\&report.pdf`;
443 const htmlAmpLeaf = String.raw`C:\work\&report.png`;
444 const htmlLeadingNewlineAmp = String.raw`C:\work\a&b.png`;
445 const markdown = [
446 `![shot](${image} "Shot")`,
447 String.raw`![paren](C:\a\)b.png)`,
448 `[notes](<${link}>)`,
449 `[Report](${ampLeaf})`,
450 `<img src="${image}">`,
451 String.raw`![amp](C:\R&D\.t3\a&amp;b.png)`,
452 String.raw`<img src="C:\R&amp;D\.t3\b.png">`,
453 String.raw`<img src="C:\work\&amp;report.png">`,
454 `<img src="\n${String.raw`C:\work\a&amp;b.png`}">`,
455 "> ![quoted](\n> " + image + ")",
456 ].join("\n\n");
457​
458 const native = await parseMarkdown(
459 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
460 );
461 const urls: string[] = [];
462 const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => {
463 if (node.attributes?.url) urls.push(node.attributes.url);
464 node.children?.forEach((child) => collect(child as typeof node));
465 };
466 collect(native);
467 const paren = String.raw`C:\a\)b.png`;
468 const amp = String.raw`C:\R&D\.t3\a&b.png`;
469 const htmlAmp = String.raw`C:\R&D\.t3\b.png`;
470 expect(urls).toEqual([
471 image,
472 paren,
473 link,
474 ampLeaf,
475 image,
476 amp,
477 htmlAmp,
478 htmlAmpLeaf,
479 htmlLeadingNewlineAmp,
480 image,
481 ]);
482 expect(markdownImageSources(markdown)).toEqual([
483 image,
484 paren,
485 amp,
486 htmlAmp,
487 htmlAmpLeaf,
488 htmlLeadingNewlineAmp,
489 ]);
490 });
491});
492​
493it("keeps backslashes in drive paths in mobile Markdown prose", () => {
494 const path = String.raw`Saved to C:\Users\me\.t3\_build\shot.png and C:/work\.config.`;
495​
496 expect(parseMarkdownDocument(String.raw`${path} Then \*this\*.`).children).toMatchObject([
497 { type: "paragraph", children: [{ type: "text", value: `${path} Then *this*.` }] },
498 ]);
499});