Fast and small markdown parser and renderer
[![npm version][npm version]][npm link] ![][wasm size]
Fast and Small markdown parser and renderer based on mity/md4c.
==mark==), footnotes, inline attributes…yay -S md4x # md4x-gitThe examples above are the npm CLI (npx md4x). The native binary — the one zig build
produces and md4x(1) documents — is a smaller tool: it reads a local file or stdin, with
no URL, gh: or npm: shorthands, and its formats are html (the default), text,
json, ansi, markdown and heal, where the npm CLI spells the AST format ast and
adds meta.
Available as a native Node.js addon (NAPI) for maximum performance, or as a portable WASM module that works in any JavaScript runtime (Node.js, Deno, Bun, browsers, edge workers, etc.).
The bare md4x import auto-selects NAPI on Node.js and WASM elsewhere.
…Both NAPI and WASM export a unified API with init(). For WASM, init() must be called before rendering. For NAPI, it is optional (the native binding loads lazily on first render call).
Synchronous, zero-overhead native addon. Best performance for server-side use.
import { renderToHtml } from "md4x/napi";Works anywhere with WebAssembly support. Requires a one-time async initialization.
import { init, renderToHtml } from "md4x/wasm";
await init(); // call once before rendering
const html = renderToHtml("# Hello");init() accepts an optional options object with a wasm property (ArrayBuffer, Response, WebAssembly.Module, or Promise). When called with no arguments, it loads the bundled .wasm file automatically.
A single, minified, dependency-free ES module (~140 KB) with the same API as md4x/wasm, the WASM binary embedded into the same chunk.
import { init, renderToHtml } from "md4x/standalone";
await init(); // inflates and instantiates the inlined binary
const html = renderToHtml("# Hello");This is also what md4x and md4x/wasm resolve to under the browser export condition, so browser bundlers get the self-contained module automatically (the explicit unwasm condition still wins where it is set).
Benchmarks
(source: packages/md4x/bench)
…Notes:
parseAST group at the top (ox-content, md4x.napi, md4w) sits within ~20% of each other, which is close to run-to-run noise on this machine — repeat runs reorder them. Treat them as roughly tied; the clear gaps are further down the list.position data on every node, and ox-content hands back the tree as a JSON string (the bench JSON.parses it so every entry ends at a materialized tree).{ gfm: true } to put it on the same fixture as the rest.gfm-commonmark.0.31.2 WASM component, not an npm package — the bench fetches it once into bench/.cache/ (gitignored) and skips the entry if the download fails. It renders through fixed 2 MiB in/out buffers with no imports, and exposes HTML only, so it does not appear in the parseAST group.renderToHtml and renderToAnsi support a highlighter option for custom syntax highlighting of fenced code blocks. It receives the raw code (HTML-unescaped) and the block's metadata (language, filename, highlighted lines), and returns a replacement string or undefined to keep the default rendering.
import { renderToHtml } from "md4x";
import { codeToHtml } from "rangi";
import { githubDark } from "rangi/themes";
const html = renderToHtml("```js\nconst x = 1;\n```", {
highlighter: (code, block) => {
if (!block.lang) return; // keep default for fences with no language
return codeToHtml(code, { lang: block.lang, theme: githubDark });
},
});Any synchronous highlighter works. These examples use rangi (a separate install: npm i rangi) because it needs no async setup and inlines its theme colors, so the markup is self-contained.
Code block metadata from the info string is parsed automatically:
```ts [app.ts] {1,3-5}
// block.lang = "ts"
// block.filename = "app.ts"
// block.highlights = [1, 3, 4, 5]
```renderToAnsi renders a document straight to ANSI escape sequences — headings, emphasis, tables, lists, blockquotes, alerts and OSC 8 clickable links — ready to console.log in a CLI or TUI.
import { renderToAnsi } from "md4x";
import { codeToAnsi } from "rangi";
console.log(
renderToAnsi(doc, {
highlighter: (code, block) =>
block.lang ? codeToAnsi(code, { lang: block.lang }) : undefined,
}),
);The highlighter is the same hook as for HTML, returning terminal escapes instead of markup. Code arrives with the block's indentation stripped, and md4x re-applies it to every line that comes back — so a block nested in a blockquote or list keeps its bars and indent without the highlighter knowing anything about the surrounding document. Control bytes in the source are neutralized before the code is handed over, so a fenced block cannot smuggle escape sequences into the terminal.
Options: showUrls prints link targets after the text (for terminals without OSC 8 support), showFrontmatter renders frontmatter as dim text instead of hiding it, and heal: true closes unterminated markup — the combination that makes streaming LLM output render cleanly frame by frame.
renderToAnsi(chunk, { heal: true, showUrls: true });The CLI is this renderer with a file argument: npx md4x README.md previews any document in the terminal, since it defaults to ansi when stdout is a TTY (and text when piped — pass --format=ansi to force escapes into a pipe).
heal() fixes incomplete markdown from streaming LLM output — closing unclosed bold, italic, strikethrough, inline code, code blocks, links, and more. Useful for rendering partial markdown in real-time as tokens arrive (inspired by streamdown/remend).
import { heal } from "md4x";
heal("**bold"); // "**bold**"
heal("*ita"); // "*ita*"
heal("~~strike"); // "~~strike~~"
heal("`code"); // "`code`"
heal("```js\ncode"); // "```js\ncode\n```"
heal("[text](http:"); // "" (strips broken links)All render functions also accept a { heal: true } option to heal input before rendering in a single pass:
import { renderToHtml, parseAST, renderToAnsi, renderToText } from "md4x";
// Heal + render in one call — ideal for streaming LLM output
renderToHtml("# Hello **world", { heal: true });
// "
Hello world
\n"
parseAST("# Hello **world", { heal: true });
// { nodes: [["h1", {}, "Hello ", ["strong", {}, "world"]]], ... }
renderToAnsi("# Hello **world", { heal: true });
renderToText("# Hello **world", { heal: true });
// Combines with other options
renderToHtml("# Hello **world", { heal: true, full: true });Benchmarks
bun packages/md4x/bench/heal.mjs
cpu: Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz
runtime: bun 1.4.2 (x64-linux)
benchmark avg (min … max) p75 / p99 (min … top 1%)
md4x-napi heal (small) 1.23 µs/iter 1.22 µs 1.79 µs ▇█▂▁▁▁▁▁▁▁▁
md4x-wasm heal (small) 1.80 µs/iter 1.80 µs 2.16 µs ▆█▃▂▁▁▁▁▁▁▁
remend heal (small) 3.16 µs/iter 3.17 µs 9.27 µs █▄▂▁▁▁▁▁▁▁▁
summary
md4x-napi heal (small)
1.47x faster than md4x-wasm heal (small)
2.57x faster than remend heal (small)
md4x-napi heal (medium) 3.14 µs/iter 3.16 µs 3.44 µs ▃▂▅█▃▁▁▁▁▁▁
md4x-wasm heal (medium) 4.17 µs/iter 4.26 µs 4.38 µs ▅▅▂▁▂▃█▆▅▃▃
remend heal (medium) 19.24 µs/iter 18.97 µs 32.81 µs █▇▂▂▁▁▂▁▁▁▁
summary
md4x-napi heal (medium)
1.33x faster than md4x-wasm heal (medium)
6.12x faster than remend heal (medium)
md4x-napi heal (large) 148.63 µs/iter 147.74 µs 230.79 µs ▂█▂▁▁▁▁▁▁▁▁
md4x-wasm heal (large) 184.50 µs/iter 186.32 µs 259.67 µs ▅▆█▂▁▁▁▁▁▁▁
remend heal (large) 603.85 µs/iter 604.93 µs 762.44 µs ▃█▃▂▁▁▁▁▁▁▁
summary
md4x-napi heal (large)
1.24x faster than md4x-wasm heal (large)
4.06x faster than remend heal (large)MD4X ships its own YAML parser — a Zig port of libyaml, with no C dependency in the shipped artifacts. It backs frontmatter parsing, and is exposed directly for standalone YAML documents. Any root node is accepted (mapping, sequence, or bare scalar); an empty document yields null.
import { parseYAML, yamlToJson } from "md4x";
parseYAML("title: Hello\ncount: 42\ndraft: true");
// { title: "Hello", count: 42, draft: true }
yamlToJson("title: Hello"); // '{"title":"Hello"}' (raw JSON string)yamlToJson is parseYAML without the JSON.parse — use it when the value is headed straight back out as JSON.
Benchmarks
bun packages/md4x/bench/yaml.mjs
cpu: Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz
runtime: bun 1.4.2 (x64-linux)
benchmark avg (min … max) p75 / p99 (min … top 1%)
md4x.napi (parseYAML) (medium) 21.87 µs/iter 21.80 µs 22.98 µs ▅▃▃▃▃█▁▁▁▁▃
md4x.wasm (parseYAML) (medium) 31.16 µs/iter 33.67 µs 34.15 µs ▅█▅▁█▅▅▁▁█▅
js-yaml (parseYAML) (medium) 46.59 µs/iter 46.55 µs 83.79 µs ▃█▄▂▁▁▁▁▁▁▁
yaml (parseYAML) (medium) 292.90 µs/iter 301.71 µs 527.77 µs ▂█▄▂▂▁▁▁▁▁▁
confbox (parseYAML) (medium) 44.69 µs/iter 45.34 µs 76.02 µs ▃█▅▂▁▁▁▁▁▁▁
summary
md4x.napi (parseYAML) (medium)
1.42x faster than md4x.wasm (parseYAML) (medium)
2.04x faster than confbox (parseYAML) (medium)
2.13x faster than js-yaml (parseYAML) (medium)
13.39x faster than yaml (parseYAML) (medium)
md4x.napi (yamlToJson) (medium) 17.24 µs/iter 17.36 µs 17.45 µs ▅▁▁█▁█▅▅▅█▅
md4x.wasm (yamlToJson) (medium) 24.42 µs/iter 24.81 µs 25.12 µs ▃▁▁▁▆█▃▁▃▃▆
js-yaml (yamlToJson) (medium) 43.13 µs/iter 43.01 µs 45.38 µs ▆▁▆▆█▁▁▃▁▁▃
yaml (yamlToJson) (medium) 253.26 µs/iter 253.56 µs 412.91 µs ▂█▃▂▁▁▁▁▁▁▁
summary
md4x.napi (yamlToJson) (medium)
1.42x faster than md4x.wasm (yamlToJson) (medium)
2.5x faster than js-yaml (yamlToJson) (medium)
14.69x faster than yaml (yamlToJson) (medium)
…
zig
const md4x = @import("md4x"); // src/lib.zig
fn sink(text: [*c]const u8, size: c_uint, userdata: ?*anyopaque) void {
const out: *std.ArrayListUnmanaged(u8) = @ptrCast(@alignCast(userdata.?));
out.appendSlice(gpa, text[0..size]) catch {};
}
var out: std.ArrNo open issues yet, or sync has not completed.