mausmark 0.1.0-alpha.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/LICENSE +21 -0
- package/README.md +177 -0
- package/dist/browser.d.ts +4 -0
- package/dist/browser.js +16 -0
- package/dist/core.d.ts +74 -0
- package/dist/core.js +237 -0
- package/dist/mausmark.wasm +0 -0
- package/dist/node.d.ts +4 -0
- package/dist/node.js +9 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Kirill Myshkin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# Mausmark
|
|
2
|
+
|
|
3
|
+
A fast, dependency-free Markdown parser in C.
|
|
4
|
+
|
|
5
|
+
It parses Markdown into a document tree and ships a renderer for HTML.
|
|
6
|
+
|
|
7
|
+
## Why
|
|
8
|
+
|
|
9
|
+
- **No dependencies.** The core uses no C standard library and no OS calls:
|
|
10
|
+
no hidden allocations, no I/O. All memory comes from a single
|
|
11
|
+
caller-provided arena, so the caller controls where memory lives and how
|
|
12
|
+
much is used, and the parser runs anywhere a C function can be called —
|
|
13
|
+
including `wasm32` with no runtime shims.
|
|
14
|
+
- **No build system** Single translation unit, one compiler invocation,
|
|
15
|
+
no build system or link step. The same source compiles to native or wasm.
|
|
16
|
+
- **Fast.** A real-world article (~7 KB) parses and renders in ~4 µs; a book
|
|
17
|
+
(Moby-Dick, 1.2 MB) in ~0.33 ms on an M3 Pro. See
|
|
18
|
+
[Performance](#performance).
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
./build.sh cli # builds ./mausmark
|
|
23
|
+
./mausmark README.md # markdown file -> HTML on stdout
|
|
24
|
+
cat README.md | ./mausmark # or read stdin
|
|
25
|
+
./mausmark format file.md # reformat markdown -> markdown
|
|
26
|
+
|
|
27
|
+
Default output is an HTML fragment; `--full` emits a complete document.
|
|
28
|
+
|
|
29
|
+
## npm package
|
|
30
|
+
|
|
31
|
+
The alpha npm package exposes the parser's indexed AST without imposing a
|
|
32
|
+
renderer. It is ESM-only and includes TypeScript declarations.
|
|
33
|
+
|
|
34
|
+
npm install mausmark@alpha
|
|
35
|
+
|
|
36
|
+
Initialize WebAssembly once, then parsing is synchronous:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import {createParser, ListFlags, NodeType} from 'mausmark'
|
|
40
|
+
|
|
41
|
+
const parser = await createParser()
|
|
42
|
+
const doc = parser.parse('# Hello\n\n1. one\n2. two')
|
|
43
|
+
const escapeHtml = (value: string) => value
|
|
44
|
+
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
45
|
+
|
|
46
|
+
function render(index: number): string {
|
|
47
|
+
const children = () => [...doc.children(index)].map(render).join('')
|
|
48
|
+
switch (doc.type(index)) {
|
|
49
|
+
case NodeType.DOC:
|
|
50
|
+
case NodeType.SPAN:
|
|
51
|
+
return children()
|
|
52
|
+
case NodeType.HEADER:
|
|
53
|
+
return `<h${doc.level(index)}>${children()}</h${doc.level(index)}>`
|
|
54
|
+
case NodeType.PARAGRAPH:
|
|
55
|
+
return `<p>${children()}</p>`
|
|
56
|
+
case NodeType.LIST: {
|
|
57
|
+
const tag = doc.flags(index) & ListFlags.ORDERED ? 'ol' : 'ul'
|
|
58
|
+
return `<${tag}>${children()}</${tag}>`
|
|
59
|
+
}
|
|
60
|
+
case NodeType.LIST_ITEM:
|
|
61
|
+
return `<li>${children()}</li>`
|
|
62
|
+
case NodeType.TEXT:
|
|
63
|
+
return escapeHtml(doc.text(index))
|
|
64
|
+
default:
|
|
65
|
+
return children()
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const html = render(0)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`MausmarkDocument` is a compact, JS-owned snapshot: parsing another document
|
|
73
|
+
does not invalidate it. Nodes are addressed by integer index. `children(index)`
|
|
74
|
+
iterates direct content children and hides the internal URL/title/label field
|
|
75
|
+
nodes; `subtreeEnd(index)` exposes the preorder boundary for lower-level walks.
|
|
76
|
+
`joinedText(index)` assembles chunked code span, code block, and image content,
|
|
77
|
+
and `link(index)` returns a link's raw URL, title, label, and reference style.
|
|
78
|
+
Reference resolution remains renderer policy and is not performed by the core
|
|
79
|
+
package.
|
|
80
|
+
|
|
81
|
+
The alpha supports Node.js 22.14+ and modern browsers with WebAssembly SIMD.
|
|
82
|
+
Inputs are limited to 64 MiB and parser arena growth to 512 MiB. The API and AST
|
|
83
|
+
helpers may change between alpha releases.
|
|
84
|
+
|
|
85
|
+
## Decisions & divergences
|
|
86
|
+
|
|
87
|
+
Mausmark aims to be mostly compatible with CommonMark. It’s leaning towards the
|
|
88
|
+
original Markdown and uses curly brakets to allow for custom functionality. Here
|
|
89
|
+
are some of intentional divergences:
|
|
90
|
+
|
|
91
|
+
- **Backslash escapes** use original Markdown’s set (``\ ` * _ { } [ ] ( ) # + - . !``),
|
|
92
|
+
not CommonMark’s full ASCII-punctuation set. A backslash before any other
|
|
93
|
+
byte is a literal backslash.
|
|
94
|
+
- **Fenced code** uses backtick fences only (` ``` `, ≥3) — no `~~~`
|
|
95
|
+
fences. A fence cannot be indented: it must start at the beginning of the
|
|
96
|
+
line’s content (blockquote markers may precede it, so fences work inside
|
|
97
|
+
blockquotes, but not inside list items, where content is indented). The
|
|
98
|
+
info string (language) after an opening fence is ignored.
|
|
99
|
+
- **Reference links are resolved by the renderer, not the parser.** The
|
|
100
|
+
parser emits a link/image node carrying the reference label and which
|
|
101
|
+
source form it was written in (`[text]`, `[text][id]`, or `[text][]`);
|
|
102
|
+
renderers look the label up against the document’s definitions and, when
|
|
103
|
+
there is no match, use the source form to emit the literal source text.
|
|
104
|
+
- **Paragraph continuation lines** are left-trimmed (CommonMark behavior) —
|
|
105
|
+
leading whitespace on wrapped lines is not content.
|
|
106
|
+
- **Whitespace after a block marker** (1–3 spaces) is normalized away in
|
|
107
|
+
the AST.
|
|
108
|
+
|
|
109
|
+
Known limits:
|
|
110
|
+
|
|
111
|
+
- Inputs are limited to 4 GB (offsets are 32-bit by design).
|
|
112
|
+
- The HTML renderer allocates its scratch into the parse arena, so parse
|
|
113
|
+
and render currently share one arena’s lifetime and budget.
|
|
114
|
+
- No tables yet.
|
|
115
|
+
|
|
116
|
+
TODO:
|
|
117
|
+
|
|
118
|
+
- A link url/title/label that spans a soft-wrap seam renders empty, so a
|
|
119
|
+
multi-line reference definition fails its lookup. Now that these are child
|
|
120
|
+
nodes they could carry the value as several chunks, the way link text
|
|
121
|
+
already does.
|
|
122
|
+
|
|
123
|
+
## Embedding
|
|
124
|
+
|
|
125
|
+
The API is not settled yet; embedding docs will come once it is. For now the
|
|
126
|
+
public surface is `src/parser.h`, and the consumer roots (`src/mausmark.c`,
|
|
127
|
+
`src/wasm.c`, `test/test.c`) show the include layout.
|
|
128
|
+
|
|
129
|
+
## Building
|
|
130
|
+
|
|
131
|
+
`build.sh` is the whole build system. Each target is one `gcc`/`clang`
|
|
132
|
+
invocation; there is no library to install.
|
|
133
|
+
|
|
134
|
+
./build.sh test # build + run the test harness
|
|
135
|
+
./build.sh spec # CommonMark conformance (gated; needs node)
|
|
136
|
+
./build.sh bench [input-file] # build + run the benchmark (default: mobydick.md)
|
|
137
|
+
./build.sh cli # build ./mausmark
|
|
138
|
+
./build.sh wasm # build web/mausmark.wasm (browser demo in web/)
|
|
139
|
+
./build.sh wasm-core # build dist/mausmark.wasm (AST-only npm artifact)
|
|
140
|
+
./build.sh wasm-check # SIMD vs scalar wasm + JS-DOM equivalence
|
|
141
|
+
npm test # build and test the npm package + its types
|
|
142
|
+
|
|
143
|
+
On macOS, the wasm targets use Homebrew `llvm` + `lld` (Apple clang ships no
|
|
144
|
+
wasm backend). Elsewhere they use `clang` + `wasm-ld`; override with `WASM_CC`
|
|
145
|
+
/ `WASM_LD_DIR`.
|
|
146
|
+
|
|
147
|
+
Strict mode (lint + Address/UB sanitizers, warnings as errors):
|
|
148
|
+
|
|
149
|
+
CC=clang SANITIZE=1 WERROR=1 ./build.sh test
|
|
150
|
+
|
|
151
|
+
## Performance
|
|
152
|
+
|
|
153
|
+
Measured on an M3 Pro over cache-resident inputs (`./build.sh bench <file>`
|
|
154
|
+
reproduces; sanitizer-free build, median of 5).
|
|
155
|
+
|
|
156
|
+
| Input | to AST | to HTML | vs memcpy |
|
|
157
|
+
|------------------------------------------------------|---------:|--------------------:|----------:|
|
|
158
|
+
| `mobydick.md` (1.2 MB, prose ~183 B/line) | 5.2 GB/s | 3.5 GB/s (~0.33 ms) | ~22× |
|
|
159
|
+
| `mobydick-hard.md` (1.2 MB, wrapped ~62 B/line) | 4.2 GB/s | 2.6 GB/s (~0.44 ms) | ~30× |
|
|
160
|
+
| 10 real articles, mean 6.8 KB (link/ref-heavy) | 2.3 GB/s | 1.6 GB/s (~4.2 µs) | ~51× |
|
|
161
|
+
|
|
162
|
+
Sizing the arena: the document is 16 B per node — 130 KB for Moby-Dick's 8346
|
|
163
|
+
nodes, ~0.1× the input. Total arena use after parse and render is ~0.8× the input
|
|
164
|
+
for a book and ~1.3× for a small article.
|
|
165
|
+
|
|
166
|
+
The wasm build runs at ~0.55–0.65× native speed, on every input tested.
|
|
167
|
+
|
|
168
|
+
## Status
|
|
169
|
+
|
|
170
|
+
Alpha: actively developed, API not yet stable. Correctness is exercised
|
|
171
|
+
by a fixture test suite (`./build.sh test`), also run under Address/UB
|
|
172
|
+
sanitizers (see strict mode above).
|
|
173
|
+
Project page with a live browser demo: https://myshkin.eu/mausmark
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
|
|
2
|
+
export type { LinkFields, MausmarkDocument, MausmarkParser } from './core.js';
|
|
3
|
+
/** Fetch and initialize the package-relative WASM parser in a browser. */
|
|
4
|
+
export declare function createParser(): Promise<import('./core.js').MausmarkParser>;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { parserFromInstance } from './core.js';
|
|
2
|
+
export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
|
|
3
|
+
/** Fetch and initialize the package-relative WASM parser in a browser. */
|
|
4
|
+
export async function createParser() {
|
|
5
|
+
const response = await fetch(new URL('./mausmark.wasm', import.meta.url));
|
|
6
|
+
if (!response.ok)
|
|
7
|
+
throw new Error(`mausmark: failed to fetch WASM (${response.status} ${response.statusText})`);
|
|
8
|
+
let instance;
|
|
9
|
+
try {
|
|
10
|
+
instance = (await WebAssembly.instantiateStreaming(response.clone(), {})).instance;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
instance = (await WebAssembly.instantiate(await response.arrayBuffer(), {})).instance;
|
|
14
|
+
}
|
|
15
|
+
return parserFromInstance(instance);
|
|
16
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
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];
|
|
49
|
+
export interface LinkFields {
|
|
50
|
+
readonly url: string;
|
|
51
|
+
readonly title: string;
|
|
52
|
+
readonly label: string;
|
|
53
|
+
readonly style: ReferenceStyle;
|
|
54
|
+
}
|
|
55
|
+
/** An immutable JS-owned snapshot of a parsed mausmark AST. */
|
|
56
|
+
export interface MausmarkDocument {
|
|
57
|
+
readonly nodeCount: number;
|
|
58
|
+
type(index: number): NodeType;
|
|
59
|
+
level(index: number): number;
|
|
60
|
+
flags(index: number): number;
|
|
61
|
+
subtreeEnd(index: number): number;
|
|
62
|
+
offset(index: number): number;
|
|
63
|
+
length(index: number): number;
|
|
64
|
+
text(index: number): string;
|
|
65
|
+
children(index: number): Iterable<number>;
|
|
66
|
+
joinedText(index: number): string;
|
|
67
|
+
link(index: number): LinkFields;
|
|
68
|
+
}
|
|
69
|
+
/** A synchronously usable parser after its WASM module has initialized. */
|
|
70
|
+
export interface MausmarkParser {
|
|
71
|
+
parse(markdown: string): MausmarkDocument;
|
|
72
|
+
}
|
|
73
|
+
/** @internal Shared loader validation used by the Node and browser entry points. */
|
|
74
|
+
export declare function parserFromInstance(instance: WebAssembly.Instance): MausmarkParser;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
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 });
|
|
15
|
+
const PAGE_SIZE = 64 * 1024;
|
|
16
|
+
const ALIGNMENT = 16;
|
|
17
|
+
const NODE_SIZE = 16;
|
|
18
|
+
const MAX_INPUT_BYTES = 64 * 1024 * 1024;
|
|
19
|
+
const MAX_ARENA_BYTES = 512 * 1024 * 1024;
|
|
20
|
+
const MAX_WASM_ADDRESS = 0x7fffffff;
|
|
21
|
+
const decoder = new TextDecoder();
|
|
22
|
+
function align(value) {
|
|
23
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > MAX_WASM_ADDRESS - (ALIGNMENT - 1)) {
|
|
24
|
+
throw new Error('mausmark: invalid WASM heap base');
|
|
25
|
+
}
|
|
26
|
+
return (value + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
|
|
27
|
+
}
|
|
28
|
+
function checkedAdd(left, right, message) {
|
|
29
|
+
if (!Number.isSafeInteger(left) || !Number.isSafeInteger(right) || left < 0 || right < 0 || left > MAX_WASM_ADDRESS - right) {
|
|
30
|
+
throw new RangeError(`mausmark: ${message}`);
|
|
31
|
+
}
|
|
32
|
+
return left + right;
|
|
33
|
+
}
|
|
34
|
+
function initialArenaSize(inputLength) {
|
|
35
|
+
// Most documents need far less than the old fixed 64 MiB arena.
|
|
36
|
+
return Math.min(MAX_ARENA_BYTES, Math.max(PAGE_SIZE, inputLength * 8 + 4096));
|
|
37
|
+
}
|
|
38
|
+
function isField(type) {
|
|
39
|
+
return type === NodeType.URL || type === NodeType.TITLE || type === NodeType.LABEL;
|
|
40
|
+
}
|
|
41
|
+
class PackedDocument {
|
|
42
|
+
#source;
|
|
43
|
+
#nodes;
|
|
44
|
+
#view;
|
|
45
|
+
#nodeCount;
|
|
46
|
+
constructor(source, nodes, nodeCount) {
|
|
47
|
+
this.#source = source;
|
|
48
|
+
this.#nodes = nodes;
|
|
49
|
+
this.#view = new DataView(nodes.buffer, nodes.byteOffset, nodes.byteLength);
|
|
50
|
+
this.#nodeCount = nodeCount;
|
|
51
|
+
this.validateTable();
|
|
52
|
+
}
|
|
53
|
+
get nodeCount() {
|
|
54
|
+
return this.#nodeCount;
|
|
55
|
+
}
|
|
56
|
+
type(index) {
|
|
57
|
+
this.checkIndex(index);
|
|
58
|
+
return this.#view.getUint8(index * NODE_SIZE);
|
|
59
|
+
}
|
|
60
|
+
level(index) {
|
|
61
|
+
this.checkIndex(index);
|
|
62
|
+
return this.#view.getUint8(index * NODE_SIZE + 1);
|
|
63
|
+
}
|
|
64
|
+
flags(index) {
|
|
65
|
+
this.checkIndex(index);
|
|
66
|
+
return this.#view.getInt16(index * NODE_SIZE + 2, true);
|
|
67
|
+
}
|
|
68
|
+
subtreeEnd(index) {
|
|
69
|
+
this.checkIndex(index);
|
|
70
|
+
return this.#view.getInt32(index * NODE_SIZE + 4, true);
|
|
71
|
+
}
|
|
72
|
+
offset(index) {
|
|
73
|
+
this.checkIndex(index);
|
|
74
|
+
return this.#view.getUint32(index * NODE_SIZE + 8, true);
|
|
75
|
+
}
|
|
76
|
+
length(index) {
|
|
77
|
+
this.checkIndex(index);
|
|
78
|
+
return this.#view.getUint16(index * NODE_SIZE + 12, true);
|
|
79
|
+
}
|
|
80
|
+
text(index) {
|
|
81
|
+
this.checkIndex(index);
|
|
82
|
+
const offset = this.offset(index);
|
|
83
|
+
return this.decode(offset, this.length(index));
|
|
84
|
+
}
|
|
85
|
+
*children(index) {
|
|
86
|
+
this.checkIndex(index);
|
|
87
|
+
const end = this.subtreeEnd(index);
|
|
88
|
+
let child = index + 1;
|
|
89
|
+
while (child < end && isField(this.type(child)))
|
|
90
|
+
child = this.subtreeEnd(child);
|
|
91
|
+
while (child < end) {
|
|
92
|
+
yield child;
|
|
93
|
+
child = this.subtreeEnd(child);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
joinedText(index) {
|
|
97
|
+
this.checkIndex(index);
|
|
98
|
+
let foundChild = false;
|
|
99
|
+
let result = '';
|
|
100
|
+
for (const child of this.children(index)) {
|
|
101
|
+
foundChild = true;
|
|
102
|
+
if (this.type(child) === NodeType.TEXT) {
|
|
103
|
+
const join = this.level(child);
|
|
104
|
+
if (join === Join.SPACE)
|
|
105
|
+
result += ' ';
|
|
106
|
+
else if (join === Join.NL)
|
|
107
|
+
result += '\n';
|
|
108
|
+
}
|
|
109
|
+
result += this.text(child);
|
|
110
|
+
}
|
|
111
|
+
return foundChild ? result : this.text(index);
|
|
112
|
+
}
|
|
113
|
+
link(index) {
|
|
114
|
+
this.checkIndex(index);
|
|
115
|
+
const type = this.type(index);
|
|
116
|
+
if (type !== NodeType.LINK && type !== NodeType.IMAGE && type !== NodeType.REF_DEF) {
|
|
117
|
+
throw new TypeError(`mausmark: node ${index} is not a link, image, or reference definition`);
|
|
118
|
+
}
|
|
119
|
+
let url = '';
|
|
120
|
+
let title = '';
|
|
121
|
+
let label = '';
|
|
122
|
+
const end = this.subtreeEnd(index);
|
|
123
|
+
for (let child = index + 1; child < end && isField(this.type(child)); child = this.subtreeEnd(child)) {
|
|
124
|
+
if (this.type(child) === NodeType.URL)
|
|
125
|
+
url = this.text(child);
|
|
126
|
+
else if (this.type(child) === NodeType.TITLE)
|
|
127
|
+
title = this.text(child);
|
|
128
|
+
else
|
|
129
|
+
label = this.text(child);
|
|
130
|
+
}
|
|
131
|
+
return { url, title, label, style: this.level(index) };
|
|
132
|
+
}
|
|
133
|
+
checkIndex(index) {
|
|
134
|
+
if (!Number.isInteger(index) || index < 0 || index >= this.nodeCount) {
|
|
135
|
+
throw new RangeError(`mausmark: node index ${String(index)} is out of bounds`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
decode(offset, length) {
|
|
139
|
+
if (offset > this.#source.byteLength || length > this.#source.byteLength - offset) {
|
|
140
|
+
throw new Error('mausmark: malformed AST text range');
|
|
141
|
+
}
|
|
142
|
+
return decoder.decode(this.#source.subarray(offset, offset + length));
|
|
143
|
+
}
|
|
144
|
+
validateTable() {
|
|
145
|
+
if (!Number.isInteger(this.nodeCount) || this.nodeCount < 0 || this.#nodes.byteLength !== this.nodeCount * NODE_SIZE) {
|
|
146
|
+
throw new Error('mausmark: malformed AST node table');
|
|
147
|
+
}
|
|
148
|
+
for (let index = 0; index < this.nodeCount; index += 1) {
|
|
149
|
+
const type = this.type(index);
|
|
150
|
+
const end = this.subtreeEnd(index);
|
|
151
|
+
if (type < NodeType.DOC || type > NodeType.LABEL || end <= index || end > this.nodeCount) {
|
|
152
|
+
throw new Error(`mausmark: malformed AST node ${index}`);
|
|
153
|
+
}
|
|
154
|
+
const offset = this.offset(index);
|
|
155
|
+
const length = this.length(index);
|
|
156
|
+
if (offset > this.#source.byteLength || length > this.#source.byteLength - offset) {
|
|
157
|
+
throw new Error(`mausmark: malformed text range on node ${index}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
class WasmParser {
|
|
163
|
+
#wasm;
|
|
164
|
+
constructor(wasm) {
|
|
165
|
+
this.#wasm = wasm;
|
|
166
|
+
}
|
|
167
|
+
parse(markdown) {
|
|
168
|
+
if (typeof markdown !== 'string')
|
|
169
|
+
throw new TypeError('mausmark: markdown must be a string');
|
|
170
|
+
const source = new TextEncoder().encode(markdown);
|
|
171
|
+
if (source.byteLength > MAX_INPUT_BYTES) {
|
|
172
|
+
throw new RangeError(`mausmark: input exceeds the ${MAX_INPUT_BYTES / 1024 / 1024} MiB limit`);
|
|
173
|
+
}
|
|
174
|
+
const inputPointer = align(this.#wasm.heapBase);
|
|
175
|
+
const arenaPointer = align(checkedAdd(inputPointer, source.byteLength, 'input address exceeds the WASM address limit'));
|
|
176
|
+
let arenaSize = initialArenaSize(source.byteLength);
|
|
177
|
+
while (true) {
|
|
178
|
+
const required = checkedAdd(arenaPointer, arenaSize, 'input and arena exceed the WASM address limit');
|
|
179
|
+
this.ensureMemory(required);
|
|
180
|
+
new Uint8Array(this.#wasm.memory.buffer, inputPointer, source.byteLength).set(source);
|
|
181
|
+
const headerPointer = this.#wasm.parseDom(inputPointer, source.byteLength, arenaPointer, arenaSize);
|
|
182
|
+
if (headerPointer >= 0)
|
|
183
|
+
return this.copyDocument(source, headerPointer);
|
|
184
|
+
if (arenaSize >= MAX_ARENA_BYTES) {
|
|
185
|
+
throw new RangeError(`mausmark: parsing requires more than the ${MAX_ARENA_BYTES / 1024 / 1024} MiB arena limit`);
|
|
186
|
+
}
|
|
187
|
+
arenaSize = Math.min(MAX_ARENA_BYTES, arenaSize * 2);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
ensureMemory(required) {
|
|
191
|
+
const available = this.#wasm.memory.buffer.byteLength;
|
|
192
|
+
if (required <= available)
|
|
193
|
+
return;
|
|
194
|
+
try {
|
|
195
|
+
this.#wasm.memory.grow(Math.ceil((required - available) / PAGE_SIZE));
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
throw new RangeError(`mausmark: unable to grow WASM memory for parse: ${error instanceof Error ? error.message : String(error)}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
copyDocument(source, headerPointer) {
|
|
202
|
+
const memory = this.#wasm.memory.buffer;
|
|
203
|
+
if (!Number.isInteger(headerPointer) || headerPointer < 0 || headerPointer > memory.byteLength - 8) {
|
|
204
|
+
throw new Error('mausmark: malformed AST header pointer');
|
|
205
|
+
}
|
|
206
|
+
const header = new DataView(memory, headerPointer, 8);
|
|
207
|
+
const nodesPointer = header.getInt32(0, true);
|
|
208
|
+
const nodeCount = header.getInt32(4, true);
|
|
209
|
+
if (nodesPointer < 0 || nodeCount < 0 || nodeCount > Math.floor((memory.byteLength - nodesPointer) / NODE_SIZE)) {
|
|
210
|
+
throw new Error('mausmark: malformed AST header');
|
|
211
|
+
}
|
|
212
|
+
const nodeBytes = nodeCount * NODE_SIZE;
|
|
213
|
+
return new PackedDocument(source, new Uint8Array(memory, nodesPointer, nodeBytes).slice(), nodeCount);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** @internal Shared loader validation used by the Node and browser entry points. */
|
|
217
|
+
export function parserFromInstance(instance) {
|
|
218
|
+
const exports = instance.exports;
|
|
219
|
+
const memory = exports.memory;
|
|
220
|
+
const heapBase = exports.__heap_base;
|
|
221
|
+
const abiVersion = exports.mm_abi_version;
|
|
222
|
+
const parseDom = exports.mm_parse_dom;
|
|
223
|
+
if (!(memory instanceof WebAssembly.Memory) || !(heapBase instanceof WebAssembly.Global) ||
|
|
224
|
+
typeof abiVersion !== 'function' || typeof parseDom !== 'function') {
|
|
225
|
+
throw new Error('mausmark: WASM module is missing required ABI exports');
|
|
226
|
+
}
|
|
227
|
+
if (typeof heapBase.value !== 'number' || !Number.isInteger(heapBase.value) || heapBase.value < 0) {
|
|
228
|
+
throw new Error('mausmark: WASM __heap_base is invalid');
|
|
229
|
+
}
|
|
230
|
+
if (abiVersion() !== 1)
|
|
231
|
+
throw new Error('mausmark: unsupported WASM ABI version');
|
|
232
|
+
return new WasmParser({
|
|
233
|
+
memory,
|
|
234
|
+
heapBase: heapBase.value,
|
|
235
|
+
parseDom: parseDom,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
Binary file
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
|
|
2
|
+
export type { LinkFields, MausmarkDocument, MausmarkParser } from './core.js';
|
|
3
|
+
/** Load the package's WASM parser for Node.js. */
|
|
4
|
+
export declare function createParser(): Promise<import('./core.js').MausmarkParser>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { parserFromInstance } from './core.js';
|
|
3
|
+
export { Join, ListFlags, NodeType, ReferenceStyle, } from './core.js';
|
|
4
|
+
/** Load the package's WASM parser for Node.js. */
|
|
5
|
+
export async function createParser() {
|
|
6
|
+
const wasm = await readFile(new URL('./mausmark.wasm', import.meta.url));
|
|
7
|
+
const result = await WebAssembly.instantiate(wasm, {});
|
|
8
|
+
return parserFromInstance(result.instance);
|
|
9
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mausmark",
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "A fast, dependency-free Markdown parser compiled to WebAssembly",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/browser.d.ts",
|
|
9
|
+
"browser": "./dist/browser.js",
|
|
10
|
+
"node": "./dist/node.js",
|
|
11
|
+
"default": "./dist/browser.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"clean": "rm -rf dist",
|
|
21
|
+
"build:wasm": "./build.sh wasm-core",
|
|
22
|
+
"build:js": "tsc -p tsconfig.json",
|
|
23
|
+
"build": "npm run clean && npm run build:wasm && npm run build:js",
|
|
24
|
+
"test:package": "node --test test/npm-package.test.mjs",
|
|
25
|
+
"test:types": "tsc -p tsconfig.test.json --noEmit",
|
|
26
|
+
"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"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22.14"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"markdown",
|
|
36
|
+
"parser",
|
|
37
|
+
"wasm",
|
|
38
|
+
"webassembly"
|
|
39
|
+
],
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/mauskin/mausmark.git"
|
|
43
|
+
},
|
|
44
|
+
"homepage": "https://myshkin.eu/mausmark",
|
|
45
|
+
"license": "MIT",
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "26.1.2",
|
|
52
|
+
"typescript": "7.0.2"
|
|
53
|
+
}
|
|
54
|
+
}
|