WASM

Bring your own WASM. Your page code is TypeScript, and most of the time that's all you need. Sometimes it isn't: the library you need only exists in Rust or Go, or the work (parsing, image processing, crypto, number crunching) is too slow in JS. WASM lets your page code call code written in another language, compiled to WebAssembly, as if it were a JavaScript function:

const out = await $wasm.run.async<{ greeting: string }>("hello", { name: "pocket" })
// out is { greeting: "Hello, POCKET!" }

It's built into pocketone. There's nothing to install and nothing to configure: put a module in pb_hooks/ and call it from your page code.

How it works

A module is a small program compiled to WebAssembly: a .pb.wasm file in pb_hooks/. A call works like running a command-line tool:

  1. Your code calls $wasm.run.async(name, input).
  2. The module starts fresh, reads the input, and writes its answer.
  3. Your code gets the answer back, parsed from JSON, and carries on.

The module runs in a sealed box. It can't touch your database, your files, the network or other programs; it sees only the input your code gives it, and its answer goes only back to your code. Your code stays in charge: it decides what goes in and what to do with what comes out. A module that crashes, loops or runs out of memory fails its own call, and the app goes on.

Try it in two minutes

You don't need a compiler to try it. The Markdown module from the recipes is kept built in the repository. In your app's folder:

curl -L -o pb_hooks/markdown.pb.wasm \
  https://github.com/pocketonehq/pocketone/raw/main/ext/wasm/example/markdown/markdown.pb.wasm

Add an API route that saves a note with its Markdown rendered to HTML:

// pb_pages/notes.ts
export async function post(ctx: any) {
  const { body } = ctx.req.body()
  const note = new Record(ctx.app.findCollectionByNameOrId("notes"))
  note.load({ body, html: await $wasm.run.async<string>("markdown", body) })
  ctx.app.save(note)
  return ctx.res.json(201, { id: note.id, html: note.getString("html") })
}

Make a notes collection with two text fields, body and html, then post a note with # Hello and some **bold** text in its body:

curl -X POST localhost:8090/notes -H "Content-Type: application/json" -d '{"body":"# Hello\n\nSome **bold** text"}'

The saved note's html field is the rendered HTML. This module passes raw HTML through, so for text your users write, add Sanitize HTML after it.

Write your first module

A module is an ordinary program: it reads its input from stdin and prints its answer to stdout. Here's one in Go:

// main.go
package main

import (
	"encoding/json"
	"os"
	"strings"
)

func main() {
	var in struct {
		Name string `json:"name"`
	}
	json.NewDecoder(os.Stdin).Decode(&in)
	if in.Name == "" {
		os.Stderr.WriteString(`{"code":"no_name","message":"say who to greet"}`)
		os.Exit(1)
	}
	json.NewEncoder(os.Stdout).Encode(map[string]string{
		"greeting": "Hello, " + strings.ToUpper(in.Name) + "!",
	})
}

Build it into your pb_hooks/. Go can build WebAssembly with nothing extra; TinyGo makes the same program 15 times smaller and much faster to call:

GOOS=wasip1 GOARCH=wasm go build -o pb_hooks/hello.pb.wasm .                    # Go: 4.3 MB
tinygo build -target=wasip1 -opt=z -no-debug -scheduler=none -o pb_hooks/hello.pb.wasm .   # TinyGo: 284 KB

Call it from an API route:

// pb_pages/hello/[name].ts
export async function get(ctx: any) {
  const out = await $wasm.run.async<{ greeting: string }>("hello", { name: ctx.params.name })
  return ctx.res.json(out)
}
curl localhost:8090/hello/pocket
# {"greeting":"Hello, POCKET!"}

That's the whole contract:

  • Input: your code's value arrives on stdin, as JSON (a string or bytes arrive as they are).
  • Output: what the module prints comes back to your code, parsed if it's JSON.
  • Errors: to fail, the module exits non-zero. If it prints {"code", "message"} to stderr, your code's catch gets those as err.code and err.message.

Good to know

  • Calls are async. Use await $wasm.run.async(...) in an async handler. The module runs off the JS engine, so the rest of your app keeps serving requests while it works.
  • Every call starts fresh. Nothing carries over from one call to the next, so a module can't remember anything. When it needs to, your code keeps the state and passes it in: see Keeping state in JS.
  • The first call compiles, later calls don't. A module's first call compiles it and keeps the result on disk; every later call, after a restart too, loads it from there. A C, Rust or Zig module takes 17 to 33 ms the first time and 1 to 2 ms after; a Go module about a second, then 38 ms. Choosing a language compares them.
  • Modules deploy with your app. They live in pb_hooks/, so git, pocketone deploy and anything else that ships pb_hooks/ ships them too. Replacing a module's file takes effect on the next call.

Next

  • Choosing a language: C and C++, Go, TinyGo, Rust, Zig, AssemblyScript, and what else runs.
  • Recipes: modules built on real libraries, each with page code that calls it: Markdown, HTML sanitizing, thumbnails, QR codes, diffs, CSV.
  • Keeping state in JS: modules that work on a series, with the state held by your app.
  • Extension reference: every call, error code, limit and setting, and how it works inside.