npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

xstate-diagram

v0.2.1

Published

Convert XState v5 state machines into publication-quality SVG statechart diagrams with closed-loop verification

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 / DOWN layouts, and download .svg diagrams.
  • From Your Terminal: Render any .ts, .js, or .json XState machine file directly via npx:
    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) and elkjs. 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 #tag pills)
    • Guarded transitions with explicit evaluation-priority badges ([#1], [#2]), transition actions, eventless (always), delayed (after(...)), completion (onDone), actor onDone(...) / onError(...), external self-loops, and simultaneous multi-target forks (● fork junction on a shared pre-fork trunk)
  • Compact Multi-Line Transition Cards: Multi-clause transition labels automatically wrap into clean, left-aligned stacked cards (event -> [guard] -> / actions, <= 280px pill width) while preserving exact canonical label text in SVG <tspan class="edge-label-line"> elements.
  • Adaptive AUTO Orientation (RIGHT vs. 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 xstate

To build and verify from source in this repository:

npm install
npm run build
CI=1 npm test

Programmatic 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 v5 StateMachine instance 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 canonical StatechartAST.
  • renderAstToSvg(ast: StatechartAST, options?: RenderOptions): Promise<string> — Renders a pre-extracted StatechartAST to SVG.
  • RenderOptions:
    • direction?: 'AUTO' | 'RIGHT' | 'DOWN' — Layout orientation ('AUTO' by default).
    • theme?: ThemeTokens — Optional visual theme overrides (DEFAULT_THEME exported).

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.svg

CLI 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: auto

Interactive Browser Playground

Because xstate-diagram uses a 100% browser-free pure-JS runtime, it runs directly in the browser.


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:

  1. Bump the version in package.json and push a matching v* tag (e.g., npm version patch && git push origin main --follow-tags).
  2. GitHub Actions runs npm run typecheck, npm run build, and the full 4-Gate test suite (CI=1 npm test).
  3. 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 .tgz asset, 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:

  1. Gate 1 — Lossless Semantic Round-Trip (src/verifier/extract-svg.ts): Parses the rendered <svg> DOM and real Chromium geometry (getBBox(), getPointAtLength()) to independently reconstruct StatechartAST and verify deepEqual(extractFromSvg(svg), extractFromMachine(input))—catching missing nodes/edges, wrong endpoints, unrendered compartments, and hierarchical containment violations.
  2. 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 (>= 8px inset), zero interior obstacle piercing, outward/inward terminal tangents (dot >= 0.50), >= 14px multi-edge & label clearance, Voronoi nearest-neighbor label attribution (> 8px margin), multi-line card wrapping (<= 280px), and balanced canvas aspect ratios (<= 3.5:1).
  3. Gate 3 — Multimodal Visual & Semantic Critique: Inspects rasterized contact-sheet galleries (npm run gallery:tier1 .. npm run gallery:tier4) alongside ground-truth statelyai/docs reference screenshots for visual clarity, balance, and typographic polish.
  4. 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 bounded O(1) CPU call stack
  • Native & Systems (lavi): Embedded-friendly Rust
  • Web, Node.js, React & React Native (lavi-fsm): 1-line drop-in replacement for xstate and @xstate/react backed by WebAssembly (wasm2js on 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.