A fast, extensible Markdown parser for TypeScript. It speaks all of CommonMark and GitHub Flavored Markdown, plus GitHub alerts, emoji shortcodes and generic directives, and gives you a typed AST with exact source positions.
import { parse, toHtml } from "rundown";
const { tree } = parse("# Hello *world*");
toHtml(tree); // "<h1>Hello <em>world</em></h1>\n"- Spec-complete. 672/672 of cmark-gfm's
spec.txtand 30/30 ofextensions.txt: tables, task lists, strikethrough, extended autolinks, the tagfilter and footnotes. - Fast. End to end, about 4× faster than markdown-it and 3–6× faster than marked, on both Bun and Node. Linear time is tested on 36 pathological input shapes (see Performance).
- Its own AST. A discriminated union with one shape per node type and UTF-16
start/endoffsets on every node. Lines and columns are computed lazily. - Render to anything.
render<T>walks the tree with your callbacks;toHtml,toTextandtoElements(framework-agnostic{ tag, props, children }, handy for React) are built on it. - Directives.
:text[label]{attrs},::leaf[label]{attrs}and:::containerblocks, following micromark-extension-directive, with a registry that validates and coerces attributes and reports diagnostics. - Made for LLM output. The directive registry can describe itself as a prompt section or JSON Schema, and its diagnostics come back as plain text a model can fix its answer from (see Language models).
- GitHub alerts (
> [!NOTE]) and opt-in emoji shortcodes (:tada:). - Extensible. Add inline and block syntax; your code only runs at the trigger characters you register.
- Robust.
parsenever throws, deep nesting can't overflow the stack, and a seeded fuzzer checks AST invariants and timing. - Zero runtime dependencies. Runs in Bun, Node 20+ and browsers.
rundown is not published to npm. Install it directly from GitHub and pin to a tag:
bun add github:brielov/rundown#v0.1.0The package ships its TypeScript source (exports point at src/), so it needs a runtime or bundler that compiles TypeScript in dependencies, such as Bun. Node won't strip types inside node_modules; for plain Node, clone the repository and run bun run build, which writes ESM and .d.ts files to dist/.
The emoji table is a separate entry point, rundown/emoji, so it's only bundled when you import it.
parse never throws. Problems found by the directive registry come back as diagnostics:
const { tree, diagnostics } = parse(src);parse(src, {
gfm: true, // or false (plain CommonMark), or { tables, strikethrough, autolinks, tasklists, footnotes }
alerts: true, // GitHub alerts
emoji: false, // or a table, e.g. gemoji (below)
textDirectives: "strict", // or "reference" (exact micromark-extension-directive behavior)
});For repeated use, createParser(config) compiles options, extensions and the registry once:
const md = createParser({ gfm: true });
md.parse(src);The shortcode table is a separate entry point, so it's only bundled when you import it:
import { gemoji } from "rundown/emoji";
parse(":tada: done", { emoji: gemoji }); // emoji node, value "🎉"Without the option, :tada: stays literal text. :name: is never a directive.
By default, a text directive can't start right after a letter or digit, so 10:30 and status:error stay text. textDirectives: "reference" follows micromark exactly, where only a preceding : blocks a directive.
toHtml(tree, {
tagfilter: true, // GFM's disallowed raw HTML filter (default on)
alertIcons: false, // GitHub's Octicons in alert titles
nodes: { heading: (node, children) => `<h${node.depth} class="h">${children.join("")}</h${node.depth}>\n` },
directives: { youtube: (node) => `<iframe src="https://youtube.com/embed/${node.attributes.id}"></iframe>` },
unknownDirective: () => null, // drop directives without a callback
});Default directive markup:
| Directive | HTML |
|---|---|
| text | <span data-directive="name" …>label</span> |
| leaf | <div data-directive="name" …>label</div> |
| container | <div data-directive="name" …>children</div> |
| alert | GitHub's alert markup |
id and class become real attributes and every other attribute becomes data-*. Values are escaped.
Raw HTML is passed through, minus the tagfilter. URLs aren't sanitized, because that's what the spec expects. If your input isn't trusted, sanitize the output.
import { render } from "rundown";
const out = render<string>(tree, {
text: (value) => value,
fragment: (children) => children.join(""),
nodes: {
strong: (node, children) => `**${children.join("")}**`,
link: (node, children, ctx) => `${children.join("")} (${node.url})`,
},
});Callbacks:
- A node without a callback renders as
fragment(children). - Returning
nullomits the node. - Directive callbacks are tried in this order:
directives[name], thenunknownDirective, thennodes[type].
What ctx gives a callback: use it during the callback only.
parents,parentandindex;tight, which is true for paragraphs in tight lists;point(offset), the lazy line and column of an offset;definition(label)andfootnote(label);render(nodes), for rendering other nodes such as a container directive'slabel.
No recursion: rendering uses an explicit stack, so arbitrarily deep trees can't overflow the JS stack.
createStringRenderer(overrides) gives a Renderer<string> whose defaults concatenate. toText(tree) renders plain text.
toElements(tree) returns a framework-agnostic tree of { tag, props, children } elements:
- props use HTML attribute names, such as
class; - raw HTML becomes
{ tag: "#raw", props: { html } }, so you decide how, or whether, to inject it.
With React:
import { createElement, type ReactNode } from "react";
import { parse, toElements, type ElementChild } from "rundown";
function toReact(el: ElementChild, key?: number): ReactNode {
if (typeof el === "string") return el;
if (el.tag === "#raw") return createElement("span", { key, dangerouslySetInnerHTML: { __html: el.props.html } });
const props: Record<string, unknown> = { key };
for (const [k, v] of Object.entries(el.props)) props[k === "class" ? "className" : k] = v;
return createElement(el.tag, props, ...el.children.map((c, i) => toReact(c, i)));
}
export function Markdown({ source }: { source: string }) {
return <>{toElements(parse(source).tree).map((el, i) => toReact(el, i))}</>;
}For full control, use render<ReactNode> directly.
:abbr[HTML]{title="HyperText Markup Language"}
::video[Intro]{#intro .wide src=intro.mp4}
:::warning[Careful]
Content is **markdown**. Nest with longer fences on the outer one.
:::> [!NOTE] alerts and :::note are the same node type, containerDirective. The source field, "alert" or "directive", tells them apart.
import { createParser, defineDirective, oneOf, string, integer, withDefault, toHtml } from "rundown";
const chart = defineDirective({
kind: "leaf", // "text" | "leaf" | "container", or an array of them
attributes: { type: oneOf("pie", "bar", "line"), src: string(), height: withDefault(integer(), 200) },
transform: (node, ctx) => {
// node.data: { type: "pie" | "bar" | "line"; src: string; height: number }
if (!node.data.src.endsWith(".csv")) ctx.report("expected a CSV file", { severity: "warning" });
},
});
const md = createParser({ directives: { chart }, unknownDirectives: "keep" });
const { tree, diagnostics } = md.parse("::chart{type=pie src=data.csv}");
// Render callbacks typed from the schema:
const html = toHtml(tree, {
directives: md.renderers<string>({
chart: (node) => (node.data ? `<figure data-chart="${node.data.type}"></figure>` : null),
}),
});Schemas:
- Helpers:
string(),number(),integer(),boolean(),oneOf(...)andcustom(expected, fn). - Wrappers:
optional(s),withDefault(s, value)andwithDescription(s, text)(for language models). - Coerced values go into
node.data; the raw strings stay innode.attributes.
When something's wrong:
- Invalid or missing attributes, or the wrong kind: a diagnostic with source offsets. Bad attributes point at the value. The node stays as it was, with
data: null. - Unregistered names follow
unknownDirectives:"keep"(the default) leaves them as nodes;"text"turns them back into their literal source text;"error"keeps them and adds a diagnostic.
- A throwing transform becomes a diagnostic.
- Transforms may return a replacement node,
nullto remove the node, or nothing. - Typing: use
defineDirectivefor precisely typed transforms. Specs written inline increateParserget the general node types.
If nothing is registered and unknownDirectives is "keep", the registry costs nothing.
import { createParser, toHtml, type InlineExtension } from "rundown";
const mark: InlineExtension = {
name: "mark",
triggers: "=",
tokenize(ctx, pos) {
if (ctx.text.charCodeAt(pos + 1) !== 61) return -1; // "=="
const close = ctx.find("==", pos + 2); // bounded by the leaf; -1 if absent
if (close < 0) return -1;
ctx.add(
{ type: "mark", start: ctx.sourceOffset(pos), end: ctx.sourceOffset(close + 2), children: ctx.parseInline(pos + 2, close) },
pos,
close + 2,
);
return close + 2;
},
html: { mark: (_node, children) => `<mark>${children.join("")}</mark>` },
};
const md = createParser({ inline: [mark] });
toHtml(md.parse("==hi==").tree, { extensions: [mark] }); // "<p><mark>hi</mark></p>\n"Triggers:
- Triggers are ASCII characters, looked up in a precomputed 128-entry table. Plain text never calls your code.
- On a character a built-in also uses, the built-in goes first. Set
before: "link"(or another built-in name) to go first instead.
What tokenize can do through ctx:
- read the leaf's text,
ctx.text[ctx.start, ctx.end).ctx.textcan be the whole document (verbatim leaves are parsed in place), so stay within that range, and search withctx.find, which stops atctx.end; - claim pending text before the trigger, back to
ctx.textStart; - check
ctx.inBracketto see whether it's inside link text.
Emoji shortcodes are built on this interface.
import type { BlockExtension } from "rundown";
const math: BlockExtension<true> = {
name: "math",
triggers: "$",
kind: "leaf", // or "container" (content parsed as blocks)
interruptsParagraph: false, // the default
open(line) {
if (!line.source.startsWith("$$", line.firstNonspace)) return null;
line.skipRest();
return true;
},
continue(line) { // "continue" | "close" (consumes the line) | "end"
return line.source.slice(line.firstNonspace, line.lineEnd).trim() === "$$" ? "close" : "continue";
},
finish(_state, block) {
const value = block.lines.map(([a, b]) => block.source.slice(a, b)).join("\n");
return { type: "math", start: block.start, end: block.end, value };
},
};Block extension rules:
- Block extensions are tried after the built-in block starts.
- A container can consume a line prefix in
continue, throughline.advance(columns). Withlazy: false, lazy lines don't continue paragraphs inside it. - Leaf and container directives are built on this interface.
declare module "rundown" {
interface InlineNodeMap { mark: { type: "mark"; start: number; end: number; children: Inline[] } }
interface BlockNodeMap { math: { type: "math"; start: number; end: number; value: string } }
}Augmentations are global to the program. Once declared, Inline and Block include the new types everywhere, and render callbacks can be keyed by them.
type Block =
| Paragraph | Heading | ThematicBreak | Blockquote | List | Code | HtmlBlock | Definition | Table
| FootnoteDefinition | LeafDirective | ContainerDirective;
type Inline =
| Text | Emphasis | Strong | Delete | InlineCode | Break | Link | Image | HtmlInline
| FootnoteReference | TextDirective | Emoji;Positions: every node has start and end, UTF-16 offsets into the source string, which is never modified. pointAt(tree, offset) gives the 1-based line and column.
Shapes: each node type has exactly one shape. All fields are always present, and absent strings are "".
References: they're resolved at parse time. link.kind records the syntax, and link.label holds the normalized definition label. Definitions stay in the tree where they were written.
See src/ast.ts for the full types and DECISIONS.md for every design and conformance decision.
Directives give a model a way to ask for things in the middle of its answer: a chart, a callout, a mention, an embed. You register them once. The same registry then produces the prompt that tells the model what's available, validates the reply, and renders it.
import {
createParser, defineDirective, formatDiagnostics, integer, oneOf, string, toHtml,
withDefault, withDescription,
} from "rundown";
const chart = defineDirective({
kind: "leaf",
description: "Render a chart from a CSV file.",
label: "The chart's caption.",
additionalAttributes: false, // report invented attributes instead of ignoring them
attributes: {
type: withDescription(oneOf("pie", "bar", "line"), "Chart type."),
src: withDescription(string(), "URL of a CSV file."),
height: withDefault(integer(), 200),
},
examples: ["::chart[Revenue by region]{type=bar src=/data/revenue.csv}"],
});
const md = createParser({ directives: { chart }, unknownDirectives: "error" });
const system = `You are a reporting assistant.\n\n${md.describeDirectives()}`;md.describeDirectives() returns a Markdown section along these lines:
## Directives
You can use the directives below in your Markdown. Use only these: any other directive is an error.
Directive syntax:
- Leaf directive, on a line of its own: `::name[label]{key="value"}`.
- `[label]` and `{…}` are optional. Separate attributes with spaces and put values in double quotes; …
### chart
Render a chart from a CSV file.
Use it as a leaf directive: `::chart[…]{…}` on a line of its own.
- Label: The chart's caption.
- Attributes:
- `type` (one of "pie", "bar", "line", required): Chart type.
- `src` (a string, required): URL of a CSV file.
- `height` (an integer, default 200)
- No other attributes.
Example:
```markdown
::chart[Revenue by region]{type=bar src=/data/revenue.csv}
```The syntax part only explains the directive kinds you registered. Options: heading (or false), level and syntax: false. The standalone describeDirectives(specs, options) does the same without a parser.
When the reply comes back, parse it. If anything is wrong, formatDiagnostics gives the model something it can act on:
let reply = await complete({ system, messages });
let { tree, diagnostics } = md.parse(reply);
if (diagnostics.length > 0) {
messages.push(
{ role: "assistant", content: reply },
{ role: "user", content: `Fix these problems in your answer:\n\n${formatDiagnostics(diagnostics, reply)}` },
);
reply = await complete({ system, messages });
({ tree, diagnostics } = md.parse(reply));
}
const html = toHtml(tree, { directives: md.renderers<string>({ chart: (node) => /* … */ "" }) });error [invalid-attribute] line 3, column 14: Directive "chart", attribute "type": expected one of "pie", "bar", "line", got "donut"
::chart{type=donut src=/a.csv color=red}
error [unknown-attribute] line 3, column 37: Directive "chart" has no attribute "color" (allowed: type, src, height)
::chart{type=donut src=/a.csv color=red}
error [unknown-directive] line 5, column 1: Unknown directive "map" (known directives: chart)
::map{q=paris}
Details:
directiveJsonSchema(spec)gives a directive's attributes as JSON Schema (enum,default,required,additionalProperties), for tool or structured-output definitions.- Test your examples with the parser that describes them, e.g.
expect(md.parse(example).diagnostics).toEqual([]). A wrong example teaches the model wrong syntax. - Directives fit things your app does with the answer afterwards. When the model needs a result back before it can go on writing, such as fetching data, use your model API's tool calling.
bun run scoreboard prints pass rates per spec section; SCOREBOARD.md keeps the latest.
| Suite | Passing |
|---|---|
cmark-gfm spec.txt (GFM 0.29) |
672 / 672 |
cmark-gfm extensions.txt |
30 / 30 |
spec/alerts.md, spec/emoji.md, spec/directives.md (includes micromark-extension-directive's fixtures, ported) |
300 / 300 |
Where the specs leave room, or where sources disagree, the choice is written down in DECISIONS.md.
Parse plus HTML, on a corpus of 24 real READMEs and docs (about 1.2 MB), output flattened to a single string. MB/s, higher is better; from bun run bench and bun run bench:node (Bun 1.4.3, Node 24):
| Library | Bun | Node |
|---|---|---|
Bun.markdown (native, Bun only) |
115 | — |
| rundown | 74 | 54 |
| markdown-it | 18 | 15 |
| marked | 13 | 16 |
| micromark + GFM | 1.5 | 1.0 |
Measured separately with the same corpus: commonmark.js runs at about 36 MB/s on both engines, and markdown-wasm (md4c compiled to WebAssembly) at about 130 on Bun and 100 on Node. Both of those return HTML only, with no tree.
Rendering a parsed tree to HTML is ahead of markdown-it and marked on Bun and level with them on Node. Every pathological shape in bench/pathological.ts (deep nesting, unclosed brackets, emphasis runs, directive edge cases, …) is checked for linear time. Full results, history and methodology are in BENCHMARKS.md.
Everything runs on Bun:
bun install
bun test # spec examples, AST invariants, linearity, extensions
bun run scoreboard # per-section pass rates
bun run typecheck # project + src-only (no runtime APIs in src/)
bun run lint
bun run bench # benchmarks (Bun); bench:node for Node
bun run smoke:node # the spec suite under Node
bun run fuzz # seeded fuzzing (see DECISIONS.md T7)
bun run build # dist/ (ESM + .d.ts)Profiling: bun --cpu-prof --cpu-prof-dir=bench/.profiles bench/profile/run.ts parse 5, or bun run profile:node parse 5 for V8, then summarize with bench/profile/summarize.ts.
Issues and pull requests are welcome. A few ground rules keep the project what it is:
src/stays runtime-agnostic and dependency-free.- No change may break a passing spec example. Run
bun testandbun run scoreboard. - Performance changes come with numbers on both Bun and Node (
bench/profile/abp.tsdoes process-level A/B runs). A change that speeds up one engine but slows the other by more than 5% needs a good reason. - Behavior that isn't dictated by a spec gets an entry in
DECISIONS.md.
rundown is tested against, and borrows data from, these projects:
- cmark-gfm:
spec.txt,extensions.txtandnormalize.py, vendored intest/vendor/(BSD-2-Clause; spec text CC-BY-SA 4.0). - micromark-extension-directive: the directive syntax and its test fixtures (MIT).
- gemoji: the emoji shortcode table (MIT).
- Primer Octicons: the alert icons (MIT).
- WHATWG HTML: the named character reference table.
The benchmark corpus in bench/corpus/ keeps each file's original license; see bench/corpus/SOURCES.md.
MIT © Gabriel Vaquer