What is AFSM
AFSM (Automatic Finite State Machine) is a TypeScript decorator library for automatically managing async state machines.
Why
Anyone who has written async flows has hit this problem: an async operation often has “in progress”, “success”, and “failure” states, and managing them by hand is tedious and error-prone.
// Manual state managementclass Service { state = 'idle' async fetch() { this.state = 'fetching' try { const data = await api() this.state = 'success' return data } catch (e) { this.state = 'error' throw e } }}Every method repeats the same “set state → try/catch → change state” boilerplate, and as methods multiply the relationships between states become hard to track.
AFSM’s approach
AFSM hands this boilerplate to decorators. You declare from which state to which state, and the intermediate state, event dispatch, and error rollback are all automatic.
import { FSM, ChangeState } from 'afsm'
class Service extends FSM { @ChangeState('idle', 'success') async fetch() { return await api() // failure auto-rolls back to idle }}When fetch() is called, AFSM will:
- Check that the current state is
idle, otherwise throwFSMError - Enter the intermediate state
fetching(auto-appendsing) - Run the original method
- Success → state becomes
success; failure → state rolls back toidleand the error is thrown - Throughout, events are dispatched via
eventemitter3so listeners can react in real time
Core features
@ChangeState(from, to)— state transition decorator, auto-manages intermediate states@Includes/@Excludes— state guards, restrict method calls to specific states@ActionState— action state, temporarily switch to a state during async, return to old state afterFSM.stateDiagram— auto-generates a mermaid state diagram for visualizing the topologycontext— compose multiple independent state machines in one classabortAction— interrupt an in-flight MiddleState- DevTools extension — Chrome / Edge panel to inspect running state machines live
Use cases
- Network connection management (connect / disconnect / reconnect)
- Data fetching with retry
- Any “finite state + async transition” business flow
- Complex state machines that need visualization and observability
Next, head to Quick Start to write your first state machine, or install DevTools first. You can also watch the Bilibili video tutorial.