/**
* Tests of the safe Markdown renderer (M3.4, `assist/markdown.ts`): the
* supported blocks and inlines, and that nothing in a server answer turns
* into HTML, script, a link target or an image source (XSS).
*/
import { describe, expect, it } from "vitest";
import { MAX_MARKDOWN, renderMarkdown } from "../../../src/components/editor/assist/markdown";
/** Tag names of every element below `root`. */
function tags(root: Element): string[] {
return [...root.querySelectorAll("*")].map((e) => e.tagName.toLowerCase());
}
describe("renderMarkdown", () => {
it("renders code fences, headings, rules, lists and paragraphs", () => {
const root = renderMarkdown(
[
"```php",
"class A { }",
"```",
"",
"---",
"",
"# Title",
"First line",
"second line ",
"third",
"",
"- one",
"- two",
"1. first",
"> quoted",
].join("\n"),
);
expect(root.className).toBe("lt-markdown");
const code = root.querySelector("pre > code");
expect(code?.textContent).toBe("class A { }");
expect((code as HTMLElement | null)?.dataset.language).toBe("php");
expect(root.querySelector("hr")).not.toBeNull();
expect(root.querySelector(".lt-markdown-heading strong")?.textContent).toBe("Title");
const paragraph = [...root.querySelectorAll("p")].find((p) => p.textContent.startsWith("First"));
expect(paragraph?.textContent).toBe("First line second linethird");
expect(paragraph?.querySelector("br")).not.toBeNull();
expect([...root.querySelectorAll("ul > li")].map((li) => li.textContent)).toEqual(["one", "two"]);
expect(root.querySelector("ol > li")?.textContent).toBe("first");
expect(root.querySelector("blockquote")?.textContent).toBe("quoted");
});
it("renders inline code, strong, emphasis, links and escapes", () => {
const root = renderMarkdown("Use `a*b*c` with **bold**, *em*, _em2_, snake_case_name, [docs](https://php.net) and \\*not em\\*.");
const p = root.querySelector("p");
expect(p?.querySelector("code")?.textContent).toBe("a*b*c");
expect(p?.querySelector("strong")?.textContent).toBe("bold");
expect([...(p?.querySelectorAll("em") ?? [])].map((e) => e.textContent)).toEqual(["em", "em2"]);
expect(p?.querySelector(".lt-markdown-link")?.textContent).toBe("docs");
expect(p?.textContent).toContain("snake_case_name");
expect(p?.textContent).toContain("*not em*.");
});
it("never creates HTML, links, images or script from the source (XSS)", () => {
const attacks = [
"
",
"",
"[click](javascript:alert(1))",
"",
"a",
"