createBehavioralFsm
Overview
Section titled “Overview”createBehavioralFsm defines a set of states and transitions once, then applies that behavior to any number of independent client objects. machina tracks per-client state in a WeakMap and doesn’t stamp anything onto the client object itself. The client IS the context. Handlers receive it as ctx.
When to use it
Section titled “When to use it”Use createBehavioralFsm when:
- You have many instances that share the same state-machine logic, such as network connections or game entities (or if you want the primitives for an actor pattern)
- You don’t want the FSM to own or modify the client object’s shape
- The client already exists and you want to layer FSM behavior onto it without touching its structure
Use createFsm when you have one instance with its own dedicated context object.
Config
Section titled “Config”The config is the same as createFsm with one difference: there’s no context property. The client object IS the context. Because the client type can’t be inferred from the config, you provide it via a curried call: createBehavioralFsm<Connection>() fixes the client type, and the function it returns infers everything else from the config you pass it:
State names, input names, and transition-target validation all work identically, inferred from the states config at compile time.
The client-scoped methods take the client object as their first argument, and the rest of the API mirrors Fsm. The instance-wide methods (on, emit, dispose) don’t take a client.
| Method | Description |
|---|---|
handle(client, inputName, ...args) |
Dispatch an input to the client’s current state handler |
canHandle(client, inputName) |
True when the client’s current state (or its _child chain) handles this input |
transition(client, toState) |
Directly transition the client; fires _onExit, _onEnter, events |
reset(client) |
Transition the client back to initialState |
currentState(client) |
Returns the client’s current state, or undefined if never initialized |
compositeState(client) |
Dot-delimited path including active child FSM states |
dehydrate(client) |
Snapshot everything tracked for a client: state, deferrals, children |
rehydrate(client, compositeState) (string form) |
Place a client at the given (string) state with lifecycle hooks and events skipped |
rehydrate(client, snapshot) (snapshot form) |
Restore a dehydrate() snapshot: state and deferred queues, hooks skipped |
on(eventName, callback) |
Subscribe to a lifecycle event. Returns a { off() } subscription |
emit(eventName, data?) |
Emit a custom event to subscribers |
dispose() |
Permanently shut down the entire FSM. Runs onDispose once per live client, then cascades to child FSMs by default |
State storage
Section titled “State storage”Client state is tracked in a WeakMap<TClient, ClientMeta> inside the FSM instance (machina doesn’t add properties to your client object to keep track of machina-specific state). When a client is garbage collected, its state entry goes with it automatically. You don’t need to clean up.
First contact with a new client (via handle(), transition(), or reset()) runs the full initialization. The client transitions into initialState, and _onEnter and the lifecycle events fire. A client the FSM has never seen is transparently initialized on the first call.
Rehydrating persisted clients
Section titled “Rehydrating persisted clients”The behavioral pattern naturally supports a cold-resume workflow: serialize the client, store it externally (database, file, message queue), and later feed it back to the FSM. The client is just data, and the FSM behavior is stateless.
The problem is placement. When a new process tries to use a deserialized client, handle() and transition() both trigger initialization at initialState first, so _onEnter fires and events emit for states the client should never visit during resume.
rehydrate() solves this. It writes the client directly into the FSM’s internal tracking at the specified state, and it skips the lifecycle hooks and events. rehydrate accepts either a specific state name (string) or a captured snapshot.
Rehydrating With a State Name (string)
Section titled “Rehydrating With a State Name (string)”For hierarchical FSMs, pass the full dot-delimited path from compositeState(). rehydrate() walks the _child chain and places the client at each level:
rehydrate() throws synchronously on invalid state names or structural mismatches (missing _child, Fsm children). Writes are atomic. When validation fails at any level of a composite path, the FSM leaves the client’s state untouched at every level.
Rehydrating With Snapshots: persisting deferred inputs too
Section titled “Rehydrating With Snapshots: persisting deferred inputs too”The string form above only captures the composite state, and it drops anything sitting in a client’s deferred queue. If a client can have pending deferrals when it gets persisted, use dehydrate() and the object form of rehydrate() instead. dehydrate() returns a plain, JSON-serializable snapshot of everything machina tracks for a client (current state, pending deferred inputs with their args and until targets, and the same for every _child in the hierarchy, active or not):
dehydrate() returns undefined for a client the FSM has never seen, and it does not trigger initialization, which mirrors currentState(). It throws if any deferred input’s arguments contain something that serialization would lose or corrupt (a function, undefined, a Date/Map/class instance, a symbol, NaN/Infinity, or a circular reference). The error identifies the exact input and the path to the offending value, plus the until target if one exists.
Both the string and object forms of rehydrate() place the client silently (_onEnter, _onExit, and the transitioning/transitioned events are all skipped), and both validate the entire hierarchy before writing anything, at any level. The object form also requeues each level’s deferred inputs so they replay exactly as they would have if the client had never left memory. For hierarchical FSMs, dehydrate() walks every state’s _child recursively, including states the client currently isn’t in. A child left mid-flight when the parent moved on is captured too, so its pending _onExit/_onEnter and deferred replay behavior still runs on the parent’s next re-entry. See Persisting clients for the full repository/service pattern.
Events
Section titled “Events”BehavioralFsm emits the same lifecycle events as Fsm, and each built-in payload includes a client field, so you can identify which client the event pertains to:
| Event | Payload | Fired when |
|---|---|---|
transitioning |
{ fromState, toState, client } |
A transition is about to occur |
transitioned |
{ fromState, toState, client } |
A transition completed |
handling |
{ inputName, client } |
An input is about to be dispatched |
handled |
{ inputName, client } |
An input was successfully handled |
nohandler |
{ inputName, args, client } |
No handler found in current state |
invalidstate |
{ stateName, client } |
Transition targeted a nonexistent state |
deferred |
{ inputName, client } |
An input was deferred |
A custom event emitted with emit() passes through with exactly the payload you supply. machina doesn’t add a client field to it.
Full example
Section titled “Full example”Per-client teardown
Section titled “Per-client teardown”dispose() shuts down the whole FSM, which for a long-lived BehavioralFsm usually means process shutdown. It runs the config-level onDispose hook once for each client the FSM has initialized or rehydrated and that is still reachable, with that client as ctx. Clients the garbage collector already reclaimed get skipped, because the FSM tracks them through WeakRefs, and the order between the remaining clients is unspecified.
One client going away is a different event, and it is a state. Give the graph a terminal state whose _onEnter releases that client’s resources, and transition the client there when its connection closes:
The onDispose hook still runs for that client at shutdown, so it must tolerate a resource that a terminal state already released. It must also tolerate a resource that was never acquired: rehydrate() skips _onEnter, so a client restored into connecting has no socket unless your own code opened one after the restore. See Disposal in the concepts guide.
TypeScript
Section titled “TypeScript”The client type is the one thing you supply explicitly, via the curried call createBehavioralFsm<Connection>(). State names and input names are inferred from the states config the same way createFsm handles it.
String shorthand transition targets are validated against actual state keys at compile time. A typo like connect: "conecting" is a type error.
There’s a third, rarely-needed call form: supplying both the client type and an already-resolved
states type explicitly, as createBehavioralFsm<Connection, typeof connectivityStates>({ ... }).
It skips inference entirely, so it predates (and was never affected by) the curried form’s
introduction.