connectWorker
Connects to a worker running the WebAssembly module and returns the machine API with every call turned into a promise. This is how a page runs machines without blocking its main thread — see the Worker guide.
Function Signature
connectWorker(endpoint: MessageEndpoint): CartesiMachineClientendpoint: anything withpostMessageandonmessage— aWorker, aMessagePort, aSharedWorkerport.
It returns immediately: the module is instantiated in the worker on the first call.
Returns
A CartesiMachineClient, which is the surface of init with the same method names and arguments, minus module and fs (the module lives in the worker), plus:
rollups(machine, options?): wraps a machine the worker holds in the rollups protocol, returning aRemoteRollupsMachine;terminate(): stops the worker, discarding every machine it holds.
Calls that return a machine return a RemoteMachine — a proxy for a machine that stays in the worker — with the CartesiMachine methods as promises, plus release() to drop the worker's reference to it.
Because generators cannot cross a message port, advance and inspect on a RemoteRollupsMachine always collect: they resolve with the full result rather than streaming.
Example
import { } from "@cartesi/machine/wasm";
const = new (
new ("@cartesi/machine/worker", import.meta.),
{ : "module" },
);
const = ();
const = await .({ : { : 0x4000000 } });
await .(1_000_000n);
.(await .());
// let the worker drop it; the page's proxy alone cannot tell it to
await .();
.();serve
The other side of the same facade, and all @cartesi/machine/worker does:
serve(endpoint: MessageEndpoint, options?: InitOptions): voidendpoint: in a worker,self; in a test, either end of aMessageChannel;options: passed to init when the module is instantiated, on the first call.
Use it to run the facade somewhere other than the default worker entry point:
// @filename: my-worker.ts
import { } from "@cartesi/machine/wasm";
( as unknown as <typeof >[0]);Errors
Errors thrown in the worker are flattened, sent across, and rebuilt on the page side, so a MachineError arrives with its code and description intact and instanceof MachineError holds.
Calling a method on a proxy that was already released rejects with handle <n> was already released.