JSVM

Version 0.2.0 · Owners: @benallfree

PocketOne's JS engine for pb_hooks and pb_migrations. It runs the same JS API as PocketBase ($app, onX, routerAdd, cronAdd, $http, $security, ...) on QuickJS, with one VM per app:

  • Real globals. Every hook file runs in the app's one global scope, so top-level helpers, constants and state are visible to every handler. No more require() inside each handler.
  • ES modules. *.pb.mjs (and TypeScript *.pb.ts/*.pb.mts) hook files and modules use import/export, including top-level await; *.pb.js and *.pb.cjs stay scripts with require(). Both share the same module instances.
  • TypeScript. .ts, .mts and .cts hooks, migrations and modules run directly (types stripped by esbuild, linked into the binary), with error positions in your .ts source.
  • Async. Handlers can be async. Every Go function has an .async(...) twin that runs off the VM and returns a promise, so one app serves other requests while it waits: await $app.findRecordById.async("posts", id).
  • Timers. setTimeout, setInterval, clearTimeout, clearInterval and queueMicrotask, as in browsers and Node.js. A timer set while serving a request is cleared once the request is answered or its client goes away.
  • Cancellation. Go contexts, as in PocketBase: TimeoutContext and $app.withContext(ctx), plus CancelContext for stopping work for any other reason. A Go function that takes a context.Context gets one, and fn.async(ctx, ...args) rejects as soon as ctx ends.
  • Hard limits per app. A memory cap (JS heap plus Go objects JS holds), a CPU and a wall-clock budget per task, and caps on queued tasks and async calls. A runaway script stops with an error; other apps in the process keep running.
  • Real error positions. Stack traces name pb_hooks/<file>:<line>.

Every PocketOne app runs on it: a standalone app or an instance on a multisite host, whatever the runtime. PocketBase's own plugins/jsvm (goja) is for pure PocketBase compatibility only: jsvm: goja under app: in pocketone.yaml (or --jsvm goja) runs a standalone app on it, with pages, $mcp, $apiTokens, $bulkmail and JS contracts off.

Install · Configure · Use · Integrations · Example

Install

The engine is pure Go (QuickJS translated to Go by modernc.org/libquickjs, the way PocketBase uses modernc.org/sqlite), so it needs no cgo: CGO_ENABLED=0 builds and cross-compiles work as with stock PocketBase. In your own Go build, register it where you'd register plugins/jsvm:

jsvm.MustRegister(app, jsvm.Config{HooksDir: "pb_hooks", MigrationsDir: "pb_migrations"})

The module is pocketone.dev/ext/jsvm.

Configure

Config takes PocketBase's jsvm fields (HooksDir, HooksWatch, HooksFilesPattern, MigrationsDir, MigrationsFilesPattern, TypesDir; HooksPoolSize is accepted and ignored) plus:

  • OnInit func(rt js.Runtime): add globals after everything else is set up.
  • VM: the limits. MemoryLimit (JS heap plus the Go objects JS holds, default 64 MiB), TaskBudget (JS time per stretch, default 5 s), TaskWall (wall time per stretch, sync Go calls included, default 30 s), AwaitLimit (a whole async handler, awaits included, default 15 min), WaitTimeout (a handler's synchronous part, queue wait included, default 30 s), QueueSize, MaxAsync, MaxTimers (timers pending at once, default 1024), MaxPumpDepth. A stretch is the JS between two awaits, so time spent awaiting an .async call counts only toward AwaitLimit. Past AwaitLimit, or when the HTTP request a handler serves ends (the client went away), the call fails and the handler stops at its next await: async calls it started are dropped when they finish and new ones throw. A detached promise outlives its handler. A timer belongs to the call that set it: each run is a task of its own (its own TaskBudget and TaskWall), it's cleared when that call is given up, and for a request also when the request is answered. Timers set at the top of a file run until cleared. The pocketone binary sets memory, task_time, task_wall and await_time in pocketone.yaml's app: js_limits: (QuickJS hooks). Array methods that walk every index (join, indexOf, slice, forEach, concat, flat, ...) and arrays passed to Go throw a RangeError past MemoryLimit / 16 elements: QuickJS doesn't check TaskBudget inside those loops, and a sparse array (new Array(1e9)) or array-like costs no memory, so the cap is what stops them. No dense array that long fits in MemoryLimit.
  • Extensions: values that extend it (below).

Use

Write hooks and migrations as in PocketBase's JS docs; they run unchanged. What's new:

// pb_hooks/main.pb.js
const cache = new Map()

routerAdd("GET", "/post/{slug}", async (e) => {
	const slug = e.request.pathValue("slug")
	if (!cache.has(slug)) {
		cache.set(slug, await e.app.findFirstRecordByData.async("posts", "slug", slug))
	}
	return e.json(200, cache.get(slug))
})
  • Hook files run before the app opens its database, as in PocketBase, so a $app query at a file's top level fails. Read data in onBootstrap after e.next(), or in a handler:

    let users = null
    onBootstrap((e) => {
    	e.next()
    	users = e.app.findCollectionByNameOrId("users")
    })
    
  • Globals live as long as the app's VM. A restart, a hooks reload or running out of memory starts a fresh one, so keep durable data in the database.

  • After an await, other requests may have run: use e.app, not the global $app, and keep transactions short across awaits (they hold SQLite's write lock).

  • Use .async for anything slow ($http.send, sleep, slow queries). Without it, other requests still run while a call waits, but they nest on one stack and wait on each other: under load, a plain sleep(100) served 19 requests a second where await sleep.async(100) served 481 (benchmark).

  • process.env and a small Buffer (from, toString with utf8, base64, hex) are there.

Cancelling Go calls

A Go function whose first parameter is a context.Context gets one from the engine; JS passes only the other arguments (or a Go context of its own, such as e.request.context(), first). The context is cancelled when the request or hook the call runs for is given up (its client went away, AwaitLimit passed) and when the VM closes, so abandoned work stops instead of running on. Answering the request doesn't cancel it: background work keeps going.

To stop a call early, pass it a Go context of your own as its first argument. new TimeoutContext(seconds, [parent]) ends after a time; new CancelContext([parent]) ends when you call ctx.cancel([reason]), for any other reason (a user pressed stop, another request said so). Make one the other's parent to stop at whichever comes first:

// a model call that gives up after a minute, even in background work after the response was sent
const ctx = new TimeoutContext(60)
try {
	const reply = await callModel.async(ctx, prompt)
} finally {
	ctx.cancel() // frees its timer
}

// stop it yourself, or after a minute, whichever comes first
const stop = new CancelContext()
const either = new TimeoutContext(60, stop)
// elsewhere: stop.cancel("the user pressed stop")

When the context ends, the promise rejects at once with its cause (context deadline exceeded, context canceled, or context canceled: <reason>), and the Go function's context is cancelled with it. The context also ends when the request is given up or the VM closes. A TimeoutContext runs on a Go timer, so it keeps working after the request is answered, where setTimeout is refused.

App methods take no context argument: call them through $app.withContext(ctx), a copy of $app whose queries use ctx (await $app.withContext(ctx).findRecordById.async("articles", id)). A Go function that takes no context can't be stopped; give it one if it should be.

Modules: import and require

Name a file for what it is: .mjs is an ES module, .cjs is CommonJS. A plain .js file is CommonJS, so existing PocketBase hooks run unchanged (inside node_modules, Node's rule applies: "type": "module" in the package's package.json makes its .js files ES modules). TypeScript is written as ES modules, so .ts and .mts are ES modules and .cts is the CommonJS exception.

File Runs as Shares through
pb_hooks/*.pb.mjs, *.pb.ts, *.pb.mts ES module: import, export, top-level await, import.meta export / import; its top-level names are private
pb_hooks/*.pb.js, *.pb.cjs, *.pb.cts script in the app's one global scope, with require() globals
pb_migrations/*.mjs, *.ts, *.mts ES module each migration has its own scope either way
pb_migrations/*.js, *.cjs, *.cts script in its own function scope

All of them run in the app's one VM: scripts and modules share the global object (a module can read a script's globals) and one instance of every module.

// pb_hooks/lib/store.mjs
export const state = { hits: 0 }
export const bump = () => ++state.hits

// pb_hooks/main.pb.mjs
import { bump } from "./lib/store.mjs"
import legacy from "./lib/legacy.cjs"      // CommonJS: module.exports is the default export
import { hello } from "some-package"       // node_modules, CommonJS or ES
const { greeting } = await import("./lib/greeting.mjs")      // top-level await: done before the app serves

routerAdd("GET", "/hit", (e) => e.json(200, { hits: bump() }))
  • import and require() resolve the same way: relative paths (.js, .mjs, .cjs, .json and index.* tried in turn), then node_modules packages by package.json exports (the import or require condition) or main.
  • A module loads once per app, however many files import or require it, so its state is shared by every request. Importing a CommonJS module gives its module.exports as the default export, its keys as named exports, and the same instance require() returns.
  • require() of an ES module returns its namespace (the same instance import gives), as in Node 22, as long as the module has no top-level await; for one that does, use await import("./lib/x.mjs").

TypeScript

.ts, .mts and .cts files run as they are: esbuild strips the types when the file loads, and each file's source map is kept, so an error names pb_hooks/main.pb.mts:12:5 in your source, not in the stripped code.

  • There's no type checking at runtime. Check with tsc --noEmit or your editor; types.d.ts and tsconfig.json in the project root type the whole JS API.
  • Imports may name the compiled file, as TypeScript's NodeNext style does: import { add } from "./math.js" loads math.ts when there's no math.js.
  • import type and other type-only imports disappear, so a *.pb.cts script can use them and stay a script.
  • A .cts module may still be written with import/export; it's turned into CommonJS.

Types

When the app starts, types.d.ts in the project root (the folder holding pb_hooks, next to pb_data and pocketone.yaml) gets the declarations of the whole JS API, for your editor and tsc:

  • PocketBase's API generated from PocketOne's core (its extra hooks included), by PocketBase's own generator.
  • What this engine adds (pocketone.d.ts): .async on every Go function, fully typed (await $app.findRecordById.async(...) is a Promise<core.Record>, and a context.Context first parameter is optional), CancelContext, require, process, Buffer, console, import.meta.
  • Each extension's own API, for the extensions on in that app ($mcp, $apiTokens, $bulkmail, onContracts and the contracts' action hooks).

Beside it, the app writes a tsconfig.json when the folder has none, so your editor and tsc --noEmit work right away. It's yours from then on: the app never overwrites it.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": ["ES2022"],
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "skipLibCheck": true
  },
  "include": ["types.d.ts", "pb_hooks/**/*", "pb_migrations/**/*", "pb_pages/**/*"]
}

skipLibCheck skips two type errors inside PocketBase's own generated declarations. Commit both files: a fresh checkout is then typed before the app first runs, and a diff in types.d.ts shows what an upgrade or a new extension changed in the JS API. Empty hook files get a /// <reference path="../types.d.ts" /> line.

Config.TypesDir puts both somewhere else. With hooks embedded in the binary (Bundle) and no TypesDir, neither is written. In a PocketOne checkout, go generate in ext/jsvm regenerates the declarations after a core change (the TestTypes tests fail until you do).

Integrations

Extensions plug in through Config.Extensions with the engine-neutral types in ext/extkit/js. A value implements any of:

  • OnInit(rt): set up the VM. BindJS(app, rt): expose a Go API. TypeScript(): declare it for editors and tsc (appended to types.d.ts). FilterTypes(decl): change the finished declarations (the sandbox declares what it hides never).
  • OnCall(rt): wrap every handler call; an error refuses it.
  • HTTPClient(rt): the client $http.send uses.
  • HookFiles, MigrationFiles, Modules: hooks, migrations and require() modules from somewhere other than disk.
  • OnLoad(rt, root, file, content): wrap loading each hook file.

js.Run(app, fn) runs Go code on the app's VM; a js.Func kept from JS can be called from any goroutine.

To make your extension's calls cancellable, give the Go function a ctx context.Context first parameter. JS passes the other arguments and the engine fills in the context, which is cancelled when the request is given up.

In PocketBase's JS API, a context comes with the object you call: $app.withContext(ctx) returns a copy of $app whose every call uses ctx, and $app.context() returns it. An extension API that page code can set a time limit on or cancel follows the same convention, with withContext(ctx) and context(), so page code writes $mine.withContext(deadline).completeAsync(...). $llm and $wasm work this way:

// Go: n.Set("call", func(ctx context.Context, kind, op, opts string) (string, error) { ... })
const build = (ctx) => {
  const callAsync = async (kind, op, o) => {
    const s = JSON.stringify(o ?? {})
    return JSON.parse(await (ctx == null ? n.call.async(kind, op, s) : n.call.async(ctx, kind, op, s)))
  }
  return Object.freeze({
    withContext: (c) => build(c),
    context: () => ctx ?? n.background, // n.background: context.Background(), as an unbound $app.context()
    completeAsync: (o) => callAsync("text", "complete", o),
  })
}
globalThis.$mine = build(null)

The same function called without .async gets the handler's context, so one Go function serves both. Under goja (jsvm: goja), JS must pass the context itself, and CancelContext doesn't exist.

Bundle uses these to serve hooks and migrations embedded in the binary.

Example

// Command example serves example/pb_hooks with the jsvm extension: one QuickJS VM for the app, so the hook file's
// top-level helpers and state are visible to every handler.
//
//	cd example && go run . serve
//	curl http://127.0.0.1:8090/hello/world
package main

import (
	"log"

	"ganigeorgiev.com/pocketbase/pocketbase"
	"pocketone.dev/ext/devusers"
	"pocketone.dev/ext/jsvm"
)

func main() {
	app := pocketbase.New()
	devusers.Register(app)
	jsvm.MustRegister(app, jsvm.Config{HooksDir: "pb_hooks", MigrationsDir: "pb_migrations"})
	if err := app.Start(); err != nil {
		log.Fatal(err)
	}
}

How it works

  • Each app's VM is owned by one goroutine, its loop; everything that touches the VM runs there. Go code elsewhere posts tasks and waits. A Go call made from JS that fires a hook runs it inline, so Go → JS → Go → JS works.
  • Go values cross live through two QuickJS classes: GoObject (property get/set/has/keys go to Go by reflection, with PocketBase's JS names) and GoFunc (calls go to Go). Each holds a handle into the VM's table; QuickJS's refcounting frees it as soon as JS drops it.
  • Memory: QuickJS caps its own heap. Go objects JS holds are charged to the same budget: a per-type estimate, and a reachability walk for fresh results of Go calls.
  • QuickJS is modernc.org/libquickjs, Bellard's QuickJS translated to Go, so there is no cgo. It runs about as fast as goja; deep recursion stops at VM.StackSize (QuickJS stack slots, about one per call; default 5000) with "InternalError: stack overflow".
  • Benchmarks and the red team (27 attacks against 50 VMs in one process) are in the package's tests (ASYNCVM_BENCH=1, ASYNCVM_REDTEAM=1).

License

MIT