AssemblyScript
AssemblyScript looks like TypeScript and compiles straight to WebAssembly, so it's the closest you can get to writing a module in the language your page code is in. Its modules are tiny: the summary example is 10 KB, its first call compiles in about 13 ms, and later calls load it from the cache in half a millisecond.
It looks like TypeScript, but it isn't: types are WebAssembly's (i32, f64, u8), there's no any and no union types, and npm packages written for JavaScript don't work in it. Only packages written for AssemblyScript do.
Set up
AssemblyScript builds for the browser by default. @assemblyscript/wasi-shim makes it build a WASI program instead, with process.argv, process.stdin, process.stdout and process.exit:
npm install --save-dev --save-exact assemblyscript @assemblyscript/wasi-shim
asconfig.json extends the shim's settings and sets the release build:
{
"extends": "./node_modules/@assemblyscript/wasi-shim/asconfig.json",
"targets": {
"release": {
"outFile": "summary.pb.wasm",
"optimizeLevel": 3,
"shrinkLevel": 2,
"noAssert": true,
"runtime": "stub"
}
}
}
- The shim is required. Without it, a module imports
env.abortfrom the browser's world, and it's refused when it loads. "runtime": "stub"leaves out the garbage collector: a call reads, computes and exits, so nothing needs collecting, and the module is smaller. A module that builds large data in a loop can use"incremental"instead.
The module
example/summary/assemblyscript counts the words of a text and returns the first twelve. AssemblyScript's standard library has no JSON, so, like the C example, it takes the text as it is (your code can pass a string) and prints JSON:
// what `summary --describe` prints: AssemblyScript can't embed a file, so the manifest is a string here
const manifest = `{ "description": "Summarizes a text: its first words, and a word count", ... }`
function fail(code: string, message: string): void {
process.stderr.write(`{"code":"${code}","message":"${message}"}`)
process.exit(1)
}
const fn = process.argv.length > 1 ? process.argv[1] : ""
if (fn == "--describe") {
process.stdout.write(manifest)
} else if (fn != "run") {
fail("no_such_function", "only run")
} else {
const text = readStdin() // process.stdin.read() into a growing buffer, then String.UTF8.decode
// ... split into words, keep the first 12
process.stdout.write(`{"text":${jsonString(short)},"words":${words.length}}`)
}
To take JSON in, add a JSON package written for AssemblyScript, such as json-as.
Build
npx asc assembly/index.ts --target release
cp summary.pb.wasm pb_hooks/
The manifest says "language": "AssemblyScript", since the module doesn't say it itself.
Call it
An API route that saves a post with its summary and word count:
// pb_pages/posts.ts
export async function post(ctx: any) {
const { body } = ctx.req.body()
const out = await $wasm.run.async<{ text: string; words: number }>("summary", String(body ?? "")) // a string goes in as it is
const record = new Record(ctx.app.findCollectionByNameOrId("posts"))
record.load({ body, summary: out.text, words: out.words })
ctx.app.save(record)
return ctx.res.json(201, { id: record.id, summary: out.text, words: out.words })
}
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.