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