Skip to content

aifsmjs: State Machine

aifsmjs is a small, strict FSM (finite state machine) library. Its core philosophy is separating definition from implementation: the state graph is pure JSON data, and guards/actions/effects are injected at runtime, so an entire machine definition can be serialised, sent across Workers, or stored in a database.

The lifecycle is a pure function: step() runs guards → exit → action → entry in a fixed order, cannot be interrupted, and can be replayed deterministically.

終端機視窗
npm install aifsmjs
import { setup, createRuntime, assign } from "aifsmjs";
type Ctx = { ticks: number };
type Evt = { type: "NEXT" };
// 1. The definition is pure data: setup<Ctx, Evt>() lets States be inferred from the keys of states
const trafficLight = setup<Ctx, Evt>().defineMachine({
id: "trafficLight",
initial: "red",
context: { ticks: 0 },
states: {
red: { on: { NEXT: { target: "green", actions: ["bump"] } } },
green: { on: { NEXT: { target: "yellow", actions: ["bump"] } } },
yellow: { on: { NEXT: { target: "red", actions: ["bump"] } } },
},
});
// 2. The implementation is injected at runtime
const runtime = createRuntime(trafficLight, {
actions: {
bump: assign(({ context }) => ({ ticks: context.ticks + 1 })),
},
});
// 3. Send events
runtime.send({ type: "NEXT" });
console.log(runtime.getSnapshot().value); // "green"
console.log(runtime.getSnapshot().context); // { ticks: 1 }

Hit stun followed by invulnerability frames is one of the most common state machines in games. In the demo below, the entry actions of hit and invulnerable only enqueue effects, and the effects call after() from aifsmjs/timer to send RECOVER and EXPIRE when the time is up. Neither state handles HIT, so attacks during the invulnerability window are simply ignored. A hit arrives every 1.1 s on its own, and a click or tap sends one too; the status line lists the last 3 transitions from the logger middleware in aifsmjs/inspect.

Loading the interactive demo…

CharacterBrain: hit, invulnerability frames and state inspection
Demo source
src/demos/fsm-character.ts
/**
* CharacterBrain: hit, invulnerability frames and state inspection with aifsmjs.
*
* A character patrols (idle <-> walk). A hit sends it to `hit`, whose entry action enqueues
* an effect that starts an `aifsmjs/timer` `after()` for the stun; the timer sends RECOVER,
* and `invulnerable` starts the i-frame window the same way, ending in EXPIRE. Neither `hit`
* nor `invulnerable` handles HIT, so hits that arrive meanwhile are ignored: that is the
* i-frame rule, written as data. Hits arrive on their own every 1.1 s, and a click or tap
* sends one too.
*
* The `logger` middleware from `aifsmjs/inspect` feeds the last 3 transitions to the readout.
* Run-to-completion (0.6.0): nothing here reads a nested send()'s result; the readout reads
* getSnapshot() after the outermost call returns.
*/
import { assign, createRuntime, setup } from 'aifsmjs';
import { logger } from 'aifsmjs/inspect';
import { after } from 'aifsmjs/timer';
import { ColorMatrixFilter, Container, Graphics, type Application } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const GROUND_Y = 300;
const PATROL = { left: 220, right: 580 };
const WALK_SPEED = 90; // px per second
const IDLE_MS = 900;
const WALK_MS = 1800;
const STUN_MS = 350;
const IFRAME_MS = 1500;
const AUTO_HIT_MS = 1100;
const FLASH_MS = 260;
const IMPACT_MS = 380;
const MAX_STEP_MS = 50;
type Ctx = { hits: number };
type Evt = { type: 'MOVE' | 'STOP' | 'HIT' | 'RECOVER' | 'EXPIRE' };
// The machine is plain data: states, events and named actions. The code lives in createRuntime.
const brain = setup<Ctx, Evt>().defineMachine({
id: 'characterBrain',
initial: 'idle',
context: { hits: 0 },
states: {
idle: { on: { MOVE: 'walk', HIT: { target: 'hit', actions: ['countHit'] } } },
walk: { on: { STOP: 'idle', HIT: { target: 'hit', actions: ['countHit'] } } },
hit: { entry: ['armStun'], on: { RECOVER: 'invulnerable' } },
invulnerable: { entry: ['armIFrames'], on: { EXPIRE: 'idle' } },
},
});
/**
* A timer queue driven by update(), injected into after() in place of setTimeout, so the stun
* and i-frame windows pause with the demo (offscreen, Pause, reduced motion).
*/
function createDemoClock() {
type Timer = { at: number; fn: () => void };
let now = 0;
const timers = new Set<Timer>();
return {
setTimeout(fn: () => void, ms: number): Timer {
const timer = { at: now + ms, fn };
timers.add(timer);
return timer;
},
clearTimeout(handle: unknown): void {
timers.delete(handle as Timer);
},
advance(ms: number): void {
now += ms;
for (const timer of [...timers]) {
if (timer.at > now) continue;
timers.delete(timer);
timer.fn();
}
},
};
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
body: cssColor('--sl-color-accent'),
ground: cssColor('--sl-color-gray-4'),
hit: cssColor('--sl-color-orange'),
ignored: cssColor('--sl-color-gray-3'),
};
}
const READOUT = {
'zh-TW': (state: string, hits: number, ignored: number, log: string) =>
`狀態:${state}|命中 ${hits}、無敵中忽略 ${ignored}|最近轉移:${log || '—'}`,
en: (state: string, hits: number, ignored: number, log: string) =>
`State: ${state} | hits ${hits}, ignored while invulnerable ${ignored} | recent: ${log || '—'}`,
};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle {
const clock = createDemoClock();
const recent: string[] = []; // newest first
const timerOptions = (signal: AbortSignal) => ({ signal, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout });
const runtime = createRuntime(
brain,
{
actions: {
countHit: assign(({ context }) => ({ hits: context.hits + 1 })),
// Entry actions stay pure: they only enqueue effects, which run after the commit.
armStun: ({ enqueue }) => enqueue.effect('stunTimer'),
armIFrames: ({ enqueue }) => enqueue.effect('iFrameTimer'),
},
effects: {
// `signal` is the runtime's own: dispose() aborts it, which cancels a pending after().
stunTimer: (_effect, { signal }) => {
after(STUN_MS, () => runtime.send({ type: 'RECOVER' }), timerOptions(signal));
},
iFrameTimer: (_effect, { signal }) => {
after(IFRAME_MS, () => runtime.send({ type: 'EXPIRE' }), timerOptions(signal));
},
},
},
{
middleware: [
logger((line) => {
recent.unshift(line); // "[HIT] walk → hit"
recent.length = Math.min(recent.length, 3);
}),
],
},
);
// Scene: ground, an impact ring, and the character (body with eye holes, under a flash filter).
const arena = new Container();
const ground = new Graphics();
const impact = new Graphics();
const hero = new Container();
const body = new Graphics();
const flash = new ColorMatrixFilter();
flash.enabled = false;
body.filters = [flash];
hero.addChild(body);
arena.addChild(ground, hero, impact);
app.stage.addChild(arena);
let colors = readColors(cssColor);
const paint = () => {
ground.clear().moveTo(60, GROUND_Y).lineTo(ARENA.width - 60, GROUND_Y).stroke({ width: 2, color: colors.ground });
body.clear().roundRect(-26, -64, 52, 64, 16).fill(colors.body);
body.roundRect(2, -50, 7, 12, 3).roundRect(14, -50, 7, 12, 3).cut(); // eyes, facing right
const [r, g, b] = [colors.hit >> 16, (colors.hit >> 8) & 0xff, colors.hit & 0xff].map((c) => c / 255);
flash.matrix = [0, 0, 0, 0, r, 0, 0, 0, 0, g, 0, 0, 0, 0, b, 0, 0, 0, 1, 0]; // solid colour, same alpha
};
const fit = () => {
const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height);
arena.scale.set(scale);
arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2);
};
fit();
app.renderer.on('resize', fit);
let x = (PATROL.left + PATROL.right) / 2;
let facing = 1;
let stateMs = 0; // time in the current state
let sinceHit = 0;
let ignored = 0;
let flashMs = 0;
let clockMs = 0; // for bobbing and blinking
let ring = { age: IMPACT_MS, landed: false };
runtime.subscribe((snap) => {
stateMs = 0;
if (snap.value === 'hit') flashMs = FLASH_MS;
});
let shown = '';
const report = () => {
const { value, context } = runtime.getSnapshot(); // read after the outermost send() returned
const text = READOUT[lang](value, context.hits, ignored, recent.join(' · '));
if (text !== shown) setStatus((shown = text));
};
/** One incoming hit: HIT is only handled by idle and walk, so can() tells if it lands. */
const strike = () => {
const landed = runtime.can({ type: 'HIT' });
if (!landed) ignored++;
runtime.send({ type: 'HIT' });
ring = { age: 0, landed };
report();
};
app.canvas.addEventListener('pointerdown', strike);
app.canvas.style.cursor = 'pointer';
/** Poses the character for the current state and draws the impact ring. */
const place = () => {
const state = runtime.getSnapshot().value;
const shake = state === 'hit' ? Math.sin(clockMs * 0.09) * 5 : 0;
const bob = state === 'walk' ? -Math.abs(Math.sin(clockMs * 0.012)) * 6 : Math.sin(clockMs * 0.004) * 1.5;
hero.position.set(x + shake, GROUND_Y + bob);
hero.scale.x = facing;
hero.alpha = state === 'invulnerable' && Math.floor(clockMs / 80) % 2 === 0 ? 0.35 : 1; // i-frame blink
flash.enabled = flashMs > 0;
flash.alpha = flashMs / FLASH_MS;
const t = ring.age / IMPACT_MS;
impact.clear();
if (t < 1) {
impact.circle(x, GROUND_Y - 34, 30 + t * 40).stroke({ width: 4, color: ring.landed ? colors.hit : colors.ignored, alpha: 1 - t });
}
};
paint();
place(); // the first frame is drawn even if the demo never plays (reduced motion)
report();
return {
update(deltaMS) {
const ms = Math.min(deltaMS, MAX_STEP_MS);
clockMs += ms;
stateMs += ms;
clock.advance(ms); // may send RECOVER or EXPIRE from a pending after()
const state = runtime.getSnapshot().value;
if (state === 'idle' && stateMs >= IDLE_MS) runtime.send({ type: 'MOVE' });
if (state === 'walk' && stateMs >= WALK_MS) runtime.send({ type: 'STOP' });
if (state === 'walk') {
x += facing * WALK_SPEED * (ms / 1000);
if (x <= PATROL.left || x >= PATROL.right) facing = x <= PATROL.left ? 1 : -1;
}
if (state === 'hit') x = Math.min(Math.max(x - facing * 120 * (ms / 1000), PATROL.left), PATROL.right); // knockback
sinceHit += ms;
if (sinceHit >= AUTO_HIT_MS) {
sinceHit = 0;
strike();
}
flashMs = Math.max(0, flashMs - ms);
ring.age += ms;
place();
report();
},
onThemeChange() {
colors = readColors(cssColor);
paint();
place();
},
dispose() {
app.renderer.off('resize', fit);
app.canvas.removeEventListener('pointerdown', strike);
app.canvas.style.cursor = '';
runtime.dispose(); // aborts its signal: pending after() timers are cancelled
body.filters = [];
flash.destroy();
arena.destroy({ children: true });
},
};
}
MachineDefinition (pure data) + Implementations (injected at runtime)
↓
step(def, snapshot, event, impl)
→ guards → exit → action → entry
→ returns a new snapshot (immutable)
Subpath Purpose
aifsmjs Core: setup, createRuntime, assign, step
aifsmjs/guards and, or, not, stateIn guard combinators (a guard must be a synchronous function)
aifsmjs/effects createEnqueuer() and runEffects()
aifsmjs/inspect Middleware that only observes and never modifies transitions: logger, persist, recorder
aifsmjs/replay Event sequence replay
aifsmjs/pbt fast-check fc.commands integration, for property-based testing
aifsmjs/timer after() and createScheduler()
  • send() / reset() run to completion: a send() / reset() called inside middleware, an effect handler or a listener is queued and runs after all notifications for the current event have finished. A nested call returns the snapshot committed at that moment, so read getSnapshot() (or use subscribe) after the outermost call returns, and put try/catch around the outermost call; errors from queued events are thrown from the outermost call.
  • A listener removed during notification (unsubscribe, once, signal, dispose()) is not called again in this round; if it still needs to receive the current event, defer the removal with queueMicrotask(off).
  • An action on an object context should return a plain-object partial (or undefined), and the merge preserves the context’s prototype; returning a primitive such as false or 0 throws InvalidActionResultError.
  • When a transition replaces a sub-machine, the new child is created before the old child is disposed; if the new child fails to initialise, the old child stays valid.
  • For after() / createScheduler().after(), ms must be a finite number >= 0 (otherwise RangeError is thrown) and fn must be a function (otherwise TypeError is thrown). Delays beyond 2^31-1 ms (about 24.8 days) are capped at that limit. To express “never”, do not schedule anything.
  • Misuse of the arguments of defineMachine, createRuntime and the runtime methods throws InvalidDefinitionError: impl must be passed as {} even when there are no named implementations, an event must be an object with a string type, and a listener must be a function.
  • Game scene switching: the FSM manages lobby → game → paused → gameOver and emits events to the rendering layer
  • Multi-step forms: each step is a state, and guards validate the fields before allowing the NEXT transition
  • With aiecsjs: an entity in the ECS can carry an FSM snapshot to manage behaviour state (for example a character’s idle / walk / attack)
  • With aibridgejs: a machine definition can be serialised as JSON directly and sent through the bridge to another context