xstate-diagram
v0.2.1
Published
Convert XState v5 state machines into publication-quality SVG statechart diagrams with closed-loop verification
Maintainers
Readme
xstate-diagram
Convert XState v5 state machines (raw JSON/TypeScript machine configs or instantiated StateMachine objects from createMachine) into clean, compact, publication-quality SVG statechart diagrams—powered by elkjs and verified by a 4-gate closed-loop AST & browser-geometry harness.
Try It Now
- In Your Browser: Open the Live Interactive Playground ↗ — Explore built-in statechart presets, edit XState v5 configs live, toggle
AUTO/RIGHT/DOWNlayouts, and download.svgdiagrams. - From Your Terminal: Render any
.ts,.js, or.jsonXState machine file directly vianpx:npx xstate-diagram src/checkoutMachine.ts -o diagram.svg
Features
- 100% Browser-Free Runtime: Zero headless browser, canvas, or OS font binary dependencies at runtime—only
xstate(v5) andelkjs. Runs anywhere Node.js or a browser runs. - Full Harel & XState v5 Statechart Semantics:
- Atomic, compound (hierarchical), parallel (dashed orthogonal regions), final (double-bordered), and shallow/deep history (
H/H*) states - Structured state compartments (
entry / ...,exit / ...,invoke / ..., targetless internal transitions, and#tagpills) - Guarded transitions with explicit evaluation-priority badges (
[#1],[#2]), transition actions, eventless (always), delayed (after(...)), completion (onDone), actoronDone(...)/onError(...), external self-loops, and simultaneous multi-target forks (●fork junction on a shared pre-fork trunk)
- Atomic, compound (hierarchical), parallel (dashed orthogonal regions), final (double-bordered), and shallow/deep history (
- Compact Multi-Line Transition Cards: Multi-clause transition labels automatically wrap into clean, left-aligned stacked cards (
event->[guard]->/ actions,<= 280pxpill width) while preserving exact canonical label text in SVG<tspan class="edge-label-line">elements. - Adaptive
AUTOOrientation (RIGHTvs.DOWN): Automatically evaluates horizontal, vertical, per-subtree (SEPARATE_CHILDREN), parallel-region grid, and chain-wrapped (MULTI_EDGE) layouts to produce balanced, compact diagrams (max(W/H, H/W) <= 3.5). - Deterministic Cross-Platform Typography: Uses metrically compatible sans-serif (
Arial, Helvetica, "Liberation Sans", sans-serif) and monospace (Menlo, Consolas, "DejaVu Sans Mono", monospace) stacks measured via an exact ASCII width table.
Installation
npm install xstate-diagram xstateTo build and verify from source in this repository:
npm install
npm run build
CI=1 npm testProgrammatic API
import { createMachine } from 'xstate';
import { renderMachineToSvg } from 'xstate-diagram';
import { writeFile } from 'node:fs/promises';
const checkoutMachine = createMachine({
id: 'checkout',
initial: 'cart',
states: {
cart: {
entry: ['loadSavedCart'],
on: {
ADD_ITEM: {
actions: ['assignItem', 'recalculateSubtotal'],
},
CHECKOUT: {
guard: 'hasItems',
target: 'payment',
actions: ['lockCart'],
},
},
},
payment: {
invoke: {
id: 'chargeCard',
src: 'stripePaymentActor',
onDone: { target: 'confirmed', actions: ['sendReceipt'] },
onError: { target: 'cart', actions: ['notifyPaymentError'] },
},
},
confirmed: {
type: 'final',
},
},
});
// Render with adaptive AUTO orientation (default)
const svg = await renderMachineToSvg(checkoutMachine);
await writeFile('checkout.svg', svg, 'utf8');
// Or explicitly force 'RIGHT' (left-to-right) or 'DOWN' (top-to-bottom)
const verticalSvg = await renderMachineToSvg(checkoutMachine, {
direction: 'DOWN',
});Exported Functions & Types
renderMachineToSvg(machineOrConfig: unknown, options?: RenderOptions): Promise<string>— Accepts either an XState v5StateMachineinstance or a raw JSON/object machine configuration and resolves to a standalone<svg>document string.extractFromMachine(machineOrConfig: unknown): StatechartAST— Normalizes an XState v5 machine or config into the canonicalStatechartAST.renderAstToSvg(ast: StatechartAST, options?: RenderOptions): Promise<string>— Renders a pre-extractedStatechartASTto SVG.RenderOptions:direction?: 'AUTO' | 'RIGHT' | 'DOWN'— Layout orientation ('AUTO'by default).theme?: ThemeTokens— Optional visual theme overrides (DEFAULT_THEMEexported).
CLI Usage
xstate-diagram includes a standalone CLI that directly renders TypeScript (.ts), JavaScript (.js / .mjs), or JSON (.json) XState machine files (or JSON from stdin) into SVG:
# Render a TypeScript or JavaScript XState machine module (auto-discovers default or named export)
npx xstate-diagram src/checkoutMachine.ts -o checkout.svg
# Select a specific named export when a file exports multiple machines
npx xstate-diagram src/machines.ts --export paymentMachine -o payment.svg
# Render a JSON machine config file to an SVG file (adaptive AUTO layout)
npx xstate-diagram machine.json -o diagram.svg
# Force top-to-bottom or left-to-right layout direction
npx xstate-diagram src/checkoutMachine.ts -o diagram-down.svg --direction down
npx xstate-diagram src/checkoutMachine.ts -o diagram-right.svg --direction right
# Pipe from stdin to stdout
cat machine.json | npx xstate-diagram --direction auto > diagram.svgCLI Options
| Flag | Description |
| :--- | :--- |
| -o, --output <file> | Write SVG output to <file> (defaults to stdout) |
| -d, --direction <dir> | Layout direction: auto (default), right, or down |
| -e, --export <name> | Named export to render when input is a .ts/.js module |
| -v, --version | Print the package version |
| -h, --help | Show CLI usage instructions |
GitHub Action (Auto-Generate Diagrams in CI)
Use emmby/xstate-diagram directly as a composite GitHub Action in any repository to keep your statechart SVGs automatically up to date:
- name: Render XState diagram
uses: emmby/[email protected]
with:
input: src/machines/checkoutMachine.ts
output: docs/diagrams/checkout.svg
direction: autoInteractive Browser Playground
Because xstate-diagram uses a 100% browser-free pure-JS runtime, it runs directly in the browser.
- Hosted Playground (emmby.github.io/xstate-diagram): Automatically deployed to GitHub Pages on every push to
mainvia.github/workflows/pages.yml. - Local Build: Run
npm run build:playgroundto generate the self-contained static playground indist/playground/index.html.
Styling & Interactive Diagrams
Generated SVGs include semantic data-* attributes (data-state-path, data-parent-path, data-edge-event, data-edge-source-path, etc.) and built-in CSS classes (.is-active, .is-enabled, .is-clickable, .is-triggered, .is-disabled) so you can highlight active states, make transitions clickable, or customize colors with --xsd-* CSS variables. See Section 4 of ARCHITECTURE.md for the full DOM and CSS reference.
Release & Publishing Strategy
Releases are automated via .github/workflows/release.yml:
- Bump the version in
package.jsonand push a matchingv*tag (e.g.,npm version patch && git push origin main --follow-tags). - GitHub Actions runs
npm run typecheck,npm run build, and the full 4-Gate test suite (CI=1 npm test). - On passing all gates, the workflow packs a slim tarball (
dist/,README.md,ARCHITECTURE.md), creates a GitHub Release with auto-generated release notes and attached.tgzasset, and publishes to npm via tokenless OIDC Trusted Publishing (--provenance).
Closed-Loop 4-Gate Verification Architecture
Every diagram across our 72-machine conformance & statelyai/docs Harel reference corpus (spanning Tiers 1–4, up to the 77-state, 81-transition Harel Citizen Quartz Multi-Alarm Watch) is validated through four independent gates:
- Gate 1 — Lossless Semantic Round-Trip (
src/verifier/extract-svg.ts): Parses the rendered<svg>DOM and real Chromium geometry (getBBox(),getPointAtLength()) to independently reconstructStatechartASTand verifydeepEqual(extractFromSvg(svg), extractFromMachine(input))—catching missing nodes/edges, wrong endpoints, unrendered compartments, and hierarchical containment violations. - Gate 2 — Automated Geometric & Compactness Linter (
src/verifier/geometry-lint.ts): Evaluates rendered bounding boxes and sampled SVG path geometry in Playwright Chromium to enforce zero node/label overlaps, strict parent containment (>= 8pxinset), zero interior obstacle piercing, outward/inward terminal tangents (dot >= 0.50),>= 14pxmulti-edge & label clearance, Voronoi nearest-neighbor label attribution (> 8pxmargin), multi-line card wrapping (<= 280px), and balanced canvas aspect ratios (<= 3.5:1). - Gate 3 — Multimodal Visual & Semantic Critique: Inspects rasterized contact-sheet galleries (
npm run gallery:tier1..npm run gallery:tier4) alongside ground-truthstatelyai/docsreference screenshots for visual clarity, balance, and typographic polish. - Gate 4 — Human Sign-Off: Final inspection of generated galleries and benchmark metrics (
npx tsx scripts/benchmark-compactness.ts).
See ARCHITECTURE.md for full details on the StatechartAST schema, SVG DOM semantic contract, and layout pipeline.
Related Project: Run Your Statecharts Anywhere with Lavi
If you use xstate-diagram, you might also be interested in Lavi—a portable, low-memory XState v5 statechart and actor runtime written in Rust.
The exact same XState v5 JSON or createMachine(...) definitions you visualize with xstate-diagram run identically on:
- Embedded Microcontrollers (
lavi-c-cpp): C & C++11 on ESP32 and ARM Cortex-M via PlatformIO & Arduino IDE with a boundedO(1)CPU call stack - Native & Systems (
lavi): Embedded-friendly Rust - Web, Node.js, React & React Native (
lavi-fsm): 1-line drop-in replacement forxstateand@xstate/reactbacked by WebAssembly (wasm2json Hermes/JSC) - Backend, Mobile & Desktop: Python (
lavi-py), Java/Kotlin/Android (lavi-jvm), Swift/iOS/macOS (lavi-swift), Dart/Flutter (lavi-dart), and C#/.NET (lavi-csharp)
Found a Diagram That Doesn't Render as Expected?
If you have a machine that doesn't render or lay out the way you expect, please open a bug report on GitHub with your JSON machine definition!
Real-world statecharts are the best way to improve our layout and routing heuristics—every reported JSON machine config can be added directly to our 4-gate conformance test suite so it stays clean and regression-free.
