mausmark 0.3.0 → 0.4.1

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.
@@ -0,0 +1,38 @@
1
+ WHATWG HTML named character reference data
2
+ Source: https://html.spec.whatwg.org/entities.json
3
+ License: https://github.com/whatwg/html/blob/main/LICENSE
4
+
5
+ Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
6
+
7
+ This work is licensed under a Creative Commons Attribution 4.0 International
8
+ License. To the extent portions of it are incorporated into source code,
9
+ such portions in the source code are licensed under the BSD 3-Clause License instead.
10
+
11
+ The named character reference data in src/html_entities.inc is incorporated
12
+ into source code under the following BSD 3-Clause License. Mausmark selects
13
+ semicolon-terminated spellings and rearranges them into its own lookup layout.
14
+
15
+ Redistribution and use in source and binary forms, with or without
16
+ modification, are permitted provided that the following conditions are met:
17
+
18
+ 1. Redistributions of source code must retain the above copyright notice, this
19
+ list of conditions and the following disclaimer.
20
+
21
+ 2. Redistributions in binary form must reproduce the above copyright notice,
22
+ this list of conditions and the following disclaimer in the documentation
23
+ and/or other materials provided with the distribution.
24
+
25
+ 3. Neither the name of the copyright holder nor the names of its
26
+ contributors may be used to endorse or promote products derived from
27
+ this software without specific prior written permission.
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
30
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
32
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
33
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
36
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
37
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -13,6 +13,9 @@ Project page and demo: https://myshkin.eu/mausmark
13
13
 
14
14
  npm install mausmark
15
15
 
16
+ Requires Node.js 22.14+ or a modern browser with WebAssembly SIMD.
17
+ Browser bundlers must emit the package-relative `.wasm` asset.
18
+
16
19
  ## Usage
17
20
 
18
21
  import {createParser, Dialect, NodeType} from "mausmark";
@@ -88,19 +91,18 @@ raw, and CommonMark treats braces as ordinary text.
88
91
  Compare node types against the exported constants: their numeric values
89
92
  can change between versions.
90
93
 
91
- ### Upgrading from 0.2.x
94
+ ### Upgrading from 0.3.x to 0.4.0
95
+
96
+ For most projects this is a drop-in update: if your renderer doesn't
97
+ output images, you don't need to change anything.
92
98
 
93
- Version 0.3.0 changes inline brace spans from raw `NodeType.CUSTOM` leaf
94
- nodes to `NodeType.BRACE_SPAN` containers. To preserve visible braces,
95
- wrap their rendered children in curly braces. Alternatively if you use
96
- curly braces for custom functionality you can either traverse span’s
97
- inline children or read the raw interior with `text(index)`. Multiline
98
- `CUSTOM` blocks are unchanged, and CommonMark still treats braces as
99
- ordinary text.
99
+ - To output images in the Markdown dialect, make sure you read the
100
+ description with `joinedText(index)`.
101
+ - CommonMark image descriptions should be read the same way; they are
102
+ plain text now. A reference inside one stays a LINK or IMAGE node
103
+ for your renderer to resolve.
100
104
 
101
- The WASM ABI version is now **5**. Keep the WASM binary and bindings
102
- from the same release. The node record remains 16 bytes, and existing
103
- node-type numeric values are unchanged.
105
+ For more details, see the [release notes](RELEASE-NOTES.md).
104
106
 
105
107
  ## Writing a renderer
106
108
 
@@ -145,13 +147,8 @@ HTML, custom nodes, list markers, and entity decoding:
145
147
  const parser = await createParser()
146
148
  console.log(plainText(parser.parse("# Hello\n\nA **wrapped** paragraph.")))
147
149
 
148
- For a complete renderer, the package includes `dom-example.js`. It
149
- builds DOM nodes directly: text goes in through text nodes and
150
- attributes through `setAttribute`, so it never has to escape HTML by
151
- hand. It covers every node type, including entity decoding, reference
152
- lookup, tight lists, fence info strings and image alt text, and it
153
- leaves raw HTML inert. It is an example, not an export: copy it and
154
- adapt it.
150
+ For a starting point that renders to the DOM, the package includes
151
+ `dom-example.js`, an incomplete renderer meant to be copied and adapted.
155
152
 
156
153
  Things to decide when building a richer renderer:
157
154
 
@@ -171,7 +168,9 @@ Things to decide when building a richer renderer:
171
168
  definitions in containers), store the first definition for each
172
169
  normalized label, and decide how to render unresolved references.
173
170
  CommonMark label matching uses Unicode case folding and whitespace
174
- collapse, not just `toLowerCase()`. An `AUTOLINK_EMAIL` URL is the
171
+ collapse, not just `toLowerCase()`;
172
+ `normalizeReferenceLabel(label, "markdown" | "commonmark")` from
173
+ `mausmark/references` does either. An `AUTOLINK_EMAIL` URL is the
175
174
  bare address; add `mailto:` when emitting it. `title === ""` alone
176
175
  does not distinguish an absent title from an explicit empty title;
177
176
  inspect the leading `TITLE` field if that matters to your output.
@@ -189,38 +188,39 @@ Things to decide when building a richer renderer:
189
188
 
190
189
  ## Performance
191
190
 
192
- The SIMD WebAssembly parser build is **75.8 KB**, uncompressed, or
193
- **25.2 KB with Brotli** (quality 11, offline precompression).
191
+ The SIMD WebAssembly parser build is **78.0 KB**, uncompressed, or
192
+ **26.1 KB with Brotli** (quality 11, offline precompression).
194
193
  Source-to-AST measurements on an Apple M3 Pro, Node.js 26.3.1 and
195
194
  Bun 1.4.2, compiled with Clang 22.1.7 at `-Os` with LTO:
196
195
 
197
196
  | Input | Node (µs) | Bun (µs) | Node (GB/s) | Bun (GB/s) |
198
197
  | ---------------------- | --------: | -------: | ----------: | ---------: |
199
- | Moby-Dick (1.2 MB) | ~303 | ~255 | ~4.0 | ~4.7 |
200
- | Line-wrapped Moby-Dick | ~414 | ~291 | ~2.9 | ~4.1 |
201
- | Pro Git chapters | 36.5 | 30.7 | 1.53 | 1.82 |
202
- | tldr pages | 1.7 | 1.5 | 0.33 | 0.37 |
198
+ | Moby-Dick (1.2 MB) | ~287 | ~242 | ~4.2 | ~5.0 |
199
+ | Line-wrapped Moby-Dick | ~413 | ~287 | ~2.9 | ~4.2 |
200
+ | Pro Git chapters | 37.2 | 30.0 | 1.50 | 1.86 |
201
+ | tldr pages | 1.6 | 1.3 | 0.36 | 0.43 |
203
202
 
204
203
  These are warmed parser-export timings with preloaded UTF-8 input and a
205
204
  reused arena, including JavaScript iteration and export-call overhead.
206
205
  They exclude initialization, input encoding/copying, AST snapshot
207
206
  copying, and rendering; they are not end-to-end timings of the package’s
208
- `parse()` method. The last row (tldr) reports average time per document;
209
- figures are medians across three alternating passes, each with five
210
- timing samples. Pro Git uses Markdown, tldr uses CommonMark; Moby-Dick
211
- rounds the close results from both dialects. GB/s uses decimal bytes.
207
+ `parse()` method. The corpus rows (Pro Git, tldr) report average time
208
+ per document; figures are medians across three alternating passes, each
209
+ with five timing samples. Pro Git uses Markdown, tldr uses CommonMark;
210
+ Moby-Dick rounds the close results from both dialects. GB/s uses decimal
211
+ bytes.
212
212
 
213
213
  ## Notes
214
214
 
215
- - Node.js 22.14+ or a modern browser with WebAssembly SIMD.
216
- - Browser bundlers must emit the package-relative `.wasm` asset.
217
215
  - Input is limited to 64 MiB; parser arena growth is limited to 512
218
216
  MiB.
219
- - Two input dialects, parsed at the same speed. `Dialect.MARKDOWN`
220
- (the default) is original Markdown; `Dialect.COMMONMARK` is
221
- CommonMark 0.31.2, currently 649/652 (99.5%) of the 0.31.2 spec
222
- suite byte-exact. Three definition-dependent reference-link cases
223
- remain unresolved.
217
+ - Two input dialects. `Dialect.MARKDOWN` (the default) is original
218
+ Markdown; `Dialect.COMMONMARK` is based on CommonMark 0.31.2,
219
+ currently 649/652 (99.5%) of its spec suite byte-exact. Three
220
+ definition-dependent reference-link cases are intentionally
221
+ unresolved.
222
+ - Unlike CommonMark, an image description is plain alt text, not
223
+ inline content.
224
224
  - No GFM yet: no tables, strikethrough, task lists or autolink
225
225
  literals.
226
226
 
@@ -231,5 +231,6 @@ MIT.
231
231
 
232
232
  ## License
233
233
 
234
- MIT. See [LICENSE](LICENSE). Unicode classification data carries the
235
- notice in [UNICODE-LICENSE.txt](UNICODE-LICENSE.txt).
234
+ MIT. See [LICENSE](LICENSE). Unicode data carries the notice in
235
+ [UNICODE-LICENSE.txt](UNICODE-LICENSE.txt); HTML entity data carries the
236
+ notice in [HTML-LICENSE.txt](HTML-LICENSE.txt).
@@ -0,0 +1,38 @@
1
+ # Mausmark v0.4.1
2
+
3
+ - Simplified the DOM renderer example and fixed rendering of email
4
+ autolinks and literal-text line joins.
5
+ - Fixed: Node and browser bindings preserve a leading UTF-8 BOM when
6
+ decoding source ranges instead of silently stripping it.
7
+ - Faster emphasis classification in native ARM64 builds.
8
+ - Added real-browser regression coverage and browser benchmark
9
+ tooling.
10
+ - Package exports and WASM ABI remain unchanged.
11
+
12
+ # Mausmark v0.4.0
13
+
14
+ - Image descriptions are alt text, not inline formatting. CommonMark
15
+ keeps the text between the markup (`![a *b*](/i)` → `a b`); Markdown
16
+ keeps the literal source, one chunk per line. Reference nodes remain
17
+ until the renderer resolves them or restores literal brackets.
18
+ - Image descriptions nested deeper than 32 levels now stay literal.
19
+ - New `mausmark/references` export:
20
+ `normalizeReferenceLabel(label, 'markdown' | 'commonmark')`.
21
+ - DOM example: `renderToDom(doc, parent, {referenceMatching})`,
22
+ explicit empty titles, entities decoded in alt text.
23
+ - Fixed: CommonMark list markers indented four or more columns no
24
+ longer interrupt a paragraph.
25
+ - Fixed: an HTML block or fence on a line without `>` ends the
26
+ blockquote instead of continuing its paragraph.
27
+ - Fixed: in CommonMark, code inside an indented fence keeps the right
28
+ indentation when its lines start with tabs.
29
+ - Fixed: link titles and labels continuing onto a following `> ` line
30
+ keep their content.
31
+ - Faster source-to-AST in WASM: Moby-Dick 4–11%, tldr pages 10–24%;
32
+ articles and docs unchanged.
33
+ - WASM build 78.0 KB (26.1 KB Brotli), up from 75.8 KB.
34
+ - `joinedText()` applies line joins to `LITERAL_TEXT` chunks too.
35
+ - Package includes `HTML-LICENSE.txt`.
36
+ - Migration: CommonMark image children are text chunks plus reference
37
+ containers; use the DOM example's alt-text traversal for references,
38
+ or `joinedText()` for chunk-only descriptions. WASM ABI stays 5.
package/dist/core.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Dialect, NodeType } from './abi.js';
2
2
  import type { ReferenceStyle } from './abi.js';
3
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 `''`. */
4
+ /** Raw, unresolved LINK/IMAGE/REF_DEF fields. Absent and empty fields are `''`;
5
+ * a leading TITLE node distinguishes an explicit empty title from no title. */
5
6
  export interface LinkFields {
6
7
  /** Destination as written: backslash escapes and entities are not processed. */
7
8
  readonly url: string;
@@ -25,7 +26,7 @@ export interface MausmarkDocument {
25
26
  type(index: number): NodeType;
26
27
  /**
27
28
  * Type-specific value: the heading level on HEADING, the `ReferenceStyle` on
28
- * LINK and IMAGE, the `Join` code on TEXT, the marker character on LIST.
29
+ * LINK and IMAGE, the `Join` code on TEXT/LITERAL_TEXT, the marker on LIST.
29
30
  */
30
31
  level(index: number): number;
31
32
  /** `ListFlags` bits on LIST and LIST_ITEM. Other bits and nodes are internal. */
@@ -46,7 +47,8 @@ export interface MausmarkDocument {
46
47
  children(index: number): Iterable<number>;
47
48
  /**
48
49
  * The node's text chunks joined with their `Join` codes; not recursive.
49
- * Use text() for a BRACE_SPAN's raw interior.
50
+ * Use text() for a BRACE_SPAN's raw interior. Image descriptions with
51
+ * reference containers need renderer-side traversal and resolution instead.
50
52
  */
51
53
  joinedText(index: number): string;
52
54
  /** Raw link fields of a LINK, IMAGE or REF_DEF; throws for other nodes. */
package/dist/core.js CHANGED
@@ -5,7 +5,7 @@ const ALIGNMENT = 16;
5
5
  const MAX_INPUT_BYTES = 64 * 1024 * 1024;
6
6
  const MAX_ARENA_BYTES = 512 * 1024 * 1024;
7
7
  const MAX_WASM_ADDRESS = 0x7fffffff;
8
- const decoder = new TextDecoder();
8
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
9
9
  function align(value) {
10
10
  if (!Number.isSafeInteger(value) || value < 0 || value > MAX_WASM_ADDRESS - (ALIGNMENT - 1)) {
11
11
  throw new Error('mausmark: invalid WASM heap base');
@@ -88,7 +88,7 @@ class PackedDocument {
88
88
  let result = '';
89
89
  for (const child of this.children(index)) {
90
90
  foundChild = true;
91
- if (this.type(child) === NodeType.TEXT) {
91
+ if (this.type(child) === NodeType.TEXT || this.type(child) === NodeType.LITERAL_TEXT) {
92
92
  const join = this.level(child);
93
93
  if (join === Join.SPACE)
94
94
  result += ' ';
Binary file
package/dist/node.js CHANGED
@@ -7,10 +7,6 @@ function createSourceDecoder(source) {
7
7
  const buffer = Buffer.from(source.buffer, source.byteOffset, source.byteLength);
8
8
  return (offset, length) => {
9
9
  const end = offset + length;
10
- // TextDecoder removes a leading UTF-8 BOM from each decoded range.
11
- if (length >= 3 && buffer[offset] === 0xef && buffer[offset + 1] === 0xbb && buffer[offset + 2] === 0xbf) {
12
- offset += 3;
13
- }
14
10
  return buffer.toString('utf8', offset, end);
15
11
  };
16
12
  }
package/dom-example.js CHANGED
@@ -1,4 +1,6 @@
1
- // A small Markdown-to-DOM renderer over a mausmark document. Copy it and adapt it.
1
+ // A small DOM renderer showing how to walk the tree. It is a starting point,
2
+ // not a package export or a complete renderer: copy it and tweak the
3
+ // node-to-element switch.
2
4
  //
3
5
  // import {createParser} from "mausmark"
4
6
  // import {renderToDom} from "./dom-example.js"
@@ -6,22 +8,44 @@
6
8
  // const parser = await createParser()
7
9
  // renderToDom(parser.parse(markdown), document.querySelector("article"))
8
10
  //
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).
11
+ // Code goes in through textContent, mixed content through text nodes, and
12
+ // link/image fields through setAttribute, so nothing is escaped by hand.
13
+ //
14
+ // Limitations:
15
+ // - Reference labels match with toLowerCase(), not Unicode case folding and
16
+ // whitespace collapse; see normalizeReferenceLabel in mausmark/references.
17
+ // - Image descriptions are read as plain text; a reference nested in one is
18
+ // not resolved.
19
+ // - Empty and absent titles are both omitted.
20
+ // - Entities and backslash escapes are not decoded.
21
+ // - No URL-scheme policy: javascript: URLs pass through to href/src. Add one
22
+ // before rendering untrusted input.
13
23
 
14
24
  import {Join, ListFlags, NodeType, ReferenceStyle} from "mausmark";
15
25
 
16
26
  /** @import {MausmarkDocument} from "mausmark" */
27
+ /** @import {LinkFields} from "mausmark" */
17
28
 
18
29
  /**
19
- * Append the rendered document to `parent`.
30
+ * Append the rendered document to `parent`, leaving existing content intact.
20
31
  * @param {MausmarkDocument} doc
21
32
  * @param {ParentNode} parent
22
33
  */
23
34
  export function renderToDom(doc, parent) {
24
- const definitions = collectDefinitions(doc);
35
+ /** @type {Record<string, LinkFields>} */
36
+ const references = Object.create(null);
37
+ for (let index = 0; index < doc.nodeCount; index += 1) {
38
+ if (doc.type(index) !== NodeType.REF_DEF) continue;
39
+ const link = doc.link(index);
40
+ references[link.label.toLowerCase()] ??= link; // first definition wins
41
+ }
42
+
43
+ /** @param {string} text @param {ParentNode} into */
44
+ function text(text, into) {
45
+ if (text) {
46
+ into.appendChild(document.createTextNode(text));
47
+ }
48
+ }
25
49
 
26
50
  /** @param {number} index @param {ParentNode} into */
27
51
  function children(index, into) {
@@ -34,152 +58,179 @@ export function renderToDom(doc, parent) {
34
58
  function element(tag, index, into) {
35
59
  const el = document.createElement(tag);
36
60
  children(index, el);
37
- into.append(el);
61
+ into.appendChild(el);
38
62
  return el;
39
63
  }
40
64
 
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
65
  /** @param {number} index @param {ParentNode} into */
60
66
  function render(index, into) {
61
67
  switch (doc.type(index)) {
68
+
62
69
  case NodeType.DOC:
63
70
  case NodeType.SPAN:
64
71
  children(index, into);
65
72
  return;
73
+
66
74
  case NodeType.BRACE_SPAN:
67
- // Remove these two append calls to omit delimiters. Alternatively,
68
- // interpret doc.text(index) yourself and skip children entirely.
69
- into.append("{");
75
+ // Omit the delimiters for a transparent container, or interpret
76
+ // doc.text(index) yourself instead of traversing the children.
77
+ text("{", into);
70
78
  children(index, into);
71
- into.append("}");
79
+ text("}", into);
72
80
  return;
81
+
73
82
  case NodeType.PARAGRAPH:
74
83
  element("p", index, into);
75
84
  return;
85
+
76
86
  case NodeType.HEADING:
77
87
  element("h" + doc.level(index), index, into);
78
88
  return;
89
+
79
90
  case NodeType.BLOCKQUOTE:
80
91
  element("blockquote", index, into);
81
92
  return;
93
+
82
94
  case NodeType.LIST: {
83
- const list = element(doc.flags(index) & ListFlags.ORDERED ? "ol" : "ul", index, into);
84
- // The start number's digits; empty in the Markdown dialect, where it has no meaning.
95
+ const list = element((doc.flags(index) & ListFlags.ORDERED) ? "ol" : "ul", index, into);
96
+ // CommonMark ordered lists retain their starting digits.
85
97
  const start = doc.text(index);
86
98
  if (start !== "" && Number(start) !== 1) {
87
99
  list.setAttribute("start", String(Number(start)));
88
100
  }
89
101
  return;
90
102
  }
103
+
91
104
  case NodeType.LIST_ITEM: {
92
105
  const item = document.createElement("li");
93
- const loose = doc.flags(index) & ListFlags.LOOSE;
94
106
  for (const child of doc.children(index)) {
95
- // A tight item's paragraphs render without <p> wrappers.
96
- if (!loose && doc.type(child) === NodeType.PARAGRAPH) {
107
+ // Tight lists omit paragraph wrappers inside each item.
108
+ if (!(doc.flags(index) & ListFlags.LOOSE) && doc.type(child) === NodeType.PARAGRAPH) {
97
109
  children(child, item);
98
110
  } else {
99
111
  render(child, item);
100
112
  }
101
113
  }
102
- into.append(item);
114
+ into.appendChild(item);
103
115
  return;
104
116
  }
117
+
105
118
  case NodeType.CODE_BLOCK: {
106
119
  const code = document.createElement("code");
107
- // A fenced block's info string is its leading LABEL field, which
108
- // children() and joinedText() skip.
109
- const hasInfo = index + 1 < doc.subtreeEnd(index) && doc.type(index + 1) === NodeType.LABEL;
110
- const language = hasInfo ? decodeEntities(doc.joinedText(index + 1)).trim().split(/\s+/)[0] : "";
111
- if (language) {
112
- code.className = "language-" + language;
120
+
121
+ // A fenced block's leading LABEL field holds its info string.
122
+ {
123
+ const hasInfo = (index + 1 < doc.subtreeEnd(index)) && (doc.type(index + 1) === NodeType.LABEL);
124
+ const language = (
125
+ hasInfo
126
+ ? doc.joinedText(index + 1).trim().split(/\s+/)[0]
127
+ : ""
128
+ );
129
+ if (language) {
130
+ code.className = "language-" + language;
131
+ }
113
132
  }
114
- code.append(doc.joinedText(index));
133
+
134
+ code.textContent = doc.joinedText(index);
115
135
  const pre = document.createElement("pre");
116
- pre.append(code);
117
- into.append(pre);
136
+ pre.appendChild(code);
137
+ into.appendChild(pre);
118
138
  return;
119
139
  }
140
+
141
+ case NodeType.CODE_SPAN: {
142
+ const code = document.createElement("code");
143
+ code.textContent = doc.joinedText(index);
144
+ into.appendChild(code);
145
+ return;
146
+ }
147
+
120
148
  case NodeType.THEMATIC_BREAK:
121
- into.append(document.createElement("hr"));
149
+ into.appendChild(document.createElement("hr"));
122
150
  return;
151
+
123
152
  case NodeType.EMPH:
124
153
  element("em", index, into);
125
154
  return;
155
+
126
156
  case NodeType.STRONG:
127
157
  element("strong", index, into);
128
158
  return;
129
- case NodeType.CODE_SPAN: {
130
- const code = document.createElement("code");
131
- code.append(doc.joinedText(index));
132
- into.append(code);
133
- return;
134
- }
135
- case NodeType.LINK: {
136
- const target = resolve(doc, index, definitions);
137
- if (!target) {
138
- literalReference(index, into);
139
- return;
140
- }
141
- const a = document.createElement("a");
142
- a.setAttribute("href", target.url);
143
- if (target.title) {
144
- a.setAttribute("title", target.title);
145
- }
146
- children(index, a);
147
- into.append(a);
148
- return;
149
- }
159
+
160
+ case NodeType.LINK:
150
161
  case NodeType.IMAGE: {
151
- const target = resolve(doc, index, definitions);
162
+ const image = doc.type(index) === NodeType.IMAGE;
163
+ const raw = doc.link(index);
164
+ const {style} = raw;
165
+ const isReference = style === ReferenceStyle.FULL || style === ReferenceStyle.COLLAPSED || style === ReferenceStyle.SHORTCUT;
166
+ const target = (
167
+ isReference
168
+ ? references[raw.label.toLowerCase()]
169
+ : raw
170
+ );
171
+
152
172
  if (!target) {
153
- literalReference(index, into);
173
+ // An undefined reference is not a link: put its brackets back as text.
174
+ if (image) {
175
+ text("![" + doc.joinedText(index), into);
176
+ } else {
177
+ text("[", into);
178
+ children(index, into);
179
+ }
180
+ text(
181
+ (
182
+ style === ReferenceStyle.FULL
183
+ ? "][" + raw.label + "]"
184
+ : (
185
+ style === ReferenceStyle.COLLAPSED
186
+ ? "][]"
187
+ : "]"
188
+ )
189
+ ),
190
+ into
191
+ );
154
192
  return;
155
193
  }
156
- const img = document.createElement("img");
157
- img.setAttribute("src", target.url);
158
- img.setAttribute("alt", plainText(doc, index));
159
- if (target.title) {
160
- img.setAttribute("title", target.title);
194
+
195
+ const {url, title} = target;
196
+ const el = document.createElement(image ? "img" : "a");
197
+ el.setAttribute(
198
+ image ? "src" : "href",
199
+ (
200
+ style === ReferenceStyle.AUTOLINK_EMAIL
201
+ ? "mailto:" + url
202
+ : url
203
+ )
204
+ );
205
+
206
+ if (title) el.setAttribute("title", title);
207
+
208
+ if (image) {
209
+ el.setAttribute("alt", doc.joinedText(index));
210
+ } else {
211
+ children(index, el);
161
212
  }
162
- into.append(img);
213
+
214
+ into.appendChild(el);
163
215
  return;
164
216
  }
217
+
165
218
  case NodeType.HTML_BLOCK:
166
219
  case NodeType.HTML_INLINE:
167
- // Raw HTML stays inert text. To render trusted HTML instead, parse
168
- // joinedText() with a <template> element, after sanitizing it.
169
- into.append(doc.joinedText(index));
170
- return;
171
220
  case NodeType.CUSTOM:
172
- // A raw multiline custom block: yours to interpret.
173
- into.append(doc.joinedText(index));
221
+ // Other source-backed content stays text; customize as needed.
222
+ text(doc.joinedText(index), into);
174
223
  return;
224
+
175
225
  case NodeType.TEXT:
176
- into.append(joinPrefix(doc.level(index)) + decodeEntities(doc.text(index)));
177
- return;
178
- case NodeType.LITERAL_TEXT:
179
- into.append(doc.text(index)); // must not be entity-decoded
226
+ case NodeType.LITERAL_TEXT: {
227
+ const join = doc.level(index);
228
+ text((join === Join.NL ? "\n" : (join === Join.SPACE ? " " : "")) + doc.text(index), into);
180
229
  return;
230
+ }
231
+
181
232
  case NodeType.HARD_BREAK:
182
- into.append(document.createElement("br"));
233
+ into.appendChild(document.createElement("br"));
183
234
  return;
184
235
  // REF_DEFS and REF_DEF produce no output.
185
236
  }
@@ -187,109 +238,3 @@ export function renderToDom(doc, parent) {
187
238
 
188
239
  render(0, parent);
189
240
  }
190
-
191
- // A text chunk's join code is what comes before it: Join.NL is a soft line break.
192
- /** @param {number} join */
193
- function joinPrefix(join) {
194
- return join === Join.NL ? "\n" : join === Join.SPACE ? " " : "";
195
- }
196
-
197
- // A <textarea>'s content is RCDATA: assigning innerHTML decodes character
198
- // references but never creates elements, whatever the input.
199
- /** @param {string} text */
200
- function decodeEntities(text) {
201
- if (!text.includes("&")) {
202
- return text;
203
- }
204
- const area = document.createElement("textarea");
205
- area.innerHTML = text;
206
- return area.value;
207
- }
208
-
209
- // Alt text is the plain text of an image's content, with markup dropped.
210
- /** @param {MausmarkDocument} doc @param {number} index @returns {string} */
211
- function plainText(doc, index) {
212
- let text = "";
213
- for (const child of doc.children(index)) {
214
- const type = doc.type(child);
215
- if (type === NodeType.TEXT) {
216
- text += joinPrefix(doc.level(child)) + decodeEntities(doc.text(child));
217
- } else if (type === NodeType.LITERAL_TEXT) {
218
- text += doc.text(child);
219
- } else if (type === NodeType.CODE_SPAN) {
220
- text += doc.joinedText(child);
221
- } else {
222
- text += plainText(doc, child);
223
- }
224
- }
225
- return text;
226
- }
227
-
228
- // Reference links arrive unresolved. Definitions can sit anywhere, including
229
- // inside lists and quotes, so scan every node; the first definition of a label wins.
230
- /** @param {MausmarkDocument} doc */
231
- function collectDefinitions(doc) {
232
- /** @type {Map<string, {url: string, title: string}>} */
233
- const definitions = new Map();
234
- for (let index = 0; index < doc.nodeCount; index += 1) {
235
- if (doc.type(index) !== NodeType.REF_DEF) continue;
236
-
237
- const {label, url, title} = doc.link(index);
238
- const key = normalizeLabel(label);
239
- if (!definitions.has(key)) {
240
- definitions.set(key, {url, title});
241
- }
242
- }
243
- return definitions;
244
- }
245
-
246
- // CommonMark matches labels under full Unicode case folding; toLowerCase() is
247
- // the approximation.
248
- /** @param {string} label */
249
- function normalizeLabel(label) {
250
- return label.trim().replace(/\s+/g, " ").toLowerCase();
251
- }
252
-
253
- // Where a LINK or IMAGE points, or null for a reference with no definition.
254
- /**
255
- * @param {MausmarkDocument} doc
256
- * @param {number} index
257
- * @param {Map<string, {url: string, title: string}>} definitions
258
- */
259
- function resolve(doc, index, definitions) {
260
- const {url, title, label, style} = doc.link(index);
261
- // Autolinks take entities but no backslash escapes.
262
- if (style === ReferenceStyle.AUTOLINK_EMAIL) {
263
- return {
264
- url: "mailto:" + decodeEntities(url),
265
- title: ""
266
- };
267
- }
268
- if (style === ReferenceStyle.AUTOLINK_URI) {
269
- return {
270
- url: decodeEntities(url),
271
- title: ""
272
- };
273
- }
274
- if (style === ReferenceStyle.INLINE) {
275
- return {
276
- url: unescapeLink(url),
277
- title: unescapeLink(title)
278
- };
279
- }
280
- const definition = definitions.get(normalizeLabel(label));
281
- if (!definition) return null;
282
-
283
- return {
284
- url: unescapeLink(definition.url),
285
- title: unescapeLink(definition.title)
286
- };
287
- }
288
-
289
- // Destinations and titles are raw source: drop backslash escapes, decode
290
- // entities. The browser percent-encodes the URL when it resolves it.
291
- // WIP — it’s weird to expose this in a tree, it’s likely will change
292
- /** @param {string} text */
293
- function unescapeLink(text) {
294
- return decodeEntities(text.replace(/\\([!-/:-@[-`{-~])/g, "$1"));
295
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mausmark",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "A fast, dependency-free Markdown parser compiled to WebAssembly",
5
5
  "type": "module",
6
6
  "exports": {
@@ -9,26 +9,41 @@
9
9
  "browser": "./dist/browser.js",
10
10
  "node": "./dist/node.js",
11
11
  "default": "./dist/browser.js"
12
+ },
13
+ "./references": {
14
+ "types": "./reference-matching.d.ts",
15
+ "default": "./reference-matching.js"
12
16
  }
13
17
  },
14
18
  "files": [
15
19
  "dist",
16
20
  "dom-example.js",
21
+ "reference-matching.js",
22
+ "reference-matching.d.ts",
17
23
  "README.md",
24
+ "RELEASE-NOTES.md",
18
25
  "LICENSE",
19
- "UNICODE-LICENSE.txt"
26
+ "UNICODE-LICENSE.txt",
27
+ "HTML-LICENSE.txt"
20
28
  ],
21
29
  "scripts": {
22
30
  "clean": "rm -rf dist",
23
- "build:wasm": "./build.sh wasm-core",
31
+ "build:wasm": "./build.sh wasm --ast-only",
24
32
  "build:js": "./build.sh codegen && tsc -p tsconfig.json",
25
33
  "build": "npm run clean && npm run build:wasm && npm run build:js",
26
34
  "check:wasm-size": "node test/wasm_size.mjs",
27
- "test:package": "node --test test/npm-package.test.mjs test/wasm-size.test.mjs test/source-retention.test.mjs",
28
- "test:types": "tsc -p tsconfig.test.json --noEmit",
29
- "check:unicode": "node tools/unicode.mjs --check",
30
- "test:unicode": "node --test test/unicode.test.mjs",
31
- "test": "npm run build && npm run check:wasm-size && npm run test:package && npm run test:types",
35
+ "test:package": "node --test test/npm-package.test.mjs test/dom-example.test.mjs test/text-decoding.test.mjs test/webdriver.test.mjs test/browser-benchmark.test.mjs test/wasm-size.test.mjs test/source-retention.test.mjs test/test-registration.test.mjs test/reference-matching.test.mjs",
36
+ "test:types": "tsc -p tsconfig.test.json --noEmit && tsc -p tsconfig.references.json",
37
+ "test:browser": "node test/browser/run.mjs",
38
+ "bench:browser": "npm run build && ./build.sh wasm && node benchmark/browser/run.mjs",
39
+ "setup:chrome": "node test/browser/setup-chrome.mjs",
40
+ "test:layers": "node --test test/layers.test.mjs",
41
+ "test:build": "node --test test/build.test.mjs",
42
+ "check:unicode": "node tools/unicode.mjs --check && node tools/case-fold.mjs --check",
43
+ "test:unicode": "node --test test/unicode.test.mjs test/case-fold.test.mjs",
44
+ "check:entities": "node tools/entities.mjs --check",
45
+ "test:entities": "node --test test/entities.test.mjs",
46
+ "test": "npm run test:build && npm run test:layers && npm run build && npm run check:wasm-size && npm run test:package && npm run test:types && npm run test:browser",
32
47
  "prepack": "npm test"
33
48
  },
34
49
  "engines": {
@@ -0,0 +1,7 @@
1
+ /** Reference lookup policy, independent of the parser's input dialect. */
2
+ export type ReferenceMatching = 'markdown' | 'commonmark';
3
+
4
+ /** Normalize raw label spelling; no entity/escape decoding or NFC.
5
+ * An empty CommonMark key returns null and must never match a definition.
6
+ */
7
+ export function normalizeReferenceLabel(label: string, matching?: ReferenceMatching): string | null;
@@ -0,0 +1,32 @@
1
+ /** @typedef {'markdown' | 'commonmark'} ReferenceMatching */
2
+
3
+ // Fold each scalar independently: whole-string lowercasing has contextual sigma
4
+ // rules. Upper/lower conversion expands ligatures and sharp s; these exceptions
5
+ // preserve dotless i, expand capital sharp s, and keep Cherokee in uppercase.
6
+ /** @param {string} char */
7
+ function foldCharacter(char) {
8
+ const cp = char.codePointAt(0) ?? 0;
9
+ if (cp === 0x131) return char;
10
+ if (cp === 0x1E9E) return 'ss';
11
+ if ((cp >= 0x13A0 && cp <= 0x13F5) || (cp >= 0x13F8 && cp <= 0x13FD) ||
12
+ (cp >= 0xAB70 && cp <= 0xABBF)) return char.toUpperCase();
13
+ return char.toUpperCase().toLowerCase();
14
+ }
15
+
16
+ /** Normalize raw label spelling. Does not decode entities/escapes or apply NFC.
17
+ * Markdown matches ASCII case only, preserving whitespace. CommonMark trims and
18
+ * collapses ASCII whitespace and folds Unicode using runtime case conversion.
19
+ * Returns null for an empty CommonMark key, which must never match a definition.
20
+ * @param {string} label
21
+ * @param {ReferenceMatching} matching
22
+ * @returns {string | null}
23
+ */
24
+ export function normalizeReferenceLabel(label, matching = 'markdown') {
25
+ if (matching === 'markdown') return label.replace(/[A-Z]/g, char => String.fromCharCode(char.charCodeAt(0) + 32));
26
+ if (matching !== 'commonmark') throw new RangeError(`Unknown reference matching policy: ${matching}`);
27
+ const text = label.replace(/[ \t\n\v\f\r]+/g, ' ').replace(/^ | $/g, '');
28
+ if (!text) return null;
29
+ let result = '';
30
+ for (const char of text) result += foldCharacter(char);
31
+ return result;
32
+ }