Skip to content

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

ts
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&amp;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.

md
::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:

CaseMessage
invalid YAMLpost.md:3: frontmatter: YAML Parse error: Unexpected token, with the line in the file
frontmatter that is not a mappingpost.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 cyclepost.md:1: frontmatter: alias *a makes a cycle; the value must be JSON
a line list that is not numbers and rangespost.md:8: fence {1,a}: a line list holds numbers and ranges (got "a")
a block with no closing linepost.md:12: ::alert is not closed; add a line :: after its body
a closing line that matches no open blockpost.md:20: ::: closes no component
a component named like a Markdown elementpost.md:3: ::table: "table" is a Markdown element; give the component another name
bad JSON in a :key attributepost.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 mappingpost.md:4: ::alert props must be a mapping (got array)
a slot line outside a blockpost.md:9: #title is a slot and needs an enclosing component
a Markdoc close that does not matchpost.md:15: {% /card %} closes {% alert %}
U+FDD0 – U+FDD2 in the sourcepost.md:2: U+FDD0 is reserved by Hamur's Markdown pre-pass
components or spans nested more than 64 levelspost.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".

ts
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

ts
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.

ts
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

ts
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 html node is written as it is only with the option html: true, and left out otherwise, so an AST read at run time (stored JSON, a CMS) cannot write markup; pass html: true for a document parsed with html: true from a source you trust.
  • href and src are percent-encoded like Bun.markdown.html does. A scheme that app.linkProtocols does not list (javascript:, data:, vbscript: by default) gives href="#", as Link does, and an empty value in the other URL attributes (src, action, formaction, poster, cite, data, ping, background); such a srcset candidate is left out.
  • Only a lowercase HTML attribute name (/^[a-z][a-z0-9-]*$/) or xlink:href is written, never one starting with on, nor style, key or ref; so innerHTML, textContent, prop:x or .x are left out, as in every MarkdownRenderer. A prop that is true is written bare, and one that is false or null is left out. pre writes its language as class="language-<lang>" on its code child and does not write filename, highlights or meta. A task-list li gets the checkbox markup of Bun.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: "…" }). With components given, a tag it lacks logs [markdown] no component for "alert" once. Without one, a custom element name (with a hyphen, such as x-card) renders as that element, and any other tag (script, iframe, alert) renders as its children only.
ts
import { renderMarkdownAst } from "hamur/markdown"

renderMarkdownAst(["root", {}, ["p", {}, "1 < 2 ", ["a", { href: "javascript:alert(1)" }, "x"]]])
// <p>1 &lt; 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

FieldTypeWhat
astMdRootthe document
frontmatterRecord<string, unknown>the frontmatter, {} without one
titlestring | undefinedfrontmatter title, else the text of the first h1 (contentHeading)
descriptionstring | undefinedfrontmatter description, else the text of the first paragraph
excerptMdRoot | undefinedthe top-level nodes before a <!--more--> line, which is removed from ast; without one, the first top-level paragraph; undefined when there is neither
headingsMdHeading[]every heading in order, inside components up to toc.searchDepth levels deep
tocTocLink[]the headings in toc.depth, each nested under the nearest shallower one
textstringthe text outside code blocks and raw HTML, one space between blocks
readingTimenumberminutes to read text: its words (runs of letters or digits) over wordsPerMinute, rounded up, at least 1
componentsstring[]the Markdown component names the document uses, nested ones included, sorted, once each
assetsstring[]relative image URLs (./logo.png) as written

A node is a string (text, never escaped) or an element [tag, props, ...children], such as ["h2", { id: "intro" }, "Intro"]. Adjacent strings are merged.

ts
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[]
}
TagProps
p, blockquote, ul, thead, tbody, tr, em, strong, del, u, code, hr, brnone
h1 – h6id
olstart
lichecked in a task list
prelanguage, filename, highlights, meta; one child ["code", {}, text]
th, tdalign: "left", "center" or "right"
ahref, title; a wiki link [[Page|label]] is ["a", { href: "Page" }, "label"]
imgsrc, alt, title
htmlnone; 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
spanclass, id and the other attributes of [text]{…}
templateslot: a named slot of a component
any other taga 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).

OptionTypeDefaultWhat
htmlbooleanfalsekeep raw HTML as html nodes
autolinksboolean | { url?, www?, email? }trueGFM autolinks; www. links get http://, addresses mailto:
hardSoftBreaks, underline, latexMath, wikiLinksbooleanfalsepassed to Bun.markdown under the same names
contentHeadingbooleantruetitle falls back to the first h1
tocfalse | { depth?: [number, number]; searchDepth?: number }{ depth: [2, 3], searchDepth: 2 }the heading depths that enter toc; false leaves it empty
headingLinksfalse | "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
headingLinkDepthnumber[][2, 3, 4]the heading depths that get a link
externalLinksfalse | { target?: string; rel?: string[] }falsean 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
wordsPerMinutenumber200the reading speed of readingTime; must be a positive number
remarkPlugins, rehypePluginsArray<Attacher | [Attacher, options]>[]imported attachers, run by the build on every .md page and import; see Plugins. parseMarkdown called by itself runs none
highlightfalse | { langs?: string[]; excludeLangs?: string[]; theme?: HighlightTheme }on, no theme CSSthe 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
filestringParseMarkdownOptions only
siteUrlstringParseMarkdownOptions 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.

ts
// 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.
  • file has path (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, and fail(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, containerDirective and text (data.hName and data.hProperties are read back); in hast root, element, text and raw.
  • What a plugin adds renders through the same rules as the parser's own output: an onclick, a style, a <script> element or a javascript: link never reaches the page, and a raw node is written only with markdown.html: true.
CaseMessage
a string in place of the imported pluginmarkdown.remarkPlugins[0] is "remark-foo", a string; import the plugin and list it: import remarkFoo from "remark-foo"
an entry that is not a functionmarkdown.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 typepost.md: remark plugin "remark-foo" left a "footnoteReference" node, which the Markdown AST has no form for
a plugin that throwspost.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):

  1. The build hook markdown:highlight runs first, for Markdown pages, .md imports and @hamur/content entries (a module parses through useMarkdownParser), with or without @hamur/content. It gets a HighlightBlock; the first hook result that is not undefined wins. A Markdown AST node (a ["root", {}, …] gives its children) replaces the text of code; a string is HTML and becomes ["html", { text: <source> }, html], which a Markdown page renders even with markdown.html: false, since the app's own build code wrote it. A renderer that does not write raw HTML (a ContentRenderer or MarkdownRenderer without raw, renderMarkdownAst without html: true) writes the node's text instead, and ProsePre's code is that source either way.
  2. Otherwise, for a language of the tokenizer that markdown.highlight allows, highlight colours the block, and each line listed in highlights gets the class line line-highlight.
  3. Otherwise the block stays text, and code gets class="language-<lang>" as before.
ts
// 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.

CaseMessage
a highlighted line beyond the blockthe warning [markdown] post.md:8: fence {12}: the block has 9 lines; the line is ignored
a hook that throwspost.md:8: markdown:highlight failed: <message>
a hook result of another typepost.md:8: markdown:highlight returned number; return a Markdown AST node, an HTML string or undefined
a theme name that is not shippedmarkdown.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 aliasaddHighlightLanguage: "ts" is already a language
a module's tokens that do not join to the block's codeaddHighlightLanguage: 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

ts
interface HighlightTheme {
  light: string
  dark?: string
}

The type of markdown.highlight.theme.

HighlightBlock

ts
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

ts
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.

ts
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

ts
interface HighlightLanguage {
  name: string
  aliases: string[]
}
const highlightLanguages: readonly HighlightLanguage[]
NameAliases
tstypescript, mts, cts
tsx
jsjavascript, mjs, cjs
jsx
jsonjsonc
css
htmlhtm
bashsh, shell, zsh
vue
svelte
yamlyml
toml
markdownmd
diff
sql
graphqlgql
pythonpy
go
rustrs
shell-sessionconsole

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.