Open History to see the last commit
1import type { Root } from "mdast";
2import { describe, expect, it, vi } from "vite-plus/test";
3
4import { parseMarkdownAst } from "./markdownDocument";
5import {
6 EMPTY_LINK_URLS,
7 getCachedMarkdownAst,
8 getCachedMarkdownLinkUrls,
9 getCachedNativeMarkdown,
10} from "./markdownParseCache";
11
12describe("markdownParseCache", () => {
13 it("caches repeated AST parses and native transforms for identical markdown strings", () => {
14 const parse = vi.fn((): Root => ({ type: "root", children: [] }));
15 const first = getCachedMarkdownAst("# Hello world\n`src/a.ts`", parse);
16 const second = getCachedMarkdownAst("# Hello world\n`src/a.ts`", parse);
17 expect(first).toBe(second);
18 expect(parse).toHaveBeenCalledTimes(1);
19
20 const compute = vi.fn((text: string) => `rendered:${text}`);
21 expect(getCachedNativeMarkdown("abc", compute)).toBe("rendered:abc");
22 expect(getCachedNativeMarkdown("abc", compute)).toBe("rendered:abc");
23 expect(compute).toHaveBeenCalledTimes(1);
24 });
25
26 it("extracts and caches unique link URLs while skipping parsing for link-free prose", () => {
27 const parse = vi.fn((input: string): Root => {
28 if (input.includes("[ref]")) {
29 return {
30 type: "root",
31 children: [
32 {
33 type: "paragraph",
34 children: [
35 { type: "link", url: "src/a.ts", children: [] },
36 {
37 type: "linkReference",
38 identifier: "ref",
39 referenceType: "shortcut",
40 children: [],
41 },
42 { type: "link", url: "src/a.ts", children: [] },
43 ],
44 },
45 { type: "definition", identifier: "ref", url: "https://example.com" },
46 ],
47 } as unknown as Root;
48 }
49 return { type: "root", children: [] };
50 });
51
52 expect(getCachedMarkdownLinkUrls("Just plain text without links.", parse)).toBe(
53 EMPTY_LINK_URLS,
54 );
55 expect(parse).not.toHaveBeenCalled();
56
57 const doc = "Check [a](<src/a.ts>) and [ref]\n\n[ref]: https://example.com";
58 const first = getCachedMarkdownLinkUrls(doc, parse);
59 const second = getCachedMarkdownLinkUrls(doc, parse);
60 expect(first).toEqual(["src/a.ts", "https://example.com"]);
61 expect(second).toBe(first);
62 expect(parse).toHaveBeenCalledTimes(1);
63 });
64
65 it("extracts GFM email autolinks with the configured remark-gfm parser", () => {
66 const urls = getCachedMarkdownLinkUrls("Contact contact@example.com", parseMarkdownAst);
67 expect(urls).toEqual(["mailto:contact@example.com"]);
68 expect(getCachedMarkdownLinkUrls("Contact contact@example.com", parseMarkdownAst)).toBe(urls);
69 expect(
70 getCachedMarkdownLinkUrls("Ping @alice or contact@example.com", parseMarkdownAst),
71 ).toEqual(["mailto:contact@example.com"]);
72 const parse = vi.fn((): Root => ({ type: "root", children: [] }));
73 expect(getCachedMarkdownLinkUrls("a".repeat(20_000), parse)).toBe(EMPTY_LINK_URLS);
74 expect(parse).not.toHaveBeenCalled();
75 });
76});