hamur/markdown
Markdown parsing for the build. parseMarkdown turns a Markdown document into the Markdown AST, a tree of plain arrays that can be written as JSON, together with its frontmatter, title, headings and table of contents. It runs where Bun.markdown exists: in hamur build, in hamur dev and on the bun preset. The module imports cleanly anywhere else, and parseMarkdown called there throws parseMarkdown runs at build or on the bun preset. renderMarkdownAst turns the AST into HTML on every preset and in the browser. The guide to Markdown pages, imports, MDC components and highlighting is Markdown.
parseMarkdown
function parseMarkdown(source: string, options?: ParseMarkdownOptions): Promise<MarkdownDocument>
GFM is on: tables, strikethrough, task lists and autolinks. A leading block between two --- lines is frontmatter, parsed as YAML. Raw HTML in the source is read as text unless html is true; autolinks such as <https://hamur.dev> stay links either way. Backslash escapes and character references in link and image URLs and titles are decoded ([a](/a&b) links to /a&b). Fenced code keeps its language, and a fence written ```ts [app.ts] {1,3-4} also gives filename: "app.ts", highlights: [1, 3, 4] and meta: "[app.ts] {1,3-4}" on the pre node. A code block in a language of the tokenizer is coloured into tok-<kind> spans, one line span per line; see Highlighting.
Markdown components are written as data, never as JavaScript (no MDX). A block ::alert{type="info"} … :: on their own lines becomes ["alert", { type: "info" }, …children]; a nested block takes one more colon (:::card … :::), a block with nothing after it (::divider) needs no closing line, and its first lines between two --- lines are YAML props, under the {} ones. A line #title inside a block starts the named slot ["template", { slot: "title" }, …]. Inline, :badge[New]{color="green"} becomes ["badge", { color: "green" }, "New"], [text]{.note #intro} becomes ["span", { class: "note", id: "intro" }, "text"], and {{ $doc.author }} is the frontmatter value as text. {% alert type="info" %} … {% /alert %} is the same block. Attributes are key="value", key=value, key alone (true), :key='<JSON>', .class and #id; names are kebab case (::MyCard is my-card). Nothing in code is read, and a colon that starts none of these forms (10:30, a::b) stays text.
::card{:tags='["a","b"]'}
#title
Hello :badge[New]{color="green"}
::
Every heading gets an id by GitHub's rules: the text lower-cased, everything but letters, digits, -, _ and spaces removed, spaces replaced by -. A repeated heading gets -1, -2 and so on, and a heading with no such characters gets section.
Errors start with file when it is given:
| Case | Message |
|---|---|
| invalid YAML | post.md:3: frontmatter: YAML Parse error: Unexpected token, with the line in the file |
| frontmatter that is not a mapping | post.md:1: frontmatter must be a mapping (got array) |
no closing --- | post.md:1: frontmatter is not closed by a --- line |
| an alias that makes a cycle | post.md:1: frontmatter: alias *a makes a cycle; the value must be JSON |
| a line list that is not numbers and ranges | post.md:8: fence {1,a}: a line list holds numbers and ranges (got "a") |
| a block with no closing line | post.md:12: ::alert is not closed; add a line :: after its body |
| a closing line that matches no open block | post.md:20: ::: closes no component |
| a component named like a Markdown element | post.md:3: ::table: "table" is a Markdown element; give the component another name |
bad JSON in a :key attribute | post.md:7: :count="3,": not JSON |
an attribute list with no } | post.md:7: {type="info" is not closed by } |
| YAML props that are not a mapping | post.md:4: ::alert props must be a mapping (got array) |
| a slot line outside a block | post.md:9: #title is a slot and needs an enclosing component |
| a Markdoc close that does not match | post.md:15: {% /card %} closes {% alert %} |
| U+FDD0 – U+FDD2 in the source | post.md:2: U+FDD0 is reserved by Hamur's Markdown pre-pass |
| components or spans nested more than 64 levels | post.md:3: components and spans nest more than 64 levels deep |
A binding to a frontmatter field that does not exist renders as nothing, and the build warns [markdown] post.md:5: {{ $doc.autor }}: frontmatter has no "autor".
import { parseMarkdown } from "hamur/markdown"
const post = await parseMarkdown(await Bun.file("content/post.md").text(), { file: "content/post.md" })
post.ast // ["root", {}, ["h1", { id: "hello" }, "Hello"], ["p", {}, "First paragraph."]]
toc
function toc(headings: MdHeading[], options?: { depth?: [number, number] }): TocLink[]
Nests the headings whose depth is in depth (default [2, 3]) under the nearest shallower kept heading, in document order. A skipped level nests as you read it: an h4 after an h2 is a child of that h2. A heading shallower than every open entry starts a new top-level entry. MarkdownDocument.toc is toc(headings, markdown.toc); call toc with document.headings to get another range.
import { toc } from "hamur/markdown"
toc(post.headings, { depth: [2, 4] }) // [{ id: "intro", text: "Intro", depth: 2, children: [{ id: "setup", text: "Setup", depth: 4, children: [] }] }]
renderMarkdownAst
function renderMarkdownAst(
node: MdNode | MdNode[],
options?: {
components?: Record<string, (props: MdProps, children: string, slots: Record<string, string>) => string>
html?: boolean
},
): string
Writes the HTML that Bun.markdown.html writes for the same document, with Hamur's heading ids. It uses no Bun or Node API, so it runs on every preset, in Workers and in the browser.
- Text and attribute values are escaped. An
htmlnode is written as it is only with the optionhtml: true, and left out otherwise, so an AST read at run time (stored JSON, a CMS) cannot write markup; passhtml: truefor a document parsed withhtml: truefrom a source you trust. hrefandsrcare percent-encoded likeBun.markdown.htmldoes. A scheme thatapp.linkProtocolsdoes not list (javascript:,data:,vbscript:by default) giveshref="#", asLinkdoes, and an empty value in the other URL attributes (src,action,formaction,poster,cite,data,ping,background); such asrcsetcandidate is left out.- Only a lowercase HTML attribute name (
/^[a-z][a-z0-9-]*$/) orxlink:hrefis written, never one starting withon, norstyle,keyorref; soinnerHTML,textContent,prop:xor.xare left out, as in everyMarkdownRenderer. A prop that istrueis written bare, and one that isfalseornullis left out.prewrites itslanguageasclass="language-<lang>"on itscodechild and does not writefilename,highlightsormeta. A task-listligets the checkbox markup ofBun.markdown.html. - A tag that is not a Markdown element is a component: it renders through
components[tag], which gets the props, the rendered default slot and the rendered named slots by name ({ title: "…" }). Withcomponentsgiven, a tag it lacks logs[markdown] no component for "alert"once. Without one, a custom element name (with a hyphen, such asx-card) renders as that element, and any other tag (script,iframe,alert) renders as its children only.
import { renderMarkdownAst } from "hamur/markdown"
renderMarkdownAst(["root", {}, ["p", {}, "1 < 2 ", ["a", { href: "javascript:alert(1)" }, "x"]]])
// <p>1 < 2 <a href="#">x</a></p>
renderMarkdownAst(["alert", { type: "info" }, "Hi"], {
components: { alert: (_props, children) => `<div role="note">${children}</div>` },
})
// <div role="note">Hi</div>
MarkdownDocument
| Field | Type | What |
|---|---|---|
ast | MdRoot | the document |
frontmatter | Record<string, unknown> | the frontmatter, {} without one |
title | string | undefined | frontmatter title, else the text of the first h1 (contentHeading) |
description | string | undefined | frontmatter description, else the text of the first paragraph |
excerpt | MdRoot | undefined | the top-level nodes before a <!--more--> line, which is removed from ast; without one, the first top-level paragraph; undefined when there is neither |
headings | MdHeading[] | every heading in order, inside components up to toc.searchDepth levels deep |
toc | TocLink[] | the headings in toc.depth, each nested under the nearest shallower one |
text | string | the text outside code blocks and raw HTML, one space between blocks |
readingTime | number | minutes to read text: its words (runs of letters or digits) over wordsPerMinute, rounded up, at least 1 |
components | string[] | the Markdown component names the document uses, nested ones included, sorted, once each |
assets | string[] | relative image URLs (./logo.png) as written |
MdNode, MdElement, MdRoot, MdProps, MdHeading, TocLink
A node is a string (text, never escaped) or an element [tag, props, ...children], such as ["h2", { id: "intro" }, "Intro"]. Adjacent strings are merged.
type MdNode = string | MdElement
type MdElement = [tag: string, props: MdProps, ...children: MdNode[]]
type MdRoot = ["root", MdProps, ...MdNode[]]
type MdProps = Record<string, MdValue>
type MdValue = string | number | boolean | null | MdValue[] | { [key: string]: MdValue }
interface MdHeading {
depth: number
id: string
text: string
}
interface TocLink {
id: string
text: string
depth: number
children: TocLink[]
}
| Tag | Props |
|---|---|
p, blockquote, ul, thead, tbody, tr, em, strong, del, u, code, hr, br | none |
h1 – h6 | id |
ol | start |
li | checked in a task list |
pre | language, filename, highlights, meta; one child ["code", {}, text] |
th, td | align: "left", "center" or "right" |
a | href, title; a wiki link [[Page|label]] is ["a", { href: "Page" }, "label"] |
img | src, alt, title |
html | none; one text child, the raw HTML, only with html: true; text, the code it stands for, on the node a markdown:highlight hook's HTML makes |
span | class, id and the other attributes of [text]{…} |
template | slot: a named slot of a component |
| any other tag | a Markdown component and its props |
MarkdownOptions, ParseMarkdownOptions
MarkdownOptions is the type of the markdown key of HamurConfig. ParseMarkdownOptions adds file, the path that starts every error message, and siteUrl, the origin externalLinks compares against (the build passes site.url).
| Option | Type | Default | What |
|---|---|---|---|
html | boolean | false | keep raw HTML as html nodes |
autolinks | boolean | { url?, www?, email? } | true | GFM autolinks; www. links get http://, addresses mailto: |
hardSoftBreaks, underline, latexMath, wikiLinks | boolean | false | passed to Bun.markdown under the same names |
contentHeading | boolean | true | title falls back to the first h1 |
toc | false | { depth?: [number, number]; searchDepth?: number } | { depth: [2, 3], searchDepth: 2 } | the heading depths that enter toc; false leaves it empty |
headingLinks | false | "prepend" | "wrap" | false | "prepend" inserts <a class="heading-anchor" href="#id" aria-hidden="true">#</a> before the heading's text, "wrap" wraps the text in <a href="#id">; written into the AST, so every renderer prints it, and text, headings and toc do not contain it |
headingLinkDepth | number[] | [2, 3, 4] | the heading depths that get a link |
externalLinks | false | { target?: string; rel?: string[] } | false | an a whose href is an absolute http(s) URL with another origin than site.url (any absolute one without site.url) gets target (default "_blank") and rel (default ["noopener", "noreferrer"], joined by spaces); written into the AST, so every renderer prints it |
wordsPerMinute | number | 200 | the reading speed of readingTime; must be a positive number |
remarkPlugins, rehypePlugins | Array<Attacher | [Attacher, options]> | [] | imported attachers, run by the build on every .md page and import; see Plugins. parseMarkdown called by itself runs none |
highlight | false | { langs?: string[]; excludeLangs?: string[]; theme?: HighlightTheme } | on, no theme CSS | the tokenizer's languages to colour: false none, langs only these, excludeLangs all but these, by name or alias, a built-in language or one a module added (checked once modules have run); a name no language has is markdown.highlight.langs[0] "cobol" is not a tokenizer language (have: ts, tsx, js, jsx, json, css, html, bash, vue, svelte, yaml, toml, markdown, diff, sql, graphql, python, go, rust, shell-session). theme picks the colours, see Themes |
file | string | ParseMarkdownOptions only | |
siteUrl | string | ParseMarkdownOptions only |
Plugins
markdown.remarkPlugins and markdown.rehypePlugins take unified-style plugins that the app installed or wrote: each entry is the imported attacher, or [attacher, options]. Hamur calls attacher(options) and then the transformer it returns with (tree, file). Hamur has no unified, remark or rehype dependency: remark plugins get an mdast view of the Markdown AST, rehype plugins a hast view, and the result is converted back. Remark plugins run before heading ids, rehype plugins after heading ids and external links and before headingLinks; title, headings, toc and text are read from the result.
// hamur.config.ts
import { defineConfig } from "hamur"
import remarkUpper from "./plugins/remark-upper.ts"
import rehypeH2Class from "rehype-h2-class"
export default defineConfig({
markdown: {
remarkPlugins: [remarkUpper],
rehypePlugins: [[rehypeH2Class, { className: "section" }]],
},
})
- A transformer may return a new tree, a promise, or take a third parameter
next(error, tree), as in unified. filehaspath(the file relative to the app root),value(the source),data(an object shared by every plugin of the document),history,messages,message(reason), which records a message and logs it as a build warning, andfail(reason), which stops the build with<file>: <reason>.- The views hold only the node types the Markdown AST has a form for: in mdast
root,paragraph,heading,blockquote,list,listItem,code,thematicBreak,break,table,tableRow,tableCell,emphasis,strong,delete,inlineCode,link,image,inlineMath,html,textDirective,containerDirectiveandtext(data.hNameanddata.hPropertiesare read back); in hastroot,element,textandraw. - What a plugin adds renders through the same rules as the parser's own output: an
onclick, astyle, a<script>element or ajavascript:link never reaches the page, and arawnode is written only withmarkdown.html: true.
| Case | Message |
|---|---|
| a string in place of the imported plugin | markdown.remarkPlugins[0] is "remark-foo", a string; import the plugin and list it: import remarkFoo from "remark-foo" |
| an entry that is not a function | markdown.rehypePlugins[1] must be an imported plugin or [plugin, options] (got an object) |
a plugin that reads the unified processor (this.data, this.parser) | post.md: remark plugin "remark-foo" needs a unified processor, which Hamur does not provide |
| a plugin that leaves another node type | post.md: remark plugin "remark-foo" left a "footnoteReference" node, which the Markdown AST has no form for |
| a plugin that throws | post.md: rehype plugin "rehype-x" failed: <message> |
Highlighting
Code blocks are coloured where the document is parsed, at build (and by parseMarkdown on the bun preset), so a page ships the coloured markup and no client JS. For each pre whose code holds plain text (a block a rehype plugin already changed is left alone):
- The build hook
markdown:highlightruns first, for Markdown pages,.mdimports and@hamur/contententries (a module parses throughuseMarkdownParser), with or without@hamur/content. It gets aHighlightBlock; the first hook result that is notundefinedwins. A Markdown AST node (a["root", {}, …]gives its children) replaces the text ofcode; a string is HTML and becomes["html", { text: <source> }, html], which a Markdown page renders even withmarkdown.html: false, since the app's own build code wrote it. A renderer that does not write raw HTML (aContentRendererorMarkdownRendererwithoutraw,renderMarkdownAstwithouthtml: true) writes the node'stextinstead, andProsePre'scodeis that source either way. - Otherwise, for a language of the tokenizer that
markdown.highlightallows,highlightcolours the block, and each line listed inhighlightsgets the classline line-highlight. - Otherwise the block stays text, and
codegetsclass="language-<lang>"as before.
// hamur.config.ts
import { defineConfig } from "hamur"
export default defineConfig({
hooks: {
"markdown:highlight": ({ code, language }) =>
language === "diff" ? ["span", { class: "my-diff" }, code] : undefined,
},
})
The tokenizer writes classes; the colours come from the theme CSS, or from the app's own CSS for .tok-keyword, .tok-string and the other kinds when the app styles them itself. A module adds a language with addHighlightLanguage; the build's tokenizer uses it, and the bun preset's run-time parseMarkdown does not.
| Case | Message |
|---|---|
| a highlighted line beyond the block | the warning [markdown] post.md:8: fence {12}: the block has 9 lines; the line is ignored |
| a hook that throws | post.md:8: markdown:highlight failed: <message> |
| a hook result of another type | post.md:8: markdown:highlight returned number; return a Markdown AST node, an HTML string or undefined |
a theme name that is not shipped | markdown.highlight.theme.light "nord" is not a theme (have: hamur-light, hamur-dark, github-light, github-dark) |
| a language a module adds with a taken name or alias | addHighlightLanguage: "ts" is already a language |
| a module's tokens that do not join to the block's code | addHighlightLanguage: the tokens of "mini" must join, with a newline between lines, to the code of the block |
A hook's Markdown AST renders by the same rules as the parser's: a tag that is not a Markdown element is read as a component, so a hook writes span elements.
Themes
markdown.highlight.theme is { light: string; dark?: string }, each a shipped theme: hamur-light, hamur-dark, github-light or github-dark. With theme set (and highlight not false) the build writes .hamur/markdown/highlight.css and adds it to the global CSS, in hamur build and hamur dev, whether or not any Markdown is parsed; without theme the app ships no theme CSS and styles the tok-* classes itself. The file sets --tok-keyword, --tok-string and one variable for each other token kind, and --tok-line-highlight, --tok-line-added and --tok-line-removed, on :root for light; the dark set goes under @media (prefers-color-scheme: dark) on :root:not([data-theme="light"]) and under :root[data-theme="dark"]. The rules that follow (.tok-keyword { color: var(--tok-keyword); }, and .line-highlight, .line-added and .line-removed backgrounds) use the variables, so an app overrides a colour by setting the variable. Without dark, there are no dark rules. A theme of the app's own is its own CSS for the tok-* classes, with markdown.highlight.theme left alone or the CSS loaded after the theme's.
HighlightTheme
interface HighlightTheme {
light: string
dark?: string
}
The type of markdown.highlight.theme.
HighlightBlock
interface HighlightBlock {
code: string // the block's text
language: string // as written in the fence, "" without one
meta: string // the info string after the language, "" without one
filename?: string // from [name] in the meta
highlights: number[] // from {1,3-4} in the meta, sorted
file?: string // the document, relative to the app root
}
hamur/markdown/highlight
Hamur's tokenizer: a hand-written scanner per language, linear in the length of the code, with no regular-expression grammar and no dependency. It runs anywhere, in the build, on every preset and in the browser.
highlight
function highlight(code: string, language: string): MdNode[] | undefined
The lines of code as Markdown AST nodes, or undefined for a language the tokenizer does not know. Each line is ["span", { class: "line" }, …tokens] and lines are joined by "\n", so the text of the result is code; a token is ["span", { class: "tok-<kind>" }, text] and plain text stays a string. The kinds are keyword, string, number, comment, function, type, variable, property, operator, punctuation, tag, attribute, regexp, constant, builtin and meta. The scanners know strings, template literals with nested ${}, comments, regular-expression literals, numbers and JSX and HTML tags; vue and svelte are HTML whose <script> and <style> bodies, directive values, {{ }} and {…} are read as script and CSS.
import { highlight } from "hamur/markdown/highlight"
highlight("let a", "ts")
// [["span", { class: "line" }, ["span", { class: "tok-keyword" }, "let"], " ", ["span", { class: "tok-variable" }, "a"]]]
highlightLanguages, HighlightLanguage
interface HighlightLanguage {
name: string
aliases: string[]
}
const highlightLanguages: readonly HighlightLanguage[]
| Name | Aliases |
|---|---|
ts | typescript, mts, cts |
tsx | |
js | javascript, mjs, cjs |
jsx | |
json | jsonc |
css | |
html | htm |
bash | sh, shell, zsh |
vue | |
svelte | |
yaml | yml |
toml | |
markdown | md |
diff | |
sql | |
graphql | gql |
python | py |
go | |
rust | rs |
shell-session | console |
In diff, a line that starts with + or - gets the class line line-added or line line-removed, after the file headers (---, +++) and until the next diff line; a highlighted line adds line-highlight to its classes. In shell-session, a line that starts with a prompt ($, #, % or >, or one after user@host:~) is read as bash and the other lines are output.
A fence's language matches a name or an alias in any case.