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

markdownChunks.test.ts

1,080 lines39.5 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import { toHtml } from "hast-util-to-html";
4import remarkGfm from "remark-gfm";
5import remarkParse from "remark-parse";
6import remarkRehype from "remark-rehype";
7import { unified } from "unified";
8​
9import {
10 buildMarkdownFootnotesSection,
11 findFootnoteRefChunkIndex,
12 joinMarkdownChunks,
13 LARGE_MARKDOWN_CHUNK_MAX_CHARS,
14 markdownFlowLineLookup,
15 prepareMarkdownChunk,
16 splitMarkdown,
17 withMarkdownDefinitions,
18} from "./markdownChunks.ts";
19import { taskListMarkerOffset } from "./markdownTaskEdits.ts";
20​
21const splitLargeMarkdown = (text: string, targetChars?: number) =>
22 splitMarkdown(text, targetChars).chunks;
23​
24const starts = (text: string) =>
25 splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]);
26​
27describe("splitMarkdown", () => {
28 it("cuts only where a new top-level block starts, and keeps every byte", () => {
29 const text = [
30 "# Title",
31 "Intro paragraph",
32 "",
33 "- item one",
34 "",
35 " continued item",
36 "- item two",
37 "",
38 "2. ordered",
39 "",
40 "```md",
41 "# not a heading",
42 "",
43 "Not a paragraph",
44 "```",
45 "",
46 "> quote",
47 "",
48 "Closing paragraph",
49 "## Next",
50 "---",
51 "",
52 "| a | b |",
53 ].join("\n");
54 const chunks = splitLargeMarkdown(text, 1);
55 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
56 expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length);
57 expect(starts(text)).toEqual([
58 "# Title",
59 "```md",
60 "> quote",
61 "Closing paragraph",
62 "## Next",
63 "| a | b |",
64 ]);
65 });
66​
67 it("keeps a fence open until a matching closer", () => {
68 const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n");
69 expect(starts(text)).toEqual(["````", "after"]);
70 });
71​
72 it("treats nonbreaking spaces as content rather than fence suffixes or blank lines", () => {
73 const fence = ["```md", "x".repeat(4100), "```\u00a0", "# literal", "```"].join("\n");
74 expect(splitLargeMarkdown(fence)).toHaveLength(1);
75​
76 const prose = ["*" + "x".repeat(4100), "\u00a0", "more*"].join("\n");
77 expect(splitLargeMarkdown(prose)).toHaveLength(1);
78​
79 const htmlBlock = ["<div>", "x".repeat(4100), "\u00a0", "# literal", "</div>"].join("\n");
80 expect(splitLargeMarkdown(htmlBlock)).toHaveLength(1);
81​
82 const rawTag = ["<pre\u00a0>", "", "x".repeat(4100), "", "# heading"].join("\n");
83 expect(splitLargeMarkdown(rawTag).map((chunk) => chunk.text.split("\n")[0])).toEqual([
84 "<pre\u00a0>",
85 "# heading",
86 ]);
87​
88 const listFence = "- ~~~md\n\u00a0\n\n [real]: /right\n\n[real]";
89 expect(splitMarkdown(listFence, 1).definitions).toBe("[real]: /right");
90 });
91​
92 it("still closes fences and recognizes blank lines with ASCII spaces, tabs, and CRLF", () => {
93 const fence = ["```md", "x".repeat(4100), "``` \t", "# heading"].join("\r\n");
94 expect(splitLargeMarkdown(fence).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
95 "```md",
96 "# heading",
97 ]);
98​
99 const prose = ["a".repeat(4100), " \t", "next paragraph"].join("\r\n");
100 expect(splitLargeMarkdown(prose).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
101 "a".repeat(4100),
102 "next paragraph",
103 ]);
104​
105 const htmlBlock = ["<div>", "x".repeat(4100), " \t", "# heading"].join("\r\n");
106 expect(splitLargeMarkdown(htmlBlock).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
107 "<div>",
108 "# heading",
109 ]);
110 });
111​
112 it("splits CR-only Markdown into bounded chunks like LF and preserves line endings", () => {
113 const cr = `first\r\r# ${"x\r\r# ".repeat(30_000)}end`;
114 const lf = cr.replaceAll("\r", "\n");
115 const crResult = splitMarkdown(cr);
116 const lfResult = splitMarkdown(lf);
117​
118 expect(crResult.chunks.length).toBe(lfResult.chunks.length);
119 expect(crResult.chunks.length).toBeGreaterThan(1);
120 expect(
121 crResult.chunks.every((chunk) => chunk.text.length <= LARGE_MARKDOWN_CHUNK_MAX_CHARS),
122 ).toBe(true);
123 expect(crResult.chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(
124 lfResult.chunks.reduce((sum, chunk) => sum + chunk.lines, 0),
125 );
126 expect(joinMarkdownChunks(crResult.chunks)).toBe(cr);
127 const rendered = unified().use(remarkParse).use(remarkRehype);
128 expect(toHtml(rendered.runSync(rendered.parse(crResult.chunks[1]!.text)))).toContain(
129 "<h1>x</h1>",
130 );
131​
132 const mixed = `---\rtitle: cr\r---\r\r[ref]: /cr-link\r\r- \`\`\`md\r\r [fake]: /wrong\r \`\`\`\r\r\`\`\`md\r# inside fence\r\`\`\`\r\r<details>\r\r${"x".repeat(32 * 1024)}\r\r</details>\r\r# After [ref]\r\n\r\n- [ ] task`;
133 const mixedResult = splitMarkdown(mixed);
134 expect(mixedResult.definitions).toBe("[ref]: /cr-link");
135 expect(mixedResult.chunks.map((chunk) => chunk.text.split(/\r\n?|\n/)[0])).toEqual([
136 "---",
137 "# After [ref]",
138 ]);
139 expect(joinMarkdownChunks(mixedResult.chunks)).toBe(mixed);
140 const secondChunk = withMarkdownDefinitions(
141 mixedResult.chunks[1]!.text,
142 mixedResult.definitions,
143 );
144 const list = unified()
145 .use(remarkParse)
146 .use(remarkGfm)
147 .parse(secondChunk)
148 .children.find((node) => node.type === "list");
149 const marker = taskListMarkerOffset(secondChunk, list!.position!.start.offset!);
150 const secondStart = mixedResult.chunks[0]!.text.length + 1;
151 expect(secondStart + marker! - (mixedResult.definitions.length + 2)).toBe(mixed.indexOf("[ ]"));
152 });
153​
154 it("keeps HTML blocks and display math open across blank lines", () => {
155 const text = [
156 "<!--",
157 "",
158 "# hidden",
159 "-->",
160 "",
161 "$$",
162 "",
163 "Inside math",
164 "$$",
165 "",
166 "<pre>",
167 "",
168 "Preformatted",
169 "</pre>",
170 "",
171 "<!-- one line -->",
172 "",
173 "<div>",
174 "# literal",
175 "</div>",
176 "",
177 '<p class="lead">text',
178 "# literal",
179 "</p>",
180 "",
181 '<span class="box">',
182 "# literal",
183 "</span>",
184 "",
185 "<details>",
186 "<summary>Answer</summary>",
187 "",
188 "Inside details",
189 "",
190 "</details>",
191 "",
192 "<table><tr><td>",
193 "",
194 "```ts",
195 "inside a cell",
196 "```",
197 "",
198 "</td></tr></table>",
199 "",
200 '<ol start="10">',
201 "",
202 "<li>one</li>",
203 "",
204 "<li>two</li>",
205 "",
206 "</ol>",
207 "",
208 "```html",
209 "<details>",
210 "```",
211 "",
212 "after",
213 ].join("\n");
214 expect(starts(text)).toEqual(["<!--", "```html", "after"]);
215 const multiline = [
216 "<details",
217 ' class="faq"><!-- </details> -->',
218 "",
219 "Inside details",
220 "",
221 "</details>",
222 "",
223 "after",
224 ].join("\n");
225 expect(starts(multiline)).toEqual(["<details", "after"]);
226 const unclosed = ["<details>", "", "x".repeat(32 * 1024), "", "after"].join("\n");
227 expect(starts(unclosed)).toEqual(["<details>", "after"]);
228 const head = ["<details>", "", "a".repeat(8 * 1024), "", ""].join("\n");
229 const longLine = "x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - head.length);
230 expect(starts(head + longLine)).toEqual(["<details>"]);
231 expect(starts(`${head}${longLine}x`)).toEqual(["<details>", `${longLine}x`]);
232 expect(starts(`${head}\`\`\`json\n${longLine}\n\`\`\`\n\n</details>`)).toEqual([
233 "<details>",
234 "```json",
235 ]);
236 });
237​
238 it("treats an autolink or inline HTML line as a paragraph, so a following fence still opens", () => {
239 const text = [
240 "<https://example.com>",
241 "```md",
242 "",
243 "# literal",
244 "```",
245 "",
246 "<b>bold</b> text",
247 "```md",
248 "",
249 "# literal",
250 "```",
251 "",
252 "after",
253 ].join("\n");
254 expect(starts(text)).toEqual(["<https://example.com>", "after"]);
255 });
256​
257 it("waits for the target size before cutting", () => {
258 const text = ["# a", "", "b", "", "# c", "", "d"].join("\n");
259 expect(splitLargeMarkdown(text, 6).map((chunk) => chunk.text)).toEqual([
260 "# a\n\nb\n",
261 "# c\n\nd",
262 ]);
263 });
264​
265 it("keeps the complete sample fence before a later oversized source chunk", () => {
266 const example = ["```md", "Sample Markdown", "", "# Sample heading", "```"].join("\n");
267 const preview = ["x".repeat(4200), "<span>", example, "More prose", "<span>"].join("\n");
268 const oversized = "# Appendix\n" + "[link](/example) ".repeat(11_000);
269 const { chunks } = splitMarkdown(preview + "\n" + oversized);
270 expect(chunks.map((chunk) => chunk.text)).toEqual([preview, oversized]);
271 });
272​
273 it.each(["===", "---", "***"])(
274 "keeps HTML together after a long paragraph and %s",
275 (boundary) => {
276 const text = ["x".repeat(9000), boundary, "<span>", "# literal"].join("\n");
277 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([text]);
278 },
279 );
280​
281 it.each([
282 ["a fence", "```md", "```"],
283 ["an HTML comment", "<!--", "-->"],
284 ["display math", "$$", "$$"],
285 ])("keeps %s intact after an ambiguous standalone tag", (_, open, close) => {
286 const block = [open, "Sample Markdown", "", "# Sample heading", close].join("\n");
287 const preview = ["x".repeat(9000), "<span>", block].join("\n");
288 expect(splitMarkdown(preview).chunks.map((chunk) => chunk.text)).toEqual([preview]);
289 });
290​
291 it("ends an unclosed HTML block in a list item with the item", () => {
292 expect(starts("- Item\n\n <pre>\n example\n\n# Heading")).toEqual(["- Item", "# Heading"]);
293 });
294​
295 it("keeps display math in a list item scoped like top-level math", () => {
296 const math = "- $$\n x\n $$ trailing\n [fake]: /wrong\n $$\n\n[fake]: /right";
297 expect(splitMarkdown(math).definitions).toBe("[fake]: /right");
298 expect(starts("- Item\n\n $$\n a\n$$\n\n# Heading")).toEqual(["- Item", "# Heading"]);
299 });
300​
301 it("preserves an oversized ambiguous region for source display", () => {
302 const oversized = ["x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS), "<span>", "# Heading"].join(
303 "\n",
304 );
305 const next = "# Next";
306 const text = oversized + "\n\n" + next;
307 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([oversized + "\n", next]);
308 });
309​
310 it.each([
311 ["multiline math with backticks", ["$$", "```", "$$", " # Heading"]],
312 ["single-line display math", ["$$x$$"]],
313 ])("keeps standalone HTML intact after %s", (_, math) => {
314 const text = ["x".repeat(4200), "<span>", ...math, "<span>", "# literal"].join("\n");
315 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([text]);
316 });
317​
318 it("can cut at a heading after a tag in a lazy quote continuation", () => {
319 const quote = ["> " + "x".repeat(4200), "continued", "<span>"].join("\n");
320 const heading = "# Next";
321 expect(splitMarkdown(quote + "\n" + heading).chunks.map((chunk) => chunk.text)).toEqual([
322 quote,
323 heading,
324 ]);
325 });
326​
327 it("keeps leading frontmatter in the first piece", () => {
328 const text = ["---", "title: x", "", "# not a heading", "---", "", "# Heading"].join("\n");
329 expect(starts(text)).toEqual(["---", "# Heading"]);
330 });
331​
332 it("cuts after a leading horizontal rule with no frontmatter closer", () => {
333 const md =
334 "---\n\n" +
335 Array.from({ length: 300 }, (_, i) => `## Part ${i}\n${"a".repeat(450)}`).join("\n\n");
336 const { chunks } = splitMarkdown(md);
337 expect(chunks.length).toBeGreaterThan(1);
338 expect(chunks.every((chunk) => chunk.text.length <= LARGE_MARKDOWN_CHUNK_MAX_CHARS)).toBe(true);
339 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(md);
340 });
341​
342 it.each([
343 ["one space", " # References"],
344 ["two spaces", " ### References"],
345 ["three spaces", " ###### References"],
346 ])("collects definitions after headings indented by %s without cutting there", (_, heading) => {
347 const intro = "[Release notes][release]\n";
348 const definition = "[release]: /releases";
349 const appendix = ["## Appendix", heading, definition].join("\n");
350 const result = splitMarkdown(`${intro}\n${appendix}`, 1);
351​
352 expect(result.definitions).toBe(definition);
353 expect(result.chunks.map((chunk) => chunk.text)).toEqual([intro, appendix]);
354 });
355​
356 it("collects definitions immediately after equals-sign Setext headings", () => {
357 const text = `Read [guide]. ${"filler ".repeat(600)}\n\nNotes\n===\n[guide]: https://example.com/guide\n`;
358 const result = splitMarkdown(text);
359​
360 expect(result.chunks.length).toBeGreaterThan(1);
361 expect(result.definitions).toBe("[guide]: https://example.com/guide");
362 });
363​
364 it("resumes Markdown after a standalone HTML block following a long Setext heading", () => {
365 const intro = ["x".repeat(9000), "===", "<span>", "```", ""].join("\n");
366 const appendix = "# Appendix\n[guide]: /guide";
367 const result = splitMarkdown(`${intro}\n${appendix}`);
368​
369 expect(result.chunks.map((chunk) => chunk.text)).toEqual([intro, appendix]);
370 expect(result.definitions).toBe("[guide]: /guide");
371 });
372​
373 it("collects definitions after Setext underlines only when they end a paragraph", () => {
374 const cases = [
375 "Notes\n=\n[s1]: /single-eq",
376 "Line 1\nLine 2\n === \n[s2]: /multiline-eq",
377 "Subheading\n--\n[s3]: /double-dash",
378 "Heading\n--- | ---\n===\n[s4]: /mismatched-table-header",
379 "- item\n\n Notes\n===\n[s5]: /after-list-blank",
380 "Notes\n===\n===\n[n1]: /second-eq-is-paragraph",
381 "Notes\n ===\n[n2]: /indented-underline",
382 "> quote\nlazy\n===\n[n3]: /in-blockquote",
383 "- item\n===\n[n4]: /in-list",
384 "- item\n\n sub\n===\n[n5]: /in-loose-list",
385 " code\n===\n[n6]: /after-indented-code",
386 "a | b\n--- | ---\n===\n[n7]: /in-table",
387 "<!-- comment -->\n===\n[n8]: /after-html-comment",
388 ].join("\n\n");
389​
390 expect(splitMarkdown(cases).definitions).toBe(
391 [
392 "[s1]: /single-eq",
393 "[s2]: /multiline-eq",
394 "[s3]: /double-dash",
395 "[s4]: /mismatched-table-header",
396 "[s5]: /after-list-blank",
397 ].join("\n"),
398 );
399 });
400​
401 it.each([
402 ["an ordered item whose content starts farther right", "10. Item\n\n", ""],
403 ["an item padded to the next tab stop", "-\tItem\n\n", ""],
404 ["a blockquote that ends the list", "- Item\n> quote\n", ""],
405 ["an HTML comment that ends the list", "- Item\n<!-- note -->\n", ""],
406 ["an HTML block that ends the list", "- Item\n<div>top level</div>\n\n", ""],
407 ["a math block that ends the list", "- Item\n$$\nx\n$$\n", ""],
408 ["an indented thematic break", " - - -\n", ""],
409 ["an empty list item", "-\n\n", " "],
410 ["an empty list item with trailing spaces", "- \n\n", " "],
411 ["an empty list item followed by dedented prose", "-\nfoo\n", " "],
412 ])("collects definitions after a fence following %s", (_, beforeFence, definitionIndent) => {
413 const definition = "[ref]: /target";
414 const text = beforeFence + " ```sh\n example\n ```\n" + definitionIndent + definition;
415 expect(splitMarkdown(text).definitions).toBe(definition);
416 });
417​
418 it("keeps list sample definitions literal and retains outside definitions", () => {
419 for (const listFence of [
420 "- ```md\n\n [fake]: /wrong\n ```",
421 "-\t```md\n\n [fake]: /wrong\n ```",
422 "* ````md\n ```\n\n [fake]: /wrong\n ````",
423 "2. ~~~md\n\n [fake]: /wrong\n ~~~",
424 "1. First\n2. ```md\n\n [fake]: /wrong\n ```",
425 "1.\tFirst\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
426 "1. First\n\n continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
427 "1. First\n - nested\n\n outer continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
428 "1. First\nlazy continuation\n2. ```md\n\n [fake]: /wrong\n ```",
429 "1. --\nlazy continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
430 "+\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
431 "1. First\n2.\n3. ~~~md\n\n [fake]: /wrong\n ~~~",
432 "- ```md\n\tcode\n\n [fake]: /wrong\n ```",
433 ]) {
434 expect(splitMarkdown(`${listFence}\n\n[fake]`).definitions).toBe("");
435 }
436 // "2." cannot interrupt a paragraph, and a less-indented line ends the list item's fence.
437 expect(splitMarkdown("Text\n2. ```md\n\n [real]: /right\n\n[real]").definitions).toBe(
438 "[real]: /right",
439 );
440 expect(splitMarkdown("- item\n 2. ~~~md\n[fake]: /wrong\n\n[fake]").definitions).toBe("");
441 for (const text of [
442 "- item\n<pre></pre>\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
443 "- item\n<!-- comment -->\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
444 "- item\n> quote\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
445 "1. First\n\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
446 "1. First\n --\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
447 "paragraph\n+\n2. ~~~md\n\n [real]: /right\n\n[real]",
448 "1. ```md\n x\n ```\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
449 "123. ~~~\n\t\tcode\n ~~~\n[real]: /right\n\n[real]",
450 "1.\t```md\n\t```\n[real]: /right\n\n[real]",
451 ]) {
452 const result = splitMarkdown(text, 1);
453 expect(result.definitions).toBe("[real]: /right");
454 expect(result.chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
455 }
456 expect(splitMarkdown("- ```md\n\n [fake]: /wrong\n[real]: /right").definitions).toBe(
457 "[real]: /right",
458 );
459 const multilineAfterListFence =
460 "- ```md\n\n [fake]:\n /wrong\n ```\n[real]:\n /right\n\n[fake] [real]";
461 expect(splitMarkdown(multilineAfterListFence, 1).definitions).toBe("[real]:\n /right");
462 });
463​
464 it.each([
465 ["an ordered list", "1. Item", " ", "```", ""],
466 ["a tab-padded list", "-\tItem", "\t", "~~~", ""],
467 ["a bullet list with extra fence indentation", "- Item", " ", "```", ""],
468 ["a nested list with markers on the same line", "- - Item", " ", "```", " "],
469 ])(
470 "shares a dedented definition after a continuation fence in %s",
471 (_, item, indent, fence, outdent) => {
472 const definition = "[real]: /right";
473 const text = [
474 item,
475 `${indent}${fence}md`,
476 "",
477 `${indent}[fake]: /wrong`,
478 outdent + definition,
479 ].join("\n");
480 expect(splitMarkdown(text).definitions).toBe(definition);
481 },
482 );
483​
484 it.each([
485 [
486 "an initially empty same-line item",
487 "- -\n ```\n\n [release]: /right",
488 "[release]: /right",
489 ],
490 ["an empty marker inside a parent item", "- - x\n 2.\n ```\n [release]: /wrong", ""],
491 [
492 "indented code in an initially empty item",
493 "1. x\n+\n ```\n code\n ```\n[release]: /right",
494 "[release]: /right",
495 ],
496 ["a bullet item that interrupts prose", "text\n- -\n ```\n [release]: /right", ""],
497 [
498 "indented code after an empty nested item",
499 "- - x\n 2.\n\n ~~~\n[release]: /right",
500 "[release]: /right",
501 ],
502 ["an outdented empty marker", "1. x\n -\n\n ```\n\n[release]: /wrong", ""],
503 [
504 "an intermediate same-line item",
505 "- - - x\n ```\n\n [release]: /right",
506 "[release]: /right",
507 ],
508 [
509 "a deeper marker indented relative to its parent",
510 "- outer\n - inner\n - deep\n ```\n code\n[release]: /right",
511 "[release]: /right",
512 ],
513 ])("shares only real definitions when a fence follows %s", (_, body, definitions) => {
514 const split = splitMarkdown(`[Notes][release]\n\n# Sample\n\n${body}`, 1);
515 expect(split.definitions).toBe(definitions);
516 });
517​
518 it.each([
519 ["nested markers on one line", "- - ```\n code\n ```"],
520 ["a line of many nested markers", "- ".repeat(70_000) + "x"],
521 ["a heading in a list item", "- # Heading\n 2. Item\n ```\n code\n ```"],
522 ["a lazy ordered marker", "- outer\n - inner\n2. lazy\n ```\n ```"],
523 ])("collects a list item definition after %s", (_, list) => {
524 const definition = "[ref]: /target";
525 expect(splitMarkdown(`${list}\n\n ${definition}`).definitions).toBe(definition);
526 });
527​
528 it.each([
529 ["after a list fence", ["- Item", " ```", " code", "```", "[ref]: /fake", "```"]],
530 ["after a paragraph", ["Paragraph", "2. continuation", " ```", "[ref]: /fake", " ```"]],
531 [
532 "in a parent item after a nested item",
533 ["- outer", " - inner", " ```", " ```", " [ref]: /fake", " ```"],
534 ],
535 ])("keeps definitions inside a top-level fence %s literal", (_, lines) => {
536 expect(splitMarkdown(lines.join("\n")).definitions).toBe("");
537 });
538​
539 it.each(["", " ", " ", " "])(
540 "collects link definitions outside code with fence indent %j",
541 (indent) => {
542 const text = [
543 "[![badge][b]][site]",
544 "",
545 "```md",
546 "[fake]: /not-a-definition",
547 "```",
548 "",
549 "Paragraph",
550 "[inline]: /continues-the-paragraph",
551 "",
552 "[site]: https://example.com",
553 "[b]: https://example.com/badge.svg 'Badge'",
554 "[^note]: a footnote",
555 "",
556 '[x]: /url "title" is paragraph text',
557 "",
558 "# Heading",
559 "[h]: /after-heading",
560 "",
561 "---",
562 "[t]: /after-break",
563 "",
564 "===",
565 "[p]: /paragraph-text",
566 "",
567 `${indent}\`\`\`sh`,
568 "npm install",
569 `${indent}\`\`\``,
570 "[fence]: /after-fence",
571 "~~~",
572 "~~~",
573 "Text after a fence",
574 "[q]: /continues-the-paragraph",
575 "",
576 "$$",
577 "x",
578 "$$ trailing",
579 "[math]: /inside-math",
580 "",
581 "<!-->",
582 "```",
583 "-->",
584 "```",
585 "[comment]: /after-a-closed-comment",
586 "```",
587 "[code]: /inside-a-fence-after-a-comment",
588 "```",
589 "",
590 "<!-- Links",
591 "[hidden]: /inside-a-comment",
592 "-->",
593 "[html]: /after-an-html-block",
594 "",
595 "<pre></pre>",
596 "[pre]: /after-a-one-line-html-block",
597 "",
598 "- ```md",
599 " ~~~",
600 " ~~~",
601 " [list]: /inside-a-list-fence",
602 " ```",
603 ].join("\n");
604 expect(splitMarkdown(text).definitions).toBe(
605 "[site]: https://example.com\n[b]: https://example.com/badge.svg 'Badge'\n[h]: /after-heading\n[t]: /after-break\n[fence]: /after-fence\n[comment]: /after-a-closed-comment\n[html]: /after-an-html-block\n[pre]: /after-a-one-line-html-block",
606 );
607 const frontmatter = ["---", "title: x", "...", "[fm]: /after-frontmatter", "", "# A"];
608 expect(splitMarkdown(frontmatter.join("\n")).definitions).toBe("[fm]: /after-frontmatter");
609 const unclosed = ["---", ...Array<string>(1000).fill("text"), "[u]: /paragraph-text"];
610 expect(splitMarkdown(unclosed.join("\n")).definitions).toBe("");
611 expect(splitMarkdown("---\n[rule]: /after-leading-rule\n\n# A").definitions).toBe(
612 "[rule]: /after-leading-rule",
613 );
614 const unbalanced = [
615 "[x]: /docs/example)",
616 "[after]: /continues-paragraph",
617 "",
618 "[open]: /docs/example(",
619 "",
620 "[bs]: /docs/example\\\\)",
621 "",
622 "[balanced]: /docs/example(a(b))",
623 "[escaped]: /docs/example\\)",
624 "[angle]: </docs/example)>",
625 ];
626 expect(splitMarkdown(unbalanced.join("\n")).definitions).toBe(
627 "[balanced]: /docs/example(a(b))\n[escaped]: /docs/example\\)\n[angle]: </docs/example)>",
628 );
629 },
630 );
631});
632​
633describe("withMarkdownDefinitions", () => {
634 const html = (text: string) => {
635 const processor = unified().use(remarkParse).use(remarkRehype);
636 return toHtml(processor.runSync(processor.parse(text)));
637 };
638​
639 it("keeps the first document definition ahead of later chunk definitions", () => {
640 const text = "[id]: /first\n\n" + "x".repeat(4100) + "\n\n# Next\n[id]: /later\n\n[id]";
641 const { chunks, definitions } = splitMarkdown(text);
642 expect(html(text)).toContain('href="/first"');
643 expect(chunks).toHaveLength(2);
644 expect(html(withMarkdownDefinitions(chunks[1]!.text, definitions))).toContain('href="/first"');
645 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
646 });
647​
648 it.each([
649 ["a wrapped label with an inline destination", "[release\nnotes]: /first", "/first", ""],
650 ["a wrapped label with a next-line destination", "[release\nnotes]:\n /first", "/first", ""],
651 [
652 "a definition after indented code",
653 " [release notes]: /example\n[release notes]: /first",
654 "/first",
655 "",
656 ],
657 [
658 "a title on the next line of the preceding definition",
659 '[other]: /other\n "Other"\n[release notes]: /first',
660 "/first",
661 "",
662 ],
663 [
664 "a title starting on the destination line",
665 '[release notes]: /first "First\n release"',
666 "/first",
667 'title="First\nrelease"',
668 ],
669 [
670 "a destination ending in a nonbreaking space",
671 "[release notes]:\n /first\u00a0",
672 "/first%C2%A0",
673 "",
674 ],
675 ])("preserves the first reference with %s", (_, first, href, title) => {
676 const text = `${first}\n\n${"x".repeat(4100)}\n\n# Next\n[release notes]: /later\n\n[Release][release notes]`;
677 const { chunks, definitions } = splitMarkdown(text);
678 expect(chunks).toHaveLength(2);
679 const rendered = html(withMarkdownDefinitions(chunks[1]!.text, definitions));
680 expect(rendered).toContain(`href="${href}"`);
681 if (title) expect(rendered).toContain(title);
682 });
683​
684 it("ignores definitions after a paragraph continuation and keeps large indented code lookup", () => {
685 expect(splitMarkdown("[a]: /u\n bar\n[b]: /v").definitions).toBe("[a]: /u");
686 const largeCode = `\t${"a".repeat(17_000)}\n\t~~~\n\nhttps://example.com/demo.mp4`;
687 expect(markdownFlowLineLookup(largeCode)(2)).toBe("indented-code");
688 });
689​
690 it("shares a wrapped label at the Markdown length limit with an escaped bracket", () => {
691 const definition = `[${"a".repeat(995)}\\]\nct]: /first`;
692 expect(splitMarkdown(definition).definitions).toBe(definition);
693 });
694​
695 it("leaves oversized titles with their source definitions", () => {
696 const title = "t".repeat(16 * 1024);
697 const text = `[id]\n\n[id]:\n /first\n "${title}"\n\n# Next\n[ID]: /later\n\n[id]`;
698 const { chunks, definitions } = splitMarkdown(text);
699 expect(chunks).toHaveLength(2);
700 const first = html(withMarkdownDefinitions(chunks[0]!.text, definitions));
701 expect(first).toContain('href="/first"');
702 expect(first).toContain(`title="${title}"`);
703 });
704​
705 it.each(["", '" trailing text', '\\"'])(
706 "shares a complete definition before a long quote-led paragraph ending in %j",
707 (suffix) => {
708 const text = `[id]:\n /first\n "${"x".repeat(16 * 1024)}${suffix}\n\n# Next\n[id]: /later\n\n[id]`;
709 const { chunks, definitions } = splitMarkdown(text);
710 expect(chunks).toHaveLength(2);
711 const rendered = html(withMarkdownDefinitions(chunks[1]!.text, definitions));
712 expect(rendered).toContain('href="/first"');
713 },
714 );
715​
716 it.each([
717 ["inline links", "[a](/x)".repeat(2000), "\n\n", 64],
718 ["link-like text separated by thematic breaks", "[note] text\n***", "\n", 2000],
719 ["invalid definitions separated by thematic breaks", "[note]: /invalid)\n***", "\n", 2000],
720 ])("keeps long runs of %s out of shared definitions", (_, block, separator, count) => {
721 const text = Array.from({ length: count }, () => block).join(separator);
722 const { chunks, definitions } = splitMarkdown(text);
723 expect(definitions).toBe("");
724 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
725 });
726​
727 it("keeps a display math opener and its contents out of shared definitions", () => {
728 const text = "[actual]\n\n[unused]:\n$$\n\n[actual]: /wrong\n\n$$\n\n[actual]: /right";
729 const { chunks, definitions } = splitMarkdown(text, 1);
730 expect(html(withMarkdownDefinitions(chunks[0]!.text, definitions))).toContain('href="/right"');
731 expect(definitions).toBe("[actual]: /right");
732 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
733 });
734​
735 it("collects a long run of titled references within the shared definition budget", () => {
736 const references = Array.from({ length: 2000 }, (_, index) => `[r${index}]:\n /url "Title"`);
737 const source = references.join("\n");
738 const { definitions } = splitMarkdown(source);
739 expect(definitions).toBe(source.slice(0, definitions.length));
740 expect(definitions).toContain(references[500]);
741 expect(definitions.length).toBeLessThanOrEqual(16 * 1024);
742 expect(definitions).not.toContain("[r1999]");
743 });
744​
745 it("keeps frontmatter hidden and task offsets shifted by exactly the prefix", () => {
746 const text = "\uFEFF---\r\ntitle: hidden\r\n---\r\n\r\n[ref]: /x\r\n\r\n- [ ] task";
747 const { definitions } = splitMarkdown(text);
748 const rendered = withMarkdownDefinitions(text, definitions);
749 expect(html(rendered)).not.toContain("hidden");
750 const list = unified()
751 .use(remarkParse)
752 .use(remarkGfm)
753 .parse(rendered)
754 .children.find((node) => node.type === "list");
755 const marker = taskListMarkerOffset(rendered, list!.position!.start.offset!);
756 expect(marker! - (definitions.length + 2)).toBe(text.indexOf("[ ]"));
757 });
758​
759 it("keeps shared definitions out of a trailing unclosed code fence", () => {
760 const text = "[ref]: /dst\n\n```text\nshown";
761 const { definitions } = splitMarkdown(text);
762 expect(html(withMarkdownDefinitions(text, definitions))).toBe(html(text));
763 });
764});
765​
766describe("chunked Markdown footnotes", () => {
767 it.each([{ renderedChunkSize: LARGE_MARKDOWN_CHUNK_MAX_CHARS }, { renderedChunkSize: 0 }])(
768 "counts only rendered references with a $renderedChunkSize-character sibling",
769 ({ renderedChunkSize }) => {
770 const ref = "[^note]";
771 const rendered = renderedChunkSize
772 ? `${"a".repeat(renderedChunkSize - ref.length - 1)}${ref}\n\n`
773 : "";
774 const oversized = `${"b".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - ref.length)}${ref}\n\n`;
775 const definition = "[^note]: Shared explanation.";
776 const { definitions, footnotes } = splitMarkdown(
777 `${rendered}${oversized}# Appendix\n\n${definition}`,
778 1,
779 );
780 const section = buildMarkdownFootnotesSection(definitions, footnotes);
781 expect(section?.text ?? null).toBe(renderedChunkSize ? `${ref}\n\n${definition}` : null);
782 },
783 );
784​
785 it("keeps footnotes undefined for single-chunk files and unreferenced definitions", () => {
786 const small = "A footnote reference.[^1]\n\n[^1]: The footnote text.\n";
787 expect(splitMarkdown(small).footnotes).toBeUndefined();
788​
789 const unreferenced = [
790 "Intro paragraph.",
791 "",
792 ...Array.from({ length: 40 }, (_, i) => `Paragraph ${i}. ${"Lorem ipsum. ".repeat(12)}`),
793 "",
794 "[^unused]: Never referenced.",
795 ].join("\n");
796 const split = splitMarkdown(unreferenced);
797 expect(split.chunks.length).toBeGreaterThan(1);
798 expect(split.footnotes).toBeUndefined();
799 });
800​
801 it("collects footnote definitions and per-chunk references across pieces", () => {
802 const paragraphs = Array.from(
803 { length: 60 },
804 (_, i) =>
805 `Paragraph ${i}. ${"Lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(2)}`,
806 );
807 const text = [
808 "A footnote reference.[^1] Escaped \\[^1], code `[^1]`, [link](https://example.com/[^1]).",
809 "",
810 ...paragraphs.slice(0, 35).flatMap((p) => [p, ""]),
811 "Second ref[^note] and repeat[^1].",
812 "",
813 ...paragraphs.slice(35).flatMap((p) => [p, ""]),
814 "```md",
815 "[^fake]: inside code fence",
816 "```",
817 "",
818 "[^1]: The footnote text.",
819 " Second paragraph of footnote 1.",
820 "",
821 "[^note]: First note definition.",
822 "",
823 "[^note]: Duplicate ignored.",
824 ].join("\n");
825​
826 const { chunks, definitions, footnotes } = splitMarkdown(text);
827 expect(chunks.length).toBeGreaterThan(1);
828 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
829 expect(footnotes).toBeDefined();
830 expect(footnotes!.stubs).toBe("[^1]: .\n[^note]: .");
831 expect(footnotes!.definitions).toBe(
832 "[^1]: The footnote text.\n Second paragraph of footnote 1.\n\n[^note]: First note definition.",
833 );
834 expect(footnotes!.chunkRefs.flat()).toEqual(["1", "note", "1"]);
835​
836 const firstRefChunk = footnotes!.chunkRefs.findIndex((refs) => refs.length > 0);
837 const secondRefChunk = footnotes!.chunkRefs.findIndex(
838 (refs, index) => index > firstRefChunk && refs.length > 0,
839 );
840 expect(firstRefChunk).toBe(0);
841 expect(secondRefChunk).toBeGreaterThan(0);
842​
843 const preparedFirst = prepareMarkdownChunk(
844 chunks[firstRefChunk]!.text,
845 firstRefChunk,
846 definitions,
847 footnotes,
848 );
849 expect(preparedFirst.footnotesMode).toBe("omit");
850​
851 const preparedSecond = prepareMarkdownChunk(
852 chunks[secondRefChunk]!.text,
853 secondRefChunk,
854 definitions,
855 footnotes,
856 );
857 expect(preparedSecond.footnotesMode).toBe("omit-seeded");
858 expect(preparedSecond.text).toContain("[^1]\n\n");
859​
860 const section = buildMarkdownFootnotesSection(definitions, footnotes)?.text;
861 expect(section).toContain("[^1] [^note] [^1]");
862 expect(section).toContain("Second paragraph of footnote 1.");
863 expect(section).not.toContain("Duplicate ignored.");
864​
865 expect(findFootnoteRefChunkIndex(footnotes!, 1, 1)).toBe(firstRefChunk);
866 expect(findFootnoteRefChunkIndex(footnotes!, 2, 1)).toBe(secondRefChunk);
867 expect(findFootnoteRefChunkIndex(footnotes!, 1, 2)).toBe(secondRefChunk);
868 expect(findFootnoteRefChunkIndex(footnotes!, 1, 3)).toBeNull();
869 });
870​
871 it.each([" \t", " \t", " \t"])(
872 "keeps a footnote paragraph indented with %j as a continuation",
873 (indent) => {
874 const definition = `[^b]: First paragraph\n\n${indent}Second paragraph`;
875 const { footnotes } = splitMarkdown(
876 `Filler ${"x".repeat(4100)}\n\nReal[^b]\n\n${definition}`,
877 );
878 expect(footnotes?.definitions).toBe(definition);
879 },
880 );
881​
882 it.each([" \t", " \t", " \t"])(
883 "keeps a footnote-like reference in indented code after a list dedented with %j literal",
884 (indent) => {
885 const { footnotes } = splitMarkdown(
886 `Filler ${"x".repeat(4100)}\n\n123. item\n\n${indent}code\n\n code[^a]\n\n[^a]: note`,
887 );
888 expect(footnotes).toBeUndefined();
889 },
890 );
891​
892 it.each([" \t", " \t", " \t"])(
893 "does not count a footnote-like reference in code indented with %j",
894 (indent) => {
895 const { footnotes } = splitMarkdown(
896 `Filler ${"x".repeat(4100)}\n\nParagraph\n\n${indent}code[^a]\n\n[^a]: note`,
897 );
898 expect(footnotes).toBeUndefined();
899 },
900 );
901​
902 it("keeps task list offsets exact when footnote seed prefix is prepended", () => {
903 const filler = Array.from({ length: 40 }, (_, i) => `Section ${i} ${"x".repeat(120)}`).join(
904 "\n\n",
905 );
906 const text = [
907 "[site]: https://example.com",
908 "",
909 "Lead[^1] with [site].",
910 "",
911 filler,
912 "",
913 "- [ ] task in chunk with seeded ref[^1]",
914 "",
915 "[^1]: Footnote body.",
916 ].join("\n");
917 const { chunks, definitions, footnotes } = splitMarkdown(text);
918 const taskChunkIndex = chunks.findIndex((chunk) => chunk.text.includes("- [ ] task"));
919 expect(taskChunkIndex).toBeGreaterThan(0);
920 const prepared = prepareMarkdownChunk(
921 chunks[taskChunkIndex]!.text,
922 taskChunkIndex,
923 definitions,
924 footnotes,
925 );
926 const list = unified()
927 .use(remarkParse)
928 .use(remarkGfm)
929 .parse(prepared.text)
930 .children.find((node) => node.type === "list");
931 const marker = taskListMarkerOffset(prepared.text, list!.position!.start.offset!);
932 let chunkStart = 0;
933 for (let i = 0; i < taskChunkIndex; i++) {
934 chunkStart += chunks[i]!.text.length + 1;
935 }
936 expect(chunkStart + marker! - prepared.offsetShift).toBe(text.indexOf("[ ]"));
937 });
938​
939 it("counts references followed by ':' or '(', skips inline math, and stays linear", () => {
940 const filler = Array.from(
941 { length: 40 },
942 (_, i) => `Paragraph ${i}. ${"word ".repeat(25)}`,
943 ).join("\n\n");
944 const text = [
945 "As noted[^a]: see this. Quote.[^b](emphasis added) and [^c](https://example.com). Math $x[^a]y$.",
946 "",
947 // Unclosed marks rescanned from each opener took seconds; nested quotes took minutes.
948 `${"> ".repeat(40)}x[^b]: t`,
949 "",
950 `[^c] ${"](( ".repeat(20000)}`,
951 "",
952 `[^a] ${"$x ".repeat(20000)}`,
953 "",
954 `[^c] ${"<!-- ](<".repeat(16_000)}`,
955 "",
956 "Literal ](see[^b]) but [link](x[^a]) is a destination.",
957 "",
958 filler,
959 "",
960 "[^a]: First note.",
961 "[^b]: Second note.",
962 "[^c]: Third note.",
963 ].join("\n");
964​
965 const { chunks, footnotes } = splitMarkdown(text);
966 expect(chunks.length).toBeGreaterThan(1);
967 expect(footnotes?.chunkRefs.flat()).toEqual(["a", "b", "c", "b", "c", "a", "c", "b"]);
968 });
969​
970 it("falls back when footnote definitions exceed the shared cap", () => {
971 const sections = Array.from(
972 { length: 400 },
973 (_, i) => `Paragraph ${i} referencing [^f${i}].\n\n[^f${i}]: ${"note text ".repeat(20)}`,
974 ).join("\n\n");
975 const split = splitMarkdown(sections);
976 expect(split.chunks.length).toBeGreaterThan(1);
977 expect(split.footnotes).toBeUndefined();
978 });
979​
980 it("separates stub footnote definitions from a chunk starting with indented code", () => {
981 const filler = Array.from({ length: 40 }, (_, i) => `Section ${i} ${"x".repeat(120)}`).join(
982 "\n\n",
983 );
984 const text = [
985 " indented()",
986 "",
987 "Ref[^1].",
988 "",
989 filler,
990 "",
991 " code[^a]",
992 "",
993 "- item",
994 "",
995 " item text[^2]",
996 "",
997 "[^1]: Footnote body.",
998 "",
999 "[^a]: Literal in code.",
1000 "",
1001 "[^2]: In a list item.",
1002 ].join("\n");
1003​
1004 const { chunks, definitions, footnotes } = splitMarkdown(text);
1005 const prepared = prepareMarkdownChunk(chunks[0]!.text, 0, definitions, footnotes);
1006 expect(prepared.footnotesMode).toBe("omit");
1007 expect(prepared.text).toContain("<!-- -->\n\n indented()");
1008 expect(footnotes?.chunkRefs.flat()).toEqual(["1", "2"]);
1009 // The unreferenced `[^a]` definition is dropped when the section renders.
1010 const section = buildMarkdownFootnotesSection(definitions, footnotes)!.text;
1011 expect(section.startsWith("[^1] [^2]\n\n")).toBe(true);
1012 });
1013​
1014 it("scans a heading that interrupts a paragraph apart from the surrounding code spans", () => {
1015 const text = [
1016 `Filler ${"x".repeat(4100)}`,
1017 "",
1018 "`open",
1019 "# Heading[^a]`",
1020 "",
1021 "Real[^b]",
1022 "",
1023 "[^a]: Heading note",
1024 "[^b]: Body note",
1025 ].join("\n");
1026​
1027 const { chunks, definitions, footnotes } = splitMarkdown(text);
1028 expect(chunks.length).toBeGreaterThan(1);
1029 expect(footnotes?.chunkRefs.flat()).toEqual(["a", "b"]);
1030 const section = buildMarkdownFootnotesSection(definitions, footnotes)!.text;
1031 expect(section.startsWith("[^a] [^b]\n\n")).toBe(true);
1032 });
1033​
1034 it.each([
1035 ["a list item", "- Item[^a]`"],
1036 ["a quote", "> Quote[^a]`"],
1037 ["a thematic break", "***\nText[^a]`"],
1038 ["an equals Setext underline", "===\nText[^a]`"],
1039 ["a dash Setext underline", "---\nText[^a]`"],
1040 ])(
1041 "scans %s that interrupts a paragraph apart from the surrounding code spans",
1042 (_name, block) => {
1043 const text = [
1044 `Filler ${"x".repeat(4100)}`,
1045 "",
1046 "`open",
1047 block,
1048 "",
1049 "Real[^b]",
1050 "",
1051 "[^a]: First note",
1052 "[^b]: Second note",
1053 ].join("\n");
1054​
1055 const { chunks, footnotes } = splitMarkdown(text);
1056 expect(chunks.length).toBeGreaterThan(1);
1057 expect(footnotes?.chunkRefs.flat()).toEqual(["a", "b"]);
1058 },
1059 );
1060​
1061 it.each([
1062 ["a continued quote line", "> `open\n> Quote[^a]`"],
1063 ["a list marker that cannot interrupt", "`open\n2. Item[^a]`"],
1064 ])("keeps code spans paired across %s", (_name, block) => {
1065 const text = [
1066 `Filler ${"x".repeat(4100)}`,
1067 "",
1068 block,
1069 "",
1070 "Real[^b]",
1071 "",
1072 "[^a]: First note",
1073 "[^b]: Second note",
1074 ].join("\n");
1075​
1076 const { chunks, footnotes } = splitMarkdown(text);
1077 expect(chunks.length).toBeGreaterThan(1);
1078 expect(footnotes?.chunkRefs.flat()).toEqual(["b"]);
1079 });
1080});