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