Web and Oak

Monad's web profile compiles a program to a freestanding wasm32-unknown-unknown module that a browser page instantiates with a small JavaScript import object. The Oak stack (oak, oak_wasm, oak_ui, web_wasm) turns that into an Elm-shaped SPA: a pure model/update/view, a diffing DOM runtime, and typed event handlers.

This chapter is the end-to-end guide the web_wasm/oak mote READMEs assume. It is also the reference for the sharp edges an external consumer hits.

The web profile

monad build --target wasm32-unknown-unknown app.mo -o app.wasm

The profile is freestanding: it links -nostdlib, imports only the JS module "monad", and needs no sysroot. A host clang with the wasm32 backend (and wasm-ld) is enough; WASI_SDK_PATH is only required for the wasm32-unknown-wasip1 profile. The web C compiler is MONAD_WEB_CC if set, else the wasi-sdk clang when WASI_SDK_PATH is set, else host clang; a nixpkgs wrapped clang needs MONAD_WEB_CC=clang-unwrapped (its hardening flags are rejected by the wasm target). The output is a .wasm plus a JS loader.

Four files make a deployable directory:

File Origin
web.js Generated by web_wasm::Glue.loader from WebAbi (scripts/gen-web-js.sh). Build output, never committed.
web_runtime.js Hand-written host: DOM, events, fetch, storage, WebCrypto, timers. Copy it beside web.js.
app.wasm The compiled program.
index.html Generated by web_wasm::Shell.index_html (a library call in your build script).

There is no monad web build command: shell assembly is web tooling, so an app's [[script]] produces the directory. See Serving and reload.

An Oak SPA

An app exposes three #[export "c"] thunks; the loader calls oak_mount once, oak_dispatch_event(id) from each DOM listener, and oak_tick once per animation frame.

#![mote { name := "counter", deps := [oak, oak_wasm, web_wasm, web_event] }]

use oak::typed {Oak.Node}
use oak::elements {Html.div, Html.button, Html.id_, Html.text}
use oak::events {Html.on_click}
use oak::app {Command, Host, Program}
use oak_wasm::program {Runtime.dispatch, Runtime.mount, Runtime.tick}

type Msg { increment }

def update (m : I64) (msg : Msg) : Pair I64 (Command Unit Msg) :=
    match msg { Msg.increment => Pair.pair (m + 1i64) Command.none }

def view (m : I64) : Oak.Node Msg :=
    Html.div [Html.id_ "app"]
        [Html.text (I64.to_string m),
            Html.button [Html.on_click Msg.increment] [Html.text "add"]]

def app : Program I64 Msg Unit := Program.app 0i64 update view
def host : Host IO Unit Msg := Host.host (fn _e => IO.pure Option.none)

#[export "c"] def oak_mount : IO Unit := Runtime.mount app
#[export "c"] def oak_dispatch_event (handler : I64) : IO Unit := Runtime.dispatch handler
#[export "c"] def oak_tick : IO Unit := Runtime.tick app host
def main : IO Unit := IO.pure unit

The page is tiny:

<script type="module">
  import { start } from './web.js';
  start('./app.wasm', '#app');
</script>

Commands, timers and focus

Command is none, quit, dispatch, perform, plus three runtime commands:

Subscription.window_filter event (WebEvent -> Option Msg) ignores an event when it returns Option.none: a keydown that only cares about Escape should use it instead of re-rendering on every key.

Handler ids and view shape

A handler id is an integer hash of the node's patch path and event name. It is stable while the view shape is stable; inserting or removing siblings changes later ids and the runtime replaces those listeners. For a changing list, stamp children with Html.key k: a keyed list is reconciled by key, so DOM nodes (and their listeners, focus and scroll) keep their identity.

Subscriptions and the heap

The web heap is garbage-collected. It collects only when an export (oak_mount, oak_dispatch_event, oak_tick) returns to JS, because a running frame's wasm locals cannot be scanned. An event-driven app therefore stays flat; only code that never returns to JS keeps its garbage. Linear memory never shrinks, so freed memory is reused rather than returned. Exhaustion calls the host's oom import (a console.error naming the sizes) and traps — not a silent 0 or a negative-offset RangeError. Memory.heap_bytes / Memory.heap_used expose committed/used bytes.

Avoid idle Subscription.animation_frame: each frame re-renders and allocates. Prefer Command.after for a one-shot delay, and handlers only on elements that can change.

WebSockets

A socket belongs to a subscription, not to the model:

def subs (_m : Model) : List (Subscription Msg) :=
    [Subscription.websocket "wss://example.test/game" ["v1"] (fn (e : WsEvent) => Msg.socket e)]

def update (m : Model) (msg : Msg) : Pair Model (Command E Msg) :=
    match msg {
        Msg.socket (WsEvent.opened _) =>
            Pair.pair m (Command.ws_send "wss://example.test/game" (WsData.text "join"))
        ...
    }

The runtime opens the socket when the subscription appears and closes it when it goes away; each event (opened protocol, message data, closed code reason clean, failed) becomes one message, and ws_send addresses the socket by the same URL. A URL with no live subscription drops the send. Payloads cross as bytes (a text message is its UTF-8), so a frame is not capped by the 64 KiB scratch string.

For an app with its own loop (a game engine), the imperative API is web_wasm::websocket: WebSocket.connect, drain (everything queued, for a per-frame poll), next, send, close, watch/unwatch.

Browser surface (web_wasm)

Module What it gives you
dom create/append/patch, attributes, listeners (flags cdsopr, r releases implicit touch capture), element_at/attr hit testing, focus, query/value
event the live WebEvent snapshot: coordinates, modifiers, key, pointer, form value, drag/clipboard data
fetch two-phase begin/begin_with (request headers), poll, status, response_headers, read
storage has/get_raw/get/set/remove/clear (get_raw distinguishes absent from empty)
clock now_ms (wall clock) and monotonic_ms (performance.now)
media matches query, watch/unwatch for matchMedia changes
crypto random_bytes (getRandomValues), a two-phase SHA-256, and ECDSA P-256 (WebCrypto.generate_key_begin/sign_begin/export_public_jwk_begin/export_public_raw_begin)
keystore IndexedDB put/get/delete of a non-extractable ECDSA key, so it survives a page reload
window / memory origin/href/pathname/search/search_param reads, reload/navigate/replace, committed/used heap
timer the Command.after bridge
websocket WebSocket.connect/drain/next/send/close/watch — the imperative socket behind Subscription.websocket

Fetch.begin_with and Fetch.response_headers carry headers as length-prefixed blobs; that is what an authenticated API (bearer tokens, Content-Type, DPoP nonces) needs.

WebCrypto, and signing in from the browser

The two-phase shape is not incidental: a JS promise callback must not re-enter wasm while a Monad frame is on the stack, so every promise-based operation is a *_begin that returns an op handle plus a Crypto.poll the page drives from its own frame loop. 0 = pending, 1 = done, 2 = failed (Crypto.error gives the DOMException name).

The ECDSA keypair is non-extractable and signing-only, and it is an id into the host's table: the private scalar never enters wasm memory, so there is nothing in the module's heap to leak. Only the public half is ever exported -- as a JSON Web Key (kty:EC, crv:P-256, for an RFC 7638 jkt thumbprint and the OAuth client-metadata document) and as the raw 65-byte SEC1 point (0x04‖X‖Y, for a multikey). WebCrypto.sign_begin answers ES256 as the 64-byte IEEE P1363 r‖s, which is already the JWS form.

Why the keystore exists. A browser OAuth login redirects away and back, which unloads the page; the DPoP key that signs the token exchange has to survive that. KeyStore.put_begin/get_begin store the CryptoKey in IndexedDB, which keeps it by structured clone -- the browser holds the material opaque and hands back a live handle on the next page. That is strictly safer than stashing an exported JWK in localStorage, where any XSS could read it.

Polling a KeyStore.get_begin finishes with state 3 when the slot is empty, which is a miss rather than a failure: "this browser has no key for this account" is the ordinary answer on a first visit. KeyStore.get is the same question already answered -- none for that empty slot -- but it drives the poll itself, so it is for a caller with no frame loop of its own.

// The redirect carries its result in the URL, so read it from `location`.
let code <- Window.search_param "code";
let state <- Window.search_param "state";
let iss <- Window.search_param "iss";

Window.search_param percent-decodes (and turns + into a space), so a base64url code or a state carrying = arrives intact. After exchanging the code, Window.replace rewrites the URL without pushing a history entry -- otherwise a Back button would re-submit a code that has already been spent.

Serving and reload

Serving is a script, not a CLI verb. Add a [[script]] with [script-dependencies] on moon (and http), then:

use moon::server {Server.serve_static}
use moon::static_files {StaticConfig, StaticConfig.default}

Server.serve_static (StaticConfig.default "dist") "127.0.0.1" 8000u16 is a fiber-per-connection static server (MIME types, ETags, ranges, traversal guard). For live reload, moon::Live provides SSE plus a tree watcher, and monad script --watch rebuilds and reruns the script when its tree changes.

Debugging