Markdown to HTML

What it's for

Your users write posts, docs or product descriptions in Markdown, and your pages show HTML. Render it once, when the record is saved, and keep the HTML beside the Markdown: pages then show it with no work per view. The module is pulldown-cmark, the CommonMark parser behind rustdoc and mdBook, with tables, strikethrough and task lists on.

The route

A posts collection with a body text field (the Markdown) and an html text field:

// pb_pages/posts.ts: posts are written in Markdown; html is what your pages show
async function renderPost(markdown: string): Promise<string> {
  const html = (await $wasm.run.async<string | null>("markdown", markdown || "")) ?? ""
  return (await $wasm.run.async<string | null>("sanitize-html", html)) ?? "" // users wrote it: keep only safe HTML
}

export async function post(ctx: any) {
  if (!ctx.auth) throw ctx.httpError(401, "Sign in to post")
  const { body } = ctx.req.body()
  const record = new Record(ctx.app.findCollectionByNameOrId("posts"))
  record.load({ body, html: await renderPost(body) })
  ctx.app.save(record)
  return ctx.res.json(201, { id: record.id })
}

A route that saves an edit sets html the same way, from the new body, before it saves.

CommonMark passes raw HTML through, so <script> in a post would reach your pages. The second call runs the result through sanitize-html, which keeps the formatting and drops scripts, event handlers and javascript: links. Leave it out only for Markdown you wrote yourself.

?? "" is there because an empty output comes back as null.

The module

The Markdown is the module's stdin, as text, and the HTML is its stdout (src/main.rs):

let mut input = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut input) {
    fail("bad_input", &format!("the input isn't UTF-8 text: {e}"));
}
let opts = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS;
let mut out = String::with_capacity(input.len() * 3 / 2);
html::push_html(&mut out, Parser::new_ext(&input, opts));
std::io::stdout().write_all(out.as_bytes()).unwrap();

Other options (footnotes, heading ids, smart punctuation) are one more flag each.

Build

cd ext/wasm/example/markdown
cargo build --release --target wasm32-wasip1   # rustup target add wasm32-wasip1 first
cp target/wasm32-wasip1/release/markdown.wasm pb_hooks/markdown.pb.wasm

Cost

258 KB. The first call compiles it (about 60 ms); later calls load it from the cache in about 2.5 ms and render a short post in under 1 ms. With sanitize-html after it, a save takes under 10 ms more than without, once both are in the cache.

Limits

  • Input and output are each at most 4 MB (MaxPayload).
  • Each call still loads and starts the module (a few ms), so render on save, not on every page view.