mausmark 0.1.0-alpha.2 → 0.2.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/README.md CHANGED
@@ -2,70 +2,177 @@
2
2
 
3
3
  A fast, renderer-agnostic Markdown parser.
4
4
 
5
- > Alpha: still in active development the API may change.
5
+ It aims to support and extend Markdown.
6
+ It is also practical, so it parses CommonMark too.
7
+
8
+ > Pre-1.0: minor versions may change the API.
6
9
 
7
10
  ## Install
8
11
 
9
- ```sh
10
- npm install mausmark@alpha
11
- ```
12
+ npm install mausmark
12
13
 
13
14
  ## Usage
14
15
 
15
- ```ts
16
- import {createParser, NodeType} from 'mausmark'
16
+ import {createParser, Dialect, NodeType} from "mausmark";
17
17
 
18
- const parser = await createParser()
19
- const document = parser.parse('# Hello\n\nThis is **Mausmark**.')
18
+ const parser = await createParser();
19
+ const document = parser.parse("# Hello\n\nThis is **Mausmark**.");
20
20
 
21
- function visit(index: number): unknown {
22
- switch (document.type(index)) {
23
- case NodeType.TEXT:
24
- return document.text(index)
25
- default:
26
- return [...document.children(index)].map(visit)
27
- }
28
- }
21
+ // ...or parser.parse(source, Dialect.COMMONMARK) for CommonMark input.
29
22
 
30
- const result = visit(0)
31
- ```
23
+ for (let index = 0; index < document.nodeCount; index += 1) {
24
+ if (document.type(index) === NodeType.HEADING) {
25
+ console.log(document.joinedText(index)); // "Hello"
26
+ }
27
+ }
32
28
 
33
- Initialize the parser once and reuse it. Initialization is asynchronous;
34
- `parse()` is synchronous. Returned documents are independent snapshots and
35
- remain valid after later parses.
29
+ The document is a flat array of nodes, so finding every node of one type
30
+ is a single loop; [Writing a renderer](#writing-a-renderer) walks it as a
31
+ tree. Initialize the parser once and reuse it. Initialization is
32
+ asynchronous; `parse()` is synchronous. Returned documents are
33
+ independent snapshots and remain valid after later parses.
36
34
 
37
35
  ## AST
38
36
 
39
- The root is node `0`. Nodes use integer indexes into a compact preorder table.
40
- TypeScript declarations and runtime constants are included.
37
+ The root is node `0`. Nodes use integer indexes into a compact preorder
38
+ table. TypeScript declarations and runtime constants are included.
41
39
 
42
40
  - `type(index)` returns a `NodeType`.
43
41
  - `children(index)` iterates direct content children.
44
- - `text(index)` decodes one node's source slice.
45
- - `joinedText(index)` joins chunked code or image content.
42
+ - `text(index)` decodes one node’s source slice.
43
+ - `joinedText(index)` joins a node’s text chunks back into one string.
46
44
  - `link(index)` returns raw URL, title, label, and `ReferenceStyle`.
47
- - `level(index)` carries heading levels and other type-specific values.
48
- - `flags(index)` carries `ListFlags.ORDERED` and `ListFlags.LOOSE`.
45
+ - `level(index)` carries heading levels and other type-specific
46
+ values.
47
+ - `flags(index)` carries `ListFlags.ORDERED` and `ListFlags.LOOSE` on
48
+ lists.
49
49
  - `offset(index)` and `length(index)` are UTF-8 byte offsets.
50
50
  - `subtreeEnd(index)` supports lower-level preorder traversal.
51
51
 
52
- `children()` hides internal URL, title, and label nodes. Reference links remain
53
- unresolved so renderers can choose their own lookup and URL policies. Raw HTML
54
- is returned as `NodeType.HTML`; sanitize it when parsing untrusted input.
52
+ Text arrives in chunks, one per source line: a soft line break is not a
53
+ byte inside a slice but the next chunk’s join code, so line structure is
54
+ read off the tree rather than by scanning for newlines. `joinedText()`
55
+ reassembles a run when you just want the string; `children()` walks the
56
+ chunks when you care about source lines.
57
+
58
+ In the CommonMark dialect, an escaped ampersand is
59
+ `NodeType.LITERAL_TEXT` rather than `NodeType.TEXT`: its text is literal
60
+ and must not be entity-decoded together with the following chunk. Both
61
+ types contain source-backed text slices.
62
+
63
+ The tree also holds internal URL, title, and label nodes; `children()`
64
+ skips them. Reference links remain unresolved so renderers can choose
65
+ their own lookup approach. The tree is meant to carry enough info about
66
+ the document so that you could reproduce it exactly (minus whitespace).
67
+ Raw HTML is returned as `NodeType.HTML_BLOCK` or `NodeType.HTML_INLINE`;
68
+ sanitize it when parsing untrusted input.
69
+
70
+ Compare node types against the exported constants: their numeric values
71
+ can change between versions.
72
+
73
+ ## Writing a renderer
74
+
75
+ Walk from node `0` with `children(index)`, which yields direct content
76
+ children and skips a link’s leading URL/title/label fields. Do not
77
+ iterate every node index as though each were a sibling:
78
+ `subtreeEnd(index)` is the next sibling in the preorder table. For
79
+ example, this deliberately simple plain-text renderer omits URLs, raw
80
+ HTML, custom nodes, list markers, and entity decoding:
81
+
82
+ import {createParser, Join, NodeType} from "mausmark"
83
+ import type {MausmarkDocument} from "mausmark"
84
+
85
+ function plainText(doc: MausmarkDocument, index = 0): string {
86
+ const type = doc.type(index)
87
+ switch (type) {
88
+ case NodeType.TEXT: {
89
+ const join = doc.level(index)
90
+ return (join === Join.SPACE ? " " : join === Join.NL ? "\n" : "") + doc.text(index)
91
+ }
92
+ case NodeType.LITERAL_TEXT:
93
+ return doc.text(index)
94
+ case NodeType.HARD_BREAK:
95
+ return "\n"
96
+ case NodeType.CODE_SPAN:
97
+ case NodeType.CODE_BLOCK:
98
+ return doc.joinedText(index)
99
+ case NodeType.HTML_INLINE:
100
+ case NodeType.HTML_BLOCK:
101
+ case NodeType.CUSTOM:
102
+ case NodeType.REF_DEFS:
103
+ case NodeType.REF_DEF:
104
+ return ""
105
+ }
106
+
107
+ let text = ""
108
+ for (const child of doc.children(index)) text += plainText(doc, child)
109
+ if (type === NodeType.PARAGRAPH || type === NodeType.HEADING || type === NodeType.LIST_ITEM) text += "\n"
110
+ return text
111
+ }
112
+
113
+ const parser = await createParser()
114
+ console.log(plainText(parser.parse("# Hello\n\nA **wrapped** paragraph.")))
115
+
116
+ For a complete renderer, the package includes `dom-example.js`. It
117
+ builds DOM nodes directly: text goes in through text nodes and
118
+ attributes through `setAttribute`, so it never has to escape HTML by
119
+ hand. It covers every node type, including entity decoding, reference
120
+ lookup, tight lists, fence info strings and image alt text, and it
121
+ leaves raw HTML inert. It is an example, not an export: copy it and
122
+ adapt it.
123
+
124
+ Things to decide when building a richer renderer:
125
+
126
+ - Text is source-backed and split into chunks, often by line or by the
127
+ 65,535-byte slice limit. For `TEXT` chunks, `level()` is a `Join`
128
+ code to emit *before* `text()` (`Join.NL` is a soft break).
129
+ `joinedText()` assembles a node’s immediate text chunks, useful for
130
+ code spans/blocks and metadata fields; it does not recursively
131
+ render arbitrary inline markup. In CommonMark, a `LITERAL_TEXT` leaf
132
+ must not be entity-decoded with its neighboring `TEXT`.
133
+ - `link(index)` works on `LINK`, `IMAGE`, and `REF_DEF` and returns
134
+ **raw** URL, title, label, and `ReferenceStyle`. Inline links and
135
+ autolinks already have destinations; `FULL`, `COLLAPSED`, and
136
+ `SHORTCUT` need a definition lookup. Scan all node indexes for
137
+ `REF_DEF` (including definitions in containers), store the first
138
+ definition for each normalized label, and decide how to render
139
+ unresolved references. CommonMark label matching uses Unicode case
140
+ folding and whitespace collapse, not just `toLowerCase()`. An
141
+ `AUTOLINK_EMAIL` URL is the bare address; add `mailto:` when
142
+ emitting it. `title === ""` alone does not distinguish an absent
143
+ title from an explicit empty title; inspect the leading `TITLE`
144
+ field if that matters to your output.
145
+ - For lists, `flags(index)` has `ListFlags.ORDERED` and
146
+ `ListFlags.LOOSE` on `LIST` / `LIST_ITEM`. `level()` on a list
147
+ records its marker character; `text()` on a CommonMark ordered list
148
+ holds its starting digits. Tight list items normally omit paragraph
149
+ wrappers. A fenced code block’s info string is its leading `LABEL`
150
+ field: when node `index + 1` is inside the block and is a `LABEL`,
151
+ read it with `joinedText(index + 1)`. `link(index)` covers link-like
152
+ nodes only.
153
+ - `HTML_BLOCK` and `HTML_INLINE` are raw input, not sanitized HTML.
154
+ Escape output for your target format and apply an explicit policy
155
+ for untrusted input.
55
156
 
56
157
  ## Notes
57
158
 
58
159
  - ESM-only.
59
160
  - Node.js 22.14+ or a modern browser with WebAssembly SIMD.
60
161
  - Browser bundlers must emit the package-relative `.wasm` asset.
61
- - Input is limited to 64 MiB; parser arena growth is limited to 512 MiB.
62
- - Broadly CommonMark-compatible, but not fully conformant.
63
- - Backtick fences only; no `~~~` fences or tables yet.
64
- - Fence info strings are currently ignored.
65
-
66
- The npm package contains ESM bindings, TypeScript declarations, and precompiled
67
- WebAssembly. The implementation source is currently private; the distributed
68
- package is licensed under MIT.
162
+ - Input is limited to 64 MiB; parser arena growth is limited to 512
163
+ MiB.
164
+ - Two input dialects, parsed at the same speed. `Dialect.MARKDOWN`
165
+ (the default) is original Markdown; `Dialect.COMMONMARK` is
166
+ CommonMark 0.31.2, currently 649/652 (99.5%) of the 0.31.2 spec
167
+ suite byte-exact. Three definition-dependent reference-link cases
168
+ remain unresolved.
169
+ - No GFM yet: no tables, strikethrough, task lists or autolink
170
+ literals.
171
+
172
+ The npm package contains ESM bindings, TypeScript declarations,
173
+ precompiled WebAssembly, and the renderer example. The implementation
174
+ source is currently private; the distributed package is licensed under
175
+ MIT.
69
176
 
70
177
  Project page and demo: https://myshkin.eu/mausmark
71
178
 
package/dist/abi.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ export declare const NodeType: Readonly<{
2
+ readonly DOC: 0;
3
+ readonly PARAGRAPH: 1;
4
+ readonly HEADING: 2;
5
+ readonly BLOCKQUOTE: 3;
6
+ readonly LIST: 4;
7
+ readonly LIST_ITEM: 5;
8
+ readonly CODE_BLOCK: 6;
9
+ readonly HTML_BLOCK: 7;
10
+ readonly THEMATIC_BREAK: 8;
11
+ readonly REF_DEFS: 9;
12
+ readonly REF_DEF: 10;
13
+ readonly EMPH: 11;
14
+ readonly STRONG: 12;
15
+ readonly CODE_SPAN: 13;
16
+ readonly LINK: 14;
17
+ readonly IMAGE: 15;
18
+ readonly HTML_INLINE: 16;
19
+ readonly SPAN: 17;
20
+ readonly CUSTOM: 18;
21
+ readonly TEXT: 19;
22
+ readonly LITERAL_TEXT: 20;
23
+ readonly HARD_BREAK: 21;
24
+ readonly URL: 22;
25
+ readonly TITLE: 23;
26
+ readonly LABEL: 24;
27
+ }>;
28
+ export type NodeType = (typeof NodeType)[keyof typeof NodeType];
29
+ export declare const ReferenceStyle: Readonly<{
30
+ readonly INLINE: 0;
31
+ readonly FULL: 1;
32
+ readonly COLLAPSED: 2;
33
+ readonly SHORTCUT: 3;
34
+ readonly AUTOLINK_EMAIL: 4;
35
+ readonly AUTOLINK_URI: 5;
36
+ }>;
37
+ export type ReferenceStyle = (typeof ReferenceStyle)[keyof typeof ReferenceStyle];
38
+ export declare const Join: Readonly<{
39
+ readonly NONE: 0;
40
+ readonly SPACE: 1;
41
+ readonly NL: 2;
42
+ }>;
43
+ export type Join = (typeof Join)[keyof typeof Join];
44
+ export declare const ListFlags: Readonly<{
45
+ readonly ORDERED: 1;
46
+ readonly LOOSE: 2;
47
+ }>;
48
+ export type ListFlags = (typeof ListFlags)[keyof typeof ListFlags];
49
+ export declare const Dialect: Readonly<{
50
+ readonly MARKDOWN: 0;
51
+ readonly COMMONMARK: 1;
52
+ }>;
53
+ export type Dialect = (typeof Dialect)[keyof typeof Dialect];
54
+ export declare const HtmlMode: Readonly<{
55
+ readonly FULL: 0;
56
+ readonly FRAGMENT: 1;
57
+ readonly COMMONMARK: 2;
58
+ }>;
59
+ export type HtmlMode = (typeof HtmlMode)[keyof typeof HtmlMode];
60
+ export declare const NODE_TYPE_MAX: 24;
61
+ export declare const NODE_SIZE = 16;
62
+ export declare const NodeLayout: Readonly<{
63
+ TYPE: 0;
64
+ LEVEL: 1;
65
+ FLAGS: 2;
66
+ SUBTREE_END: 4;
67
+ OFFSET: 8;
68
+ LENGTH: 12;
69
+ }>;
70
+ export declare const ABI_VERSION = 4;
package/dist/abi.js ADDED
@@ -0,0 +1,61 @@
1
+ // Generated by src/codegen.c from src/abi.h and src/parser.h. Do not edit.
2
+ export const NodeType = Object.freeze({
3
+ DOC: 0,
4
+ PARAGRAPH: 1,
5
+ HEADING: 2,
6
+ BLOCKQUOTE: 3,
7
+ LIST: 4,
8
+ LIST_ITEM: 5,
9
+ CODE_BLOCK: 6,
10
+ HTML_BLOCK: 7,
11
+ THEMATIC_BREAK: 8,
12
+ REF_DEFS: 9,
13
+ REF_DEF: 10,
14
+ EMPH: 11,
15
+ STRONG: 12,
16
+ CODE_SPAN: 13,
17
+ LINK: 14,
18
+ IMAGE: 15,
19
+ HTML_INLINE: 16,
20
+ SPAN: 17,
21
+ CUSTOM: 18,
22
+ TEXT: 19,
23
+ LITERAL_TEXT: 20,
24
+ HARD_BREAK: 21,
25
+ URL: 22,
26
+ TITLE: 23,
27
+ LABEL: 24,
28
+ });
29
+ export const ReferenceStyle = Object.freeze({
30
+ INLINE: 0,
31
+ FULL: 1,
32
+ COLLAPSED: 2,
33
+ SHORTCUT: 3,
34
+ AUTOLINK_EMAIL: 4,
35
+ AUTOLINK_URI: 5,
36
+ });
37
+ export const Join = Object.freeze({
38
+ NONE: 0,
39
+ SPACE: 1,
40
+ NL: 2,
41
+ });
42
+ export const ListFlags = Object.freeze({
43
+ ORDERED: 1,
44
+ LOOSE: 2,
45
+ });
46
+ export const Dialect = Object.freeze({
47
+ MARKDOWN: 0,
48
+ COMMONMARK: 1,
49
+ });
50
+ export const HtmlMode = Object.freeze({
51
+ FULL: 0,
52
+ FRAGMENT: 1,
53
+ COMMONMARK: 2,
54
+ });
55
+ export const NODE_TYPE_MAX = NodeType.LABEL;
56
+ export const NODE_SIZE = 16;
57
+ export const NodeLayout = Object.freeze({
58
+ TYPE: 0, LEVEL: 1, FLAGS: 2, SUBTREE_END: 4,
59
+ OFFSET: 8, LENGTH: 12,
60
+ });
61
+ export const ABI_VERSION = 4;
package/dist/browser.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
1
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle, } from './core.js';
2
2
  export type { LinkFields, MausmarkDocument, MausmarkParser } from './core.js';
3
3
  /** Fetch and initialize the package-relative WASM parser in a browser. */
4
4
  export declare function createParser(): Promise<import('./core.js').MausmarkParser>;
package/dist/browser.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { parserFromInstance } from './core.js';
2
- export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
2
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle, } from './core.js';
3
3
  /** Fetch and initialize the package-relative WASM parser in a browser. */
4
4
  export async function createParser() {
5
5
  const response = await fetch(new URL('./mausmark.wasm', import.meta.url));
package/dist/core.d.ts CHANGED
@@ -1,74 +1,52 @@
1
- /** The flat AST node kinds produced by mausmark. */
2
- export declare const NodeType: Readonly<{
3
- readonly DOC: 0;
4
- readonly PARAGRAPH: 1;
5
- readonly HEADER: 2;
6
- readonly BLOCKQUOTE: 3;
7
- readonly LIST: 4;
8
- readonly LIST_ITEM: 5;
9
- readonly CODE_BLOCK: 6;
10
- readonly HR: 7;
11
- readonly TEXT: 8;
12
- readonly EMPH: 9;
13
- readonly STRONG: 10;
14
- readonly CODE_SPAN: 11;
15
- readonly LINK: 12;
16
- readonly IMAGE: 13;
17
- readonly HTML: 14;
18
- readonly LINE_BREAK: 15;
19
- readonly SPAN: 16;
20
- readonly CUSTOM: 17;
21
- readonly REF_DEFS: 18;
22
- readonly REF_DEF: 19;
23
- readonly URL: 20;
24
- readonly TITLE: 21;
25
- readonly LABEL: 22;
26
- }>;
27
- export type NodeType = (typeof NodeType)[keyof typeof NodeType];
28
- /** Raw reference syntax carried by LINK and IMAGE node levels. */
29
- export declare const ReferenceStyle: Readonly<{
30
- readonly INLINE: 0;
31
- readonly FULL: 1;
32
- readonly COLLAPSED: 2;
33
- readonly SHORTCUT: 3;
34
- readonly AUTOLINK_EMAIL: 4;
35
- }>;
36
- export type ReferenceStyle = (typeof ReferenceStyle)[keyof typeof ReferenceStyle];
37
- /** Prefix emitted before a TEXT chunk while joining chunk children. */
38
- export declare const Join: Readonly<{
39
- readonly NONE: 0;
40
- readonly SPACE: 1;
41
- readonly NL: 2;
42
- }>;
43
- export type Join = (typeof Join)[keyof typeof Join];
44
- export declare const ListFlags: Readonly<{
45
- readonly ORDERED: 1;
46
- readonly LOOSE: 2;
47
- }>;
48
- export type ListFlags = (typeof ListFlags)[keyof typeof ListFlags];
1
+ import { Dialect, NodeType } from './abi.js';
2
+ import type { ReferenceStyle } from './abi.js';
3
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle } from './abi.js';
4
+ /** The raw, unresolved fields of a LINK, IMAGE or REF_DEF. An absent field is `''`. */
49
5
  export interface LinkFields {
6
+ /** Destination as written: backslash escapes and entities are not processed. */
50
7
  readonly url: string;
8
+ /** Title as written, without its quotes. */
51
9
  readonly title: string;
10
+ /** Reference label as written; match it against REF_DEF labels yourself. */
52
11
  readonly label: string;
12
+ /** How the link was written, and whether `label` needs a definition lookup. */
53
13
  readonly style: ReferenceStyle;
54
14
  }
55
- /** An immutable JS-owned snapshot of a parsed mausmark AST. */
15
+ /**
16
+ * An immutable JS-owned snapshot of a parsed mausmark AST. Nodes are integer
17
+ * indexes into a preorder table; the root is node `0`.
18
+ */
56
19
  export interface MausmarkDocument {
20
+ /** Number of nodes; valid indexes are `0` to `nodeCount - 1`. */
57
21
  readonly nodeCount: number;
22
+ /** The node's kind. */
58
23
  type(index: number): NodeType;
24
+ /**
25
+ * Type-specific value: the heading level on HEADING, the `ReferenceStyle` on
26
+ * LINK and IMAGE, the `Join` code on TEXT, the marker character on LIST.
27
+ */
59
28
  level(index: number): number;
29
+ /** `ListFlags` bits on LIST and LIST_ITEM. Other bits and nodes are internal. */
60
30
  flags(index: number): number;
31
+ /** One past the node's last descendant, which is its next sibling's index. */
61
32
  subtreeEnd(index: number): number;
33
+ /** UTF-8 byte offset of the node's text slice in the parsed source. */
62
34
  offset(index: number): number;
35
+ /** UTF-8 byte length of the node's text slice. */
63
36
  length(index: number): number;
37
+ /** The node's own source slice, without its children's. */
64
38
  text(index: number): string;
39
+ /** Direct content children, skipping the leading URL, TITLE and LABEL fields. */
65
40
  children(index: number): Iterable<number>;
41
+ /** The node's text chunks joined with their `Join` codes; not recursive. */
66
42
  joinedText(index: number): string;
43
+ /** Raw link fields of a LINK, IMAGE or REF_DEF; throws for other nodes. */
67
44
  link(index: number): LinkFields;
68
45
  }
69
46
  /** A synchronously usable parser after its WASM module has initialized. */
70
47
  export interface MausmarkParser {
71
- parse(markdown: string): MausmarkDocument;
48
+ /** Parse `markdown`, written in `dialect` (default `Dialect.MARKDOWN`). */
49
+ parse(markdown: string, dialect?: Dialect): MausmarkDocument;
72
50
  }
73
51
  /** @internal Shared loader validation used by the Node and browser entry points. */
74
52
  export declare function parserFromInstance(instance: WebAssembly.Instance): MausmarkParser;
package/dist/core.js CHANGED
@@ -1,20 +1,7 @@
1
- /** The flat AST node kinds produced by mausmark. */
2
- export const NodeType = Object.freeze({
3
- DOC: 0, PARAGRAPH: 1, HEADER: 2, BLOCKQUOTE: 3, LIST: 4, LIST_ITEM: 5,
4
- CODE_BLOCK: 6, HR: 7, TEXT: 8, EMPH: 9, STRONG: 10, CODE_SPAN: 11,
5
- LINK: 12, IMAGE: 13, HTML: 14, LINE_BREAK: 15, SPAN: 16, CUSTOM: 17,
6
- REF_DEFS: 18, REF_DEF: 19, URL: 20, TITLE: 21, LABEL: 22,
7
- });
8
- /** Raw reference syntax carried by LINK and IMAGE node levels. */
9
- export const ReferenceStyle = Object.freeze({
10
- INLINE: 0, FULL: 1, COLLAPSED: 2, SHORTCUT: 3, AUTOLINK_EMAIL: 4,
11
- });
12
- /** Prefix emitted before a TEXT chunk while joining chunk children. */
13
- export const Join = Object.freeze({ NONE: 0, SPACE: 1, NL: 2 });
14
- export const ListFlags = Object.freeze({ ORDERED: 1, LOOSE: 2 });
1
+ import { ABI_VERSION, Dialect, Join, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType } from './abi.js';
2
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle } from './abi.js';
15
3
  const PAGE_SIZE = 64 * 1024;
16
4
  const ALIGNMENT = 16;
17
- const NODE_SIZE = 16;
18
5
  const MAX_INPUT_BYTES = 64 * 1024 * 1024;
19
6
  const MAX_ARENA_BYTES = 512 * 1024 * 1024;
20
7
  const MAX_WASM_ADDRESS = 0x7fffffff;
@@ -32,7 +19,7 @@ function checkedAdd(left, right, message) {
32
19
  return left + right;
33
20
  }
34
21
  function initialArenaSize(inputLength) {
35
- // Most documents need far less than the old fixed 64 MiB arena.
22
+ // Start small; parse() doubles the arena until the document fits.
36
23
  return Math.min(MAX_ARENA_BYTES, Math.max(PAGE_SIZE, inputLength * 8 + 4096));
37
24
  }
38
25
  function isField(type) {
@@ -55,27 +42,27 @@ class PackedDocument {
55
42
  }
56
43
  type(index) {
57
44
  this.checkIndex(index);
58
- return this.#view.getUint8(index * NODE_SIZE);
45
+ return this.#view.getUint8(index * NODE_SIZE + NodeLayout.TYPE);
59
46
  }
60
47
  level(index) {
61
48
  this.checkIndex(index);
62
- return this.#view.getUint8(index * NODE_SIZE + 1);
49
+ return this.#view.getUint8(index * NODE_SIZE + NodeLayout.LEVEL);
63
50
  }
64
51
  flags(index) {
65
52
  this.checkIndex(index);
66
- return this.#view.getInt16(index * NODE_SIZE + 2, true);
53
+ return this.#view.getInt16(index * NODE_SIZE + NodeLayout.FLAGS, true);
67
54
  }
68
55
  subtreeEnd(index) {
69
56
  this.checkIndex(index);
70
- return this.#view.getInt32(index * NODE_SIZE + 4, true);
57
+ return this.#view.getInt32(index * NODE_SIZE + NodeLayout.SUBTREE_END, true);
71
58
  }
72
59
  offset(index) {
73
60
  this.checkIndex(index);
74
- return this.#view.getUint32(index * NODE_SIZE + 8, true);
61
+ return this.#view.getUint32(index * NODE_SIZE + NodeLayout.OFFSET, true);
75
62
  }
76
63
  length(index) {
77
64
  this.checkIndex(index);
78
- return this.#view.getUint16(index * NODE_SIZE + 12, true);
65
+ return this.#view.getUint16(index * NODE_SIZE + NodeLayout.LENGTH, true);
79
66
  }
80
67
  text(index) {
81
68
  this.checkIndex(index);
@@ -122,11 +109,11 @@ class PackedDocument {
122
109
  const end = this.subtreeEnd(index);
123
110
  for (let child = index + 1; child < end && isField(this.type(child)); child = this.subtreeEnd(child)) {
124
111
  if (this.type(child) === NodeType.URL)
125
- url = this.text(child);
112
+ url = this.joinedText(child);
126
113
  else if (this.type(child) === NodeType.TITLE)
127
- title = this.text(child);
114
+ title = this.joinedText(child);
128
115
  else
129
- label = this.text(child);
116
+ label = this.joinedText(child);
130
117
  }
131
118
  return { url, title, label, style: this.level(index) };
132
119
  }
@@ -148,7 +135,7 @@ class PackedDocument {
148
135
  for (let index = 0; index < this.nodeCount; index += 1) {
149
136
  const type = this.type(index);
150
137
  const end = this.subtreeEnd(index);
151
- if (type < NodeType.DOC || type > NodeType.LABEL || end <= index || end > this.nodeCount) {
138
+ if (type < NodeType.DOC || type > NODE_TYPE_MAX || end <= index || end > this.nodeCount) {
152
139
  throw new Error(`mausmark: malformed AST node ${index}`);
153
140
  }
154
141
  const offset = this.offset(index);
@@ -164,7 +151,7 @@ class WasmParser {
164
151
  constructor(wasm) {
165
152
  this.#wasm = wasm;
166
153
  }
167
- parse(markdown) {
154
+ parse(markdown, dialect = Dialect.MARKDOWN) {
168
155
  if (typeof markdown !== 'string')
169
156
  throw new TypeError('mausmark: markdown must be a string');
170
157
  const source = new TextEncoder().encode(markdown);
@@ -178,7 +165,7 @@ class WasmParser {
178
165
  const required = checkedAdd(arenaPointer, arenaSize, 'input and arena exceed the WASM address limit');
179
166
  this.ensureMemory(required);
180
167
  new Uint8Array(this.#wasm.memory.buffer, inputPointer, source.byteLength).set(source);
181
- const headerPointer = this.#wasm.parseDom(inputPointer, source.byteLength, arenaPointer, arenaSize);
168
+ const headerPointer = this.#wasm.parseDom(inputPointer, source.byteLength, arenaPointer, arenaSize, dialect);
182
169
  if (headerPointer >= 0)
183
170
  return this.copyDocument(source, headerPointer);
184
171
  if (arenaSize >= MAX_ARENA_BYTES) {
@@ -227,7 +214,7 @@ export function parserFromInstance(instance) {
227
214
  if (typeof heapBase.value !== 'number' || !Number.isInteger(heapBase.value) || heapBase.value < 0) {
228
215
  throw new Error('mausmark: WASM __heap_base is invalid');
229
216
  }
230
- if (abiVersion() !== 1)
217
+ if (abiVersion() !== ABI_VERSION)
231
218
  throw new Error('mausmark: unsupported WASM ABI version');
232
219
  return new WasmParser({
233
220
  memory,
Binary file
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
1
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle, } from './core.js';
2
2
  export type { LinkFields, MausmarkDocument, MausmarkParser } from './core.js';
3
3
  /** Load the package's WASM parser for Node.js. */
4
4
  export declare function createParser(): Promise<import('./core.js').MausmarkParser>;
package/dist/node.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { parserFromInstance } from './core.js';
3
- export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
3
+ export { ABI_VERSION, Dialect, HtmlMode, Join, ListFlags, NODE_SIZE, NODE_TYPE_MAX, NodeLayout, NodeType, ReferenceStyle, } from './core.js';
4
4
  /** Load the package's WASM parser for Node.js. */
5
5
  export async function createParser() {
6
6
  const wasm = await readFile(new URL('./mausmark.wasm', import.meta.url));
package/dom-example.js ADDED
@@ -0,0 +1,288 @@
1
+ // A small Markdown-to-DOM renderer over a mausmark document. Copy it and adapt it.
2
+ //
3
+ // import {createParser} from "mausmark"
4
+ // import {renderToDom} from "./dom-example.js"
5
+ //
6
+ // const parser = await createParser()
7
+ // renderToDom(parser.parse(markdown), document.querySelector("article"))
8
+ //
9
+ // Text goes in through text nodes and attributes through setAttribute, so
10
+ // nothing here escapes HTML by hand. That removes escaping, not policy: with
11
+ // untrusted input you still decide which URL schemes to allow (`javascript:`
12
+ // passes through as written) and what to do with raw HTML (shown as text here).
13
+
14
+ import {Join, ListFlags, NodeType, ReferenceStyle} from "mausmark";
15
+
16
+ /** @import {MausmarkDocument} from "mausmark" */
17
+
18
+ /**
19
+ * Append the rendered document to `parent`.
20
+ * @param {MausmarkDocument} doc
21
+ * @param {ParentNode} parent
22
+ */
23
+ export function renderToDom(doc, parent) {
24
+ const definitions = collectDefinitions(doc);
25
+
26
+ /** @param {number} index @param {ParentNode} into */
27
+ function children(index, into) {
28
+ for (const child of doc.children(index)) {
29
+ render(child, into);
30
+ }
31
+ }
32
+
33
+ /** @param {string} tag @param {number} index @param {ParentNode} into */
34
+ function element(tag, index, into) {
35
+ const el = document.createElement(tag);
36
+ children(index, el);
37
+ into.append(el);
38
+ return el;
39
+ }
40
+
41
+ // An undefined reference is not a link: put its brackets back as text.
42
+ /** @param {number} index @param {ParentNode} into */
43
+ function literalReference(index, into) {
44
+ const {label, style} = doc.link(index);
45
+ if (doc.type(index) === NodeType.IMAGE) {
46
+ into.append("![" + plainText(doc, index));
47
+ } else {
48
+ into.append("[");
49
+ children(index, into);
50
+ }
51
+ into.append("]");
52
+ if (style === ReferenceStyle.FULL) {
53
+ into.append("[" + decodeEntities(label) + "]");
54
+ } else if (style === ReferenceStyle.COLLAPSED) {
55
+ into.append("[]");
56
+ }
57
+ }
58
+
59
+ /** @param {number} index @param {ParentNode} into */
60
+ function render(index, into) {
61
+ switch (doc.type(index)) {
62
+ case NodeType.DOC:
63
+ case NodeType.SPAN:
64
+ children(index, into);
65
+ return;
66
+ case NodeType.PARAGRAPH:
67
+ element("p", index, into);
68
+ return;
69
+ case NodeType.HEADING:
70
+ element("h" + doc.level(index), index, into);
71
+ return;
72
+ case NodeType.BLOCKQUOTE:
73
+ element("blockquote", index, into);
74
+ return;
75
+ case NodeType.LIST: {
76
+ const list = element(doc.flags(index) & ListFlags.ORDERED ? "ol" : "ul", index, into);
77
+ // The start number's digits; empty in the Markdown dialect, where it has no meaning.
78
+ const start = doc.text(index);
79
+ if (start !== "" && Number(start) !== 1) {
80
+ list.setAttribute("start", String(Number(start)));
81
+ }
82
+ return;
83
+ }
84
+ case NodeType.LIST_ITEM: {
85
+ const item = document.createElement("li");
86
+ const loose = doc.flags(index) & ListFlags.LOOSE;
87
+ for (const child of doc.children(index)) {
88
+ // A tight item's paragraphs render without <p> wrappers.
89
+ if (!loose && doc.type(child) === NodeType.PARAGRAPH) {
90
+ children(child, item);
91
+ } else {
92
+ render(child, item);
93
+ }
94
+ }
95
+ into.append(item);
96
+ return;
97
+ }
98
+ case NodeType.CODE_BLOCK: {
99
+ const code = document.createElement("code");
100
+ // A fenced block's info string is its leading LABEL field, which
101
+ // children() and joinedText() skip.
102
+ const hasInfo = index + 1 < doc.subtreeEnd(index) && doc.type(index + 1) === NodeType.LABEL;
103
+ const language = hasInfo ? decodeEntities(doc.joinedText(index + 1)).trim().split(/\s+/)[0] : "";
104
+ if (language) {
105
+ code.className = "language-" + language;
106
+ }
107
+ code.append(doc.joinedText(index));
108
+ const pre = document.createElement("pre");
109
+ pre.append(code);
110
+ into.append(pre);
111
+ return;
112
+ }
113
+ case NodeType.THEMATIC_BREAK:
114
+ into.append(document.createElement("hr"));
115
+ return;
116
+ case NodeType.EMPH:
117
+ element("em", index, into);
118
+ return;
119
+ case NodeType.STRONG:
120
+ element("strong", index, into);
121
+ return;
122
+ case NodeType.CODE_SPAN: {
123
+ const code = document.createElement("code");
124
+ code.append(doc.joinedText(index));
125
+ into.append(code);
126
+ return;
127
+ }
128
+ case NodeType.LINK: {
129
+ const target = resolve(doc, index, definitions);
130
+ if (!target) {
131
+ literalReference(index, into);
132
+ return;
133
+ }
134
+ const a = document.createElement("a");
135
+ a.setAttribute("href", target.url);
136
+ if (target.title) {
137
+ a.setAttribute("title", target.title);
138
+ }
139
+ children(index, a);
140
+ into.append(a);
141
+ return;
142
+ }
143
+ case NodeType.IMAGE: {
144
+ const target = resolve(doc, index, definitions);
145
+ if (!target) {
146
+ literalReference(index, into);
147
+ return;
148
+ }
149
+ const img = document.createElement("img");
150
+ img.setAttribute("src", target.url);
151
+ img.setAttribute("alt", plainText(doc, index));
152
+ if (target.title) {
153
+ img.setAttribute("title", target.title);
154
+ }
155
+ into.append(img);
156
+ return;
157
+ }
158
+ case NodeType.HTML_BLOCK:
159
+ case NodeType.HTML_INLINE:
160
+ // Raw HTML stays inert text. To render trusted HTML instead, parse
161
+ // joinedText() with a <template> element, after sanitizing it.
162
+ into.append(doc.joinedText(index));
163
+ return;
164
+ case NodeType.CUSTOM:
165
+ // A `{...}` span, its content verbatim: yours to interpret.
166
+ into.append(doc.joinedText(index));
167
+ return;
168
+ case NodeType.TEXT:
169
+ into.append(joinPrefix(doc.level(index)) + decodeEntities(doc.text(index)));
170
+ return;
171
+ case NodeType.LITERAL_TEXT:
172
+ into.append(doc.text(index)); // must not be entity-decoded
173
+ return;
174
+ case NodeType.HARD_BREAK:
175
+ into.append(document.createElement("br"));
176
+ return;
177
+ // REF_DEFS and REF_DEF produce no output.
178
+ }
179
+ }
180
+
181
+ render(0, parent);
182
+ }
183
+
184
+ // A text chunk's join code is what comes before it: Join.NL is a soft line break.
185
+ /** @param {number} join */
186
+ function joinPrefix(join) {
187
+ return join === Join.NL ? "\n" : join === Join.SPACE ? " " : "";
188
+ }
189
+
190
+ // A <textarea>'s content is RCDATA: assigning innerHTML decodes character
191
+ // references but never creates elements, whatever the input.
192
+ /** @param {string} text */
193
+ function decodeEntities(text) {
194
+ if (!text.includes("&")) {
195
+ return text;
196
+ }
197
+ const area = document.createElement("textarea");
198
+ area.innerHTML = text;
199
+ return area.value;
200
+ }
201
+
202
+ // Alt text is the plain text of an image's content, with markup dropped.
203
+ /** @param {MausmarkDocument} doc @param {number} index @returns {string} */
204
+ function plainText(doc, index) {
205
+ let text = "";
206
+ for (const child of doc.children(index)) {
207
+ const type = doc.type(child);
208
+ if (type === NodeType.TEXT) {
209
+ text += joinPrefix(doc.level(child)) + decodeEntities(doc.text(child));
210
+ } else if (type === NodeType.LITERAL_TEXT) {
211
+ text += doc.text(child);
212
+ } else if (type === NodeType.CODE_SPAN) {
213
+ text += doc.joinedText(child);
214
+ } else {
215
+ text += plainText(doc, child);
216
+ }
217
+ }
218
+ return text;
219
+ }
220
+
221
+ // Reference links arrive unresolved. Definitions can sit anywhere, including
222
+ // inside lists and quotes, so scan every node; the first definition of a label wins.
223
+ /** @param {MausmarkDocument} doc */
224
+ function collectDefinitions(doc) {
225
+ /** @type {Map<string, {url: string, title: string}>} */
226
+ const definitions = new Map();
227
+ for (let index = 0; index < doc.nodeCount; index += 1) {
228
+ if (doc.type(index) !== NodeType.REF_DEF) continue;
229
+
230
+ const {label, url, title} = doc.link(index);
231
+ const key = normalizeLabel(label);
232
+ if (!definitions.has(key)) {
233
+ definitions.set(key, {url, title});
234
+ }
235
+ }
236
+ return definitions;
237
+ }
238
+
239
+ // CommonMark matches labels under full Unicode case folding; toLowerCase() is
240
+ // the approximation.
241
+ /** @param {string} label */
242
+ function normalizeLabel(label) {
243
+ return label.trim().replace(/\s+/g, " ").toLowerCase();
244
+ }
245
+
246
+ // Where a LINK or IMAGE points, or null for a reference with no definition.
247
+ /**
248
+ * @param {MausmarkDocument} doc
249
+ * @param {number} index
250
+ * @param {Map<string, {url: string, title: string}>} definitions
251
+ */
252
+ function resolve(doc, index, definitions) {
253
+ const {url, title, label, style} = doc.link(index);
254
+ // Autolinks take entities but no backslash escapes.
255
+ if (style === ReferenceStyle.AUTOLINK_EMAIL) {
256
+ return {
257
+ url: "mailto:" + decodeEntities(url),
258
+ title: ""
259
+ };
260
+ }
261
+ if (style === ReferenceStyle.AUTOLINK_URI) {
262
+ return {
263
+ url: decodeEntities(url),
264
+ title: ""
265
+ };
266
+ }
267
+ if (style === ReferenceStyle.INLINE) {
268
+ return {
269
+ url: unescapeLink(url),
270
+ title: unescapeLink(title)
271
+ };
272
+ }
273
+ const definition = definitions.get(normalizeLabel(label));
274
+ if (!definition) return null;
275
+
276
+ return {
277
+ url: unescapeLink(definition.url),
278
+ title: unescapeLink(definition.title)
279
+ };
280
+ }
281
+
282
+ // Destinations and titles are raw source: drop backslash escapes, decode
283
+ // entities. The browser percent-encodes the URL when it resolves it.
284
+ // WIP — it’s weird to expose this in a tree, it’s likely will change
285
+ /** @param {string} text */
286
+ function unescapeLink(text) {
287
+ return decodeEntities(text.replace(/\\([!-/:-@[-`{-~])/g, "$1"));
288
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mausmark",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.2.0",
4
4
  "description": "A fast, dependency-free Markdown parser compiled to WebAssembly",
5
5
  "type": "module",
6
6
  "exports": {
@@ -13,20 +13,19 @@
13
13
  },
14
14
  "files": [
15
15
  "dist",
16
+ "dom-example.js",
16
17
  "README.md",
17
18
  "LICENSE"
18
19
  ],
19
20
  "scripts": {
20
21
  "clean": "rm -rf dist",
21
22
  "build:wasm": "./build.sh wasm-core",
22
- "build:js": "tsc -p tsconfig.json",
23
+ "build:js": "./build.sh codegen && tsc -p tsconfig.json",
23
24
  "build": "npm run clean && npm run build:wasm && npm run build:js",
24
25
  "test:package": "node --test test/npm-package.test.mjs",
25
26
  "test:types": "tsc -p tsconfig.test.json --noEmit",
26
27
  "test": "npm run build && npm run test:package && npm run test:types",
27
- "prepack": "npm test",
28
- "prepublishOnly": "node -e \"if (process.env.npm_config_tag !== 'alpha') { console.error('Refusing to publish without the alpha dist-tag. Use npm run publish:alpha.'); process.exit(1) }\"",
29
- "publish:alpha": "npm publish --tag alpha --access public"
28
+ "prepack": "npm test"
30
29
  },
31
30
  "engines": {
32
31
  "node": ">=22.14"