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

markdownChunks.ts

162 lines6.6 KB

1// About one screen of rendered Markdown; parsing costs up to ~40 ms per KB with tables and math.
2const CHUNK_TARGET_CHARS = 4 * 1024;
3// A chunk past this (one huge fence or HTML block) is too slow to parse at once; show source.
4export const LARGE_MARKDOWN_CHUNK_MAX_CHARS = 128 * 1024;
5// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
6const FENCE_OPEN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
7const ATX_HEADING = /^#{1,6}(?:[ \t]|\r?$)/;
8// A thematic break, or a "---" setext underline; no paragraph stays open after either. A lone
9// "===" is paragraph text unless it underlines one, so it is left out.
10const THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
11// A column-0 paragraph, quote or table after a blank line closes any open list, quote or table.
12const BLOCK_START = /^[\p{L}\p{N}`[!|>]/u;
13const ORDERED_ITEM = /^\d{1,9}[.)](?:[ \t]|\r?$)/;
14// CommonMark HTML blocks of types 1-5 and display math run past blank lines until their closer.
15const SPANNING_BLOCKS: ReadonlyArray<readonly [open: RegExp, close: RegExp]> = [
16 [/^ {0,3}<(?:script|pre|style|textarea)(?=[\s>]|$)/i, /<\/(?:script|pre|style|textarea)>/i],
17 [/^ {0,3}<!--/, /-->/],
18 [/^ {0,3}<\?/, /\?>/],
19 [/^ {0,3}<!\[CDATA\[/, /\]\]>/],
20 [/^ {0,3}<![A-Za-z]/, />/],
21 [/^ {0,3}\$\$/, /\$\$/],
22];
23​
24// A tag name, not an autolink such as <https://example.com>.
25const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/;
26const closesAtBlankLine = (next: string) => next.trim() === "";
27​
28// A <details> or <table> wraps the Markdown between its tags, across the blank lines that end
29// each HTML block, so a cut waits until the ones an HTML block opened are closed.
30const WRAPPER_TAG = /<(\/?)(?:details|table)(?=[\s/>]|$)/gi;
31// An end tag that never comes, or back-to-back wrappers, must not make one huge piece.
32const WRAPPED_MAX_CHARS = 32 * 1024;
33​
34function withoutComments(line: string): string {
35 let kept = "";
36 let at = 0;
37 for (let open = line.indexOf("<!--"); open !== -1; open = line.indexOf("<!--", at)) {
38 const close = line.indexOf("-->", open + 4);
39 if (close === -1) break;
40 kept += line.slice(at, open);
41 at = close + 3;
42 }
43 return kept + line.slice(at);
45​
46function openedWrappers(line: string): number {
47 let opened = 0;
48 for (const [, closing] of withoutComments(line).matchAll(WRAPPER_TAG)) {
49 opened += closing ? -1 : 1;
50 }
51 return opened;
53​
54/** Returns how to recognize the end of a block that `line` opens, or null for none. */
55function blockCloser(line: string): ((line: string) => boolean) | null {
56 const fence = FENCE_OPEN.exec(line)?.[1];
57 if (fence) {
58 return (next) => {
59 const closer = FENCE_OPEN.exec(next)?.[1];
60 return (
61 closer !== undefined &&
62 closer[0] === fence[0] &&
63 closer.length >= fence.length &&
64 !next.trim().slice(closer.length)
65 );
66 };
67 }
68 for (const [open, close] of SPANNING_BLOCKS) {
69 const opener = open.exec(line)?.[0];
70 if (opener === undefined) continue;
71 return close.test(line.slice(opener.length)) ? null : (next) => close.test(next);
72 }
73 // Other HTML blocks (CommonMark types 6 and 7) run until a blank line.
74 return HTML_BLOCK_START.test(line) ? closesAtBlankLine : null;
76​
77export interface MarkdownChunk {
78 readonly text: string;
79 readonly lines: number;
81​
82const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/;
83const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/;
84// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one.
85const FRONTMATTER_MAX_LINES = 1000;
86​
87// A one-line link reference definition; footnotes are left alone so each piece does not grow
88// a footnote section.
89const LINK_DEFINITION =
90 /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/;
91// Definitions past this are not repeated into every piece; their parse cost would outweigh links.
92const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024;
93​
94export interface SplitMarkdown {
95 readonly chunks: readonly MarkdownChunk[];
96 readonly definitions: string;
98​
99/**
100 * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs
101 * that start a new top-level block. Leading frontmatter stays in the first piece. Link
102 * definitions are collected so every piece can resolve them; footnotes resolve only inside their
103 * own piece, and duplicate heading slugs restart per piece.
104 */
105export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown {
106 const chunks: MarkdownChunk[] = [];
107 const definitions: string[] = [];
108 let lines: string[] = [];
109 let first = true;
110 let chars = 0;
111 let closes: ((line: string) => boolean) | null = null;
112 let afterBlankLine = false;
113 let afterDefinition = false;
114 let afterHeading = false;
115 let definitionChars = 0;
116 let openWrappers = 0;
117 const flush = () => {
118 chunks.push({ text: lines.join("\n"), lines: lines.length });
119 lines = [];
120 chars = 0;
121 };
122 for (const line of text.split("\n")) {
123 if (closes !== null) {
124 if (closes(line)) closes = null;
125 } else if (first && FRONTMATTER_OPEN.test(line)) {
126 let seen = 0;
127 closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES;
128 } else {
129 if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0;
130 const cut =
131 chars >= targetChars &&
132 openWrappers === 0 &&
133 (ATX_HEADING.test(line) ||
134 (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line)));
135 if (cut) flush();
136 closes = blockCloser(line);
137 // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or
138 // another definition.
139 const definition: boolean =
140 (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line);
141 afterDefinition = definition;
142 if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) {
143 definitions.push(line.trim());
144 definitionChars += line.length + 1;
145 }
146 }
147 if (closes === closesAtBlankLine)
148 openWrappers = Math.max(0, openWrappers + openedWrappers(line));
149 first = false;
150 lines.push(line);
151 chars += line.length + 1;
152 afterBlankLine = line.trim() === "";
153 afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line));
154 }
155 flush();
156 return { chunks, definitions: definitions.join("\n") };
158​
159/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */
160export function withMarkdownDefinitions(text: string, definitions: string): string {
161 return definitions ? `${text}\n\n${definitions}` : text;