Getting Started
Installation
Section titled “Installation”Your first FSM
Section titled “Your first FSM”Import createFsm and pass it a config object. Here’s a simple traffic light FSM:
A few things to note:
id: a label for debugging and events. It doesn’t need to be unique, but it helps.initialState: the state the FSM boots into._onEnterfires on every entry to a state (if present)context: a plain object scoped to this FSM instance, yours to mutate.states: a map of state names to handler maps. Each key (other than lifecycle hooks like_onEnterand_onExit) is an input name.onDispose(optional): a teardown hook besidestates.dispose()calls it once with{ ctx, emit }so the FSM can release anything it acquired.
Handlers are functions that receive { ctx, inputName, defer, emit }. Returning a valid state name triggers a transition. Returning undefined (or nothing) leaves the FSM in its current state.
Interacting with the FSM
Section titled “Interacting with the FSM”| Method | What it does |
|---|---|
handle(inputName, ...args) |
Dispatch an input to the current state |
canHandle(inputName) |
True when the current state, or a mounted child FSM, can handle this input |
currentState() |
Returns the current state name as a string |
on(eventName, callback) |
Subscribe to a lifecycle event. Returns { off() } |
emit(eventName, data?) |
Emit a custom event to subscribers |
reset() |
Transition back to initialState |
dispose() |
Permanently shut down the FSM. Runs onDispose first, when declared |
String shorthand
Section titled “String shorthand”When a handler always transitions to the same state with no logic needed, use the string shorthand instead of a function:
TypeScript validates the shorthand: the target must be a key in your states config.
Next steps
Section titled “Next steps”- Concepts, the mental model behind states, inputs, and transitions
- createFsm, the full API reference including hierarchical states, deferred input, and events
- createBehavioralFsm, which defines behavior once and applies it to many independent client objects
- Examples, real-world patterns you can copy
- Tools, static analysis and ESLint integration for catching structural bugs at dev time