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

markdownHtml.test.ts

350 lines14.7 KB

1import { describe, expect, it } from "vite-plus/test";
2import {
3 markdownForNativeRendering,
4 markdownHtmlContent,
5 markdownWithHtml,
6 markdownWithFileEmbeds,
7 parseMarkdownDocument,
8 type MarkdownNode,
9} from "./markdownDocument";
10import { markdownImageSources } from "./markdownImageSources";
11import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia";
12import { resolveMarkdownLinkPresentation } from "./markdownLinks";
13import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
14import { EnvironmentId, ThreadId } from "@t3tools/contracts";
15import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
16​
17describe("HTML in native Markdown", () => {
18 it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => {
19 expect(
20 markdownHtmlContent(
21 '<img width="900" alt="Before > after [settings]" src="https://example.com/before.png?a=1&amp;b=2" />',
22 ),
23 ).toBe("![Before > after \\[settings\\]](<https://example.com/before.png?a=1\\&b=2>)");
24 expect(
25 markdownHtmlContent(
26 "<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
27 ),
28 ).toBe("[![Review](<https://example.com/banner.svg>)](<https://example.com>)");
29 });
30​
31 it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
32 const markdown =
33 '<img alt="&amp;lt;" src="https://example.com/shot.png?label=&amp;lt;&amp;sig=a%26b">';
34 expect(markdownWithHtml(markdown)).toBe(
35 "![\\&lt;](<https://example.com/shot.png?label=\\&lt;\\&sig=a%26b>)",
36 );
37 expect(markdownImageSources(markdown)).toEqual([
38 "https://example.com/shot.png?label=&lt;&sig=a%26b",
39 ]);
40 const paragraph = parseMarkdownDocument(markdown).children[0];
41 expect(paragraph?.type).toBe("paragraph");
42 if (paragraph?.type === "paragraph")
43 expect(paragraph.children[0]).toMatchObject({ type: "image", alt: "&lt;" });
44 });
45​
46 it("ignores code delimiters in HTML attributes and comments when collecting screenshots", () => {
47 const markdown =
48 '<details data-example="`">\n<summary>Proof</summary>\n<img src="https://example.com/shot.png" alt="Screenshot">\n<!-- ` -->\n</details>';
49 expect(markdownHtmlContent(markdown)).toContain(
50 "![Screenshot](<https://example.com/shot.png>)",
51 );
52 expect(markdownImageSources(markdown)).toEqual(["https://example.com/shot.png"]);
53 expect(markdownWithHtml(markdown)).not.toContain("<img");
54 });
55​
56 it("removes bot metadata and details wrappers while keeping the content", () => {
57 const markdown =
58 "<!-- generated bot metadata -->\n<details>\n<summary>Walkthrough</summary>\n\n## Changes\n\nText\n\n</details>";
59 const result = markdownWithHtml(markdown);
60 expect(result).not.toContain("<!--");
61 expect(result).not.toContain("<details>");
62 expect(result).toContain("**Walkthrough**");
63 expect(result).toContain("## Changes");
64 expect(parseMarkdownDocument(markdown).children.some((node) => node.type === "html")).toBe(
65 false,
66 );
67 });
68​
69 it("collects HTML and Markdown screenshots while leaving inline and fenced code literal", () => {
70 const markdown =
71 '```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">';
72 expect(markdownImageSources(markdown)).toEqual(["one.png", "two.png"]);
73 const result = markdownWithHtml(markdown);
74 expect(result).toContain('```html\n<img src="literal.png">\n```');
75 expect(result).toContain('`<img src="inline.png">`');
76 });
77​
78 it("treats an unclosed fence in an HTML block as code through the end", () => {
79 // Sized so the quadratic rescan cannot finish within the test timeout.
80 const fences = Array.from({ length: 40_000 }, () => "```x y").join("\n");
81 const markdown = `<details>\n<img src="before.png">\n${fences}\n<img src="after.png">\n</details>`;
82 const result = markdownHtmlContent(markdown);
83 expect(result).toContain("![](<before.png>)");
84 expect(result).not.toContain("<details>");
85 expect(result).toContain('<img src="after.png">\n</details>');
86 });
87​
88 it("links HTML anchors in a table cell without breaking the row at <br>", () => {
89 const document = parseMarkdownDocument(
90 "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |",
91 );
92 const table = document.children[0];
93 expect(table?.type).toBe("table");
94 if (table?.type !== "table") return;
95 expect(table.children).toHaveLength(2);
96 expect(table.children[1]?.children[1]?.children).toMatchObject([
97 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
98 { type: "text", value: " " },
99 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
100 ]);
101 });
102​
103 it("keeps a table row intact when an anchor href contains a pipe", () => {
104 const document = parseMarkdownDocument(
105 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1&#124;2'>Open</a> | done |",
106 );
107 const table = document.children[0];
108 expect(table?.type).toBe("table");
109 if (table?.type !== "table") return;
110 expect(table.children[1]?.children).toMatchObject([
111 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
112 { children: [{ value: "done" }] },
113 ]);
114 });
115​
116 it("keeps anchor text unlinked for unsafe hrefs", () => {
117 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
118 });
119});
120​
121describe("file embeds in native thread and file Markdown", () => {
122 const input = {
123 environmentId: EnvironmentId.make("environment-1"),
124 threadId: ThreadId.make("thread-1"),
125 workspaceRoot: "/repo",
126 };
127 const assets = (markdown: string) => {
128 const result: MarkdownNode[] = [];
129 const visit = (node: MarkdownNode) => {
130 if (node.type === "link" || node.type === "image") result.push(node);
131 if ("children" in node) node.children.forEach(visit);
132 };
133 visit(parseMarkdownDocument(markdown));
134 return result;
135 };
136​
137 it.each([
138 [
139 "[![sheet](./report.csv)](https://example.com/download)",
140 "report.csv",
141 "https://example.com/download",
142 ],
143 ["[![report](./report.pdf)](./report.pdf)", "report.pdf", "./report.pdf"],
144 [
145 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
146 "report.csv",
147 "https://example.com/download",
148 ],
149 ])("keeps the enclosing link for %s", async (source, filename, target) => {
150 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
151 markdownFileEmbedLabel(href, input, standalone),
152 );
153 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
154 {
155 type: "Paragraph",
156 children: [
157 {
158 type: "Link",
159 attributes: { url: target },
160 children: [{ type: "Text", content: filename }],
161 },
162 ],
163 },
164 ]);
165 });
166​
167 it.each(["f", "F", "File Label", "file label"])(
168 "uses the first reference definition for %s",
169 async (identifier) => {
170 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
171 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
172 markdownFileEmbedLabel(href, input, standalone),
173 );
174 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
175 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
176 {
177 type: "Paragraph",
178 children: [
179 {
180 type: "Link",
181 attributes: { url: "./report.csv" },
182 children: [{ type: "Text", content: "report.csv" }],
183 },
184 ],
185 },
186 ]);
187 expect((await parseMarkdown(source)).children).toMatchObject([
188 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
189 ]);
190 },
191 );
192​
193 it.each([
194 "report.csv",
195 "report.tsv",
196 "report.pdf",
197 "report.docx",
198 "report.xlsx",
199 "report.pptx",
200 "report.unknown",
201 "main.tf",
202 "schema.prisma",
203 "index.astro",
204 "main.zig",
205 "Containerfile",
206 "sound.mp3",
207 "clip.mp4",
208 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
209 for (const href of [
210 `./${name}`,
211 `/tmp/${name}`,
212 `file:///tmp/${name}`,
213 `https://cdn.example.com/${name}?signature=a%2fb`,
214 ]) {
215 if (name === "Containerfile" && href.startsWith("https:")) continue;
216 for (const source of [
217 `download: ![sheet](<${href}>)`,
218 `- ![sheet](<${href}>)`,
219 `| file |\n| --- |\n| ![sheet](<${href}>) |`,
220 `download: ![sheet][file]\n\n[file]: <${href}>`,
221 `download: <img src="${href}" alt="sheet">`,
222 ]) {
223 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
224 markdownFileEmbedLabel(url, input, standalone),
225 );
226 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
227 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
228 else
229 expect(assets(converted.markdown)).toMatchObject([
230 { type: "link", url: href, children: [{ type: "text", value: name }] },
231 ]);
232 expect(converted.fileHrefs.has(href)).toBe(!image);
233 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
234 if (
235 !href.startsWith("https:") &&
236 !name.endsWith(".pdf") &&
237 !name.endsWith(".mp3") &&
238 !name.endsWith(".mp4")
239 ) {
240 expect(preview?.kind).toBe("file");
241 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
242 }
243 }
244 }
245 });
246​
247 it("retains standalone audio players and image/video embeds in threads", () => {
248 const source =
249 "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)";
250 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
251 markdownFileEmbedLabel(href, input, standalone),
252 );
253 expect(converted.markdown).toBe(source);
254 expect(converted.fileHrefs.size).toBe(0);
255 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
256 });
257​
258 it("uses audio filenames in file previews and draft workspaces", () => {
259 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
260 const converted = markdownWithFileEmbeds("![sound](./sound.mp3)", (href) =>
261 markdownFileEmbedLabel(href, draft, false),
262 );
263 expect(assets(converted.markdown)).toMatchObject([
264 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
265 ]);
266 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
267 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
268 });
269 });
270​
271 it("keeps captured images on the image path and documents on filename links", () => {
272 const captured = { ...input, captured: true };
273 const converted = markdownWithFileEmbeds(
274 "![photo](./photo.png)\n\n![clip](./clip.mp4)\n\n![sheet](./report.csv)",
275 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
276 );
277 expect(assets(converted.markdown)).toMatchObject([
278 { type: "image", url: "./photo.png" },
279 { type: "image", url: "./clip.mp4" },
280 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
281 ]);
282 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
283 });
284​
285 it("preserves table structure and filename punctuation", () => {
286 const source = "| file |\n| --- |\n| ![sheet](./report%5B1%5D%26%7C.csv) |";
287 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
288 markdownFileEmbedLabel(href, input, standalone),
289 );
290 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
291 expect(assets(converted.markdown)).toMatchObject([
292 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
293 ]);
294 });
295​
296 it("keeps authored positions, signed URLs, and code examples literal", () => {
297 const href = "https://cdn.example.com/report%23one%2520.csv?name=&lt;&signature=a%2fb";
298 const source = `![report](<${href.replaceAll("&", "\\&")}>)\n\n![source](./main.tf#L42C3)\n\n\`![sheet](./literal.csv)\`\n\n\`\`\`md\n![sheet](./fenced.csv)\n\`\`\``;
299 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
300 markdownFileEmbedLabel(url, input, standalone),
301 );
302 expect(assets(converted.markdown)).toMatchObject([
303 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
304 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
305 ]);
306 expect(converted.markdown).toContain("`![sheet](./literal.csv)`");
307 expect(converted.markdown).toContain("```md\n![sheet](./fenced.csv)\n```");
308 expect(converted.fileHrefs.has(href)).toBe(true);
309 });
310});
311​
312describe("Windows paths in native Markdown", () => {
313 // regression: #23722 Markdown escapes ate the separator before `.t3` and `_build`
314 it("keeps backslashes in Windows image and link destinations", async () => {
315 const image = String.raw`C:\work\.t3\_build\shot.png`;
316 const link = String.raw`\\server\share\.t3\notes.md`;
317 const markdown = [
318 `![shot](${image} "Shot")`,
319 String.raw`![paren](C:\a\)b.png)`,
320 `[notes](<${link}>)`,
321 `<img src="${image}">`,
322 String.raw`![amp](C:\R&D\.t3\a&amp;b.png)`,
323 String.raw`<img src="C:\R&amp;D\.t3\b.png">`,
324 "> ![quoted](\n> " + image + ")",
325 ].join("\n\n");
326​
327 const native = await parseMarkdown(
328 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
329 );
330 const urls: string[] = [];
331 const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => {
332 if (node.attributes?.url) urls.push(node.attributes.url);
333 node.children?.forEach((child) => collect(child as typeof node));
334 };
335 collect(native);
336 const paren = String.raw`C:\a\)b.png`;
337 const amp = String.raw`C:\R&D\.t3\a&b.png`;
338 const htmlAmp = String.raw`C:\R&D\.t3\b.png`;
339 expect(urls).toEqual([image, paren, link, image, amp, htmlAmp, image]);
340 expect(markdownImageSources(markdown)).toEqual([image, paren, amp, htmlAmp]);
341 });
342});
343​
344it("keeps backslashes in drive paths in mobile Markdown prose", () => {
345 const path = String.raw`Saved to C:\Users\me\.t3\_build\shot.png and C:/work\.config.`;
346​
347 expect(parseMarkdownDocument(String.raw`${path} Then \*this\*.`).children).toMatchObject([
348 { type: "paragraph", children: [{ type: "text", value: `${path} Then *this*.` }] },
349 ]);
350});