@mdsvex/parse 1.0.0-next.2 → 1.0.0-next.4

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/PLUGINS.md CHANGED
@@ -75,7 +75,8 @@ heading: {
75
75
  }
76
76
  ```
77
77
 
78
- - **`offset`** indexes the source the parser read, in which every newline is a `\n`. A document written with `\r\n` has other offsets on disk.
78
+ - **`offset`** is a JavaScript string index, in UTF-16 code units, not a byte offset. In `é🐧\n\n# Hi` the heading starts at 5, where its UTF-8 byte offset would be 8.
79
+ - **`offset` indexes the source the parser read,** in which every `\r\n` and every lone `\r` is a `\n`. A lone `\r` moves no offset, but each `\r\n` moves those after it back by one, so a document written with `\r\n` has other offsets on disk. `raw_offsets(raw)` from `@mdsvex/parse` maps them back: `null` when `raw` has no `\r\n`, else an object whose `to_raw(offset)` is the index in `raw`.
79
80
  - **`line`** counts from 1 and **`column`** from 0. Both hold in the document as it was written, `\r\n` or not.
80
81
  - **`end` is `undefined` while the node is open**, which is the case in its own open handler. The close callback has it.
81
82
  - **`position` is `undefined` for a node a plugin made**, which has no source, **and over the wire**. The wire format carries text and no offsets, so a tree built by `WireTreeBuilder` cannot say where a node was.
@@ -528,7 +529,7 @@ const { nodes, warnings, data } = parse_markdown_svelte(source, {
528
529
  });
529
530
  ```
530
531
 
531
- - **`frontmatter` is the parser of the frontmatter,** not its value. The parser does not read YAML, so without the option `ctx.frontmatter` is `undefined`.
532
+ - **`frontmatter` is the parser of the frontmatter,** not its value. The parser does not read YAML, so without the option `ctx.frontmatter` is `undefined`. Its second argument is `{ filename }`, the `filename` option, `undefined` without one.
532
533
  - **`warnings` and `data` are `undefined`** when no handler left any, and always without plugins.
533
534
 
534
535
  ## Handler Lifecycle
@@ -574,6 +575,7 @@ code_fence: {
574
575
  - **It is the whole line after the fence**, the language and what follows it. The parser does not split it. In `mdsvex`, `fence_meta(node.info)` from `mdsvex/compile` reads it the way a compile does: the language, a `[name]` or `title="..."`, a caption, `src=`, and the `key=value` pairs and flags.
575
576
  - **While the document streams**, the handlers run once the line of the opening fence is complete. Over the wire a fence with an empty info string is sent none, and its handlers run when its first text or its close arrives.
576
577
  - **Any other node has no `info`**, it reads `undefined`.
578
+ - **A plugin that renders a language itself** says so in `mdsvex` with `fences: ['mermaid']` on its bundle, and the highlighter never sees those fences, so they render plain and warn of no unknown language. Its handlers, and those of every other plugin, still see the fence. See the design in `design/plugin-directives.md`, 3.6.
577
579
 
578
580
  ### The code of a fence a plugin makes
579
581
 
@@ -845,7 +847,7 @@ An entry can hold three keys. Any other key is ignored, so a layer above can kee
845
847
 
846
848
  A handler is a function, not a `{ parse }` object. Like a plugin handler it may return a function, which runs when the node closes. A key that is not a node type throws when the tables are first used, and so does `text`: text goes to the [text handler](#text-handlers) of a sequential plugin. The one key of `children` that is no node type is `'*'`, see [A child of any type](#a-child-of-any-type).
847
849
 
848
- `directive_handlers` is an array of tables. When two tables have an entry for the same name the later one replaces the earlier one whole. The tables are read once per array, so pass the same array for every document and build a new one to change a handler.
850
+ `directive_handlers` is an array of tables. A table's entry owns its name, with or without handlers, and a name has one owner: two tables with an entry for the same name throw a `DirectiveOwnerError` when the tables are first used, with `directive` and the two plugin names as `plugins`. Another plugin that wants to see the directive [observes it](#observing-a-directive). The tables are read once per array, so pass the same array for every document and build a new one to change a handler.
849
851
 
850
852
  A table can come with the name of the plugin it belongs to, as `{ name: 'steps', directives: bound }`. The name keys what its handlers write with `ctx.set` and `ctx.add` and is the `plugin` of their warnings. `mdsvex` passes each plugin's `directives` this way.
851
853
 
@@ -957,6 +959,46 @@ A container with `children` or `descendants` handlers opens a scope when its nam
957
959
 
958
960
  Bound handlers run in the fused pass only. A sequential plugin sees the tree they left.
959
961
 
962
+ ### Observing a directive
963
+
964
+ A directive has one owner, the table that binds its name. Another plugin reads it by observing it: numbering a figure, collecting the tabs of a page, checking an arg.
965
+
966
+ ```js
967
+ const numbering = {
968
+ name: 'numbering',
969
+ observe: {
970
+ figure: {
971
+ parse(figure, ctx) {
972
+ // a block directive is never revoked, so a count in the scratch stays right
973
+ const number = (ctx.scratch.figures = (ctx.scratch.figures ?? 0) + 1);
974
+ const id = figure.attrs.args?.id;
975
+ if (id === undefined) return;
976
+ return () => {
977
+ const label = figure.first_child;
978
+ ctx.set('target:' + id, {
979
+ number,
980
+ caption: label?.type === 'directive_label' ? label.text_content : null,
981
+ });
982
+ };
983
+ },
984
+ },
985
+ },
986
+ };
987
+ ```
988
+
989
+ `observe` is a key of a parse plugin, a table keyed by directive name with the entries a table of bound handlers has: `parse`, `children` (`'*'` too) and `descendants`. Handlers get the same context as the owner's, with a `state`, an `index` and counts of their own.
990
+
991
+ - **It runs whoever owns the name.** With an owner, with only a component of the host for it, or with neither. Which plugins are installed changes nothing for an observer.
992
+ - **It changes no node.** Not the directive, not what is inside it, not anything else: a write to `attrs` or `type`, a structural method and `remove` throw a `TypeError` that names the observer, the directive and its owner. A deferred task an observer starts is held to the same. The owner decides what the directive is and how it renders, so what an observer finds goes into its plugin data, which a component reads through Svelte context.
993
+ - **What it may do:** `ctx.set` and `ctx.add`, owned by the node whose handler runs and revoked with it, `ctx.warn`, `ctx.id`, `ctx.scratch`, `ctx.defer`, and the close callbacks it returns.
994
+ - **After the owner.** At the open the global open handlers of the directive run first, then the owner's `parse`, then the observers in plugin order. At the close the observers' callbacks run last, after the owner's and the global ones. For a child the owner's `children` and `descendants` handlers run first, then the observers', and their close callbacks in the same order. An observer can change nothing the owner would see, so the only thing the order decides is what the observer sees, and this way it is the directive as the owner left it: the args it set at the open, the wrappers it made, the args it wrote at the close.
995
+ - **As the directive streams.** `children` and `descendants` handlers of an observer run as each node opens, as the owner's do, so an observer sees the label of a container when it arrives and need not wait for the close.
996
+ - **In the fused pass,** as bound handlers run, also for a plugin that is `sequential`.
997
+ - **A plugin does not observe its own directive.** A plugin whose name owns a table entry for the name and observes it too throws a `TypeError`, its own handlers already see the directive.
998
+ - **Revocation** is as for the owner: an inline directive whose bracket never closes takes what its observers wrote with it, and a directive inside a construct that goes, an emphasis that never closes or a link with no destination, stays with what they wrote.
999
+
1000
+ `mdsvex` reads `observe` from a parse plugin of `parse_plugins` and from the `parse` of a plugin bundle, which carries the bundle's name. The global directive handlers of either still never see a directive a component takes.
1001
+
960
1002
  ## Dirty Tracking
961
1003
 
962
1004
  Every mutation through the node view marks the affected node dirty. This is how the system knows what to re-render after parse plugins have run.
package/WIRE_FORMAT.md CHANGED
@@ -107,7 +107,7 @@ Appends text to a node's content. Multiple `T` opcodes for the same node should
107
107
 
108
108
  The flag says the author escaped the first character of `content` with a backslash. The backslash is not sent. A client that only shows the text ignores the flag. One that rewrites text, as `WireTreeBuilder` does for the text handler of a parse plugin, keeps where those characters are and leaves them alone.
109
109
 
110
- Text is always resolved to strings on the wire, the client never sees byte offsets or needs the source markdown.
110
+ Text is always resolved to strings on the wire, the client never sees source offsets or needs the source markdown.
111
111
 
112
112
  ### A, Attr
113
113
 
@@ -502,10 +502,10 @@ The parser runs server-side (or in a worker) and produces batches via the `WireE
502
502
  Parse a complete markdown string in one call:
503
503
 
504
504
  ```javascript
505
- import { PFMParser, WireEmitter } from '@mdsvex/parse';
505
+ import { PFMParser, WireEmitter, normalize_newlines } from '@mdsvex/parse';
506
506
 
507
507
  const emitter = new WireEmitter();
508
- emitter.set_source(source);
508
+ emitter.set_source(normalize_newlines(source));
509
509
 
510
510
  const parser = new PFMParser(emitter);
511
511
  parser.parse(source);
@@ -519,7 +519,7 @@ const batch = emitter.flush(); // single batch with all opcodes
519
519
  Feed chunks as they arrive (e.g., from an LLM stream, file read, or network):
520
520
 
521
521
  ```javascript
522
- import { PFMParser, WireEmitter } from '@mdsvex/parse';
522
+ import { PFMParser, WireEmitter, normalize_newlines } from '@mdsvex/parse';
523
523
 
524
524
  const emitter = new WireEmitter();
525
525
  const parser = new PFMParser(emitter);
@@ -529,7 +529,7 @@ let accumulated = '';
529
529
 
530
530
  function onChunk(chunk) {
531
531
  accumulated += chunk;
532
- emitter.set_source(accumulated); // must be the full source so far
532
+ emitter.set_source(normalize_newlines(accumulated)); // the full source so far
533
533
  parser.feed(chunk); // only the new chunk
534
534
  const batch = emitter.flush(); // opcodes produced by this chunk
535
535
  if (batch.length > 0) {
@@ -538,7 +538,7 @@ function onChunk(chunk) {
538
538
  }
539
539
 
540
540
  function onEnd() {
541
- emitter.set_source(accumulated);
541
+ emitter.set_source(normalize_newlines(accumulated));
542
542
  parser.finish(); // finalize all open nodes
543
543
  const batch = emitter.flush();
544
544
  if (batch.length > 0) {
@@ -563,11 +563,26 @@ function onEnd() {
563
563
 
564
564
  | Method | Description |
565
565
  | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
566
- | `set_source(source)` | Set the **full accumulated source** string. Must be called before each `feed()` and before `finish()`. The emitter uses this to resolve byte offsets to text content. |
566
+ | `set_source(source)` | Set the **full accumulated source** string, with its line endings normalized as the parser normalizes them (`normalize_newlines`). Must be called before each `feed()` and before `finish()`. The emitter uses this to resolve source offsets to text content. |
567
567
  | `flush()` | Return all accumulated opcodes as a batch (array of tuples) and clear the internal buffer. The first flush includes the `S` (schema) opcode. |
568
568
  | `flush_json()` | Convenience, calls `flush()` and returns `JSON.stringify(result)`. |
569
569
  | `reset()` | Reset all state for reuse with a new parse. |
570
570
 
571
+ #### Source offsets
572
+
573
+ The `start` and `end` an `Emitter` gets are JavaScript string indices, UTF-16 code units, not UTF-8 bytes. In `é🐧\n\n# Hi` the heading starts at 5: `é` is one code unit and `🐧` two. Its UTF-8 byte offset would be 8.
574
+
575
+ They index the source after line endings are normalized. `parse()` and `feed()` turn every `\r\n` and every lone `\r` into `\n` before the parser sees them, and `feed()` holds back a chunk's trailing `\r` until the next chunk shows whether a `\n` follows. `normalize_newlines(source)` makes the same string, and it is what `set_source()` needs, or the text the emitter slices drifts by one character for each `\r\n` before it.
576
+
577
+ A lone `\r` becomes one `\n`, so it moves no offset. A `\r\n` becomes one character, so each one moves every offset after it back by one. `raw_offsets(raw)` maps them back: it returns `null` for a source with no `\r\n`, else an object whose `to_raw(offset)` gives the index in the source as written.
578
+
579
+ ```javascript
580
+ import { raw_offsets } from '@mdsvex/parse';
581
+
582
+ const map = raw_offsets(raw);
583
+ const at = map === null ? offset : map.to_raw(offset);
584
+ ```
585
+
571
586
  ### How stalling works
572
587
 
573
588
  The parser is a streaming state machine. When fed a chunk, it advances the cursor through confirmed content and **stalls** when it reaches a point where the next chunk might change the interpretation:
@@ -727,6 +742,6 @@ source.onmessage = (event) => {
727
742
 
728
743
  2. **Text nodes are invisible.** The parser uses internal text nodes (kind=1, "text"), but these are suppressed on the wire. Their content is flattened into `T` opcodes on the parent. The client never sees text nodes.
729
744
 
730
- 3. **No source access needed.** All byte offsets are resolved to strings by the emitter. The client works purely with text content and structural opcodes.
745
+ 3. **No source access needed.** All source offsets are resolved to strings by the emitter. The client works purely with text content and structural opcodes.
731
746
 
732
747
  4. **Batch-per-chunk.** Each `feed()` call produces exactly one batch. The transport layer decides how to frame batches. The client applies them in order.
package/dist/cursor.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * cursor, zero-allocation tree traversal over NodeBuffer.
3
3
  *
4
4
  * single reusable object that provides tree-traversal semantics
5
- * (gotofirstchild / gotonextsibling / gotoparent) while reading
5
+ * (goto_first_child / goto_next_sibling / goto_parent) while reading
6
6
  * directly from the node words underneath. no per-node
7
7
  * objects are created, text is lazily sliced from the source
8
8
  * string only when requested.
@@ -11,16 +11,22 @@
11
11
  *
12
12
  * usage:
13
13
  *
14
- * const tree = new treebuilder(128);
15
- * const parser = new pfmparser(tree);
14
+ * import { PFMParser } from '@mdsvex/parse';
15
+ * import { TreeBuilder } from '@mdsvex/parse/tree-builder';
16
+ * import { Cursor } from '@mdsvex/parse/cursor';
17
+ *
18
+ * const tree = new TreeBuilder(128);
19
+ * const parser = new PFMParser(tree);
16
20
  * parser.parse(source);
17
- * const cursor = new cursor(tree.get_buffer(), source);
21
+ * const cursor = new Cursor(tree.get_buffer(), source);
18
22
  *
19
23
  * // walk tree
20
- * if (cursor.gotofirstchild()) {
21
- * do { process(cursor); } while (cursor.gotonextsibling());
22
- * cursor.gotoparent();
24
+ * if (cursor.goto_first_child()) {
25
+ * do { process(cursor); } while (cursor.goto_next_sibling());
26
+ * cursor.goto_parent();
23
27
  * }
28
+ *
29
+ * offsets are utf-16 code unit indices into the source as parsed
24
30
  */
25
31
  import { type NodeBuffer } from './utils.js';
26
32
  export declare class Cursor {
@@ -48,13 +54,13 @@ export declare class Cursor {
48
54
  get pending(): boolean;
49
55
  /** parent kind of the current node, -1 if at root. */
50
56
  get parent_kind(): number;
51
- /** byte offset where the current node starts in source. */
57
+ /** offset where the current node starts in source */
52
58
  get start(): number;
53
- /** byte offset where the current node ends in source. */
59
+ /** offset where the current node ends in source */
54
60
  get end(): number;
55
- /** byte offset where the current node's value content starts. */
61
+ /** offset where the value content of the current node starts */
56
62
  get value_start(): number;
57
- /** byte offset where the current node's value content ends. */
63
+ /** offset where the value content of the current node ends */
58
64
  get value_end(): number;
59
65
  /** get text content for the current node. prebuilt strings
60
66
  (from wiretreebuilder) are returned directly; otherwise sliced lazily. */
@@ -66,7 +72,7 @@ export declare class Cursor {
66
72
  get prebuilt(): string | undefined;
67
73
  /** get metadata for the current node, or undefined if none. */
68
74
  meta(): Record<string, unknown> | undefined;
69
- /** slice the source string by byte offsets. for resolving metadata offset pairs. */
75
+ /** slice the source by offsets, for metadata offset pairs */
70
76
  slice(start: number, end: number): string;
71
77
  goto_first_child(): boolean;
72
78
  goto_next_sibling(): boolean;
package/dist/cursor.js CHANGED
@@ -46,28 +46,28 @@ class r {
46
46
  /* NodeField.stride */
47
47
  ] & 255;
48
48
  }
49
- /** byte offset where the current node starts in source. */
49
+ /** offset where the current node starts in source */
50
50
  get start() {
51
51
  return this.n[
52
52
  this.b + 1
53
53
  /* NodeField.start */
54
54
  ];
55
55
  }
56
- /** byte offset where the current node ends in source. */
56
+ /** offset where the current node ends in source */
57
57
  get end() {
58
58
  return this.n[
59
59
  this.b + 2
60
60
  /* NodeField.end */
61
61
  ];
62
62
  }
63
- /** byte offset where the current node's value content starts. */
63
+ /** offset where the value content of the current node starts */
64
64
  get value_start() {
65
65
  return this.n[
66
66
  this.b + 3
67
67
  /* NodeField.value_start */
68
68
  ];
69
69
  }
70
- /** byte offset where the current node's value content ends. */
70
+ /** offset where the value content of the current node ends */
71
71
  get value_end() {
72
72
  return this.n[
73
73
  this.b + 4
@@ -108,7 +108,7 @@ class r {
108
108
  ];
109
109
  return t === 0 ? void 0 : this.buf._meta[t - 1];
110
110
  }
111
- /** slice the source string by byte offsets. for resolving metadata offset pairs. */
111
+ /** slice the source by offsets, for metadata offset pairs */
112
112
  slice(t, s) {
113
113
  return this.src.slice(t, s);
114
114
  }
package/dist/main.d.ts CHANGED
@@ -10,7 +10,7 @@ export type { NodeView, WrapperView, Point, Position } from './node_view.js';
10
10
  export { NodeKind, NodeBuffer, take_src } from './utils.js';
11
11
  export { HeadingIds, HeadingIdError, heading_slug } from './heading_ids.js';
12
12
  export type { HeadingIdErrorCode, HeadingInfo, HeadingSlug, } from './heading_ids.js';
13
- export { PluginDispatcher, has_directive_handlers } from './plugin_dispatch.js';
13
+ export { DirectiveOwnerError, PluginDispatcher, has_directive_handlers, } from './plugin_dispatch.js';
14
14
  export { SourceTextSource, WireTextSource } from './node_view.js';
15
15
  export { WireEmitter, WireOp } from './wire_emitter.js';
16
16
  export type { Emitter } from './opcodes.js';