xmachines-runtime-node 2.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 start options, and any other invoke source is async work the caller completes through `resolveEffect`.

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 same actor API as the WASI component (world `xmachines:runtime/runtime`), in camelCase:

```ts
function runtimeInterface(): string // "xmachines:runtime@0.3.0"
class Actor {
  static start(definition: string, options: string, now: number, implementations?: Implementations): Actor
  static restore(definition: string, options: string, snapshot: string, implementations?: Implementations): Actor
  send(event: string, now: number): void
  sendTo(address: string, event: string, now: number): void
  advance(now: number): void
  nextDeadline(): number | null
  snapshot(): string
  persist(): string
  takeEmitted(): string[]
  observeSystemEmitted(): void
  unobserveSystemEmitted(): void
  takeSystemEmitted(): string[]
  takeLogs(): string[]
  pendingEffects(): string[]
  resolveEffect(id: string, event?: string | null): void
  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
}
```

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 (the actor keeps its snapshot from before the step, in the `error` status), an action fails the actor inside its step (it keeps the step's snapshot, in the `error` status, and the step's actions after it do not run), and a root whose start throws starts in the `error` status. An actor that fails stops its children, and a child reports `xstate.error.actor` to its parent; the root's failure makes the call throw. 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 { Actor, runtimeInterface } = createRequire(import.meta.url)('./target/release/xmachines_runtime_node.node');
console.log(runtimeInterface()); // xmachines:runtime@0.3.0

const light = {
  id: 'light',
  initial: 'green',
  states: { green: { on: { car: { target: 'red', guard: { type: 'busy' } } } }, red: {} },
};
const actor = Actor.start(JSON.stringify(light), '{}', 0, {
  guard: (name, params, context, event) => name === 'busy' && JSON.parse(event).cars > 3,
});
actor.send(JSON.stringify({ type: 'car', cars: 5 }), 10);
console.log(JSON.parse(actor.snapshot()).value); // red
```

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

## Contract

The addon is the Node binding of the WIT package `xmachines:runtime@0.3.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 _; // `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 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