markemental 0.2.0 → 0.4.0

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.
package/dist/index.d.cts CHANGED
@@ -1,624 +1,771 @@
1
1
  /**
2
- * Block-level markdown constructs recognized by the MVP parser.
2
+ * Incremental modular markdown renderer.
3
3
  *
4
- * @public
4
+ * @packageDocumentation
5
5
  */
6
- type BlockKind = "heading" | "paragraph" | "fence" | "list" | "quote" | "rule" | "table";
7
6
  /**
8
- * A parsed block of markdown lines.
9
- *
10
- * @public
11
- */
12
- interface Block {
13
- /** What kind of block this is. */
14
- kind: BlockKind;
15
- /**
16
- * Block content lines. Markers are stripped: `#` prefixes for headings,
17
- * list markers for lists, `>` prefixes for quotes, and fence lines for
18
- * fenced code. Paragraph lines are raw.
19
- */
20
- lines: string[];
21
- /** Heading level (1-6) for `"heading"` blocks. */
22
- level?: number;
23
- /** Fence info string for `"fence"` blocks, when present. */
24
- language?: string;
25
- /** Whether a `"list"` block is ordered. */
26
- ordered?: boolean;
27
- /**
28
- * Number of source lines this block was parsed from, used to hold back a
29
- * trailing partial block across `push` calls.
30
- */
31
- sourceLineCount: number;
32
- }
33
-
34
- /**
35
- * Incremental markdown rendering pipeline.
7
+ * Opaque handle for a node held by a target.
36
8
  *
37
9
  * @remarks
38
- * A pipeline accepts markdown in arbitrarily-sized chunks and renders complete
39
- * blocks to its target as they arrive. A trailing partial block is held back
40
- * until more input completes it or {@link MarkdownPipeline.flush} is called.
10
+ * Minted by creation calls; never construct one by hand. Valid for
11
+ * detached nodes too, so renderers may build a subtree detached and
12
+ * attach it afterwards. Replacing or removing a node retires its id —
13
+ * and the ids of its subtree — and reusing a retired id throws.
41
14
  *
42
15
  * @public
43
16
  */
44
- interface MarkdownPipeline {
45
- /**
46
- * Push a chunk of markdown into the pipeline.
47
- *
48
- * @param chunk - Markdown text, or a promise resolving to markdown text.
49
- * @returns A promise that resolves once the chunk has been consumed and any
50
- * complete blocks have been rendered to the target.
51
- */
52
- push(chunk: string | Promise<string>): Promise<void>;
53
- /**
54
- * Render any buffered remainder and release pipeline resources.
55
- *
56
- * @returns A promise that resolves once all output has been flushed.
57
- */
58
- flush(): Promise<void>;
59
- }
60
-
17
+ type NodeId = string;
61
18
  /**
62
- * Minimal subset of the DOM `Node` interface that markemental needs.
63
- *
64
- * @remarks
65
- * Both real DOM nodes and lightweight server-side implementations (for
66
- * example linkedom) satisfy this interface.
19
+ * A target call referenced an id the target never minted or already
20
+ * retired. Carries the offending id.
67
21
  *
68
22
  * @public
69
23
  */
70
- interface DOMNodeLike {
71
- /** Numeric node type, mirroring `Node.nodeType`. */
72
- nodeType: number;
73
- /** Text content of this node, mirroring `Node.textContent`. */
74
- textContent: string | null;
75
- /** Child nodes, mirroring `Node.childNodes`. */
76
- childNodes: ArrayLike<DOMNodeLike>;
77
- /** Owning document, or `null` for detached nodes. */
78
- ownerDocument: DOMDocumentLike | null;
79
- /**
80
- * Append a child node.
81
- *
82
- * @param node - Node to append.
83
- * @returns The appended node.
84
- */
85
- appendChild(node: DOMNodeLike): DOMNodeLike;
86
- /**
87
- * Insert a node before a reference child.
88
- *
89
- * @param newNode - Node to insert.
90
- * @param referenceNode - Child to insert before, or `null` to append.
91
- * @returns The inserted node.
92
- */
93
- insertBefore(newNode: DOMNodeLike, referenceNode: DOMNodeLike | null): DOMNodeLike;
94
- /**
95
- * Remove a child node.
96
- *
97
- * @param child - Child to remove.
98
- * @returns The removed node.
99
- */
100
- removeChild(child: DOMNodeLike): DOMNodeLike;
101
- /**
102
- * Replace a child node.
103
- *
104
- * @param newChild - Replacement node.
105
- * @param oldChild - Child to replace.
106
- * @returns The replaced node.
107
- */
108
- replaceChild(newChild: DOMNodeLike, oldChild: DOMNodeLike): DOMNodeLike;
109
- /**
110
- * Set an attribute on this node, when supported.
111
- *
112
- * @param name - Attribute name.
113
- * @param value - Attribute value.
114
- */
115
- setAttribute?(name: string, value: string): void;
116
- /**
117
- * Remove an attribute from this node, when supported.
118
- *
119
- * @param name - Attribute name.
120
- */
121
- removeAttribute?(name: string): void;
24
+ export declare class UnknownNodeError extends Error {
25
+ /** The unknown id. */
26
+ readonly nodeId: string;
27
+ /**
28
+ * @param nodeId - The unknown id.
29
+ */
30
+ constructor(nodeId: string);
122
31
  }
123
32
  /**
124
- * Minimal subset of the DOM `Document` interface that markemental needs.
33
+ * A replace targeted a node that was never attached. Carries the
34
+ * detached id.
125
35
  *
126
36
  * @public
127
37
  */
128
- interface DOMDocumentLike {
129
- /**
130
- * Create an element node.
131
- *
132
- * @param tagName - Lowercase tag name (for example `"p"`).
133
- * @returns The new element.
134
- */
135
- createElement(tagName: string): DOMNodeLike;
136
- /**
137
- * Create a text node.
138
- *
139
- * @param data - Text content.
140
- * @returns The new text node.
141
- */
142
- createTextNode(data: string): DOMNodeLike;
38
+ export declare class DetachedNodeError extends Error {
39
+ /** The detached id. */
40
+ readonly nodeId: string;
41
+ /**
42
+ * @param nodeId - The detached id.
43
+ */
44
+ constructor(nodeId: string);
143
45
  }
144
46
  /**
145
- * `requestAnimationFrame` callback scheduler.
146
- *
147
- * @param callback - Invoked with the frame timestamp.
148
- * @returns A handle identifying the scheduled frame.
47
+ * An attach would have built a cycle: the node is an ancestor of the
48
+ * parent. Carries both ids.
149
49
  *
150
50
  * @public
151
51
  */
152
- type RAF = (callback: (time: number) => void) => number;
153
-
52
+ export declare class HierarchyError extends Error {
53
+ /** The node being attached. */
54
+ readonly nodeId: string;
55
+ /** The parent it was attached to. */
56
+ readonly parentId: string;
57
+ /**
58
+ * @param nodeId - The node being attached.
59
+ * @param parentId - The parent it was attached to.
60
+ */
61
+ constructor(nodeId: string, parentId: string);
62
+ }
154
63
  /**
155
- * Renders parsed markdown to DOM-like nodes.
64
+ * Write-only destination for rendered output.
156
65
  *
157
- * @typeParam Opts - Renderer-specific options.
66
+ * @remarks
67
+ * An HTML-like target: renderers build nodes through these methods without
68
+ * ever touching a DOM. Nodes start detached; appending attaches them, and
69
+ * a `null` parent addresses the top level. The target returns opaque ids
70
+ * and owns the id-to-node mapping (in memory, or however it likes); it
71
+ * cannot be queried.
72
+ *
73
+ * Attributes are set once at creation so remote targets never need
74
+ * mutation calls; replace the node to change them. Implementations must
75
+ * behave like the DOM for the operations below: appending an attached
76
+ * node moves it, and unknown ids throw. Custom targets (collectors,
77
+ * serializers, remote renderers) implement this same interface.
158
78
  *
159
79
  * @public
160
80
  */
161
- interface MarkdownRenderer<Opts> {
162
- /** Renderer-specific options. */
163
- readonly options: Opts;
164
- /**
165
- * Render one block to a DOM-like node.
166
- *
167
- * @param block - Parsed block to render.
168
- * @param doc - Document used to create nodes.
169
- * @returns The rendered node, or `null` to emit nothing.
170
- */
171
- renderBlock(block: Block, doc: DOMDocumentLike): DOMNodeLike | null;
81
+ interface HTMLTarget {
82
+ /**
83
+ * Create a detached element node with attributes.
84
+ *
85
+ * @param tag - Lowercase tag name (for example `"p"`).
86
+ * @param attrs - Attributes to set. Fixed at creation: replace the node
87
+ * to change them. Targets whose DOM cannot set attributes throw when
88
+ * this is non-empty.
89
+ * @returns Id addressing the new node.
90
+ */
91
+ createElement(tag: string, attrs?: Record<string, string>): NodeId;
92
+ /**
93
+ * Create a detached text node.
94
+ *
95
+ * @param text - Text content.
96
+ * @returns Id addressing the new node.
97
+ */
98
+ createTextNode(text: string): NodeId;
99
+ /**
100
+ * Append a child to a parent, or to the top level for a `null` parent.
101
+ * Appending an attached node moves it.
102
+ *
103
+ * @param parent - Receiving node, or `null` for the top level.
104
+ * @param child - Node to append.
105
+ * @throws {@link UnknownNodeError} for unknown ids.
106
+ * @throws {@link HierarchyError} when the child is an ancestor of the parent.
107
+ */
108
+ appendChild(parent: NodeId | null, child: NodeId): void;
109
+ /**
110
+ * Replace an attached node with another node, which takes its position.
111
+ * The old id is retired. Replacing a detached node throws; replacing a
112
+ * node with itself is a no-op.
113
+ *
114
+ * @param oldId - Attached node to replace.
115
+ * @param newId - Replacement node.
116
+ * @throws {@link UnknownNodeError} for unknown ids.
117
+ * @throws {@link DetachedNodeError} when the old node was never attached.
118
+ * @throws {@link HierarchyError} when the new node is an ancestor of the position.
119
+ */
120
+ replaceNode(oldId: NodeId, newId: NodeId): void;
121
+ /**
122
+ * Detach a node and retire its id.
123
+ *
124
+ * @param id - Node to remove.
125
+ * @throws {@link UnknownNodeError} for unknown ids.
126
+ */
127
+ remove(id: NodeId): void;
128
+ /**
129
+ * Replace a node's children with a single text run, retiring the
130
+ * children's ids. On a text node, replaces its content.
131
+ *
132
+ * @param node - Node to update.
133
+ * @param text - Replacement text.
134
+ * @throws {@link UnknownNodeError} for unknown ids.
135
+ */
136
+ setTextContent(node: NodeId, text: string): void;
137
+ /**
138
+ * Wait for all committed updates to land.
139
+ *
140
+ * @returns Nothing for synchronous targets, or a promise that resolves
141
+ * once every update has landed.
142
+ */
143
+ flush(): void | Promise<void>;
172
144
  }
173
-
174
145
  /**
175
- * Buffers pushed text and emits complete lines.
146
+ * Incremental markdown rendering pipeline.
147
+ *
148
+ * @remarks
149
+ * A pipeline is a `WritableStream` of markdown text: write unicode string
150
+ * chunks in any sizes and complete blocks render to the target as they
151
+ * arrive. Closing the stream renders the trailing remainder. The pipeline
152
+ * chunks writes into lines itself; writes after close reject with the
153
+ * platform's native closed-stream error, and non-string chunks reject with
154
+ * a `TypeError`. Aborting discards the buffered remainder without
155
+ * rendering it.
176
156
  *
177
157
  * @public
178
158
  */
179
- interface LineSource {
180
- /**
181
- * Push text into the buffer.
182
- *
183
- * @param chunk - Raw markdown text, with or without line breaks.
184
- */
185
- push(chunk: string): void;
186
- /**
187
- * Drain newline-terminated lines, holding back any trailing partial line.
188
- *
189
- * @returns Complete lines without line breaks.
190
- */
191
- readLines(): string[];
192
- /**
193
- * Close the source and drain the trailing partial line, if any.
194
- *
195
- * @returns Zero or one remaining line.
196
- */
197
- close(): string[];
159
+ interface MarkdownPipeline<Config = unknown> extends WritableStream<string> {
160
+ /**
161
+ * Reuse this pipeline for another target: subsequent commits go there.
162
+ *
163
+ * @param target - Target receiving future output.
164
+ */
165
+ setTarget(target: HTMLTarget): void;
166
+ /**
167
+ * Update the renderer config on the fly. Applies to subsequent commits.
168
+ *
169
+ * @param config - Next config.
170
+ */
171
+ setConfig(config: Config): void;
198
172
  }
199
-
200
173
  /**
201
- * Destination for rendered output.
174
+ * Incremental markdown renderer: consumes lines, updates a target.
202
175
  *
203
176
  * @remarks
204
- * A target receives rendered nodes from a pipeline and attaches them to the
205
- * host document. Targets decide when attachment happens: immediately, or
206
- * batched on animation frames for smooth streaming into a live page.
177
+ * A renderer holds whatever parse state it needs and writes finished
178
+ * output to its target as input completes. `Config` is the renderer's own
179
+ * config type (for example `GFMRendererConfig`); there is no shared base.
207
180
  *
208
- * @public
209
- */
210
- interface RenderTarget {
211
- /**
212
- * Attach a rendered node to the target.
213
- *
214
- * @param node - Node to attach. Attachment may be deferred (for example to
215
- * the next animation frame); use {@link RenderTarget.flush} to wait for it.
216
- */
217
- append(node: DOMNodeLike): void;
218
- /**
219
- * Wait for all appended nodes to be attached.
220
- *
221
- * @returns A promise that resolves once the target holds every node.
222
- */
223
- flush(): Promise<void>;
224
- }
225
-
226
- /**
227
- * Renderer for CommonMark.
181
+ * Implement this interface to plug in your own renderer, hand-written or a
182
+ * third-party adapter. The constructor is yours; the pipeline wires the
183
+ * target through {@link MarkdownRenderer.setTarget}.
184
+ *
185
+ * Sanitization is the renderer's job: the target creates exactly the tags
186
+ * and attributes it is told to, so a renderer that passes untrusted input
187
+ * through (raw HTML, link targets) must filter it before calling the
188
+ * target.
228
189
  *
229
190
  * @public
230
191
  */
231
- declare class CommonMarkRenderer implements MarkdownRenderer<CommonMarkRenderOptions> {
232
- /** Rendering options. */
233
- readonly options: CommonMarkRenderOptions;
234
- /**
235
- * @param opts - CommonMark rendering options.
236
- */
237
- constructor(opts: CommonMarkRenderOptions);
238
- /**
239
- * Whether GFM-only inlines are enabled. Always false here; overridden by
240
- * {@link GFMRenderer}.
241
- *
242
- * @returns False.
243
- */
244
- protected inlineGfm(): boolean;
245
- /**
246
- * Render one block to a DOM-like node.
247
- *
248
- * @param block - Parsed block to render.
249
- * @param doc - Document used to create nodes.
250
- * @returns The rendered node, or `null` to emit nothing.
251
- */
252
- renderBlock(block: Block, doc: DOMDocumentLike): DOMNodeLike | null;
253
- /**
254
- * Render paragraph lines, honoring two-space hard breaks.
255
- *
256
- * @param lines - Raw paragraph lines.
257
- * @param doc - Document used to create nodes.
258
- * @returns The paragraph element.
259
- */
260
- protected renderParagraph(lines: string[], doc: DOMDocumentLike): DOMNodeLike;
261
- private appendLinesInline;
192
+ interface MarkdownRenderer<Config> {
193
+ /**
194
+ * Feed one complete line to the renderer.
195
+ *
196
+ * @param line - Next source line, without its line break. The renderer
197
+ * buffers what it needs and writes completed output to its target.
198
+ */
199
+ writeLine(line: string): void;
200
+ /**
201
+ * Flush buffered partial state to the target and settle it.
202
+ *
203
+ * @returns A promise that resolves once all output has landed in the target.
204
+ */
205
+ flush(): Promise<void>;
206
+ /**
207
+ * Point the renderer at another target. Queued updates stay with the old
208
+ * target; subsequent commits go to the new one.
209
+ *
210
+ * @param target - Target receiving future output.
211
+ */
212
+ setTarget(target: HTMLTarget): void;
213
+ /**
214
+ * Replace the renderer config. Applies to subsequent commits; output
215
+ * already committed is left alone.
216
+ *
217
+ * @param config - Next config.
218
+ */
219
+ setConfig(config: Config): void;
262
220
  }
263
221
  /**
264
- * Options for {@link CommonMarkRenderer}.
222
+ * Create a streaming pipeline around any renderer and target.
223
+ *
224
+ * @remarks
225
+ * The pipeline chunks whatever strings are written into lines and feeds
226
+ * them to the renderer one at a time; the renderer owns its parse state
227
+ * and commits finished output to the target. Closing the stream renders
228
+ * the trailing remainder. Pass a built-in renderer (`GFMRenderer`,
229
+ * `CommonMarkRenderer`) or your own `MarkdownRenderer` implementation,
230
+ * and a DOM target from `createDOMTarget` or your own `HTMLTarget`.
231
+ *
232
+ * @param renderer - Line-consuming renderer holding its own parse state.
233
+ * @param target - Destination the renderer commits to.
234
+ * @returns A working pipeline.
235
+ *
236
+ * @example
237
+ * ```ts
238
+ * const target = createDOMTarget(document, document.getElementById("out")!);
239
+ * const stream = createMarkdownStream(new GFMRenderer(target, {}), target);
240
+ * const writer = stream.getWriter();
241
+ * await writer.write("# Hello\n");
242
+ * await writer.close();
243
+ * writer.releaseLock();
244
+ * ```
265
245
  *
266
246
  * @public
267
247
  */
268
- type CommonMarkRenderOptions = {};
269
-
248
+ export declare function createMarkdownStream<Config>(renderer: MarkdownRenderer<Config>, target: HTMLTarget): MarkdownPipeline<Config>;
270
249
  /**
271
- * Renderer for GitHub Flavored Markdown.
250
+ * Minimal subset of the DOM `Node` interface that markemental needs.
272
251
  *
273
252
  * @remarks
274
- * Supports CommonMark blocks and inlines plus GFM tables and strikethrough.
253
+ * These interfaces describe DOMs provided from outside the library: a real
254
+ * browser document, or a lightweight server-side implementation (for
255
+ * example linkedom). Both satisfy this interface.
275
256
  *
276
257
  * @public
277
258
  */
278
- declare class GFMRenderer extends CommonMarkRenderer implements MarkdownRenderer<GFMRenderOptions> {
279
- /** Rendering options. */
280
- readonly options: GFMRenderOptions;
281
- /**
282
- * @param opts - GFM rendering options.
283
- */
284
- constructor(opts: GFMRenderOptions);
285
- /**
286
- * GFM-only inlines are enabled.
287
- *
288
- * @returns True.
289
- */
290
- protected inlineGfm(): boolean;
291
- /**
292
- * Render one block to a DOM-like node, handling GFM tables.
293
- *
294
- * @param block - Parsed block to render.
295
- * @param doc - Document used to create nodes.
296
- * @returns The rendered node, or `null` to emit nothing.
297
- */
298
- renderBlock(block: Block, doc: DOMDocumentLike): DOMNodeLike | null;
259
+ interface DOMNodeLike {
260
+ /** Numeric node type, mirroring `Node.nodeType`. */
261
+ nodeType: number;
262
+ /** Text content of this node, mirroring `Node.textContent`. */
263
+ textContent: string | null;
264
+ /** Child nodes, mirroring `Node.childNodes`. */
265
+ childNodes: ArrayLike<DOMNodeLike>;
266
+ /** Owning document, or `null` for detached nodes. */
267
+ ownerDocument: DOMDocumentLike | null;
268
+ /**
269
+ * Append a child node.
270
+ *
271
+ * @param node - Node to append.
272
+ * @returns The appended node.
273
+ */
274
+ appendChild(node: DOMNodeLike): DOMNodeLike;
275
+ /**
276
+ * Insert a node before a reference child.
277
+ *
278
+ * @param newNode - Node to insert.
279
+ * @param referenceNode - Child to insert before, or `null` to append.
280
+ * @returns The inserted node.
281
+ */
282
+ insertBefore(newNode: DOMNodeLike, referenceNode: DOMNodeLike | null): DOMNodeLike;
283
+ /**
284
+ * Remove a child node.
285
+ *
286
+ * @param child - Child to remove.
287
+ * @returns The removed node.
288
+ */
289
+ removeChild(child: DOMNodeLike): DOMNodeLike;
290
+ /**
291
+ * Replace a child node.
292
+ *
293
+ * @param newChild - Replacement node.
294
+ * @param oldChild - Child to replace.
295
+ * @returns The replaced node.
296
+ */
297
+ replaceChild(newChild: DOMNodeLike, oldChild: DOMNodeLike): DOMNodeLike;
298
+ /**
299
+ * Set an attribute on this node, when supported.
300
+ *
301
+ * @param name - Attribute name.
302
+ * @param value - Attribute value.
303
+ */
304
+ setAttribute?(name: string, value: string): void;
305
+ /**
306
+ * Remove an attribute from this node, when supported.
307
+ *
308
+ * @param name - Attribute name.
309
+ */
310
+ removeAttribute?(name: string): void;
299
311
  }
300
312
  /**
301
- * Options for {@link GFMRenderer}.
313
+ * Minimal subset of the DOM `Document` interface that markemental needs.
302
314
  *
303
315
  * @public
304
316
  */
305
- type GFMRenderOptions = {};
306
-
317
+ interface DOMDocumentLike {
318
+ /**
319
+ * Create an element node.
320
+ *
321
+ * @param tagName - Lowercase tag name (for example `"p"`).
322
+ * @returns The new element.
323
+ */
324
+ createElement(tagName: string): DOMNodeLike;
325
+ /**
326
+ * Create a text node.
327
+ *
328
+ * @param data - Text content.
329
+ * @returns The new text node.
330
+ */
331
+ createTextNode(data: string): DOMNodeLike;
332
+ }
307
333
  /**
308
- * Create a GFM pipeline that renders into a live page.
309
- *
310
- * @param target - Container node receiving rendered blocks.
311
- * @param dom - Document used to create nodes.
312
- * @param opts - GFM rendering options.
313
- * @param raf - Optional frame scheduler. When provided, DOM writes are
314
- * batched on animation frames for smooth streaming.
315
- * @returns The configured pipeline.
334
+ * `requestAnimationFrame` callback scheduler.
316
335
  *
317
- * @example
318
- * ```ts
319
- * const pipeline = createFrontendGFMPipeline(
320
- * document.getElementById("out"),
321
- * document,
322
- * {},
323
- * requestAnimationFrame,
324
- * );
325
- * await pipeline.push("# Hello\n");
326
- * await pipeline.flush();
327
- * ```
336
+ * @param callback - Invoked with the frame timestamp.
337
+ * @returns A handle identifying the scheduled frame.
328
338
  *
329
339
  * @public
330
340
  */
331
- declare function createFrontendGFMPipeline(target: DOMNodeLike, dom: DOMDocumentLike, opts: GFMRenderOptions, raf?: RAF): MarkdownPipeline;
341
+ type RAF = (callback: (time: number) => void) => number;
332
342
  /**
333
- * Incremental GFM pipeline for browser targets.
343
+ * Leaf block constructs recognized by the MVP parser.
334
344
  *
335
- * @public
345
+ * @remarks
346
+ * Internal to the built-in renderers: the public renderer interface consumes
347
+ * lines, and each renderer is free to parse them however it wants. Tables
348
+ * and lists are not blocks: they stream as fragments (see ParseFragment).
349
+ *
350
+ * @internal
336
351
  */
337
- declare class FrontendGFMPipeline implements MarkdownPipeline {
338
- private _engine;
339
- /**
340
- * @param target - Container node receiving rendered blocks.
341
- * @param dom - Document used to create nodes.
342
- * @param opts - GFM rendering options.
343
- * @param raf - Optional frame scheduler for batched DOM writes.
344
- */
345
- constructor(target: DOMNodeLike, dom: DOMDocumentLike, opts: GFMRenderOptions, raf?: RAF);
346
- /**
347
- * Push a chunk of markdown into the pipeline.
348
- *
349
- * @param chunk - Markdown text, or a promise resolving to markdown text.
350
- * @returns A promise that resolves once the chunk has been consumed.
351
- */
352
- push(chunk: string | Promise<string>): Promise<void>;
353
- /**
354
- * Render any buffered remainder.
355
- *
356
- * @returns A promise that resolves once all output has been flushed.
357
- */
358
- flush(): Promise<void>;
359
- }
360
-
352
+ type BlockKind = "heading" | "paragraph" | "fence" | "quote" | "rule";
361
353
  /**
362
- * Create a CommonMark pipeline that renders into a live page.
354
+ * A parsed block of markdown lines.
363
355
  *
364
- * @param target - Container node receiving rendered blocks.
365
- * @param dom - Document used to create nodes.
366
- * @param opts - CommonMark rendering options.
367
- * @param raf - Optional frame scheduler. When provided, DOM writes are
368
- * batched on animation frames for smooth streaming.
369
- * @returns The configured pipeline.
356
+ * @internal
357
+ */
358
+ interface Block {
359
+ /** What kind of block this is. */
360
+ kind: BlockKind;
361
+ /**
362
+ * Block content lines. Markers are stripped: `#` prefixes for headings,
363
+ * `>` prefixes for quotes, and fence lines for fenced code. Paragraph
364
+ * lines are raw.
365
+ */
366
+ lines: string[];
367
+ /** Heading level (1-6) for `"heading"` blocks. */
368
+ level?: number;
369
+ /** Fence info string for `"fence"` blocks, when present. */
370
+ language?: string;
371
+ /**
372
+ * Number of source lines this block was parsed from, used to hold back a
373
+ * trailing partial block across writes.
374
+ */
375
+ sourceLineCount: number;
376
+ }
377
+ /**
378
+ * Structural piece of a document emitted as lines are parsed.
370
379
  *
371
- * @example
372
- * ```ts
373
- * const pipeline = createFrontendCommonMarkPipeline(
374
- * document.getElementById("out"),
375
- * document,
376
- * {},
377
- * requestAnimationFrame,
378
- * );
379
- * await pipeline.push("# Hello\n");
380
- * await pipeline.flush();
381
- * ```
380
+ * @remarks
381
+ * Whole leaf blocks (headings, paragraphs, fences, quotes, rules) arrive as
382
+ * single `block` fragments once complete. Lists stream: an opening fragment
383
+ * commits the container, one fragment per item follows, and a closing
384
+ * fragment ends it. Tables stream the same way (head, rows, end), but only
385
+ * {@link GFMState} emits those; {@link CommonMarkState} never does.
382
386
  *
383
- * @public
387
+ * @internal
384
388
  */
385
- declare function createFrontendCommonMarkPipeline(target: DOMNodeLike, dom: DOMDocumentLike, opts: CommonMarkRenderOptions, raf?: RAF): MarkdownPipeline;
389
+ type ParseFragment = {
390
+ kind: "block";
391
+ block: Block;
392
+ } | {
393
+ kind: "listStart";
394
+ ordered: boolean;
395
+ } | {
396
+ kind: "listItem";
397
+ text: string;
398
+ } | {
399
+ kind: "listEnd";
400
+ } | {
401
+ kind: "tableHead";
402
+ headLine: string;
403
+ delimLine: string;
404
+ } | {
405
+ kind: "tableRow";
406
+ line: string;
407
+ } | {
408
+ kind: "tableEnd";
409
+ };
386
410
  /**
387
- * Incremental CommonMark pipeline for browser targets.
411
+ * Incremental line-driven parser for CommonMark structure.
388
412
  *
389
- * @public
413
+ * @remarks
414
+ * Internal helper owned by a renderer. Lines arrive one at a time: leaf
415
+ * blocks buffer until a new block starts or the stream flushes (preserving
416
+ * trailing holdback), and lists commit one fragment per item with an indent
417
+ * stack for nesting. Tables are not recognized here, so table-looking lines
418
+ * stay plain paragraph text; {@link GFMState} extends this class with table
419
+ * support and nothing else.
420
+ *
421
+ * @internal
390
422
  */
391
- declare class FrontendCommonMarkPipeline implements MarkdownPipeline {
392
- private _engine;
393
- /**
394
- * @param target - Container node receiving rendered blocks.
395
- * @param dom - Document used to create nodes.
396
- * @param opts - CommonMark rendering options.
397
- * @param raf - Optional frame scheduler for batched DOM writes.
398
- */
399
- constructor(target: DOMNodeLike, dom: DOMDocumentLike, opts: CommonMarkRenderOptions, raf?: RAF);
400
- /**
401
- * Push a chunk of markdown into the pipeline.
402
- *
403
- * @param chunk - Markdown text, or a promise resolving to markdown text.
404
- * @returns A promise that resolves once the chunk has been consumed.
405
- */
406
- push(chunk: string | Promise<string>): Promise<void>;
407
- /**
408
- * Render any buffered remainder.
409
- *
410
- * @returns A promise that resolves once all output has been flushed.
411
- */
412
- flush(): Promise<void>;
423
+ declare class CommonMarkState {
424
+ protected _emit: (fragment: ParseFragment) => void;
425
+ protected _pending: string[];
426
+ private _fence;
427
+ private _quote;
428
+ private _lists;
429
+ /**
430
+ * @param emit - Receives parse fragments in document order.
431
+ */
432
+ constructor(_emit: (fragment: ParseFragment) => void);
433
+ /**
434
+ * Feed one source line; completed fragments emit to the handler.
435
+ *
436
+ * @param line - Next source line, without its line break.
437
+ */
438
+ addLine(line: string): void;
439
+ /**
440
+ * Close every open context and emit the trailing remainder.
441
+ */
442
+ flush(): void;
443
+ /**
444
+ * Feed a line to the open fence, if any.
445
+ *
446
+ * @param line - Next source line.
447
+ * @returns True when the line was consumed.
448
+ */
449
+ protected _consumeFence(line: string): boolean;
450
+ /**
451
+ * Feed a line to the open lists, if any, closing and reprocessing when
452
+ * the line is not an item.
453
+ *
454
+ * @param line - Next source line.
455
+ * @returns True when the line was consumed or reprocessed.
456
+ */
457
+ protected _consumeLists(line: string): boolean;
458
+ /**
459
+ * Feed a line to the open quote, if any, dumping it back to pending when
460
+ * the line does not continue the quote.
461
+ *
462
+ * @param line - Next source line.
463
+ * @returns True when the line was consumed.
464
+ */
465
+ protected _consumeQuote(line: string): boolean;
466
+ /**
467
+ * Classify a line that continues no open context.
468
+ *
469
+ * @param line - Next source line.
470
+ */
471
+ protected _classify(line: string): void;
472
+ /**
473
+ * Classify a line that matches no CommonMark opener. The base parser has
474
+ * no pipe syntax, so this never consumes; {@link GFMState} overrides it
475
+ * to start table candidates.
476
+ *
477
+ * @param _line - Next source line.
478
+ * @returns Always false here.
479
+ */
480
+ protected _classifyPipe(_line: string): boolean;
481
+ private _listItem;
482
+ private _closeLists;
483
+ private _takeComplete;
484
+ protected _takeAll(): void;
413
485
  }
414
-
415
486
  /**
416
- * Create a GFM pipeline for server-side rendering.
487
+ * Incremental line-driven parser for GFM structure.
417
488
  *
418
489
  * @remarks
419
- * Backend pipelines write synchronously and never schedule animation frames.
420
- * Pair with a lightweight `DOMDocumentLike` such as linkedom.
490
+ * Extends {@link CommonMarkState} with tables and nothing else: a table
491
+ * commits at the delimiter row and streams one fragment per row. All leaf
492
+ * and list parsing is inherited unchanged.
421
493
  *
422
- * @param target - Container node receiving rendered blocks.
423
- * @param dom - Document used to create nodes.
424
- * @param opts - GFM rendering options.
425
- * @returns The configured pipeline.
494
+ * @internal
495
+ */
496
+ declare class GFMState extends CommonMarkState {
497
+ private _tableOpen;
498
+ private _candidate;
499
+ /**
500
+ * Feed one source line; completed fragments emit to the handler.
501
+ *
502
+ * @param line - Next source line, without its line break.
503
+ */
504
+ addLine(line: string): void;
505
+ /**
506
+ * Close every open context and emit the trailing remainder.
507
+ */
508
+ flush(): void;
509
+ /**
510
+ * Feed a line to the open table, if any, closing and reprocessing when
511
+ * the line is not a row.
512
+ *
513
+ * @param line - Next source line.
514
+ * @returns True when the line was consumed or reprocessed.
515
+ */
516
+ private _consumeTable;
517
+ /**
518
+ * Resolve a pending table header candidate against the next line.
519
+ *
520
+ * @param line - Next source line.
521
+ * @returns True when a table opened.
522
+ */
523
+ private _consumeCandidate;
524
+ /**
525
+ * Start a table header candidate on pipe lines.
526
+ *
527
+ * @param line - Next source line.
528
+ * @returns True when the line starts a candidate.
529
+ */
530
+ protected _classifyPipe(line: string): boolean;
531
+ }
532
+ /**
533
+ * Renderer for CommonMark.
426
534
  *
427
- * @example
428
- * ```ts
429
- * import { parseHTML } from "linkedom";
535
+ * @remarks
536
+ * Constructed with its target and config. Feed it lines with
537
+ * {@link CommonMarkRenderer.writeLine}; it holds its own parse state and
538
+ * writes finished blocks to the target as they complete. Open lists are
539
+ * tracked on a stack so items — including nested ones — append to the
540
+ * right container as they arrive.
430
541
  *
431
- * const { document } = parseHTML("<div></div>");
432
- * const pipeline = createBackendGFMPipeline(document.querySelector("div"), document, {});
433
- * await pipeline.push("# Hello\n");
434
- * await pipeline.flush();
435
- * ```
542
+ * The renderer never touches the DOM: it builds everything through the
543
+ * write-only target, so the same renderer drives live pages, simulated
544
+ * DOMs, and fully custom targets.
436
545
  *
437
546
  * @public
438
547
  */
439
- declare function createBackendGFMPipeline(target: DOMNodeLike, dom: DOMDocumentLike, opts: GFMRenderOptions): MarkdownPipeline;
548
+ export declare class CommonMarkRenderer implements MarkdownRenderer<CommonMarkRendererConfig> {
549
+ protected _target: HTMLTarget;
550
+ private _config;
551
+ private _state;
552
+ private _open;
553
+ /**
554
+ * @param target - Destination for rendered output, from `createDOMTarget`
555
+ * or a custom `HTMLTarget` implementation.
556
+ * @param config - CommonMark rendering config.
557
+ */
558
+ constructor(target: HTMLTarget, config: CommonMarkRendererConfig);
559
+ /**
560
+ * Feed one source line; completed output is written to the target.
561
+ *
562
+ * @param line - Next source line, without its line break.
563
+ */
564
+ writeLine(line: string): void;
565
+ /**
566
+ * Write the buffered remainder and settle the target.
567
+ *
568
+ * @returns A promise that resolves once all output has landed in the target.
569
+ */
570
+ flush(): Promise<void>;
571
+ /**
572
+ * Point the renderer at another target; subsequent writes go there.
573
+ *
574
+ * @param target - Target receiving future output.
575
+ */
576
+ setTarget(target: HTMLTarget): void;
577
+ /**
578
+ * Replace the renderer config; applies to subsequent writes.
579
+ *
580
+ * @param config - Next config.
581
+ */
582
+ setConfig(config: CommonMarkRendererConfig): void;
583
+ /**
584
+ * Create the parser state. Overridden by `GFMRenderer` to parse
585
+ * tables.
586
+ *
587
+ * @param emit - Receives parse fragments in document order.
588
+ * @returns The state for this renderer.
589
+ */
590
+ protected _createState(emit: (fragment: ParseFragment) => void): CommonMarkState;
591
+ protected _applyFragment(fragment: ParseFragment): void;
592
+ /**
593
+ * Whether GFM-only inlines are enabled. Always false here; overridden by
594
+ * `GFMRenderer`.
595
+ *
596
+ * @returns False.
597
+ */
598
+ protected inlineGfm(): boolean;
599
+ /**
600
+ * Write one parsed block to the target.
601
+ *
602
+ * @param block - Parsed block to write.
603
+ */
604
+ protected renderBlock(block: Block): void;
605
+ /**
606
+ * Write paragraph lines into a parent, honoring two-space hard breaks.
607
+ *
608
+ * @param parentId - Node the lines append to.
609
+ * @param lines - Raw paragraph lines.
610
+ */
611
+ protected appendParagraphLines(parentId: NodeId, lines: string[]): void;
612
+ private appendJoinedLines;
613
+ }
440
614
  /**
441
- * Incremental GFM pipeline for server-side targets.
615
+ * Config for {@link CommonMarkRenderer}.
616
+ *
617
+ * @remarks
618
+ * Reserved for future renderer options.
442
619
  *
443
620
  * @public
444
621
  */
445
- declare class BackendGFMPipeline implements MarkdownPipeline {
446
- private _engine;
447
- /**
448
- * @param target - Container node receiving rendered blocks.
449
- * @param dom - Document used to create nodes.
450
- * @param opts - GFM rendering options.
451
- */
452
- constructor(target: DOMNodeLike, dom: DOMDocumentLike, opts: GFMRenderOptions);
453
- /**
454
- * Push a chunk of markdown into the pipeline.
455
- *
456
- * @param chunk - Markdown text, or a promise resolving to markdown text.
457
- * @returns A promise that resolves once the chunk has been consumed.
458
- */
459
- push(chunk: string | Promise<string>): Promise<void>;
460
- /**
461
- * Render any buffered remainder.
462
- *
463
- * @returns A promise that resolves once all output has been flushed.
464
- */
465
- flush(): Promise<void>;
466
- }
467
-
622
+ type CommonMarkRendererConfig = Record<string, never>;
468
623
  /**
469
- * Create a CommonMark pipeline for server-side rendering.
624
+ * Renderer for GitHub Flavored Markdown.
470
625
  *
471
626
  * @remarks
472
- * Backend pipelines write synchronously and never schedule animation frames.
473
- * Pair with a lightweight `DOMDocumentLike` such as linkedom.
474
- *
475
- * @param target - Container node receiving rendered blocks.
476
- * @param dom - Document used to create nodes.
477
- * @param opts - CommonMark rendering options.
478
- * @returns The configured pipeline.
479
- *
480
- * @example
481
- * ```ts
482
- * import { parseHTML } from "linkedom";
483
- *
484
- * const { document } = parseHTML("<div></div>");
485
- * const pipeline = createBackendCommonMarkPipeline(document.querySelector("div"), document, {});
486
- * await pipeline.push("# Hello\n");
487
- * await pipeline.flush();
488
- * ```
627
+ * Supports CommonMark blocks and inlines plus GFM tables and strikethrough.
628
+ * Tables commit at the delimiter row and stream one row at a time; column
629
+ * widths come from the header row, short rows are padded, and extra cells
630
+ * on wide rows are kept as unaligned cells.
489
631
  *
490
632
  * @public
491
633
  */
492
- declare function createBackendCommonMarkPipeline(target: DOMNodeLike, dom: DOMDocumentLike, opts: CommonMarkRenderOptions): MarkdownPipeline;
634
+ export declare class GFMRenderer extends CommonMarkRenderer implements MarkdownRenderer<GFMRendererConfig> {
635
+ private _table;
636
+ /**
637
+ * @param target - Destination for rendered output, from `createDOMTarget`
638
+ * or a custom `HTMLTarget` implementation.
639
+ * @param config - GFM rendering config.
640
+ */
641
+ constructor(target: HTMLTarget, config: GFMRendererConfig);
642
+ /**
643
+ * GFM-only inlines are enabled.
644
+ *
645
+ * @returns True.
646
+ */
647
+ protected inlineGfm(): boolean;
648
+ /**
649
+ * Create the GFM parser state.
650
+ *
651
+ * @param emit - Receives parse fragments in document order.
652
+ * @returns The state for this renderer.
653
+ */
654
+ protected _createState(emit: (fragment: ParseFragment) => void): GFMState;
655
+ /**
656
+ * Apply a fragment, handling tables here and delegating the rest.
657
+ *
658
+ * @param fragment - Fragment to apply.
659
+ */
660
+ protected _applyFragment(fragment: ParseFragment): void;
661
+ /**
662
+ * Commit the table with its header; body rows stream in afterwards.
663
+ *
664
+ * @param headLine - Raw header row line.
665
+ * @param delimLine - Delimiter row line carrying column alignment.
666
+ */
667
+ protected _applyTableHead(headLine: string, delimLine: string): void;
668
+ /**
669
+ * Append one body row to the open table.
670
+ *
671
+ * @param line - Raw body row line.
672
+ */
673
+ protected _applyTableRow(line: string): void;
674
+ /**
675
+ * Close the open table.
676
+ */
677
+ protected _applyTableEnd(): void;
678
+ }
493
679
  /**
494
- * Incremental CommonMark pipeline for server-side targets.
680
+ * Config for {@link GFMRenderer}.
495
681
  *
496
682
  * @public
497
683
  */
498
- declare class BackendCommonMarkPipeline implements MarkdownPipeline {
499
- private _engine;
500
- /**
501
- * @param target - Container node receiving rendered blocks.
502
- * @param dom - Document used to create nodes.
503
- * @param opts - CommonMark rendering options.
504
- */
505
- constructor(target: DOMNodeLike, dom: DOMDocumentLike, opts: CommonMarkRenderOptions);
506
- /**
507
- * Push a chunk of markdown into the pipeline.
508
- *
509
- * @param chunk - Markdown text, or a promise resolving to markdown text.
510
- * @returns A promise that resolves once the chunk has been consumed.
511
- */
512
- push(chunk: string | Promise<string>): Promise<void>;
513
- /**
514
- * Render any buffered remainder.
515
- *
516
- * @returns A promise that resolves once all output has been flushed.
517
- */
518
- flush(): Promise<void>;
519
- }
520
-
684
+ type GFMRendererConfig = CommonMarkRendererConfig;
521
685
  /**
522
- * Mutable parse state carried across `push` calls.
523
- *
524
- * @remarks
525
- * Holds buffered lines for the currently open block so a pipeline can render
526
- * complete blocks incrementally while holding back a trailing partial block.
686
+ * Options for {@link createDOMTarget}.
527
687
  *
528
688
  * @public
529
689
  */
530
- declare class RendererState {
531
- private _pending;
532
- /**
533
- * Buffer newly arrived lines.
534
- *
535
- * @param lines - Complete source lines to buffer.
536
- */
537
- addLines(lines: string[]): void;
538
- /**
539
- * Parse buffered lines, returning every block except a trailing partial one.
540
- *
541
- * @remarks
542
- * The last block is held back because more input may still extend it.
543
- * Nothing is returned while the buffer ends inside an unclosed fence.
544
- *
545
- * @returns Complete blocks ready to render.
546
- */
547
- takeCompleteBlocks(): Block[];
548
- /**
549
- * Parse and drain all buffered lines, including a trailing partial block.
550
- *
551
- * @returns Every remaining block.
552
- */
553
- takeAllBlocks(): Block[];
554
- }
555
-
690
+ type DOMTargetOptions = {
691
+ /**
692
+ * Optional frame scheduler. When provided, writes are batched on
693
+ * animation frames; otherwise updates apply synchronously.
694
+ */
695
+ raf?: RAF;
696
+ };
556
697
  /**
557
- * Create a line source that splits pushed text into lines.
698
+ * Create a target rendering into a DOM container.
558
699
  *
559
- * @returns A new line source.
700
+ * @param document - Document used to create nodes: a real browser document
701
+ * for live pages, or a simulated one such as linkedom for server-side
702
+ * rendering.
703
+ * @param targetNode - Container node receiving rendered output.
704
+ * @param options - Frame scheduler.
705
+ * @returns The target to hand to a renderer.
560
706
  *
561
707
  * @public
562
708
  */
563
- declare function createLineSource(): LineSource;
564
-
709
+ export declare function createDOMTarget(document: DOMDocumentLike, targetNode: DOMNodeLike, options?: DOMTargetOptions): HTMLTarget;
565
710
  /**
566
- * Target that appends rendered nodes synchronously.
711
+ * Create a GFM stream rendering into the given container.
712
+ *
713
+ * @remarks
714
+ * The environment is implicit: pass a real browser document for live pages
715
+ * or a simulated one such as linkedom for server-side rendering. Pass
716
+ * target options to batch DOM writes on animation frames.
717
+ *
718
+ * @param target - Container node receiving rendered output.
719
+ * @param dom - Document used to create nodes.
720
+ * @param config - GFM rendering config.
721
+ * @param targetOptions - Frame scheduler for the DOM target.
722
+ * @returns The configured pipeline.
723
+ *
724
+ * @example
725
+ * ```ts
726
+ * const stream = createGFMStream(
727
+ * document.getElementById("out")!,
728
+ * document,
729
+ * {},
730
+ * { raf: requestAnimationFrame },
731
+ * );
732
+ * const writer = stream.getWriter();
733
+ * await writer.write("# Hello\n");
734
+ * await writer.close();
735
+ * ```
567
736
  *
568
737
  * @public
569
738
  */
570
- declare class DOMTarget implements RenderTarget {
571
- private _targetNode;
572
- /**
573
- * @param targetNode - Container node receiving rendered output.
574
- */
575
- constructor(targetNode: DOMNodeLike);
576
- /**
577
- * Append a rendered node immediately.
578
- *
579
- * @param node - Node to attach.
580
- */
581
- append(node: DOMNodeLike): void;
582
- /**
583
- * Resolve immediately: synchronous targets hold every node already.
584
- *
585
- * @returns A resolved promise.
586
- */
587
- flush(): Promise<void>;
588
- }
589
-
739
+ export declare function createGFMStream(target: DOMNodeLike, dom: DOMDocumentLike, config: GFMRendererConfig, targetOptions?: DOMTargetOptions): MarkdownPipeline<GFMRendererConfig>;
590
740
  /**
591
- * Target that batches DOM writes on animation frames.
741
+ * Create a CommonMark stream rendering into the given container.
592
742
  *
593
743
  * @remarks
594
- * Uses requestAnimationFrame on the real DOM so streamed output lands once
595
- * per frame instead of once per chunk.
744
+ * The environment is implicit: pass a real browser document for live pages
745
+ * or a simulated one such as linkedom for server-side rendering. Pass
746
+ * target options to batch DOM writes on animation frames.
747
+ *
748
+ * @param target - Container node receiving rendered output.
749
+ * @param dom - Document used to create nodes.
750
+ * @param config - CommonMark rendering config.
751
+ * @param targetOptions - Frame scheduler for the DOM target.
752
+ * @returns The configured pipeline.
753
+ *
754
+ * @example
755
+ * ```ts
756
+ * const stream = createCommonMarkStream(
757
+ * document.getElementById("out")!,
758
+ * document,
759
+ * {},
760
+ * { raf: requestAnimationFrame },
761
+ * );
762
+ * const writer = stream.getWriter();
763
+ * await writer.write("# Hello\n");
764
+ * await writer.close();
765
+ * ```
596
766
  *
597
767
  * @public
598
768
  */
599
- declare class AnimatedDOMTarget implements RenderTarget {
600
- private _targetNode;
601
- private _raf;
602
- private _queue;
603
- private _scheduled;
604
- private _flushResolvers;
605
- /**
606
- * @param targetNode - Container node receiving rendered output.
607
- * @param raf - Frame scheduler used to batch writes.
608
- */
609
- constructor(targetNode: DOMNodeLike, raf: RAF);
610
- /**
611
- * Queue a rendered node for the next frame.
612
- *
613
- * @param node - Node to attach.
614
- */
615
- append(node: DOMNodeLike): void;
616
- /**
617
- * Wait until every queued node has been attached.
618
- *
619
- * @returns A promise that resolves after the next frame carrying nodes.
620
- */
621
- flush(): Promise<void>;
622
- }
623
-
624
- export { AnimatedDOMTarget, BackendCommonMarkPipeline, BackendGFMPipeline, type Block, type BlockKind, type CommonMarkRenderOptions, CommonMarkRenderer, type DOMDocumentLike, type DOMNodeLike, DOMTarget, FrontendCommonMarkPipeline, FrontendGFMPipeline, type GFMRenderOptions, GFMRenderer, type LineSource, type MarkdownPipeline, type MarkdownRenderer, type RAF, type RenderTarget, RendererState, createBackendCommonMarkPipeline, createBackendGFMPipeline, createFrontendCommonMarkPipeline, createFrontendGFMPipeline, createLineSource };
769
+ export declare function createCommonMarkStream(target: DOMNodeLike, dom: DOMDocumentLike, config: CommonMarkRendererConfig, targetOptions?: DOMTargetOptions): MarkdownPipeline<CommonMarkRendererConfig>;
770
+ export type { CommonMarkRendererConfig, DOMDocumentLike, DOMNodeLike, DOMTargetOptions, GFMRendererConfig, HTMLTarget, MarkdownPipeline, MarkdownRenderer, NodeId, RAF };
771
+ //# sourceMappingURL=index.d.cts.map