Open History to see the last commit
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&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("[](<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="&lt;" src="https://example.com/shot.png?label=&lt;&sig=a%26b">';
34 expect(markdownWithHtml(markdown)).toBe(
35 "",
36 );
37 expect(markdownImageSources(markdown)).toEqual([
38 "https://example.com/shot.png?label=<&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: "<" });
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 "",
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\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("");
84 expect(result).not.toContain("<details>");
85 expect(result).toContain('<img src="after.png">\n</details>');
86 });
87
88 it("keeps <br> line breaks in a table cell without breaking the row", () => {
89 const markdown =
90 "| 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>` |";
91 // md4c decodes the reference to a newline in the cell's text, as remark does.
92 expect(markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX)).toContain(
93 "| • One • Two **Three** | `<br>` |",
94 );
95 const table = parseMarkdownDocument(markdown).children[0];
96 expect(table?.type).toBe("table");
97 if (table?.type !== "table") return;
98 expect(table.children).toHaveLength(3);
99 expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2]);
100 expect(table.children[1]?.children[1]?.children).toMatchObject([
101 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
102 { type: "text", value: "\n" },
103 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
104 ]);
105 expect(table.children[2]?.children).toMatchObject([
106 { children: [{ value: "• One\n• Two\n" }, { type: "strong" }] },
107 { children: [{ type: "inlineCode", value: "<br>" }] },
108 ]);
109 });
110
111 it("keeps a table row intact when an anchor href contains a pipe", () => {
112 const document = parseMarkdownDocument(
113 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1|2'>Open</a> | done |",
114 );
115 const table = document.children[0];
116 expect(table?.type).toBe("table");
117 if (table?.type !== "table") return;
118 expect(table.children[1]?.children).toMatchObject([
119 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
120 { children: [{ value: "done" }] },
121 ]);
122 });
123
124 it("keeps anchor text unlinked for unsafe hrefs", () => {
125 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
126 });
127
128 it("keeps anchor labels and escaped bangs intact across nested formatting and table cells", () => {
129 const markdown =
130 '> **!<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"> |';
131 expect(markdownWithHtml(markdown)).toBe(
132 "> **\\![\\[one\\]](<https://x.test>)** and tail\n\n| A |\n| - |\n| \\![x\\[y\\]](<https://x.test>)  |",
133 );
134 expect(
135 markdownWithHtml(
136 String.raw`Before \!<a href="https://x.test">escaped</a> \\!<a href="mailto:a@b">even</a>`,
137 ),
138 ).toBe(String.raw`Before \ \\\`);
139 });
140
141 it("converts separated HTML without changing code examples or an unfinished tag", () => {
142 const literal = '`<br>`\n\n```html\n<img src="literal.png">\n```\n\n<broken';
143 expect(markdownWithHtml(literal)).toBe(literal);
144 const rows = Array.from(
145 { length: 100 },
146 (_, index) => `row ${index} <span>text</span><br>!<a href="https://x.test/${index}">go</a>`,
147 );
148 const expected = Array.from(
149 { length: 100 },
150 (_, index) => `row ${index} text \n\\`,
151 );
152 expect(markdownWithHtml(rows.join("\n\n") + "\n\n" + literal)).toBe(
153 expected.join("\n\n") + "\n\n" + literal,
154 );
155 });
156});
157
158describe("file embeds in native thread and file Markdown", () => {
159 const input = {
160 environmentId: EnvironmentId.make("environment-1"),
161 threadId: ThreadId.make("thread-1"),
162 workspaceRoot: "/repo",
163 };
164 const assets = (markdown: string) => {
165 const result: MarkdownNode[] = [];
166 const visit = (node: MarkdownNode) => {
167 if (node.type === "link" || node.type === "image") result.push(node);
168 if ("children" in node) node.children.forEach(visit);
169 };
170 visit(parseMarkdownDocument(markdown));
171 return result;
172 };
173
174 it.each([
175 [
176 "[](https://example.com/download)",
177 "report.csv",
178 "https://example.com/download",
179 ],
180 ["[](./report.pdf)", "report.pdf", "./report.pdf"],
181 [
182 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
183 "report.csv",
184 "https://example.com/download",
185 ],
186 ])("keeps the enclosing link for %s", async (source, filename, target) => {
187 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
188 markdownFileEmbedLabel(href, input, standalone),
189 );
190 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
191 {
192 type: "Paragraph",
193 children: [
194 {
195 type: "Link",
196 attributes: { url: target },
197 children: [{ type: "Text", content: filename }],
198 },
199 ],
200 },
201 ]);
202 });
203
204 it.each(["f", "F", "File Label", "file label"])(
205 "uses the first reference definition for %s",
206 async (identifier) => {
207 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
208 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
209 markdownFileEmbedLabel(href, input, standalone),
210 );
211 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
212 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
213 {
214 type: "Paragraph",
215 children: [
216 {
217 type: "Link",
218 attributes: { url: "./report.csv" },
219 children: [{ type: "Text", content: "report.csv" }],
220 },
221 ],
222 },
223 ]);
224 expect((await parseMarkdown(source)).children).toMatchObject([
225 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
226 ]);
227 },
228 );
229
230 it.each([
231 "report.csv",
232 "report.tsv",
233 "report.pdf",
234 "report.docx",
235 "report.xlsx",
236 "report.pptx",
237 "report.unknown",
238 "main.tf",
239 "schema.prisma",
240 "index.astro",
241 "main.zig",
242 "Containerfile",
243 "sound.mp3",
244 "clip.mp4",
245 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
246 for (const href of [
247 `./${name}`,
248 `/tmp/${name}`,
249 `file:///tmp/${name}`,
250 `https://cdn.example.com/${name}?signature=a%2fb`,
251 ]) {
252 if (name === "Containerfile" && href.startsWith("https:")) continue;
253 for (const source of [
254 `download: `,
255 `- `,
256 `| file |\n| --- |\n|  |`,
257 `download: ![sheet][file]\n\n[file]: <${href}>`,
258 `download: <img src="${href}" alt="sheet">`,
259 ]) {
260 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
261 markdownFileEmbedLabel(url, input, standalone),
262 );
263 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
264 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
265 else
266 expect(assets(converted.markdown)).toMatchObject([
267 { type: "link", url: href, children: [{ type: "text", value: name }] },
268 ]);
269 expect(converted.fileHrefs.has(href)).toBe(!image);
270 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
271 if (
272 !href.startsWith("https:") &&
273 !name.endsWith(".pdf") &&
274 !name.endsWith(".mp3") &&
275 !name.endsWith(".mp4")
276 ) {
277 expect(preview?.kind).toBe("file");
278 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
279 }
280 }
281 }
282 });
283
284 it("retains standalone audio players and image/video embeds in threads", () => {
285 const source =
286 "\n\n\n\n\n\ninline ";
287 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
288 markdownFileEmbedLabel(href, input, standalone),
289 );
290 expect(converted.markdown).toBe(source);
291 expect(converted.fileHrefs.size).toBe(0);
292 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
293 });
294
295 it("uses audio filenames in file previews and draft workspaces", () => {
296 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
297 const converted = markdownWithFileEmbeds("", (href) =>
298 markdownFileEmbedLabel(href, draft, false),
299 );
300 expect(assets(converted.markdown)).toMatchObject([
301 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
302 ]);
303 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
304 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
305 });
306 });
307
308 it("keeps captured images on the image path and documents on filename links", () => {
309 const captured = { ...input, captured: true };
310 const converted = markdownWithFileEmbeds(
311 "\n\n\n\n",
312 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
313 );
314 expect(assets(converted.markdown)).toMatchObject([
315 { type: "image", url: "./photo.png" },
316 { type: "image", url: "./clip.mp4" },
317 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
318 ]);
319 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
320 });
321
322 it("preserves table structure and filename punctuation", () => {
323 const source = "| file |\n| --- |\n|  |";
324 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
325 markdownFileEmbedLabel(href, input, standalone),
326 );
327 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
328 expect(assets(converted.markdown)).toMatchObject([
329 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
330 ]);
331 });
332
333 it("keeps authored positions, signed URLs, and code examples literal", () => {
334 const href = "https://cdn.example.com/report%23one%2520.csv?name=<&signature=a%2fb";
335 const source = `}>)\n\n\n\n\`\`\n\n\`\`\`md\n\n\`\`\``;
336 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
337 markdownFileEmbedLabel(url, input, standalone),
338 );
339 expect(assets(converted.markdown)).toMatchObject([
340 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
341 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
342 ]);
343 expect(converted.markdown).toContain("``");
344 expect(converted.markdown).toContain("```md\n\n```");
345 expect(converted.fileHrefs.has(href)).toBe(true);
346 });
347});
348
349describe("Windows paths in native Markdown", () => {
350 // regression: #23722 Markdown escapes ate the separator before `.t3` and `_build`
351 it("keeps backslashes in Windows image and link destinations", async () => {
352 const image = String.raw`C:\work\.t3\_build\shot.png`;
353 const link = String.raw`\\server\share\.t3\notes.md`;
354 const markdown = [
355 ``,
356 String.raw`b.png)`,
357 `[notes](<${link}>)`,
358 `<img src="${image}">`,
359 String.raw``,
360 String.raw`<img src="C:\R&D\.t3\b.png">`,
361 "> ",
362 ].join("\n\n");
363
364 const native = await parseMarkdown(
365 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
366 );
367 const urls: string[] = [];
368 const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => {
369 if (node.attributes?.url) urls.push(node.attributes.url);
370 node.children?.forEach((child) => collect(child as typeof node));
371 };
372 collect(native);
373 const paren = String.raw`C:\a\)b.png`;
374 const amp = String.raw`C:\R&D\.t3\a&b.png`;
375 const htmlAmp = String.raw`C:\R&D\.t3\b.png`;
376 expect(urls).toEqual([image, paren, link, image, amp, htmlAmp, image]);
377 expect(markdownImageSources(markdown)).toEqual([image, paren, amp, htmlAmp]);
378 });
379});
380
381it("keeps backslashes in drive paths in mobile Markdown prose", () => {
382 const path = String.raw`Saved to C:\Users\me\.t3\_build\shot.png and C:/work\.config.`;
383
384 expect(parseMarkdownDocument(String.raw`${path} Then \*this\*.`).children).toMatchObject([
385 { type: "paragraph", children: [{ type: "text", value: `${path} Then *this*.` }] },
386 ]);
387});