xmachines-runtime-node 6.0.0

Node.js native addon (napi-rs), and its library, that runs XState v6 machine definitions, with guards and actions from JavaScript
Documentation
# xmachines-runtime-node

A Node.js native addon (napi-rs) that runs XState v6 machine definitions with [`xmachines-runtime`](https://docs.rs/xmachines-runtime), and its library for addons of one's own. It is a Node-API addon, so Bun and Deno load it too (the repository's CI runs its tests in all three).

## When to use it

Use the addon to run machines natively from JavaScript, with the guards, actions, delays and expressions a definition references as JavaScript callbacks. Like the WASI component of [`xmachines-runtime-wasi`](https://docs.rs/xmachines-runtime-wasi), the addon is generic: it loads any `MachineJSON` at run time. Custom guards, actions, named delays, expressions and the evaluator of code nodes in other languages (`evaluate`, see `xmachines_runtime::HostEvaluator`) are the `implementations` callbacks, which receive and return JSON text exactly as the WIT `implementations` interface does; child machines for `invoke` come with the load options, and any other invoke source is work of kind `invoke` in the step, which the caller settles with a work input. Custom actions the load option `hostActions` names (`true`: all of them) never reach the `action` callback: each is work of kind `action`, which the caller settles `done`.

For one machine whose implementations are compiled in, with no call into JavaScript per guard, use a typed addon of [`xmachines-machine-node`](https://docs.rs/xmachines-machine-node) instead.

## The API

It exposes the WASI component's `machine` and `actor` resources (world `xmachines:runtime/runtime`), in camelCase:

```ts
function runtimeInterface(): string // "xmachines:runtime@0.4.0"
class Machine {
  static load(definition: string, options: string, implementations?: Implementations): Machine
  start(options: string, now: number): Actor
  restore(snapshot: string): Actor
}
class Actor {
  apply(batch: string): string // the step; throws when refused: `code` "WORKFLOW_REJECTED" and `rejected`, or the contract's `code`
  persist(): string
  takeLogs(): string[]
  can(event: string): boolean
  takeSystemEmitted(): string[]
  stop(): void
}
interface Implementations {
  guard?(name: string, params: string | undefined, context: string, event: string): boolean
  action?(name: string, params: string | undefined): void
  delay?(name: string, context: string, event: string): number
  expr?(name: string, scope: string): string
  contextExpr?(name: string, input: string | undefined): string
  evaluate?(code: string, scope: string): string
}
```

`Machine.load` compiles the definition once, with its load options (`{ "children", "maxSteps", "maxTimers", "observeSystemEmitted", "hostActions" }`) and the callbacks; every actor started or restored from it shares them, so a restore takes only the snapshot, and neither a start, a restore nor a refused chunk compiles it again. A load that fails throws an `Error` whose `code` is the contract's: `WORKFLOW_INVALID_MACHINE` of a definition that is not JSON or does not compile (a child's among them, or one that references an implementation the callbacks lack), `WORKFLOW_INVALID_INPUT` of options that do not parse. `start` takes `{ "input"?, "id"? }`, the root's id `root` unless it names one; a root that fails as it starts throws an `Error` whose `code` is `WORKFLOW_MACHINE_FAILED`, and options that do not parse `WORKFLOW_INVALID_INPUT`, and neither gives an actor. A snapshot that does not restore throws `WORKFLOW_INVALID_SNAPSHOT`. `apply` takes a chunk of the contract's inputs (a JSON array, or one input object): `{ "kind": "time", "now" }` and `{ "kind": "work", "id", "outcome", "data"? }`, control inputs with no `type`, and events, anything else with a string `type`; it returns the step, `{ "emitted", "root", "time", "deadline"?, "work" }`; an empty chunk, `[]`, gives the current step, which is how a caller reads the opening state after `start` or `restore`. A refused chunk throws, and leaves the actor as it was before the chunk, in one of two ways, as the contract tells them apart. A rejection, of an event the root fails on or one to a run that is `done`, in `error` or stopped, or of a `type` that starts with `xstate.`, throws an `Error` whose `code` is `WORKFLOW_REJECTED`, whose `message` is the rejection's, and whose `rejected` is the rejection itself, `{ message, data? }` (the contract's `{ "rejected": ... }`); the run goes on. A fault throws an `Error` whose `code` is the contract's and whose `message` says why: `WORKFLOW_INVALID_INPUT` of an input that is no input (a result of `done` with `data`, even `null`, among them), `WORKFLOW_INVALID_WORK_RESULT` of a result of the other kind of work, `WORKFLOW_ENGINE_FAILED` of an engine that could not put the run back. `can` says whether the root would select a transition for the event now, as XState's `snapshot.can` (`!isUnhandled`): any transition counts, an empty one among them. A time or work input that fails ends the run in `error` instead, in a step like any other (see the WIT `apply`); a result of work the actor no longer waits for is late, and changes nothing. `now` is a whole number of milliseconds, at most `2^53 - 1`; a fraction is refused, not dropped.

Callbacks run synchronously on the JavaScript thread, during the actor call that needs them. A callback that throws (or returns something unusable) is handled as XState's live actor handles an exception thrown there, the error being its `message` as `{ "@error": "Error", "message" }` (as XState persists an `Error`), as the WASI component handles an import's error: an active state's `onError` recovers from it; otherwise a guard, delay or expression fails the step, an action fails the actor inside its step (the step's actions after it do not run), and a root whose start throws fails the start. An actor that fails stops its children, and a child reports `xstate.error.actor` to its parent; the root's failure on an event rejects the chunk (`apply` throws with `WORKFLOW_REJECTED`), and the actor is as it was before it, and on a time or work input ends the run in `error`. The actor stays usable. A callback that calls back into the same actor gets an error.

## Example

Build the addon, which writes `target/release/xmachines_runtime_node.node`:

```sh
crates/xmachines-runtime-node/build.sh   # cargo build -p xmachines-runtime-node --release, then the library copied
```

and load it from JavaScript:

```js
import { createRequire } from 'node:module';

const { Machine, runtimeInterface } = createRequire(import.meta.url)('./target/release/xmachines_runtime_node.node');
console.log(runtimeInterface()); // xmachines:runtime@0.4.0

const light = {
  id: 'light',
  initial: 'green',
  states: { green: { on: { car: { target: 'red', guard: { type: 'busy' } } } }, red: {} },
};
const machine = Machine.load(JSON.stringify(light), '{}', {
  guard: (name, params, context, event) => name === 'busy' && JSON.parse(event).cars > 3,
});
const actor = machine.start('{}', 0);
const step = actor.apply(JSON.stringify([{ kind: 'time', now: 10 }, { type: 'car', cars: 5 }]));
console.log(JSON.parse(step).root.value); // red
```

In Deno, load it with `--allow-read --allow-env --allow-ffi`; in Bun, as in Node.

## Runs

`Machine.open(options)` opens a run on the record protocol of `xmachines:workflow@0.1.0` (`workflowInterface()`), the WIT `run` resource in camelCase: `run.opening` holds its opening records, `run.apply(chunk)` applies one chunk and gives its records, each JSON text, or throws its fault, an `Error` of its `code`, `message` and `seq`; `run.can(event)` and `run.checkpoint()` complete it.

## Contract

The addon is the Node binding of the WIT package `xmachines:runtime@0.4.0`: the same calls, the same JSON (the package's JSON Schemas in `wit/schemas/` of `xmachines-runtime-wasi`), and the time in milliseconds as a number. `runtimeInterface()` reports that package (`RUNTIME_INTERFACE`). In [xmachines-js](https://gitlab.com/xmachin-es/xmachines-js), this is the `NodeRuntime` contract of `@xmachines/run/native`, whose native engine runs an addon only of the interface it is written against; `@xmachines/run` defaults `evaluate` to `jsEvaluate()`, so JavaScript code nodes run as they do on its XState and WASI engines.

## As a library

The crate is a library too (`crate-type = ["cdylib", "rlib"]`), so that an addon of one's own can carry the generic runtime next to its own `#[napi]` items. napi-rs registers the items of every library linked into the addon, and Rust links a dependency only when the crate names it, so the addon names this one once:

```rust,no_run
// An addon crate (crate-type = ["cdylib"], napi_build::setup() in build.rs).
use xmachines_runtime_node as _; // `Machine`, `Actor` and `runtimeInterface` join the addon's exports

#[napi_derive::napi]
pub fn greeting() -> String {
    "hello".into()
}
```

Without the name, the addon has none of the runtime's items; with it, it has all of them, whatever the build's codegen units or LTO. The typed addons of `xmachines-machine-node` export a `Machine` and an `Actor` of their own, so one addon holds either the generic runtime or a typed machine.

## Pins

napi-rs 3 (`napi` with Node-API version 8, `napi-derive` 3), and `napi-build` 2 in the build script.

## Related crates

- [`xmachines-runtime-wasi`](https://docs.rs/xmachines-runtime-wasi): the same runtime as a WASI component.
- [`xmachines-machine-node`](https://docs.rs/xmachines-machine-node): typed addons, one machine each.
- [`xmachines-runtime`](https://docs.rs/xmachines-runtime): the runtime, and `host`, the option parsing this addon shares with the components.

## License

MIT