@orkestrel/markdown 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
1
  import { arrayOf, booleanShape, createContract, integerShape, isBoolean, isEmptyString, isNonEmptyArray, isNonEmptyString, isNumber, isString, lazyOf, literalOf, literalShape, nullableOf, objectShape, optionalShape, parseInteger, recordOf, stringShape, unionOf } from "@orkestrel/contract";
2
- import { HTML, SAFE_ATTRIBUTES, SAFE_URL_SCHEMES, TABLE_ALIGNMENTS, UNSAFE_ELEMENTS, attributeOf, foldNode as foldNode$1, renderHTML as renderHTML$1, renderText, sanitizeURL } from "@orkestrel/html";
2
+ import { HTML, SAFE_ATTRIBUTES, SAFE_URL_SCHEMES, TABLE_ALIGNMENTS, UNSAFE_ELEMENTS, attributeOf, collapseSpace, foldNode as foldNode$1, renderHTML as renderHTML$1, renderText, sanitizeURL } from "@orkestrel/html";
3
3
  //#region src/core/constants.ts
4
4
  /**
5
- * The maximum recursion depth the parse pipeline (`parseDocument` and its
6
- * `parsers.ts` helpers) and the `helpers.ts` traversal / projection functions
7
- * (`markdownToHTML`, `renderHTML`, `renderMarkdown`, `walkNodes`, `foldNode`,
8
- * `rewriteDocument`) honor before degrading. It bounds blockquote nesting, inline
5
+ * Caps the recursion depth the parse pipeline (`parseDocument` and its
6
+ * `parsers.ts` helpers), the `helpers.ts` traversal / projection functions
7
+ * (`markdownToHTML`, `renderMarkdown`, `walkNodes`, `foldNode`, `rewriteDocument`),
8
+ * and the `compilers.ts` renderer (`renderHTML`) honor before degrading. It bounds blockquote nesting, inline
9
9
  * nesting (emphasis / links), and traversal / projection recursion so pathological
10
10
  * or hostile input cannot exhaust the call stack. {@link htmlToMarkdown} is the
11
11
  * inherited exception: its fold and depth cap belong to `@orkestrel/html`.
12
12
  */
13
13
  var MAX_DEPTH = 64;
14
14
  /**
15
- * The frozen empty HTML-to-markdown projection from which projection factories
15
+ * Holds the frozen empty HTML-to-markdown projection from which projection factories
16
16
  * default every absent field.
17
17
  *
18
18
  * @example
@@ -31,182 +31,66 @@ var EMPTY_PROJECTION = Object.freeze({
31
31
  //#endregion
32
32
  //#region src/core/validators.ts
33
33
  /**
34
- * Whether `character` is an inline whitespace character (space / tab / newline) - the
35
- * emphasis flanking rule's space test.
34
+ * Determines whether a node is a heading block.
36
35
  *
37
- * @param character - The character to test
38
- * @returns `true` when it is inline whitespace
39
- *
40
- * @example
41
- * ```ts
42
- * isWhitespace(' ') // true
43
- * isWhitespace('a') // false
44
- * ```
45
- */
46
- function isWhitespace(character) {
47
- return character === " " || character === " " || character === "\n";
48
- }
49
- /**
50
- * Whether `character` is escapable by a leading backslash - the ASCII punctuation
51
- * markdown gives meaning to (so `\*` becomes `*` but `\.` stays `\.`).
52
- *
53
- * @param character - The single character after a backslash
54
- * @returns `true` when a backslash before it is an escape
55
- *
56
- * @example
57
- * ```ts
58
- * isEscapable('*') // true
59
- * isEscapable('a') // false
60
- * ```
61
- */
62
- function isEscapable(character) {
63
- return /[\\`*_{}[\]()#+\-.!>~|]/.test(character);
64
- }
65
- /**
66
- * Whether `line` is blank - empty, or containing only whitespace - the markdown
67
- * definition of a blank line that block parsing uses to separate paragraphs, skip
68
- * gaps, and end list continuations.
69
- *
70
- * @param line - The candidate line
71
- * @returns `true` when the line is blank
72
- *
73
- * @example
74
- * ```ts
75
- * isBlankLine(' ') // true
76
- * ```
77
- */
78
- function isBlankLine(line) {
79
- return isEmptyString(line.trim());
80
- }
81
- /**
82
- * Whether `line` is a blockquote line (`>` optionally indented up to three spaces) -
83
- * its content is de-quoted by {@link stripQuote}.
84
- *
85
- * @param line - The candidate line
86
- * @returns `true` when the line begins a blockquote
87
- *
88
- * @example
89
- * ```ts
90
- * isQuote('> quoted') // true
91
- * ```
92
- */
93
- function isQuote(line) {
94
- return /^\s{0,3}>/.test(line);
95
- }
96
- /**
97
- * Whether `line` closes a fence opened by `marker` - the same fence character, a run
98
- * at least as long, and nothing else but surrounding whitespace.
99
- *
100
- * @param line - The candidate closing line
101
- * @param marker - The opening fence's marker run (from {@link extractFence})
102
- * @returns `true` when `line` closes the fence
103
- *
104
- * @example
105
- * ```ts
106
- * isFenceClose('```', '```') // true
107
- * ```
108
- */
109
- function isFenceClose(line, marker) {
110
- const character = marker[0] === "~" ? "~" : "`";
111
- let index = 0;
112
- while (index < line.length && isFenceWhitespace(line[index])) index++;
113
- let run = 0;
114
- while (index < line.length && line[index] === character) {
115
- run++;
116
- index++;
117
- }
118
- if (run < marker.length) return false;
119
- while (index < line.length && isFenceWhitespace(line[index])) index++;
120
- return index === line.length;
121
- }
122
- /**
123
- * Whether `character` is a regex-`\s`-equivalent whitespace character - the
124
- * character class {@link isFenceClose}'s scan treats as surrounding padding.
125
- *
126
- * @param character - The single character to test, or `undefined` past the end of a line
127
- * @returns `true` when it is whitespace
36
+ * @param node - The AST node to test
37
+ * @returns True if the node is a {@link HeadingNode}; false otherwise
128
38
  *
129
39
  * @example
130
40
  * ```ts
131
- * isFenceWhitespace(' ') // true
132
- * isFenceWhitespace(undefined) // false
41
+ * isHeadingNode({ element: 'heading', level: 1, children: [] }) // true
133
42
  * ```
134
43
  */
135
- function isFenceWhitespace(character) {
136
- return character === " " || character === " " || character === "\n" || character === "\r" || character === "\f" || character === "\v";
44
+ function isHeadingNode(node) {
45
+ return node.element === "heading";
137
46
  }
138
47
  /**
139
- * Whether `line` is a thematic break (horizontal rule) - three or more of the SAME
140
- * marker `-`, `*`, or `_` (optionally space-separated) and nothing else (`---`,
141
- * `***`, `___`, `- - -`).
48
+ * Determines whether a node is a paragraph block.
142
49
  *
143
- * @param line - The candidate line
144
- * @returns `true` when the line is a thematic break
50
+ * @param node - The AST node to test
51
+ * @returns True if the node is a {@link ParagraphNode}; false otherwise
145
52
  *
146
53
  * @example
147
54
  * ```ts
148
- * isThematicBreak('---') // true
55
+ * isParagraphNode({ element: 'paragraph', children: [] }) // true
149
56
  * ```
150
57
  */
151
- function isThematicBreak(line) {
152
- const stripped = line.trim().replace(/\s+/g, "");
153
- if (stripped.length < 3) return false;
154
- const marker = stripped[0];
155
- if (marker !== "-" && marker !== "*" && marker !== "_") return false;
156
- return [...stripped].every((character) => character === marker);
58
+ function isParagraphNode(node) {
59
+ return node.element === "paragraph";
157
60
  }
158
61
  /**
159
- * Whether the pair (`header`, `delimiter`) opens a GFM table - `delimiter` is a row of
160
- * `|`-separated cells each matching `:?-+:?`, the GFM rule that a table requires a
161
- * header row IMMEDIATELY followed by a delimiter row.
62
+ * Determines whether a node is a list block.
162
63
  *
163
- * @param header - The candidate header line
164
- * @param delimiter - The line after it (the candidate delimiter)
165
- * @returns `true` when the two lines open a table
64
+ * @param node - The AST node to test
65
+ * @returns True if the node is a {@link ListNode}; false otherwise
166
66
  *
167
67
  * @example
168
68
  * ```ts
169
- * isTableStart('| a |', '| - |') // true
69
+ * isListNode({ element: 'list', ordered: false, start: 1, items: [] }) // true
170
70
  * ```
171
71
  */
172
- function isTableStart(header, delimiter) {
173
- if (delimiter === void 0 || !header.includes("|")) return false;
174
- const cells = splitTableRow(delimiter);
175
- if (cells.length === 0) return false;
176
- return cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
177
- }
178
- /** Determine whether a node is a heading block. */
179
- function isHeadingNode(node) {
180
- return node.element === "heading";
72
+ function isListNode(node) {
73
+ return node.element === "list";
181
74
  }
182
75
  /**
183
- * Determine whether a node is a paragraph block.
76
+ * Determines whether a node is a GFM table block.
184
77
  *
185
- * @example
186
- * ```ts
187
- * isParagraphNode({ element: 'paragraph', children: [] }) // true
188
- * ```
189
- */
190
- function isParagraphNode(node) {
191
- return node.element === "paragraph";
192
- }
193
- /**
194
- * Determine whether a node is a list block.
78
+ * @param node - The AST node to test
79
+ * @returns True if the node is a {@link TableNode}; false otherwise
195
80
  *
196
81
  * @example
197
82
  * ```ts
198
- * isListNode({ element: 'list', ordered: false, start: 1, items: [] }) // true
83
+ * isTableNode({ element: 'table', header: [], rows: [], align: [] }) // true
199
84
  * ```
200
85
  */
201
- function isListNode(node) {
202
- return node.element === "list";
203
- }
204
- /** Determine whether a node is a GFM table block. */
205
86
  function isTableNode(node) {
206
87
  return node.element === "table";
207
88
  }
208
89
  /**
209
- * Determine whether a node is a fenced code block.
90
+ * Determines whether a node is a fenced code block.
91
+ *
92
+ * @param node - The AST node to test
93
+ * @returns True if the node is a {@link CodeBlockNode}; false otherwise
210
94
  *
211
95
  * @example
212
96
  * ```ts
@@ -217,7 +101,10 @@ function isCodeBlockNode(node) {
217
101
  return node.element === "codeBlock";
218
102
  }
219
103
  /**
220
- * Determine whether a node is a blockquote block.
104
+ * Determines whether a node is a blockquote block.
105
+ *
106
+ * @param node - The AST node to test
107
+ * @returns True if the node is a {@link BlockquoteNode}; false otherwise
221
108
  *
222
109
  * @example
223
110
  * ```ts
@@ -228,7 +115,10 @@ function isBlockquoteNode(node) {
228
115
  return node.element === "blockquote";
229
116
  }
230
117
  /**
231
- * Determine whether a node is a thematic break (horizontal rule) block.
118
+ * Determines whether a node is a thematic break (horizontal rule) block.
119
+ *
120
+ * @param node - The AST node to test
121
+ * @returns True if the node is a {@link ThematicBreakNode}; false otherwise
232
122
  *
233
123
  * @example
234
124
  * ```ts
@@ -239,7 +129,10 @@ function isThematicBreakNode(node) {
239
129
  return node.element === "thematicBreak";
240
130
  }
241
131
  /**
242
- * Determine whether a node is a plain text run.
132
+ * Determines whether a node is a plain text run.
133
+ *
134
+ * @param node - The AST node to test
135
+ * @returns True if the node is a {@link TextNode}; false otherwise
243
136
  *
244
137
  * @example
245
138
  * ```ts
@@ -250,7 +143,10 @@ function isTextNode(node) {
250
143
  return node.element === "text";
251
144
  }
252
145
  /**
253
- * Determine whether a node is an emphasis run (`*em*` / `**strong**`).
146
+ * Determines whether a node is an emphasis run (`*em*` / `**strong**`).
147
+ *
148
+ * @param node - The AST node to test
149
+ * @returns True if the node is an {@link EmphasisNode}; false otherwise
254
150
  *
255
151
  * @example
256
152
  * ```ts
@@ -261,12 +157,15 @@ function isEmphasisNode(node) {
261
157
  return node.element === "emphasis";
262
158
  }
263
159
  /**
264
- * Determine whether a node is an inline code span.
160
+ * Determines whether a node is an inline code span.
265
161
  *
266
162
  * @remarks
267
163
  * Narrows to {@link CodeSpanNode} - the node whose `element` discriminant is
268
164
  * `'codeSpan'`.
269
165
  *
166
+ * @param node - The AST node to test
167
+ * @returns True if the node is a {@link CodeSpanNode}; false otherwise
168
+ *
270
169
  * @example
271
170
  * ```ts
272
171
  * isCodeSpanNode({ element: 'codeSpan', value: 'x' }) // true
@@ -276,7 +175,10 @@ function isCodeSpanNode(node) {
276
175
  return node.element === "codeSpan";
277
176
  }
278
177
  /**
279
- * Determine whether a node is a GFM hard line break.
178
+ * Determines whether a node is a GFM hard line break.
179
+ *
180
+ * @param node - The AST node to test
181
+ * @returns True if the node is a {@link LineBreakNode}; false otherwise
280
182
  *
281
183
  * @example
282
184
  * ```ts
@@ -286,12 +188,25 @@ function isCodeSpanNode(node) {
286
188
  function isLineBreakNode(node) {
287
189
  return node.element === "break";
288
190
  }
289
- /** Determine whether a node is a link. */
191
+ /**
192
+ * Determines whether a node is a link.
193
+ *
194
+ * @param node - The AST node to test
195
+ * @returns True if the node is a {@link LinkNode}; false otherwise
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * isLinkNode({ element: 'link', href: 'https://example.dev', children: [] }) // true
200
+ * ```
201
+ */
290
202
  function isLinkNode(node) {
291
203
  return node.element === "link";
292
204
  }
293
205
  /**
294
- * Determine whether a node is an image.
206
+ * Determines whether a node is an image.
207
+ *
208
+ * @param node - The AST node to test
209
+ * @returns True if the node is an {@link ImageNode}; false otherwise
295
210
  *
296
211
  * @example
297
212
  * ```ts
@@ -302,16 +217,16 @@ function isImageNode(node) {
302
217
  return node.element === "image";
303
218
  }
304
219
  /**
305
- * Determine whether an arbitrary value is a valid {@link InlineNode} - a text
220
+ * Determines whether an arbitrary value is a valid {@link InlineNode} - a text
306
221
  * run, emphasis, code span, hard break, link, or image, recursively validated.
307
222
  *
308
223
  * @remarks
309
224
  * Total: never throws, even on cyclic or pathologically deep input - every
310
225
  * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is
311
- * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).
226
+ * throw-contained per the `@orkestrel/contract` guard contract.
312
227
  *
313
228
  * @param value - The value to test
314
- * @returns `true` when `value` is a well-formed {@link InlineNode}
229
+ * @returns True if `value` is a well-formed {@link InlineNode}; false otherwise
315
230
  *
316
231
  * @example
317
232
  * ```ts
@@ -341,19 +256,19 @@ var isInlineNode = unionOf(recordOf({
341
256
  children: arrayOf(lazyOf(() => isInlineNode))
342
257
  }));
343
258
  /**
344
- * Determine whether an arbitrary value is a valid {@link BlockNode} - a
259
+ * Determines whether an arbitrary value is a valid {@link BlockNode} - a
345
260
  * heading, paragraph, list, table, code block, blockquote, or thematic break,
346
261
  * recursively validated.
347
262
  *
348
263
  * @remarks
349
264
  * Total: never throws, even on cyclic or pathologically deep input - every
350
265
  * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is
351
- * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).
266
+ * throw-contained per the `@orkestrel/contract` guard contract.
352
267
  * A list item's shape is inlined here (and in {@link isMarkdownNode}) rather
353
268
  * than named separately - it is used at exactly these two sites.
354
269
  *
355
270
  * @param value - The value to test
356
- * @returns `true` when `value` is a well-formed {@link BlockNode}
271
+ * @returns True if `value` is a well-formed {@link BlockNode}; false otherwise
357
272
  *
358
273
  * @example
359
274
  * ```ts
@@ -392,19 +307,19 @@ var isBlockNode = unionOf(recordOf({
392
307
  children: arrayOf(lazyOf(() => isBlockNode))
393
308
  }), recordOf({ element: literalOf("thematicBreak") }));
394
309
  /**
395
- * Determine whether an arbitrary value is a valid {@link MarkdownNode} - the
310
+ * Determines whether an arbitrary value is a valid {@link MarkdownNode} - the
396
311
  * {@link MarkdownDocument} root, a {@link BlockNode}, a {@link ListItemNode}, or
397
312
  * an {@link InlineNode}, recursively validated.
398
313
  *
399
314
  * @remarks
400
315
  * Total: never throws, even on cyclic or pathologically deep input - every
401
316
  * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is
402
- * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).
317
+ * throw-contained per the `@orkestrel/contract` guard contract.
403
318
  * A list item's shape is inlined here (and in {@link isBlockNode}) rather than
404
319
  * named separately - it is used at exactly these two sites.
405
320
  *
406
321
  * @param value - The value to test
407
- * @returns `true` when `value` is a well-formed {@link MarkdownNode}
322
+ * @returns True if `value` is a well-formed {@link MarkdownNode}; false otherwise
408
323
  *
409
324
  * @example
410
325
  * ```ts
@@ -419,17 +334,17 @@ var isMarkdownNode = unionOf(lazyOf(() => isMarkdownDocument), lazyOf(() => isBl
419
334
  children: arrayOf(lazyOf(() => isBlockNode))
420
335
  }), lazyOf(() => isInlineNode));
421
336
  /**
422
- * Determine whether an arbitrary value is a valid {@link MarkdownDocument} -
337
+ * Determines whether an arbitrary value is a valid {@link MarkdownDocument} -
423
338
  * the parsed-AST root {@link parseDocument} returns, recursively
424
339
  * validated.
425
340
  *
426
341
  * @remarks
427
342
  * Total: never throws, even on cyclic or pathologically deep input - every
428
343
  * combinator involved (`recordOf`, `arrayOf`) is throw-contained per the
429
- * `@orkestrel/contract` guard contract (AGENTS §14).
344
+ * `@orkestrel/contract` guard contract.
430
345
  *
431
346
  * @param value - The value to test
432
- * @returns `true` when `value` is a well-formed {@link MarkdownDocument}
347
+ * @returns True if `value` is a well-formed {@link MarkdownDocument}; false otherwise
433
348
  *
434
349
  * @example
435
350
  * ```ts
@@ -595,11 +510,16 @@ function parseBlocks(lines, depth, spans = /* @__PURE__ */ new Map(), end) {
595
510
  return blocks;
596
511
  }
597
512
  /**
598
- * Parses a markdown string into a typed {@link MarkdownDocument} AST via the
513
+ * Parses a markdown string into a typed {@link MarkdownDocument} AST through the
599
514
  * block phase.
600
515
  *
601
516
  * @param markdown - The markdown source to parse.
602
517
  * @returns The parsed document.
518
+ *
519
+ * @example
520
+ * ```ts
521
+ * parseDocument('# Hi') // { element: 'document', children: [{ element: 'heading', ... }] }
522
+ * ```
603
523
  */
604
524
  function parseDocument(markdown) {
605
525
  const [document] = parseProvenance(markdown);
@@ -610,6 +530,12 @@ function parseDocument(markdown) {
610
530
  *
611
531
  * @param markdown - The markdown source to parse.
612
532
  * @returns The parsed document and its node-identity span map.
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * const [document, spans] = parseProvenance('# Hi')
537
+ * spans.get(document) // { start: 0, end: 4 }
538
+ * ```
613
539
  */
614
540
  function parseProvenance(markdown) {
615
541
  const spans = /* @__PURE__ */ new Map();
@@ -629,714 +555,406 @@ function parseProvenance(markdown) {
629
555
  *
630
556
  * @param text - The inline markdown text to parse.
631
557
  * @returns The parsed inline nodes.
558
+ *
559
+ * @example
560
+ * ```ts
561
+ * parseInline('a *b*') // [{ element: 'text', value: 'a ' }, { element: 'emphasis', ... }]
562
+ * ```
632
563
  */
633
564
  function parseInline(text) {
634
565
  return coalesceText(scanInline(text, 0, text.length));
635
566
  }
636
567
  //#endregion
637
- //#region src/core/Markdown.ts
568
+ //#region src/core/helpers.ts
638
569
  /**
639
- * A stateful, parsed markdown document - wraps a typed {@link MarkdownDocument} AST
640
- * with the query (`find` / `filter` / `reduce` / iteration), rewrite (`map`), fold, and
641
- * streaming operations {@link MarkdownInterface} declares.
570
+ * Splits a markdown document into offset-bearing lines while normalizing CRLF and
571
+ * bare CR terminators at the line boundary. A single trailing terminator does not
572
+ * yield a final empty line.
642
573
  *
643
- * @remarks
644
- * - **Construction.** Given a `string`, the constructor runs {@link parseProvenance} (the
645
- * block phase then the inline phase) once, keeping the AST and a COPY of the span map
646
- * that parse recorded. Given a {@link MarkdownDocument}, the document is adopted AS-IS
647
- * and is NOT re-validated - gate an untrusted value with `isMarkdownDocument` first.
648
- * - **Provenance.** {@link span} reads the region of the ORIGINAL constructor string a
649
- * node was produced from, and it is handle-relative: a string-constructed handle exposes
650
- * the regions of the nodes it parsed, an adopted document exposes none, and a node from
651
- * another handle reports `undefined` here whatever that handle reports. Each call
652
- * returns a fresh value. A node reports the region THIS handle holds for its identity,
653
- * else the region of the direct input a rewrite named for it, else `undefined`: a text
654
- * run the parse joined from adjacent scanner output reports the region enclosing its
655
- * parts, and only a rewrite output that holds no region of its own and was assembled
656
- * from separate source nodes reports `undefined`.
657
- * {@link map} carries provenance across the rewrite: an unchanged node keeps its
658
- * region, a one-source replacement takes the region of the node it replaced, and a
659
- * rebuilt parent takes its original's.
660
- * - **Immutable.** {@link map} never mutates the stored AST - it returns a NEW `Markdown`
661
- * instance; the document root invariant (`element: 'document'`) always holds. An
662
- * identity rewrite still returns a new handle, over the same document tree.
663
- * - **Traversal order.** {@link walk} and the `find` / `filter` / `reduce` queries built
664
- * on it walk the AST depth-first, pre-order, root-inclusive (via {@link walkNodes});
665
- * `stream` is shallow - only the document's direct block children.
574
+ * @param markdown - The raw markdown source
575
+ * @returns The document's lines with their original-string coordinates
666
576
  *
667
577
  * @example
668
578
  * ```ts
669
- * import { Markdown, isHeadingNode, renderMarkdown } from '@src/core'
670
- *
671
- * const markdown = new Markdown('# Title\n\nA **bold** [link](https://x.dev).')
672
- * const heading = markdown.find(isHeadingNode) // the HeadingNode, or undefined
673
- * const shouted = markdown.map((node) =>
674
- * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,
675
- * )
676
- * renderMarkdown(shouted.document) // '# TITLE\n\nA **BOLD** [LINK](https://x.dev).'
579
+ * splitLines('a\r\nb') // [{ text: 'a', segments: [{ offset: 0, start: 0, end: 1 }] }, ...]
677
580
  * ```
678
581
  */
679
- var Markdown = class Markdown {
680
- #document;
681
- #spans;
682
- constructor(input) {
683
- if (typeof input === "string") {
684
- const [document, spans] = parseProvenance(input);
685
- this.#document = document;
686
- this.#spans = new Map(spans);
687
- } else {
688
- this.#document = input;
689
- this.#spans = /* @__PURE__ */ new Map();
582
+ function splitLines(markdown) {
583
+ const lines = [];
584
+ let start = 0;
585
+ let index = 0;
586
+ while (index < markdown.length) {
587
+ const character = markdown[index];
588
+ if (character !== "\r" && character !== "\n") {
589
+ index += 1;
590
+ continue;
690
591
  }
592
+ lines.push({
593
+ text: markdown.slice(start, index),
594
+ segments: [{
595
+ offset: 0,
596
+ start,
597
+ end: index
598
+ }]
599
+ });
600
+ index += character === "\r" && markdown[index + 1] === "\n" ? 2 : 1;
601
+ start = index;
691
602
  }
692
- /** The stored {@link MarkdownDocument} AST root. */
693
- get document() {
694
- return this.#document;
695
- }
696
- /**
697
- * Reads the region of the original markdown string a node of this handle's tree was
698
- * produced from.
699
- *
700
- * @param node - The node whose provenance to read
701
- * @returns A fresh {@link MarkdownSpan}, or `undefined` when this handle holds no
702
- * region for the node
703
- *
704
- * @example
705
- * ```ts
706
- * const source = '# Title\n\npara'
707
- * const markdown = new Markdown(source)
708
- * const heading = markdown.find(isHeadingNode)
709
- * const span = heading && markdown.span(heading)
710
- * span && source.slice(span.start, span.end) // '# Title'
711
- * ```
712
- */
713
- span(node) {
714
- const span = this.#spans.get(node);
715
- return span === void 0 ? void 0 : {
716
- start: span.start,
717
- end: span.end
718
- };
719
- }
720
- /**
721
- * THE deep traversal - a lazy, depth-first, pre-order, root-inclusive generator
722
- * over every {@link MarkdownNode} in the document. `find` / `filter` / `reduce`
723
- * all iterate this single traversal.
724
- *
725
- * @example
726
- * ```ts
727
- * for (const node of markdown.walk()) {
728
- * // every node, depth-first, pre-order, root-inclusive
729
- * }
730
- *
731
- * // also consumable by for-await - JS accepts a sync iterable in for-await
732
- * for await (const node of markdown.walk()) {
733
- * // same sequence, no separate async iterator needed
734
- * }
735
- * ```
736
- */
737
- *walk() {
738
- yield* walkNodes(this.#document);
739
- }
740
- find(predicate) {
741
- for (const node of this.walk()) if (predicate(node)) return node;
742
- }
743
- filter(predicate) {
744
- const out = [];
745
- for (const node of this.walk()) if (predicate(node)) out.push(node);
746
- return out;
747
- }
748
- /**
749
- * Rewrites the AST bottom-up (copy-on-write) and returns a new {@link Markdown},
750
- * carrying each output node's provenance across the rewrite. A rewrite that returns
751
- * its node unchanged shares that subtree instead of copying it, so an identity
752
- * rewrite copies no node and still returns a new handle.
753
- *
754
- * @param rewrite - The bottom-up node rewrite
755
- * @returns A new handle over the rewritten document
756
- */
757
- map(rewrite) {
758
- const [document, derivations] = rewriteDocument(this.#document, rewrite);
759
- return this.#derive(document, derivations);
760
- }
761
- /** Folds the AST depth-first, pre-order into an accumulator. */
762
- reduce(callback, initial) {
763
- let accumulator = initial;
764
- for (const node of this.walk()) accumulator = callback(accumulator, node);
765
- return accumulator;
766
- }
767
- /** Runs a total catamorphism over the document using a {@link MarkdownHandlers} table. */
768
- fold(handlers) {
769
- return foldNode(this.#document, handlers, 0);
770
- }
771
- /**
772
- * A web-standard {@link ReadableStream} over the document's top-level block nodes
773
- * (shallow, source order) - a fresh, pull-based source per call: one block is
774
- * enqueued per `pull`, so a slow reader's backpressure is respected. Cancellable,
775
- * async-iterable wherever the platform supports it (Node, Deno), and pipeable
776
- * through any {@link TransformStream} / {@link WritableStream}.
777
- *
778
- * @example
779
- * ```ts
780
- * // universal - works in every ReadableStream-supporting environment
781
- * const reader = markdown.stream().getReader()
782
- * for (let result = await reader.read(); !result.done; result = await reader.read()) {
783
- * console.log(result.value) // one BlockNode
784
- * }
785
- *
786
- * // Node / Deno / Firefox support async iteration of ReadableStream natively;
787
- * // other environments should use the reader loop above instead.
788
- * for await (const block of markdown.stream()) {
789
- * console.log(block)
790
- * }
791
- * ```
792
- */
793
- stream() {
794
- const blocks = this.#document.children;
795
- let index = 0;
796
- return new ReadableStream({ pull(controller) {
797
- if (index < blocks.length) {
798
- const block = blocks[index];
799
- if (block === void 0) {
800
- controller.close();
801
- return;
802
- }
803
- controller.enqueue(block);
804
- index += 1;
805
- } else controller.close();
806
- } });
807
- }
808
- #derive(document, derivations) {
809
- const derived = new Markdown(document);
810
- for (const node of walkNodes(document)) {
811
- const own = this.#spans.get(node);
812
- if (own !== void 0) {
813
- derived.#spans.set(node, own);
814
- continue;
815
- }
816
- const source = derivations.get(node);
817
- if (source === void 0) continue;
818
- const span = this.#spans.get(source);
819
- if (span !== void 0) derived.#spans.set(node, span);
820
- }
821
- return derived;
822
- }
823
- };
824
- //#endregion
825
- //#region src/core/shapers.ts
603
+ lines.push({
604
+ text: markdown.slice(start),
605
+ segments: [{
606
+ offset: 0,
607
+ start,
608
+ end: markdown.length
609
+ }]
610
+ });
611
+ if (lines.length > 1 && lines[lines.length - 1]?.text === "") lines.pop();
612
+ return lines;
613
+ }
826
614
  /**
827
- * The shape of a {@link TextNode} - a plain-text leaf inline run.
615
+ * Slices derived markdown text and narrows each intersecting source segment to the
616
+ * same text-relative range.
617
+ *
618
+ * @param source - The offset-bearing source to slice
619
+ * @param from - The inclusive text offset
620
+ * @param to - The exclusive text offset
621
+ * @returns The sliced text and its narrowed original-string segments
828
622
  *
829
623
  * @example
830
624
  * ```ts
831
- * import { createContract } from '@orkestrel/contract'
832
- * import { textShape } from '@src/core'
833
- *
834
- * const text = createContract(textShape)
835
- * text.is({ element: 'text', value: 'hi' }) // true
625
+ * sliceSource({ text: 'abc', segments: [{ offset: 0, start: 4, end: 7 }] }, 1, 3)
626
+ * // { text: 'bc', segments: [{ offset: 0, start: 5, end: 7 }] }
836
627
  * ```
837
628
  */
838
- var textShape = objectShape({
839
- element: literalShape(["text"]),
840
- value: stringShape()
841
- });
629
+ function sliceSource(source, from, to) {
630
+ const start = Math.max(0, Math.min(from, source.text.length));
631
+ const end = Math.max(start, Math.min(to, source.text.length));
632
+ const segments = [];
633
+ for (let index = 0; index < source.segments.length; index += 1) {
634
+ const segment = source.segments[index];
635
+ if (segment === void 0) continue;
636
+ const next = source.segments[index + 1];
637
+ const limit = Math.min(segment.offset + (segment.end - segment.start), next === void 0 ? source.text.length : next.offset);
638
+ const overlapStart = Math.max(start, segment.offset);
639
+ const overlapEnd = Math.min(end, limit);
640
+ const empty = segment.offset === limit && overlapStart === segment.offset;
641
+ if (overlapStart >= overlapEnd && !empty) continue;
642
+ const originalStart = overlapStart === limit ? segment.end : Math.min(segment.end, segment.start + overlapStart - segment.offset);
643
+ const originalEnd = overlapEnd === limit ? segment.end : Math.min(segment.end, segment.start + overlapEnd - segment.offset);
644
+ segments.push({
645
+ offset: overlapStart - start,
646
+ start: originalStart,
647
+ end: originalEnd
648
+ });
649
+ }
650
+ return {
651
+ text: source.text.slice(start, end),
652
+ segments
653
+ };
654
+ }
842
655
  /**
843
- * The shape of a {@link CodeSpanNode} - an inline code span (`` `code` ``).
656
+ * Joins offset-bearing markdown sources while mapping a separator to the original
657
+ * region between adjacent mapped sources.
658
+ *
659
+ * @param sources - The sources to join
660
+ * @param separator - The derived text inserted between sources
661
+ * @returns The joined text and every source-backed segment
844
662
  *
845
663
  * @example
846
664
  * ```ts
847
- * import { createContract } from '@orkestrel/contract'
848
- * import { codeSpanShape } from '@src/core'
849
- *
850
- * const codeSpan = createContract(codeSpanShape)
851
- * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true
665
+ * joinSources(splitLines('a\nb'), '\n')
666
+ * // { text: 'a\nb', segments: [...] }
852
667
  * ```
853
668
  */
854
- var codeSpanShape = objectShape({
855
- element: literalShape(["codeSpan"]),
856
- value: stringShape()
857
- });
669
+ function joinSources(sources, separator) {
670
+ let text = "";
671
+ const segments = [];
672
+ for (let index = 0; index < sources.length; index += 1) {
673
+ const source = sources[index];
674
+ if (source === void 0) continue;
675
+ if (index > 0) {
676
+ const previous = sources[index - 1];
677
+ const left = previous?.segments[previous.segments.length - 1];
678
+ const right = source.segments[0];
679
+ if (separator.length > 0 && left !== void 0 && right !== void 0 && left.end < right.start) segments.push({
680
+ offset: text.length,
681
+ start: left.end,
682
+ end: right.start
683
+ });
684
+ text += separator;
685
+ }
686
+ for (const segment of source.segments) segments.push({
687
+ offset: text.length + segment.offset,
688
+ start: segment.start,
689
+ end: segment.end
690
+ });
691
+ text += source.text;
692
+ }
693
+ return {
694
+ text,
695
+ segments
696
+ };
697
+ }
858
698
  /**
859
- * The shape of a {@link LineBreakNode} - a GFM hard line-break leaf.
699
+ * Projects a derived text range through its segments to a half-open region of the
700
+ * original markdown string.
701
+ *
702
+ * @param source - The offset-bearing source carrying the range
703
+ * @param from - The inclusive derived-text boundary
704
+ * @param to - The exclusive derived-text boundary
705
+ * @returns The original-string span, or `undefined` when either boundary is unmapped
860
706
  *
861
707
  * @example
862
708
  * ```ts
863
- * import { createContract } from '@orkestrel/contract'
864
- * import { lineBreakShape } from '@src/core'
865
- *
866
- * const lineBreak = createContract(lineBreakShape)
867
- * lineBreak.is({ element: 'break' }) // true
709
+ * projectSpan({ text: 'a', segments: [{ offset: 0, start: 4, end: 5 }] }, 0, 1)
710
+ * // { start: 4, end: 5 }
868
711
  * ```
869
712
  */
870
- var lineBreakShape = objectShape({ element: literalShape(["break"]) });
713
+ function projectSpan(source, from, to) {
714
+ if (from < 0 || to < from || to > source.text.length) return void 0;
715
+ let start;
716
+ let end;
717
+ for (let index = 0; index < source.segments.length; index += 1) {
718
+ const segment = source.segments[index];
719
+ if (segment === void 0) continue;
720
+ const next = source.segments[index + 1];
721
+ const limit = Math.min(segment.offset + (segment.end - segment.start), next === void 0 ? source.text.length : next.offset);
722
+ if (from === to && from >= segment.offset && from <= limit) {
723
+ if (next !== void 0 && from === next.offset) continue;
724
+ const position = from === limit ? segment.end : Math.min(segment.end, segment.start + from - segment.offset);
725
+ return {
726
+ start: position,
727
+ end: position
728
+ };
729
+ }
730
+ if (start === void 0 && from >= segment.offset && from < limit) start = segment.start + from - segment.offset;
731
+ if (to > segment.offset && to <= limit) end = to === limit ? segment.end : Math.min(segment.end, segment.start + to - segment.offset);
732
+ }
733
+ return start === void 0 || end === void 0 ? void 0 : {
734
+ start,
735
+ end
736
+ };
737
+ }
871
738
  /**
872
- * The shape of a {@link CodeBlockNode} - a fenced code block. `lang` is
873
- * optional (absent when the opening fence carries no info-string).
739
+ * Trims an offset-bearing source without losing the coordinates of its retained text.
740
+ *
741
+ * @param source - The source to trim
742
+ * @returns The trimmed text and its narrowed original-string segments
874
743
  *
875
744
  * @example
876
745
  * ```ts
877
- * import { createContract } from '@orkestrel/contract'
878
- * import { codeBlockShape } from '@src/core'
879
- *
880
- * const codeBlock = createContract(codeBlockShape)
881
- * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true
882
- * codeBlock.is({ element: 'codeBlock', code: 'x', lang: 'ts' }) // true
746
+ * trimSource({ text: ' a ', segments: [{ offset: 0, start: 4, end: 7 }] })
747
+ * // { text: 'a', segments: [{ offset: 0, start: 5, end: 6 }] }
883
748
  * ```
884
749
  */
885
- var codeBlockShape = objectShape({
886
- element: literalShape(["codeBlock"]),
887
- lang: optionalShape(stringShape()),
888
- code: stringShape()
889
- });
890
- /**
891
- * The shape of a {@link ThematicBreakNode} - a horizontal rule. Carries no
892
- * fields beyond its `element` discriminant.
750
+ function trimSource(source) {
751
+ const start = source.text.length - source.text.trimStart().length;
752
+ const end = source.text.trimEnd().length;
753
+ return sliceSource(source, start, Math.max(start, end));
754
+ }
755
+ /**
756
+ * Normalizes one paragraph line while retaining the full source run consumed by a
757
+ * trailing-space hard break.
758
+ *
759
+ * @param source - The offset-bearing paragraph line
760
+ * @param breaks - If `true`, preserves a trailing run of at least two spaces as the
761
+ * scanner's two-space hard-break syntax; if `false`, trims the line normally
762
+ * @returns The normalized line and its original-string segments
893
763
  *
894
764
  * @example
895
765
  * ```ts
896
- * import { createContract } from '@orkestrel/contract'
897
- * import { thematicBreakShape } from '@src/core'
898
- *
899
- * const thematicBreak = createContract(thematicBreakShape)
900
- * thematicBreak.is({ element: 'thematicBreak' }) // true
766
+ * normalizeParagraphLine(splitLines('text \nnext')[0], true).text // 'text '
901
767
  * ```
902
768
  */
903
- var thematicBreakShape = objectShape({ element: literalShape(["thematicBreak"]) });
769
+ function normalizeParagraphLine(source, breaks) {
770
+ if (!breaks || !source.text.endsWith(" ")) return trimSource(source);
771
+ const contentEnd = source.text.trimEnd().length;
772
+ const content = trimSource(sliceSource(source, 0, contentEnd));
773
+ const span = projectSpan(source, contentEnd, source.text.length);
774
+ return joinSources([content, {
775
+ text: " ",
776
+ segments: span === void 0 ? [] : [{
777
+ offset: 0,
778
+ start: span.start,
779
+ end: span.end
780
+ }]
781
+ }], "");
782
+ }
904
783
  /**
905
- * The shape of a {@link TableAlign} - the per-column GFM table alignment
906
- * literal.
784
+ * Counts the leading space / tab characters on `line` (a tab counts as one) - the
785
+ * indent that decides whether a list item's continuation belongs to the item.
786
+ *
787
+ * @param line - The line to measure
788
+ * @returns The number of leading space / tab characters
907
789
  *
908
790
  * @example
909
791
  * ```ts
910
- * import { createContract } from '@orkestrel/contract'
911
- * import { tableAlignShape } from '@src/core'
912
- *
913
- * const tableAlign = createContract(tableAlignShape)
914
- * tableAlign.is('left') // true
915
- * tableAlign.is('center') // true
916
- * tableAlign.is('top') // false
792
+ * countIndent(' text') // 2
917
793
  * ```
918
794
  */
919
- var tableAlignShape = literalShape([
920
- "left",
921
- "right",
922
- "center"
923
- ]);
795
+ function countIndent(line) {
796
+ let count = 0;
797
+ for (const character of line) if (character === " " || character === " ") count += 1;
798
+ else break;
799
+ return count;
800
+ }
924
801
  /**
925
- * The shape of {@link ListItemMatch} - the parsed parts of a single list-item
926
- * line the block phase's list detector returns. Fully non-recursive (no
927
- * nested node fields), so every field shapes directly.
802
+ * Checks whether `character` is whitespace under the emphasis flanking rule - a space, a
803
+ * tab, or a newline.
804
+ *
805
+ * @param character - The character to test
806
+ * @returns True if the flanking rule counts it as whitespace; false otherwise
928
807
  *
929
808
  * @example
930
809
  * ```ts
931
- * import { createContract } from '@orkestrel/contract'
932
- * import { listItemMatchShape } from '@src/core'
933
- *
934
- * const listItemParts = createContract(listItemMatchShape)
935
- * listItemParts.is({ ordered: false, start: 1, content: 'hi', indent: 0, marker: 2 }) // true
810
+ * isFlankingWhitespace(' ') // true
811
+ * isFlankingWhitespace('a') // false
936
812
  * ```
937
813
  */
938
- var listItemMatchShape = objectShape({
939
- ordered: booleanShape(),
940
- start: integerShape(),
941
- content: stringShape(),
942
- indent: integerShape(),
943
- marker: integerShape()
944
- });
945
- //#endregion
946
- //#region src/core/factories.ts
814
+ function isFlankingWhitespace(character) {
815
+ return character === " " || character === " " || character === "\n";
816
+ }
947
817
  /**
948
- * Create an HTML-to-markdown projection with absent fields defaulted from
949
- * {@link EMPTY_PROJECTION} and the block/inline exclusivity invariant enforced.
950
- *
951
- * @remarks
952
- * A block-bearing projection cannot also expose inline content. Callers may provide
953
- * both views, but `inlines` is flushed whenever `blocks` is non-empty.
818
+ * Checks whether `character` is escapable by a leading backslash - the ASCII punctuation
819
+ * markdown gives meaning to (so `\*` becomes `*` but `\.` stays `\.`).
954
820
  *
955
- * @param parts - The projection fields to provide
956
- * @returns A complete invariant-preserving projection
821
+ * @param character - The single character after a backslash
822
+ * @returns True if a backslash before it is an escape; false otherwise
957
823
  *
958
824
  * @example
959
825
  * ```ts
960
- * createProjection({
961
- * blocks: [{ element: 'thematicBreak' }],
962
- * inlines: [{ element: 'text', value: 'discarded' }],
963
- * })
964
- * // { blocks: [{ element: 'thematicBreak' }], inlines: [], text: '', cells: [], rows: [] }
826
+ * isEscapable('*') // true
827
+ * isEscapable('a') // false
965
828
  * ```
966
829
  */
967
- function createProjection(parts = {}) {
968
- const blocks = parts.blocks ?? EMPTY_PROJECTION.blocks;
969
- return {
970
- blocks,
971
- inlines: blocks.length === 0 ? parts.inlines ?? EMPTY_PROJECTION.inlines : [],
972
- text: parts.text ?? EMPTY_PROJECTION.text,
973
- cells: parts.cells ?? EMPTY_PROJECTION.cells,
974
- rows: parts.rows ?? EMPTY_PROJECTION.rows
975
- };
830
+ function isEscapable(character) {
831
+ return /[\\`*_{}[\]()#+\-.!>~|]/.test(character);
976
832
  }
977
833
  /**
978
- * Create a stateful markdown handle from a markdown string or an already-parsed
979
- * {@link MarkdownDocument} - a typed AST plus the query, rewrite, and fold operations
980
- * {@link MarkdownInterface} exposes.
981
- *
982
- * @remarks
983
- * Given a `string`, runs a block phase (headings / paragraphs / lists / GFM tables /
984
- * fenced code / blockquotes / thematic breaks) then an inline phase (emphasis /
985
- * inline code / links / images / hard breaks) to build a render-agnostic
986
- * {@link MarkdownDocument}. Given a
987
- * {@link MarkdownDocument}, adopts it AS-IS without re-validation - gate an untrusted
988
- * value with `isMarkdownDocument` first. Pure + total parse (malformed markdown
989
- * degrades to text, never throws) and zero-dependency - a hand-written scanner, no
990
- * regex-only structural parse, linear-time (no ReDoS).
834
+ * Checks whether `line` is blank - empty, or containing only whitespace - the markdown
835
+ * definition of a blank line that block parsing uses to separate paragraphs, skip
836
+ * gaps, and end list continuations.
991
837
  *
992
- * @param input - A markdown string to parse, or an already-parsed {@link MarkdownDocument}
993
- * @returns A working {@link MarkdownInterface}
838
+ * @param line - The candidate line
839
+ * @returns True if the line is blank; false otherwise
994
840
  *
995
841
  * @example
996
842
  * ```ts
997
- * import { createMarkdown } from '@src/core'
998
- *
999
- * const markdown = createMarkdown('# Hi\n\nRead the [guide](./guide.md).')
1000
- * markdown.document.children[0] // { element: 'heading', ... }
843
+ * isBlankLine(' ') // true
1001
844
  * ```
1002
845
  */
1003
- function createMarkdown(input) {
1004
- return new Markdown(input);
846
+ function isBlankLine(line) {
847
+ return isEmptyString(line.trim());
1005
848
  }
1006
849
  /**
1007
- * Compile the {@link textShape} into a {@link ContractInterface} for
1008
- * {@link TextNode} - a guard, coercing parser, JSON Schema, and seeded
1009
- * generator from one shape declaration (AGENTS §14).
850
+ * Checks whether `line` is a blockquote line (`>` optionally indented up to three spaces) -
851
+ * its content is de-quoted by {@link stripQuote}.
1010
852
  *
1011
- * @returns A `TextNode` contract bundling `schema` / `is` / `parse` / `generate`
853
+ * @param line - The candidate line
854
+ * @returns True if the line begins a blockquote; false otherwise
1012
855
  *
1013
856
  * @example
1014
857
  * ```ts
1015
- * import { createTextContract } from '@src/core'
1016
- *
1017
- * const text = createTextContract()
1018
- * text.is({ element: 'text', value: 'hi' }) // true
858
+ * isQuote('> quoted') // true
1019
859
  * ```
1020
860
  */
1021
- function createTextContract() {
1022
- return createContract(textShape);
861
+ function isQuote(line) {
862
+ return /^\s{0,3}>/.test(line);
1023
863
  }
1024
864
  /**
1025
- * Compile the {@link codeSpanShape} into a {@link ContractInterface} for
1026
- * {@link CodeSpanNode} - a guard, coercing parser, JSON Schema, and seeded
1027
- * generator from one shape declaration (AGENTS §14).
865
+ * Checks whether `line` closes a fence opened by `marker` - the same fence character, a run
866
+ * at least as long, and nothing else but surrounding whitespace.
1028
867
  *
1029
- * @returns A `CodeSpanNode` contract bundling `schema` / `is` / `parse` / `generate`
868
+ * @param line - The candidate closing line
869
+ * @param marker - The opening fence's marker run (from {@link extractFence})
870
+ * @returns True if `line` closes the fence; false otherwise
1030
871
  *
1031
872
  * @example
1032
873
  * ```ts
1033
- * import { createCodeSpanContract } from '@src/core'
1034
- *
1035
- * const codeSpan = createCodeSpanContract()
1036
- * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true
874
+ * isFenceClose('```', '```') // true
1037
875
  * ```
1038
876
  */
1039
- function createCodeSpanContract() {
1040
- return createContract(codeSpanShape);
877
+ function isFenceClose(line, marker) {
878
+ const character = marker[0] === "~" ? "~" : "`";
879
+ let index = 0;
880
+ while (index < line.length && isFenceWhitespace(line[index])) index++;
881
+ let run = 0;
882
+ while (index < line.length && line[index] === character) {
883
+ run++;
884
+ index++;
885
+ }
886
+ if (run < marker.length) return false;
887
+ while (index < line.length && isFenceWhitespace(line[index])) index++;
888
+ return index === line.length;
1041
889
  }
1042
890
  /**
1043
- * Compile the {@link lineBreakShape} into a {@link ContractInterface} for
1044
- * {@link LineBreakNode}.
891
+ * Checks whether `character` is a regex-`\s`-equivalent whitespace character - the
892
+ * character class {@link isFenceClose}'s scan treats as surrounding padding.
1045
893
  *
1046
- * @returns A `LineBreakNode` contract bundling `schema` / `is` / `parse` / `generate`
894
+ * @param character - The single character to test, or `undefined` past the end of a line
895
+ * @returns True if it is whitespace; false otherwise
1047
896
  *
1048
897
  * @example
1049
898
  * ```ts
1050
- * import { createLineBreakContract } from '@src/core'
1051
- *
1052
- * createLineBreakContract().is({ element: 'break' }) // true
899
+ * isFenceWhitespace(' ') // true
900
+ * isFenceWhitespace(undefined) // false
1053
901
  * ```
1054
902
  */
1055
- function createLineBreakContract() {
1056
- return createContract(lineBreakShape);
903
+ function isFenceWhitespace(character) {
904
+ return character === " " || character === " " || character === "\n" || character === "\r" || character === "\f" || character === "\v";
1057
905
  }
1058
906
  /**
1059
- * Compile the {@link codeBlockShape} into a {@link ContractInterface} for
1060
- * {@link CodeBlockNode} - a guard, coercing parser, JSON Schema, and seeded
1061
- * generator from one shape declaration (AGENTS §14).
907
+ * Checks whether `line` is a thematic break (horizontal rule) - three or more of the SAME
908
+ * marker `-`, `*`, or `_` (optionally space-separated) and nothing else (`---`,
909
+ * `***`, `___`, `- - -`).
1062
910
  *
1063
- * @returns A `CodeBlockNode` contract bundling `schema` / `is` / `parse` / `generate`
911
+ * @param line - The candidate line
912
+ * @returns True if the line is a thematic break; false otherwise
1064
913
  *
1065
914
  * @example
1066
915
  * ```ts
1067
- * import { createCodeBlockContract } from '@src/core'
1068
- *
1069
- * const codeBlock = createCodeBlockContract()
1070
- * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true
916
+ * isThematicBreak('---') // true
1071
917
  * ```
1072
918
  */
1073
- function createCodeBlockContract() {
1074
- return createContract(codeBlockShape);
919
+ function isThematicBreak(line) {
920
+ const stripped = line.trim().replace(/\s+/g, "");
921
+ if (stripped.length < 3) return false;
922
+ const marker = stripped[0];
923
+ if (marker !== "-" && marker !== "*" && marker !== "_") return false;
924
+ return [...stripped].every((character) => character === marker);
1075
925
  }
1076
926
  /**
1077
- * Compile the {@link thematicBreakShape} into a {@link ContractInterface} for
1078
- * {@link ThematicBreakNode} - a guard, coercing parser, JSON Schema, and
1079
- * seeded generator from one shape declaration (AGENTS §14).
927
+ * Checks whether the pair (`header`, `delimiter`) opens a GFM table - `delimiter` is a row of
928
+ * `|`-separated cells each matching `:?-+:?`, the GFM rule that a table requires a
929
+ * header row IMMEDIATELY followed by a delimiter row.
1080
930
  *
1081
- * @returns A `ThematicBreakNode` contract bundling `schema` / `is` / `parse` / `generate`
931
+ * @param header - The candidate header line
932
+ * @param delimiter - The line after it (the candidate delimiter)
933
+ * @returns True if the two lines open a table; false otherwise
1082
934
  *
1083
935
  * @example
1084
936
  * ```ts
1085
- * import { createThematicBreakContract } from '@src/core'
1086
- *
1087
- * const thematicBreak = createThematicBreakContract()
1088
- * thematicBreak.is({ element: 'thematicBreak' }) // true
937
+ * isTableStart('| a |', '| - |') // true
1089
938
  * ```
1090
939
  */
1091
- function createThematicBreakContract() {
1092
- return createContract(thematicBreakShape);
940
+ function isTableStart(header, delimiter) {
941
+ if (delimiter === void 0 || !header.includes("|")) return false;
942
+ const cells = splitTableRow(delimiter);
943
+ if (cells.length === 0) return false;
944
+ return cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
1093
945
  }
1094
- //#endregion
1095
- //#region src/core/helpers.ts
1096
946
  /**
1097
- * Splits a markdown document into offset-bearing lines while normalizing CRLF and
1098
- * bare CR terminators at the line boundary. A single trailing terminator does not
1099
- * yield a final empty line.
947
+ * Extracts an ATX heading line (`#` `######` followed by text) into its level,
948
+ * trimmed text, and the text's offset inside the line. A run of more than 6 `#`s, or
949
+ * `#`s not followed by whitespace + text, is not a heading; an optional closing
950
+ * `###` run is stripped.
1100
951
  *
1101
- * @param markdown - The raw markdown source
1102
- * @returns The document's lines with their original-string coordinates
952
+ * @param line - The candidate line
953
+ * @returns The heading level (1–6), raw inline text, and text offset, or `undefined`
1103
954
  *
1104
955
  * @example
1105
956
  * ```ts
1106
- * splitLines('a\r\nb') // [{ text: 'a', segments: [{ offset: 0, start: 0, end: 1 }] }, ...]
1107
- * ```
1108
- */
1109
- function splitLines(markdown) {
1110
- const lines = [];
1111
- let start = 0;
1112
- let index = 0;
1113
- while (index < markdown.length) {
1114
- const character = markdown[index];
1115
- if (character !== "\r" && character !== "\n") {
1116
- index += 1;
1117
- continue;
1118
- }
1119
- lines.push({
1120
- text: markdown.slice(start, index),
1121
- segments: [{
1122
- offset: 0,
1123
- start,
1124
- end: index
1125
- }]
1126
- });
1127
- index += character === "\r" && markdown[index + 1] === "\n" ? 2 : 1;
1128
- start = index;
1129
- }
1130
- lines.push({
1131
- text: markdown.slice(start),
1132
- segments: [{
1133
- offset: 0,
1134
- start,
1135
- end: markdown.length
1136
- }]
1137
- });
1138
- if (lines.length > 1 && lines[lines.length - 1]?.text === "") lines.pop();
1139
- return lines;
1140
- }
1141
- /**
1142
- * Slices derived markdown text and narrows each intersecting source segment to the
1143
- * same text-relative range.
1144
- *
1145
- * @param source - The offset-bearing source to slice
1146
- * @param from - The inclusive text offset
1147
- * @param to - The exclusive text offset
1148
- * @returns The sliced text and its narrowed original-string segments
1149
- *
1150
- * @example
1151
- * ```ts
1152
- * sliceSource({ text: 'abc', segments: [{ offset: 0, start: 4, end: 7 }] }, 1, 3)
1153
- * // { text: 'bc', segments: [{ offset: 0, start: 5, end: 7 }] }
1154
- * ```
1155
- */
1156
- function sliceSource(source, from, to) {
1157
- const start = Math.max(0, Math.min(from, source.text.length));
1158
- const end = Math.max(start, Math.min(to, source.text.length));
1159
- const segments = [];
1160
- for (let index = 0; index < source.segments.length; index += 1) {
1161
- const segment = source.segments[index];
1162
- if (segment === void 0) continue;
1163
- const next = source.segments[index + 1];
1164
- const limit = Math.min(segment.offset + (segment.end - segment.start), next === void 0 ? source.text.length : next.offset);
1165
- const overlapStart = Math.max(start, segment.offset);
1166
- const overlapEnd = Math.min(end, limit);
1167
- const empty = segment.offset === limit && overlapStart === segment.offset;
1168
- if (overlapStart >= overlapEnd && !empty) continue;
1169
- const originalStart = overlapStart === limit ? segment.end : Math.min(segment.end, segment.start + overlapStart - segment.offset);
1170
- const originalEnd = overlapEnd === limit ? segment.end : Math.min(segment.end, segment.start + overlapEnd - segment.offset);
1171
- segments.push({
1172
- offset: overlapStart - start,
1173
- start: originalStart,
1174
- end: originalEnd
1175
- });
1176
- }
1177
- return {
1178
- text: source.text.slice(start, end),
1179
- segments
1180
- };
1181
- }
1182
- /**
1183
- * Joins offset-bearing markdown sources while mapping a separator to the original
1184
- * region between adjacent mapped sources.
1185
- *
1186
- * @param sources - The sources to join
1187
- * @param separator - The derived text inserted between sources
1188
- * @returns The joined text and every source-backed segment
1189
- *
1190
- * @example
1191
- * ```ts
1192
- * joinSources(splitLines('a\nb'), '\n')
1193
- * // { text: 'a\nb', segments: [...] }
1194
- * ```
1195
- */
1196
- function joinSources(sources, separator) {
1197
- let text = "";
1198
- const segments = [];
1199
- for (let index = 0; index < sources.length; index += 1) {
1200
- const source = sources[index];
1201
- if (source === void 0) continue;
1202
- if (index > 0) {
1203
- const previous = sources[index - 1];
1204
- const left = previous?.segments[previous.segments.length - 1];
1205
- const right = source.segments[0];
1206
- if (separator.length > 0 && left !== void 0 && right !== void 0 && left.end < right.start) segments.push({
1207
- offset: text.length,
1208
- start: left.end,
1209
- end: right.start
1210
- });
1211
- text += separator;
1212
- }
1213
- for (const segment of source.segments) segments.push({
1214
- offset: text.length + segment.offset,
1215
- start: segment.start,
1216
- end: segment.end
1217
- });
1218
- text += source.text;
1219
- }
1220
- return {
1221
- text,
1222
- segments
1223
- };
1224
- }
1225
- /**
1226
- * Projects a derived text range through its segments to a half-open region of the
1227
- * original markdown string.
1228
- *
1229
- * @param source - The offset-bearing source carrying the range
1230
- * @param from - The inclusive derived-text boundary
1231
- * @param to - The exclusive derived-text boundary
1232
- * @returns The original-string span, or `undefined` when either boundary is unmapped
1233
- *
1234
- * @example
1235
- * ```ts
1236
- * projectSpan({ text: 'a', segments: [{ offset: 0, start: 4, end: 5 }] }, 0, 1)
1237
- * // { start: 4, end: 5 }
1238
- * ```
1239
- */
1240
- function projectSpan(source, from, to) {
1241
- if (from < 0 || to < from || to > source.text.length) return void 0;
1242
- let start;
1243
- let end;
1244
- for (let index = 0; index < source.segments.length; index += 1) {
1245
- const segment = source.segments[index];
1246
- if (segment === void 0) continue;
1247
- const next = source.segments[index + 1];
1248
- const limit = Math.min(segment.offset + (segment.end - segment.start), next === void 0 ? source.text.length : next.offset);
1249
- if (from === to && from >= segment.offset && from <= limit) {
1250
- if (next !== void 0 && from === next.offset) continue;
1251
- const position = from === limit ? segment.end : Math.min(segment.end, segment.start + from - segment.offset);
1252
- return {
1253
- start: position,
1254
- end: position
1255
- };
1256
- }
1257
- if (start === void 0 && from >= segment.offset && from < limit) start = segment.start + from - segment.offset;
1258
- if (to > segment.offset && to <= limit) end = to === limit ? segment.end : Math.min(segment.end, segment.start + to - segment.offset);
1259
- }
1260
- return start === void 0 || end === void 0 ? void 0 : {
1261
- start,
1262
- end
1263
- };
1264
- }
1265
- /**
1266
- * Trims an offset-bearing source without losing the coordinates of its retained text.
1267
- *
1268
- * @param source - The source to trim
1269
- * @returns The trimmed text and its narrowed original-string segments
1270
- *
1271
- * @example
1272
- * ```ts
1273
- * trimSource({ text: ' a ', segments: [{ offset: 0, start: 4, end: 7 }] })
1274
- * // { text: 'a', segments: [{ offset: 0, start: 5, end: 6 }] }
1275
- * ```
1276
- */
1277
- function trimSource(source) {
1278
- const start = source.text.length - source.text.trimStart().length;
1279
- const end = source.text.trimEnd().length;
1280
- return sliceSource(source, start, Math.max(start, end));
1281
- }
1282
- /**
1283
- * Normalizes one paragraph line while retaining the full source run consumed by a
1284
- * trailing-space hard break.
1285
- *
1286
- * @param source - The offset-bearing paragraph line
1287
- * @param breaks - If `true`, preserves a trailing run of at least two spaces as the
1288
- * scanner's two-space hard-break syntax; if `false`, trims the line normally
1289
- * @returns The normalized line and its original-string segments
1290
- *
1291
- * @example
1292
- * ```ts
1293
- * normalizeParagraphLine(splitLines('text \nnext')[0], true).text // 'text '
1294
- * ```
1295
- */
1296
- function normalizeParagraphLine(source, breaks) {
1297
- if (!breaks || !source.text.endsWith(" ")) return trimSource(source);
1298
- const contentEnd = source.text.trimEnd().length;
1299
- const content = trimSource(sliceSource(source, 0, contentEnd));
1300
- const span = projectSpan(source, contentEnd, source.text.length);
1301
- return joinSources([content, {
1302
- text: " ",
1303
- segments: span === void 0 ? [] : [{
1304
- offset: 0,
1305
- start: span.start,
1306
- end: span.end
1307
- }]
1308
- }], "");
1309
- }
1310
- /**
1311
- * The count of leading space / tab characters on `line` (a tab counts as one) - the
1312
- * indent that decides whether a list item's continuation belongs to the item.
1313
- *
1314
- * @param line - The line to measure
1315
- * @returns The number of leading space / tab characters
1316
- *
1317
- * @example
1318
- * ```ts
1319
- * countIndent(' text') // 2
1320
- * ```
1321
- */
1322
- function countIndent(line) {
1323
- let count = 0;
1324
- for (const character of line) if (character === " " || character === " ") count += 1;
1325
- else break;
1326
- return count;
1327
- }
1328
- /**
1329
- * Extracts an ATX heading line (`#` … `######` followed by text) into its level,
1330
- * trimmed text, and the text's offset inside the line. A run of more than 6 `#`s, or
1331
- * `#`s not followed by whitespace + text, is not a heading; an optional closing
1332
- * `###` run is stripped.
1333
- *
1334
- * @param line - The candidate line
1335
- * @returns The heading level (1–6), raw inline text, and text offset, or `undefined`
1336
- *
1337
- * @example
1338
- * ```ts
1339
- * extractHeading('## Title') // { level: 2, text: 'Title', offset: 3 }
957
+ * extractHeading('## Title') // { level: 2, text: 'Title', offset: 3 }
1340
958
  * ```
1341
959
  */
1342
960
  function extractHeading(line) {
@@ -1356,7 +974,7 @@ function extractHeading(line) {
1356
974
  };
1357
975
  }
1358
976
  /**
1359
- * Extract a fenced-code opening line (```` ``` ```` or `~~~`, optionally with an info
977
+ * Extracts a fenced-code opening line (```` ``` ```` or `~~~`, optionally with an info
1360
978
  * string) into its `{ marker, lang }`, or `undefined` when `line` is not a fence
1361
979
  * opener. `marker` is the exact fence run (the closer must match the same character +
1362
980
  * at least the same length); `lang` is the first word of the info string.
@@ -1381,7 +999,7 @@ function extractFence(line) {
1381
999
  };
1382
1000
  }
1383
1001
  /**
1384
- * Extract a list-item line (`-` / `*` / `+` bullet, or `1.` / `1)` ordinal, followed by
1002
+ * Extracts a list-item line (`-` / `*` / `+` bullet, or `1.` / `1)` ordinal, followed by
1385
1003
  * a space) into its {@link ListItemMatch}, or `undefined` when `line` is not a list
1386
1004
  * item. `content` is the text after the marker; `marker` is the full marker-plus-space
1387
1005
  * width (for measuring a continuation's indent).
@@ -1438,7 +1056,7 @@ function stripQuote(source) {
1438
1056
  return sliceSource(source, (/^\s{0,3}>\s?/.exec(source.text)?.[0] ?? "").length, source.text.length);
1439
1057
  }
1440
1058
  /**
1441
- * Split one GFM table row into its cell strings - outer pipes are optional, an escaped
1059
+ * Splits one GFM table row into its cell strings - outer pipes are optional, an escaped
1442
1060
  * pipe (`\|`) inside a cell is NOT a separator (it becomes a literal `|`), and the
1443
1061
  * empty leading / trailing cell produced by an outer `|` is dropped. Derives the string
1444
1062
  * form from {@link splitTableSources}, which owns the escaped-pipe splitting rule.
@@ -1504,7 +1122,7 @@ function splitTableSources(row) {
1504
1122
  return cells;
1505
1123
  }
1506
1124
  /**
1507
- * Derive the per-column {@link TableAlign} list from a GFM delimiter row - `:---`
1125
+ * Derives the per-column {@link TableAlign} list from a GFM delimiter row - `:---`
1508
1126
  * left, `---:` right, `:---:` center, and `---` as the explicit no-alignment
1509
1127
  * marker represented by `null`.
1510
1128
  *
@@ -1528,7 +1146,7 @@ function delimiterToAlignments(delimiter) {
1528
1146
  });
1529
1147
  }
1530
1148
  /**
1531
- * Whether the line at `index` starts a NEW block kind (heading / fence / thematic
1149
+ * Checks whether the line at `index` starts a NEW block kind (heading / fence / thematic
1532
1150
  * break / blockquote / list / table) - the paragraph collector stops at such a line
1533
1151
  * so a block following a paragraph without a blank line still parses (a trusted-input
1534
1152
  * caller writing a `##` heading directly under a paragraph, with no intervening blank
@@ -1536,7 +1154,7 @@ function delimiterToAlignments(delimiter) {
1536
1154
  *
1537
1155
  * @param lines - The document's lines
1538
1156
  * @param index - The line index to test
1539
- * @returns `true` when the line begins a different block
1157
+ * @returns True if the line begins a different block; false otherwise
1540
1158
  *
1541
1159
  * @example
1542
1160
  * ```ts
@@ -1548,7 +1166,7 @@ function startsBlock(lines, index) {
1548
1166
  return extractHeading(line) !== void 0 || extractFence(line) !== void 0 || isThematicBreak(line) || isQuote(line) || extractListItem(line) !== void 0 || isTableStart(line, lines[index + 1]);
1549
1167
  }
1550
1168
  /**
1551
- * Resolve backslash escapes in a raw string to their literal characters - used for a
1169
+ * Resolves backslash escapes in a raw string to their literal characters - used for a
1552
1170
  * link `href` (which is not otherwise inline-parsed) and any plain text run.
1553
1171
  *
1554
1172
  * @param text - The raw text possibly carrying `\x` escapes
@@ -1571,7 +1189,7 @@ function unescapeText(text) {
1571
1189
  return out;
1572
1190
  }
1573
1191
  /**
1574
- * Merge adjacent text nodes into one - the inline scanner emits a text node per
1192
+ * Merges adjacent text nodes into one - the inline scanner emits a text node per
1575
1193
  * unrecognized character, so coalescing keeps the AST clean and assertion-friendly.
1576
1194
  *
1577
1195
  * @param nodes - The inline nodes (possibly with adjacent text runs)
@@ -1609,7 +1227,7 @@ function coalesceText(nodes, spans) {
1609
1227
  return out;
1610
1228
  }
1611
1229
  /**
1612
- * Scan an inline code span at `start` (a `` ` ``-run … a matching `` ` ``-run of the
1230
+ * Scans an inline code span at `start` (a `` ` ``-run … a matching `` ` ``-run of the
1613
1231
  * SAME length, the CommonMark rule that lets a span contain backticks). Returns the
1614
1232
  * span's literal text + end index, or `undefined` when no matching closer exists (it
1615
1233
  * then degrades to literal backticks).
@@ -1758,7 +1376,7 @@ function locateEmphasis(source, start, to) {
1758
1376
  while (start + run < to && source[start + run] === marker && run < 2) run += 1;
1759
1377
  const strong = run === 2;
1760
1378
  const openEnd = start + run;
1761
- if (openEnd >= to || isWhitespace(source[openEnd] ?? "")) return void 0;
1379
+ if (openEnd >= to || isFlankingWhitespace(source[openEnd] ?? "")) return void 0;
1762
1380
  let index = openEnd;
1763
1381
  while (index < to) {
1764
1382
  const character = source[index] ?? "";
@@ -1781,7 +1399,7 @@ function locateEmphasis(source, start, to) {
1781
1399
  if (character === marker) {
1782
1400
  let closeRun = 0;
1783
1401
  while (index + closeRun < to && source[index + closeRun] === marker) closeRun += 1;
1784
- if (closeRun >= run && !isWhitespace(source[index - 1] ?? "")) return {
1402
+ if (closeRun >= run && !isFlankingWhitespace(source[index - 1] ?? "")) return {
1785
1403
  strong,
1786
1404
  open: openEnd,
1787
1405
  close: index,
@@ -1828,7 +1446,7 @@ function scanEmphasis(source, start, to, depth = 0) {
1828
1446
  };
1829
1447
  }
1830
1448
  /**
1831
- * Scan the window `[from, to)` of `source` into inline nodes - the single recursive
1449
+ * Scans the window `[from, to)` of `source` into inline nodes - the single recursive
1832
1450
  * engine the inline phase runs on (emphasis, link text, and image alternative
1833
1451
  * content recurse through it). Linear:
1834
1452
  * each character is consumed once; a failed construct emits its opening character as
@@ -1838,10 +1456,11 @@ function scanEmphasis(source, start, to, depth = 0) {
1838
1456
  * @param from - The inclusive start of the scan window
1839
1457
  * @param to - The exclusive end of the scan window
1840
1458
  * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);
1841
- * incremented by one on every recursive descent through {@link scanLink} /
1842
- * {@link scanEmphasis}. At {@link MAX_DEPTH} the window is never scanned for markup -
1843
- * it emits as a single literal text node - so pathological nesting (`[[[[…`,
1844
- * `****…`) cannot exhaust the call stack.
1459
+ * incremented by one on every recursive descent {@link scanInlineSource} makes into
1460
+ * itself for a link's text, an image's alternative content, or an emphasis run's
1461
+ * children. At {@link MAX_DEPTH} the window is never scanned for markup - it emits as
1462
+ * a single literal text node - so pathological nesting (`[[[[…`, `****…`) cannot
1463
+ * exhaust the call stack.
1845
1464
  * @returns The parsed inline nodes (NOT yet coalesced)
1846
1465
  *
1847
1466
  * @example
@@ -1867,7 +1486,9 @@ function scanInline(source, from, to, depth = 0) {
1867
1486
  * @param from - The inclusive start of the scan window
1868
1487
  * @param to - The exclusive end of the scan window
1869
1488
  * @param spans - The operation-owned node span recorder
1870
- * @param depth - The current inline-recursion depth
1489
+ * @param depth - The current inline-recursion depth, incremented by one on every
1490
+ * recursive descent this function makes into itself for a link's text, an image's
1491
+ * alternative content, or an emphasis run's children
1871
1492
  * @returns The parsed inline nodes before adjacent text coalescing
1872
1493
  *
1873
1494
  * @example
@@ -2209,7 +1830,7 @@ function collectList(lines, start, depth, spans = /* @__PURE__ */ new Map(), end
2209
1830
  };
2210
1831
  }
2211
1832
  /**
2212
- * Project a {@link MarkdownNode} into an unsanitized {@link HTMLDocument}.
1833
+ * Projects a {@link MarkdownNode} into an unsanitized {@link HTMLDocument}.
2213
1834
  *
2214
1835
  * @remarks
2215
1836
  * The projection is pure and iterative. Text and attribute values remain literal for
@@ -2538,29 +2159,7 @@ function markdownToHTML(node) {
2538
2159
  };
2539
2160
  }
2540
2161
  /**
2541
- * Render a {@link MarkdownNode} to sanitized canonical HTML.
2542
- *
2543
- * @remarks
2544
- * Markdown widens `@orkestrel/html`'s attribute floor by exactly `src`, because image
2545
- * syntax is meaningless without its source. `src` is still a URL attribute, so the
2546
- * floor refuses `javascript:`, `data:`, `vbscript:`, and `file:` values. A stricter
2547
- * consumer can compose {@link markdownToHTML} with `@orkestrel/html`'s `HTML` class
2548
- * directly.
2549
- *
2550
- * @param node - The markdown document or bare node to render
2551
- * @returns Sanitized canonical HTML
2552
- *
2553
- * @example
2554
- * ```ts
2555
- * renderHTML({ element: 'paragraph', children: [{ element: 'text', value: 'a & b' }] })
2556
- * // '<p>a &amp; b</p>'
2557
- * ```
2558
- */
2559
- function renderHTML(node) {
2560
- return renderHTML$1(new HTML(markdownToHTML(node)).sanitize({ attributes: [...SAFE_ATTRIBUTES, "src"] }).document);
2561
- }
2562
- /**
2563
- * Render a {@link MarkdownNode} to its CANONICAL markdown source - the inverse
2162
+ * Renders a {@link MarkdownNode} to its CANONICAL markdown source - the inverse
2564
2163
  * projection of `renderHTML`, and the serializer a `parse(renderMarkdown(doc))`
2565
2164
  * round-trip is built on. Canonical forms: `*` / `**` emphasis at even emphasis
2566
2165
  * nesting depths and `_` / `__` at odd depths, `- ` bullets, `N. ` sequential
@@ -2569,8 +2168,8 @@ function renderHTML(node) {
2569
2168
  * `> `-prefixed blockquote lines, GFM tables (1-space-padded cells, `\|`-escaped
2570
2169
  * pipes, an alignment delimiter row), `[text](href)` links, `![alt](src)` images,
2571
2170
  * and two-space hard breaks. A `text` node's literal content is backslash-escaped
2572
- * wherever it would otherwise re-parse as markup (AGENTS §14 parse↔render
2573
- * soundness).
2171
+ * wherever it would otherwise re-parse as markup, so parsing the rendered source
2172
+ * returns the node it was rendered from.
2574
2173
  *
2575
2174
  * @remarks
2576
2175
  * Total: never throws. At {@link MAX_DEPTH} a value-bearing node degrades to its
@@ -2855,32 +2454,62 @@ function renderMarkdown(node) {
2855
2454
  return "";
2856
2455
  }
2857
2456
  /**
2858
- * Trim the whitespace at the two ends of an inline run - the leading whitespace of a
2859
- * leading text node and the trailing whitespace of a trailing one - dropping either
2860
- * node when nothing survives.
2457
+ * Builds an HTML-to-markdown projection with absent fields defaulted from
2458
+ * {@link EMPTY_PROJECTION} and the block/inline exclusivity invariant enforced.
2861
2459
  *
2862
2460
  * @remarks
2863
- * Markdown trims every line of a paragraph, a heading's text, and a table cell, so an
2864
- * untrimmed run would come back from a re-parse a different AST. Expects a coalesced
2865
- * run (see {@link coalesceText}): only the outermost node on each side is examined.
2461
+ * A block-bearing projection cannot also expose inline content. Callers may provide
2462
+ * both views, but `inlines` is flushed whenever `blocks` is non-empty.
2866
2463
  *
2867
- * @param nodes - The inline run to trim
2868
- * @returns The run with its edge whitespace removed
2464
+ * @param parts - The projection fields to provide
2465
+ * @returns A complete invariant-preserving projection
2869
2466
  *
2870
2467
  * @example
2871
2468
  * ```ts
2872
- * trimInlines([{ element: 'text', value: ' a ' }]) // [{ element: 'text', value: 'a' }]
2469
+ * createProjection({
2470
+ * blocks: [{ element: 'thematicBreak' }],
2471
+ * inlines: [{ element: 'text', value: 'discarded' }],
2472
+ * })
2473
+ * // { blocks: [{ element: 'thematicBreak' }], inlines: [], text: '', cells: [], rows: [] }
2873
2474
  * ```
2874
2475
  */
2875
- function trimInlines(nodes) {
2876
- const out = [];
2877
- for (const node of nodes) if (node !== void 0) out.push(node);
2878
- const first = out[0];
2879
- if (first !== void 0 && first.element === "text") {
2880
- const value = first.value.replace(/^\s+/, "");
2881
- if (isEmptyString(value)) out.shift();
2882
- else out[0] = {
2883
- element: "text",
2476
+ function createProjection(parts = {}) {
2477
+ const blocks = parts.blocks ?? EMPTY_PROJECTION.blocks;
2478
+ return {
2479
+ blocks,
2480
+ inlines: blocks.length === 0 ? parts.inlines ?? EMPTY_PROJECTION.inlines : [],
2481
+ text: parts.text ?? EMPTY_PROJECTION.text,
2482
+ cells: parts.cells ?? EMPTY_PROJECTION.cells,
2483
+ rows: parts.rows ?? EMPTY_PROJECTION.rows
2484
+ };
2485
+ }
2486
+ /**
2487
+ * Trims the whitespace at the two ends of an inline run - the leading whitespace of a
2488
+ * leading text node and the trailing whitespace of a trailing one - dropping either
2489
+ * node when nothing survives.
2490
+ *
2491
+ * @remarks
2492
+ * Markdown trims every line of a paragraph, a heading's text, and a table cell, so an
2493
+ * untrimmed run would come back from a re-parse a different AST. Expects a coalesced
2494
+ * run (see {@link coalesceText}): only the outermost node on each side is examined.
2495
+ *
2496
+ * @param nodes - The inline run to trim
2497
+ * @returns The run with its edge whitespace removed
2498
+ *
2499
+ * @example
2500
+ * ```ts
2501
+ * trimInlines([{ element: 'text', value: ' a ' }]) // [{ element: 'text', value: 'a' }]
2502
+ * ```
2503
+ */
2504
+ function trimInlines(nodes) {
2505
+ const out = [];
2506
+ for (const node of nodes) if (node !== void 0) out.push(node);
2507
+ const first = out[0];
2508
+ if (first !== void 0 && first.element === "text") {
2509
+ const value = first.value.replace(/^\s+/, "");
2510
+ if (isEmptyString(value)) out.shift();
2511
+ else out[0] = {
2512
+ element: "text",
2884
2513
  value
2885
2514
  };
2886
2515
  }
@@ -2896,7 +2525,7 @@ function trimInlines(nodes) {
2896
2525
  return out;
2897
2526
  }
2898
2527
  /**
2899
- * Reduce an inline run to the shape markdown can actually write back: adjacent text
2528
+ * Reduces an inline run to the shape markdown can actually write back: adjacent text
2900
2529
  * coalesced, empty text dropped, and every hard break either kept as a real line
2901
2530
  * ending or spent as a space.
2902
2531
  *
@@ -2909,8 +2538,8 @@ function trimInlines(nodes) {
2909
2538
  * becomes the space it stood for.
2910
2539
  *
2911
2540
  * @param nodes - The inline run to normalize
2912
- * @param breaks - Whether the target context can carry a hard break at all; `false` for
2913
- * a heading or a table cell, where every break becomes a space
2541
+ * @param breaks - If `true`, keeps each hard break as a real line ending; if `false`, spends
2542
+ * every break as the space it stood for, as a heading or a table cell requires
2914
2543
  * @returns The normalized run
2915
2544
  *
2916
2545
  * @example
@@ -2961,7 +2590,7 @@ function normalizeInlines(nodes, breaks) {
2961
2590
  return coalesceText(out);
2962
2591
  }
2963
2592
  /**
2964
- * Combine the projections of one node's children into the projection of that node -
2593
+ * Combines the projections of one node's children into the projection of that node -
2965
2594
  * the single place inline runs become paragraphs, so no ancestor has to decide it
2966
2595
  * twice.
2967
2596
  *
@@ -3048,7 +2677,7 @@ function mergeProjections(children) {
3048
2677
  });
3049
2678
  }
3050
2679
  /**
3051
- * Read a projection as BLOCK content - the view a document, a blockquote, and a list
2680
+ * Reads a projection as BLOCK content - the view a document, a blockquote, and a list
3052
2681
  * item each need.
3053
2682
  *
3054
2683
  * @remarks
@@ -3094,7 +2723,7 @@ function projectionToBlocks(projection) {
3094
2723
  return blocks;
3095
2724
  }
3096
2725
  /**
3097
- * Read a projection as INLINE content - the view a link, an emphasis, and a table cell
2726
+ * Reads a projection as INLINE content - the view a link, an emphasis, and a table cell
3098
2727
  * each need.
3099
2728
  *
3100
2729
  * @remarks
@@ -3114,14 +2743,14 @@ function projectionToBlocks(projection) {
3114
2743
  */
3115
2744
  function projectionToInlines(projection) {
3116
2745
  if (!isNonEmptyArray(projection.blocks) && !isNonEmptyArray(projection.cells) && !isNonEmptyArray(projection.rows)) return coalesceText(projection.inlines);
3117
- const value = projectionToBlocks(projection).map(flattenText).join(" ").replace(/\s+/g, " ").trim();
2746
+ const value = collapseSpace(projectionToBlocks(projection).map(flattenText).join(" "));
3118
2747
  return isEmptyString(value) ? [] : [{
3119
2748
  element: "text",
3120
2749
  value
3121
2750
  }];
3122
2751
  }
3123
2752
  /**
3124
- * Project one HTML leaf - a text node, a comment, or a doctype - to its
2753
+ * Projects one HTML leaf - a text node, a comment, or a doctype - to its
3125
2754
  * {@link MarkdownProjection}.
3126
2755
  *
3127
2756
  * @remarks
@@ -3151,7 +2780,7 @@ function projectHTMLLeaf(leaf) {
3151
2780
  });
3152
2781
  }
3153
2782
  /**
3154
- * Project one HTML container - the document root or an element - from its children's
2783
+ * Projects one HTML container - the document root or an element - from its children's
3155
2784
  * already-computed projections. THE element mapping, and the only place that decides
3156
2785
  * what an HTML tag becomes in markdown.
3157
2786
  *
@@ -3300,7 +2929,7 @@ function projectHTMLNode(node, children) {
3300
2929
  text: merged.text
3301
2930
  });
3302
2931
  case "img": {
3303
- const alt = (attributeOf(node, "alt") ?? "").replace(/\s+/g, " ").trim();
2932
+ const alt = collapseSpace(attributeOf(node, "alt") ?? "");
3304
2933
  return createProjection({
3305
2934
  inlines: [{
3306
2935
  element: "image",
@@ -3458,7 +3087,7 @@ function projectHTMLNode(node, children) {
3458
3087
  return merged;
3459
3088
  }
3460
3089
  /**
3461
- * Project an `@orkestrel/html` {@link HTMLNode} into a {@link MarkdownDocument} - the
3090
+ * Projects an `@orkestrel/html` {@link HTMLNode} into a {@link MarkdownDocument} - the
3462
3091
  * HTML→markdown direction, and the inverse of {@link markdownToHTML}.
3463
3092
  *
3464
3093
  * @remarks
@@ -3514,7 +3143,7 @@ function htmlToMarkdown(node) {
3514
3143
  };
3515
3144
  }
3516
3145
  /**
3517
- * Depth-first, pre-order, root-inclusive traversal of a {@link MarkdownNode} - yields
3146
+ * Walks a {@link MarkdownNode} depth-first, pre-order, root-inclusive - yields
3518
3147
  * the node itself, then recurses into its children (block children, list items,
3519
3148
  * image/link inline children, table header/row cells' inline nodes) in walk order.
3520
3149
  *
@@ -3577,7 +3206,7 @@ function* walkNodes(node) {
3577
3206
  }
3578
3207
  }
3579
3208
  /**
3580
- * Fold a {@link MarkdownNode} into a `T` via a total catamorphism - children are
3209
+ * Folds a {@link MarkdownNode} into a `T` through a total catamorphism - children are
3581
3210
  * folded first (post-order), then the node's own {@link MarkdownHandler} is invoked
3582
3211
  * with the already-folded children.
3583
3212
  *
@@ -3594,13 +3223,13 @@ function* walkNodes(node) {
3594
3223
  * with an empty children list instead of recursing further.
3595
3224
  *
3596
3225
  * @param node - The AST node to fold
3597
- * @param handlers - The total {@link MarkdownHandlers} table, one handler per element
3226
+ * @param handlers - The total {@link MarkdownHandlerMap} table, one handler per element
3598
3227
  * @param depth - The starting recursion depth (pass `0` at the entry point)
3599
3228
  * @returns The folded `T`
3600
3229
  *
3601
3230
  * @example
3602
3231
  * ```ts
3603
- * const countHandlers: MarkdownHandlers<number> = {
3232
+ * const countHandlers: MarkdownHandlerMap<number> = {
3604
3233
  * document: (_, children) => children.reduce((a, b) => a + b, 1),
3605
3234
  * // ...one handler per element, each summing its folded children
3606
3235
  * }
@@ -3729,7 +3358,7 @@ function foldNode(node, handlers, depth) {
3729
3358
  }
3730
3359
  }
3731
3360
  /**
3732
- * Rewrite a {@link MarkdownDocument} bottom-up (copy-on-write) - each node's children
3361
+ * Rewrites a {@link MarkdownDocument} bottom-up (copy-on-write) - each node's children
3733
3362
  * are rewritten first (post-order), then `rewrite` is applied to the node itself; the
3734
3363
  * document ROOT is never passed to `rewrite` (the `element: 'document'` invariant
3735
3364
  * always holds). A table's inline cells and a list's items ARE rewritten.
@@ -4012,7 +3641,7 @@ function rewriteDocument(document, rewrite) {
4012
3641
  return [document, /* @__PURE__ */ new Map()];
4013
3642
  }
4014
3643
  /**
4015
- * Concatenate the `value` / `code` content of every descendant text / code-span /
3644
+ * Concatenates the `value` / `code` content of every descendant text / code-span /
4016
3645
  * code-block node under `node`, including image alternative content, in walk order -
4017
3646
  * the plain-text projection of an AST (search indexing, word counts, a text-only
4018
3647
  * preview).
@@ -4085,6 +3714,458 @@ function flattenText(node) {
4085
3714
  return value;
4086
3715
  }
4087
3716
  //#endregion
4088
- export { EMPTY_PROJECTION, MAX_DEPTH, Markdown, coalesceText, codeBlockShape, codeSpanShape, collectList, collectTable, countIndent, createCodeBlockContract, createCodeSpanContract, createLineBreakContract, createMarkdown, createProjection, createTextContract, createThematicBreakContract, delimiterToAlignments, extractFence, extractHeading, extractListItem, flattenText, foldNode, htmlToMarkdown, isBlankLine, isBlockNode, isBlockquoteNode, isCodeBlockNode, isCodeSpanNode, isEmphasisNode, isEscapable, isFenceClose, isFenceWhitespace, isHeadingNode, isImageNode, isInlineNode, isLineBreakNode, isLinkNode, isListNode, isMarkdownDocument, isMarkdownNode, isParagraphNode, isQuote, isTableNode, isTableStart, isTextNode, isThematicBreak, isThematicBreakNode, isWhitespace, joinSources, lineBreakShape, listItemMatchShape, locateEmphasis, locateLink, markdownToHTML, mergeProjections, normalizeInlines, normalizeParagraphLine, parseBlocks, parseDocument, parseInline, parseProvenance, projectHTMLLeaf, projectHTMLNode, projectSpan, projectionToBlocks, projectionToInlines, renderHTML, renderMarkdown, rewriteDocument, scanCode, scanEmphasis, scanInline, scanInlineSource, scanLink, sliceSource, splitLines, splitTableRow, splitTableSources, startsBlock, stripQuote, tableAlignShape, textShape, thematicBreakShape, trimInlines, trimSource, unescapeText, walkNodes };
3717
+ //#region src/core/compilers.ts
3718
+ /**
3719
+ * Renders a {@link MarkdownNode} to sanitized canonical HTML.
3720
+ *
3721
+ * @remarks
3722
+ * Markdown widens `@orkestrel/html`'s attribute floor by exactly `src`, because image
3723
+ * syntax is meaningless without its source. `src` is still a URL attribute, so the
3724
+ * floor refuses `javascript:`, `data:`, `vbscript:`, and `file:` values. A stricter
3725
+ * consumer can compose {@link markdownToHTML} with `@orkestrel/html`'s `HTML` class
3726
+ * directly.
3727
+ *
3728
+ * @param node - The markdown document or bare node to render
3729
+ * @returns Sanitized canonical HTML
3730
+ *
3731
+ * @example
3732
+ * ```ts
3733
+ * renderHTML({ element: 'paragraph', children: [{ element: 'text', value: 'a & b' }] })
3734
+ * // '<p>a &amp; b</p>'
3735
+ * ```
3736
+ */
3737
+ function renderHTML(node) {
3738
+ return renderHTML$1(new HTML(markdownToHTML(node)).sanitize({ attributes: [...SAFE_ATTRIBUTES, "src"] }).document);
3739
+ }
3740
+ //#endregion
3741
+ //#region src/core/shapers.ts
3742
+ /**
3743
+ * Describes the shape of a {@link TextNode} - a plain-text leaf inline run.
3744
+ *
3745
+ * @example
3746
+ * ```ts
3747
+ * import { createContract } from '@orkestrel/contract'
3748
+ * import { textShape } from '@src/core'
3749
+ *
3750
+ * const text = createContract(textShape)
3751
+ * text.is({ element: 'text', value: 'hi' }) // true
3752
+ * ```
3753
+ */
3754
+ var textShape = objectShape({
3755
+ element: literalShape(["text"]),
3756
+ value: stringShape()
3757
+ });
3758
+ /**
3759
+ * Describes the shape of a {@link CodeSpanNode} - an inline code span (`` `code` ``).
3760
+ *
3761
+ * @example
3762
+ * ```ts
3763
+ * import { createContract } from '@orkestrel/contract'
3764
+ * import { codeSpanShape } from '@src/core'
3765
+ *
3766
+ * const codeSpan = createContract(codeSpanShape)
3767
+ * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true
3768
+ * ```
3769
+ */
3770
+ var codeSpanShape = objectShape({
3771
+ element: literalShape(["codeSpan"]),
3772
+ value: stringShape()
3773
+ });
3774
+ /**
3775
+ * Describes the shape of a {@link LineBreakNode} - a GFM hard line-break leaf.
3776
+ *
3777
+ * @example
3778
+ * ```ts
3779
+ * import { createContract } from '@orkestrel/contract'
3780
+ * import { lineBreakShape } from '@src/core'
3781
+ *
3782
+ * const lineBreak = createContract(lineBreakShape)
3783
+ * lineBreak.is({ element: 'break' }) // true
3784
+ * ```
3785
+ */
3786
+ var lineBreakShape = objectShape({ element: literalShape(["break"]) });
3787
+ /**
3788
+ * Describes the shape of a {@link CodeBlockNode} - a fenced code block. `lang` is
3789
+ * optional (absent when the opening fence carries no info-string).
3790
+ *
3791
+ * @example
3792
+ * ```ts
3793
+ * import { createContract } from '@orkestrel/contract'
3794
+ * import { codeBlockShape } from '@src/core'
3795
+ *
3796
+ * const codeBlock = createContract(codeBlockShape)
3797
+ * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true
3798
+ * codeBlock.is({ element: 'codeBlock', code: 'x', lang: 'ts' }) // true
3799
+ * ```
3800
+ */
3801
+ var codeBlockShape = objectShape({
3802
+ element: literalShape(["codeBlock"]),
3803
+ lang: optionalShape(stringShape()),
3804
+ code: stringShape()
3805
+ });
3806
+ /**
3807
+ * Describes the shape of a {@link ThematicBreakNode} - a horizontal rule. Carries no
3808
+ * fields beyond its `element` discriminant.
3809
+ *
3810
+ * @example
3811
+ * ```ts
3812
+ * import { createContract } from '@orkestrel/contract'
3813
+ * import { thematicBreakShape } from '@src/core'
3814
+ *
3815
+ * const thematicBreak = createContract(thematicBreakShape)
3816
+ * thematicBreak.is({ element: 'thematicBreak' }) // true
3817
+ * ```
3818
+ */
3819
+ var thematicBreakShape = objectShape({ element: literalShape(["thematicBreak"]) });
3820
+ /**
3821
+ * Describes the shape of a {@link TableAlign} - the per-column GFM table alignment
3822
+ * literal.
3823
+ *
3824
+ * @example
3825
+ * ```ts
3826
+ * import { createContract } from '@orkestrel/contract'
3827
+ * import { tableAlignShape } from '@src/core'
3828
+ *
3829
+ * const tableAlign = createContract(tableAlignShape)
3830
+ * tableAlign.is('left') // true
3831
+ * tableAlign.is('center') // true
3832
+ * tableAlign.is('top') // false
3833
+ * ```
3834
+ */
3835
+ var tableAlignShape = literalShape([
3836
+ "left",
3837
+ "right",
3838
+ "center"
3839
+ ]);
3840
+ /**
3841
+ * Describes the shape of {@link ListItemMatch} - the parsed parts of a single list-item
3842
+ * line the block phase's list detector returns. Fully non-recursive (no
3843
+ * nested node fields), so every field shapes directly.
3844
+ *
3845
+ * @example
3846
+ * ```ts
3847
+ * import { createContract } from '@orkestrel/contract'
3848
+ * import { listItemMatchShape } from '@src/core'
3849
+ *
3850
+ * const listItemParts = createContract(listItemMatchShape)
3851
+ * listItemParts.is({ ordered: false, start: 1, content: 'hi', indent: 0, marker: 2 }) // true
3852
+ * ```
3853
+ */
3854
+ var listItemMatchShape = objectShape({
3855
+ ordered: booleanShape(),
3856
+ start: integerShape(),
3857
+ content: stringShape(),
3858
+ indent: integerShape(),
3859
+ marker: integerShape()
3860
+ });
3861
+ //#endregion
3862
+ //#region src/core/Markdown.ts
3863
+ /**
3864
+ * Wraps a typed {@link MarkdownDocument} AST as a stateful, parsed markdown document
3865
+ * with the query (`find` / `filter` / `reduce` / iteration), rewrite (`map`), fold, and
3866
+ * streaming operations {@link MarkdownInterface} declares.
3867
+ *
3868
+ * @remarks
3869
+ * - **Construction.** Given a `string`, the constructor runs {@link parseProvenance} (the
3870
+ * block phase then the inline phase) once, keeping the AST and a COPY of the span map
3871
+ * that parse recorded. Given a {@link MarkdownDocument}, the document is adopted AS-IS
3872
+ * and is NOT re-validated - gate an untrusted value with `isMarkdownDocument` first.
3873
+ * - **Provenance.** {@link span} reads the region of the ORIGINAL constructor string a
3874
+ * node was produced from, and it is handle-relative: a string-constructed handle exposes
3875
+ * the regions of the nodes it parsed, an adopted document exposes none, and a node from
3876
+ * another handle reports `undefined` here whatever that handle reports. Each call
3877
+ * returns a fresh value. A node reports the region THIS handle holds for its identity,
3878
+ * else the region of the direct input a rewrite named for it, else `undefined`: a text
3879
+ * run the parse joined from adjacent scanner output reports the region enclosing its
3880
+ * parts, and only a rewrite output that holds no region of its own and was assembled
3881
+ * from separate source nodes reports `undefined`.
3882
+ * {@link map} carries provenance across the rewrite: an unchanged node keeps its
3883
+ * region, a one-source replacement takes the region of the node it replaced, and a
3884
+ * rebuilt parent takes its original's.
3885
+ * - **Immutable.** {@link map} never mutates the stored AST - it returns a NEW `Markdown`
3886
+ * instance; the document root invariant (`element: 'document'`) always holds. An
3887
+ * identity rewrite still returns a new handle, over the same document tree.
3888
+ * - **Traversal order.** {@link walk} and the `find` / `filter` / `reduce` queries built
3889
+ * on it walk the AST depth-first, pre-order, root-inclusive (through {@link walkNodes});
3890
+ * `stream` is shallow - only the document's direct block children.
3891
+ *
3892
+ * @example
3893
+ * ```ts
3894
+ * import { Markdown, isHeadingNode, renderMarkdown } from '@src/core'
3895
+ *
3896
+ * const markdown = new Markdown('# Title\n\nA **bold** [link](https://x.dev).')
3897
+ * const heading = markdown.find(isHeadingNode) // the HeadingNode, or undefined
3898
+ * const shouted = markdown.map((node) =>
3899
+ * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,
3900
+ * )
3901
+ * renderMarkdown(shouted.document) // '# TITLE\n\nA **BOLD** [LINK](https://x.dev).'
3902
+ * ```
3903
+ */
3904
+ var Markdown = class Markdown {
3905
+ #document;
3906
+ #spans;
3907
+ constructor(input) {
3908
+ if (typeof input === "string") {
3909
+ const [document, spans] = parseProvenance(input);
3910
+ this.#document = document;
3911
+ this.#spans = new Map(spans);
3912
+ } else {
3913
+ this.#document = input;
3914
+ this.#spans = /* @__PURE__ */ new Map();
3915
+ }
3916
+ }
3917
+ /** Holds the stored {@link MarkdownDocument} AST root. */
3918
+ get document() {
3919
+ return this.#document;
3920
+ }
3921
+ /**
3922
+ * Reads the region of the original markdown string a node of this handle's tree was
3923
+ * produced from.
3924
+ *
3925
+ * @param node - The node whose provenance to read
3926
+ * @returns A fresh {@link MarkdownSpan}, or `undefined` when this handle holds no
3927
+ * region for the node
3928
+ *
3929
+ * @example
3930
+ * ```ts
3931
+ * const source = '# Title\n\npara'
3932
+ * const markdown = new Markdown(source)
3933
+ * const heading = markdown.find(isHeadingNode)
3934
+ * const span = heading && markdown.span(heading)
3935
+ * span && source.slice(span.start, span.end) // '# Title'
3936
+ * ```
3937
+ */
3938
+ span(node) {
3939
+ const span = this.#spans.get(node);
3940
+ return span === void 0 ? void 0 : {
3941
+ start: span.start,
3942
+ end: span.end
3943
+ };
3944
+ }
3945
+ /**
3946
+ * Returns THE deep traversal - a lazy, depth-first, pre-order, root-inclusive generator
3947
+ * over every {@link MarkdownNode} in the document. `find` / `filter` / `reduce`
3948
+ * all iterate this single traversal.
3949
+ *
3950
+ * @example
3951
+ * ```ts
3952
+ * for (const node of markdown.walk()) {
3953
+ * // every node, depth-first, pre-order, root-inclusive
3954
+ * }
3955
+ *
3956
+ * // also consumable by for-await - JS accepts a sync iterable in for-await
3957
+ * for await (const node of markdown.walk()) {
3958
+ * // same sequence, no separate async iterator needed
3959
+ * }
3960
+ * ```
3961
+ */
3962
+ *walk() {
3963
+ yield* walkNodes(this.#document);
3964
+ }
3965
+ find(predicate) {
3966
+ for (const node of this.walk()) if (predicate(node)) return node;
3967
+ }
3968
+ filter(predicate) {
3969
+ const out = [];
3970
+ for (const node of this.walk()) if (predicate(node)) out.push(node);
3971
+ return out;
3972
+ }
3973
+ /**
3974
+ * Rewrites the AST bottom-up (copy-on-write) and returns a new {@link Markdown},
3975
+ * carrying each output node's provenance across the rewrite. A rewrite that returns
3976
+ * its node unchanged shares that subtree instead of copying it, so an identity
3977
+ * rewrite copies no node and still returns a new handle.
3978
+ *
3979
+ * @param rewrite - The bottom-up node rewrite
3980
+ * @returns A new handle over the rewritten document
3981
+ */
3982
+ map(rewrite) {
3983
+ const [document, derivations] = rewriteDocument(this.#document, rewrite);
3984
+ return this.#derive(document, derivations);
3985
+ }
3986
+ /** Folds the AST depth-first, pre-order into an accumulator. */
3987
+ reduce(callback, initial) {
3988
+ let accumulator = initial;
3989
+ for (const node of this.walk()) accumulator = callback(accumulator, node);
3990
+ return accumulator;
3991
+ }
3992
+ /** Runs a total catamorphism over the document using a {@link MarkdownHandlerMap} table. */
3993
+ fold(handlers) {
3994
+ return foldNode(this.#document, handlers, 0);
3995
+ }
3996
+ /**
3997
+ * Returns a web-standard {@link ReadableStream} over the document's top-level block nodes
3998
+ * (shallow, source order) - a fresh, pull-based source per call: one block is
3999
+ * enqueued per `pull`, so a slow reader's backpressure is respected. Cancellable,
4000
+ * async-iterable wherever the platform supports it (Node, Deno), and pipeable
4001
+ * through any {@link TransformStream} / {@link WritableStream}.
4002
+ *
4003
+ * @example
4004
+ * ```ts
4005
+ * // universal - works in every ReadableStream-supporting environment
4006
+ * const reader = markdown.stream().getReader()
4007
+ * for (let result = await reader.read(); !result.done; result = await reader.read()) {
4008
+ * console.log(result.value) // one BlockNode
4009
+ * }
4010
+ *
4011
+ * // Node / Deno / Firefox support async iteration of ReadableStream natively;
4012
+ * // other environments use the reader loop shown earlier.
4013
+ * for await (const block of markdown.stream()) {
4014
+ * console.log(block)
4015
+ * }
4016
+ * ```
4017
+ */
4018
+ stream() {
4019
+ const blocks = this.#document.children;
4020
+ let index = 0;
4021
+ return new ReadableStream({ pull(controller) {
4022
+ if (index < blocks.length) {
4023
+ const block = blocks[index];
4024
+ if (block === void 0) {
4025
+ controller.close();
4026
+ return;
4027
+ }
4028
+ controller.enqueue(block);
4029
+ index += 1;
4030
+ } else controller.close();
4031
+ } });
4032
+ }
4033
+ #derive(document, derivations) {
4034
+ const derived = new Markdown(document);
4035
+ for (const node of walkNodes(document)) {
4036
+ const own = this.#spans.get(node);
4037
+ if (own !== void 0) {
4038
+ derived.#spans.set(node, own);
4039
+ continue;
4040
+ }
4041
+ const source = derivations.get(node);
4042
+ if (source === void 0) continue;
4043
+ const span = this.#spans.get(source);
4044
+ if (span !== void 0) derived.#spans.set(node, span);
4045
+ }
4046
+ return derived;
4047
+ }
4048
+ };
4049
+ //#endregion
4050
+ //#region src/core/factories.ts
4051
+ /**
4052
+ * Creates a stateful markdown handle from a markdown string or an already-parsed
4053
+ * {@link MarkdownDocument} - a typed AST plus the query, rewrite, and fold operations
4054
+ * {@link MarkdownInterface} exposes.
4055
+ *
4056
+ * @remarks
4057
+ * Given a `string`, runs a block phase (headings / paragraphs / lists / GFM tables /
4058
+ * fenced code / blockquotes / thematic breaks) then an inline phase (emphasis /
4059
+ * inline code / links / images / hard breaks) to build a render-agnostic
4060
+ * {@link MarkdownDocument}. Given a
4061
+ * {@link MarkdownDocument}, adopts it AS-IS without re-validation - gate an untrusted
4062
+ * value with `isMarkdownDocument` first. Pure + total parse (malformed markdown
4063
+ * degrades to text, never throws) and zero-dependency - a hand-written scanner, no
4064
+ * regex-only structural parse, linear-time (no ReDoS).
4065
+ *
4066
+ * @param input - A markdown string to parse, or an already-parsed {@link MarkdownDocument}
4067
+ * @returns A working {@link MarkdownInterface}
4068
+ *
4069
+ * @example
4070
+ * ```ts
4071
+ * import { createMarkdown } from '@src/core'
4072
+ *
4073
+ * const markdown = createMarkdown('# Hi\n\nRead the [guide](./guide.md).')
4074
+ * markdown.document.children[0] // { element: 'heading', ... }
4075
+ * ```
4076
+ */
4077
+ function createMarkdown(input) {
4078
+ return new Markdown(input);
4079
+ }
4080
+ /**
4081
+ * Compiles the {@link textShape} into a {@link ContractInterface} for
4082
+ * {@link TextNode} - a guard, coercing parser, JSON Schema, and seeded
4083
+ * generator from one shape declaration.
4084
+ *
4085
+ * @returns A `TextNode` contract bundling `schema` / `is` / `parse` / `generate`
4086
+ *
4087
+ * @example
4088
+ * ```ts
4089
+ * import { createTextContract } from '@src/core'
4090
+ *
4091
+ * const text = createTextContract()
4092
+ * text.is({ element: 'text', value: 'hi' }) // true
4093
+ * ```
4094
+ */
4095
+ function createTextContract() {
4096
+ return createContract(textShape);
4097
+ }
4098
+ /**
4099
+ * Compiles the {@link codeSpanShape} into a {@link ContractInterface} for
4100
+ * {@link CodeSpanNode} - a guard, coercing parser, JSON Schema, and seeded
4101
+ * generator from one shape declaration.
4102
+ *
4103
+ * @returns A `CodeSpanNode` contract bundling `schema` / `is` / `parse` / `generate`
4104
+ *
4105
+ * @example
4106
+ * ```ts
4107
+ * import { createCodeSpanContract } from '@src/core'
4108
+ *
4109
+ * const codeSpan = createCodeSpanContract()
4110
+ * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true
4111
+ * ```
4112
+ */
4113
+ function createCodeSpanContract() {
4114
+ return createContract(codeSpanShape);
4115
+ }
4116
+ /**
4117
+ * Compiles the {@link lineBreakShape} into a {@link ContractInterface} for
4118
+ * {@link LineBreakNode}.
4119
+ *
4120
+ * @returns A `LineBreakNode` contract bundling `schema` / `is` / `parse` / `generate`
4121
+ *
4122
+ * @example
4123
+ * ```ts
4124
+ * import { createLineBreakContract } from '@src/core'
4125
+ *
4126
+ * createLineBreakContract().is({ element: 'break' }) // true
4127
+ * ```
4128
+ */
4129
+ function createLineBreakContract() {
4130
+ return createContract(lineBreakShape);
4131
+ }
4132
+ /**
4133
+ * Compiles the {@link codeBlockShape} into a {@link ContractInterface} for
4134
+ * {@link CodeBlockNode} - a guard, coercing parser, JSON Schema, and seeded
4135
+ * generator from one shape declaration.
4136
+ *
4137
+ * @returns A `CodeBlockNode` contract bundling `schema` / `is` / `parse` / `generate`
4138
+ *
4139
+ * @example
4140
+ * ```ts
4141
+ * import { createCodeBlockContract } from '@src/core'
4142
+ *
4143
+ * const codeBlock = createCodeBlockContract()
4144
+ * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true
4145
+ * ```
4146
+ */
4147
+ function createCodeBlockContract() {
4148
+ return createContract(codeBlockShape);
4149
+ }
4150
+ /**
4151
+ * Compiles the {@link thematicBreakShape} into a {@link ContractInterface} for
4152
+ * {@link ThematicBreakNode} - a guard, coercing parser, JSON Schema, and
4153
+ * seeded generator from one shape declaration.
4154
+ *
4155
+ * @returns A `ThematicBreakNode` contract bundling `schema` / `is` / `parse` / `generate`
4156
+ *
4157
+ * @example
4158
+ * ```ts
4159
+ * import { createThematicBreakContract } from '@src/core'
4160
+ *
4161
+ * const thematicBreak = createThematicBreakContract()
4162
+ * thematicBreak.is({ element: 'thematicBreak' }) // true
4163
+ * ```
4164
+ */
4165
+ function createThematicBreakContract() {
4166
+ return createContract(thematicBreakShape);
4167
+ }
4168
+ //#endregion
4169
+ export { EMPTY_PROJECTION, MAX_DEPTH, Markdown, coalesceText, codeBlockShape, codeSpanShape, collectList, collectTable, countIndent, createCodeBlockContract, createCodeSpanContract, createLineBreakContract, createMarkdown, createProjection, createTextContract, createThematicBreakContract, delimiterToAlignments, extractFence, extractHeading, extractListItem, flattenText, foldNode, htmlToMarkdown, isBlankLine, isBlockNode, isBlockquoteNode, isCodeBlockNode, isCodeSpanNode, isEmphasisNode, isEscapable, isFenceClose, isFenceWhitespace, isFlankingWhitespace, isHeadingNode, isImageNode, isInlineNode, isLineBreakNode, isLinkNode, isListNode, isMarkdownDocument, isMarkdownNode, isParagraphNode, isQuote, isTableNode, isTableStart, isTextNode, isThematicBreak, isThematicBreakNode, joinSources, lineBreakShape, listItemMatchShape, locateEmphasis, locateLink, markdownToHTML, mergeProjections, normalizeInlines, normalizeParagraphLine, parseBlocks, parseDocument, parseInline, parseProvenance, projectHTMLLeaf, projectHTMLNode, projectSpan, projectionToBlocks, projectionToInlines, renderHTML, renderMarkdown, rewriteDocument, scanCode, scanEmphasis, scanInline, scanInlineSource, scanLink, sliceSource, splitLines, splitTableRow, splitTableSources, startsBlock, stripQuote, tableAlignShape, textShape, thematicBreakShape, trimInlines, trimSource, unescapeText, walkNodes };
4089
4170
 
4090
4171
  //# sourceMappingURL=index.js.map