百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
J

jssm

> 编程语言
开源

快速、简单的 JavaScript 有限状态机,具有可视化功能;享受一行代码的 FSM,而不是数页的代码。 MIT;使用 Typescript;100% 的测试覆盖率。 实现了

365 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

快速、简单的 JavaScript 有限状态机,具有可视化功能;享受一行代码的 FSM,而不是数页的代码。 MIT;使用 Typescript;100% 的测试覆盖率。 实现了

jssm 5.163.6

Try the live editor · Documentation · Discord · Issues

Easy. Tiny. Fast. Finite state machines as one-liner strings, for TypeScript and JavaScript. Renders to PNG, SVG, and JPEG. Runs in Node, browsers, and Deno. MIT licensed.

javascript
import { sm } from 'jssm';

const TrafficLight = sm`Red -> Green -> Yellow -> Red;`;

That's it. Using it is equally easy:

javascript
TrafficLight.state();      // 'Red'
TrafficLight.go('Green');  // true
TrafficLight.state();      // 'Green'

The point of a state machine is to refuse to do things that aren't correct:

javascript
TrafficLight.go('Red');    // false  - Green doesn't go to Red, only Yellow
TrafficLight.go('Blue');   // throws - Blue doesn't exist at all

A more involved machine, with main paths, forced paths, and per-state styling, renders to:

javascript
const TrafficLightWithOff = sm`
  Red 'next' => Green 'next' => Yellow 'next' => Red;
  [Red Yellow Green] ~> Off -> Red;

  flow: left;

  state Red    : { background-color: pink;        corners: rounded; };
  state Yellow : { background-color: lightyellow; corners: rounded; };
  state Green  : { background-color: lightgreen;  corners: rounded; };

  state Off    : {
    background-color : steelblue;
    text-color       : white;
    shape            : octagon;
    linestyle        : dashed;
  };
`;

The same string is the runtime and the diagram. They cannot drift apart.

Try it in the live editor · Documentation · Discord · Issues

Install

bash
npm install jssm

The package ships pure ES6, a CommonJS ES5 bundle, an IIFE for browsers, and TypeScript typings. A Deno build is included. Node 10 or newer.

Visualization

jssm ships with a visualization subpath that renders state machines to SVG using Graphviz (via @viz-js/viz).

typescript
import { sm }                  from 'jssm';
import { fsl_to_svg_string }   from 'jssm/viz';

const svg = await fsl_to_svg_string('a -> b;');

The viz subpath is opt-in - importing only from jssm does not pull in @viz-js/viz. See the Visualization doc page for browser, ESM, and IIFE usage patterns.

Command-line interface

jssm ships a CLI for rendering FSL machines to images and other formats.

Installation

bash
npm install -g jssm

This installs three binaries: fsl (the dispatcher), jssm (alias for fsl), and fsl-render (the render plugin).

Render

Render a single machine to SVG (default):

bash
fsl render machine.fsl
# → machine.svg next to input

Specify a format:

bash
fsl render machine.fsl --target=png --width=800
fsl render machine.fsl --target=dot --stdout > machine.dot

Render multiple machines:

bash
fsl render *.fsl --target=svg --out-dir=./diagrams

Pipe FSL via stdin:

bash
cat machine.fsl | fsl render --target=dot | dot -Tpng > out.png

Plugin architecture

Every fsl- executable on PATH is dispatched when you run fsl . Third-party plugins follow the same contract as first-party fsl-render. See notes/superpowers/specs/2026-05-12-fsl-cli-design.md for the contract.

Library API

The same render functions are available programmatically:

javascript
import { render, renderSet } from 'jssm/cli';

const result = await render(fslText, { target: 'svg' });
if (result.kind === 'text') console.log(result.content);

Static fence rendering (jssm/fence)

jssm/fence renders FSL code fences to static, editor-parity-highlighted HTML — no browser, no editor, no live machine required — for Markdown pipelines, static site generators, and doc tooling.

typescript
import { transform_markdown } from 'jssm/fence';

const html = await transform_markdown(markdown);
// every fsl/jssm fence becomes rendered, highlighted HTML
// everything else in the document passes through untouched
console.log(html);

render_fence_gif walks a machine's main path (or every edge, if there is no main path) into a looping animated GIF, one Graphviz layout patched per frame: 70cs per-frame delay, loops forever, and a 64-frame walk cap by default, all overridable via options.

PNG, JPEG, and GIF output rasterize through the same optional backend as the CLI — install it with npm install @resvg/resvg-wasm.

TextMate grammar (jssm/grammar)

jssm ships the canonical TextMate grammar for FSL as a data file at dist/grammars/fsl.tmLanguage.json (scope source.fsl), the single source consumed across the editor ecosystem — shiki (and the static-site generators built on it), GitHub Linguist, Monaco, Sublime, bat, and the vscode-fsl extension.

javascript
import grammar from 'jssm/grammar' with { type: 'json' };
// or read dist/grammars/fsl.tmLanguage.json from node_modules/jssm

The grammar is generated from — and build-verified against — the same fsl_parser.peg that drives the parser, so its highlighting never drifts from the language.

Web Components

jssm ships Lit-based web components for use in plain HTML or as a base for framework wrappers.

CDN one-liner (with an import map for @viz-js/viz):

xml

 On -> Off;">

npm one-liner:

typescript
import 'jssm/wc/viz/define';
// then use  anywhere;  is an accepted alias

Full documentation: src/doc_md/WebComponents.md.

60-second tour

Actions let a machine advance without the caller knowing the next state:

javascript
const Light = sm`Red 'next' -> Green 'next' -> Yellow 'next' -> Red;`;

Light.action('next');  // true
Light.state();         // 'Green'
Light.action('next');  // true
Light.state();         // 'Yellow'

Three arrow types distinguish kinds of transition:

javascript
const Light = sm`
  Red => Green => Yellow => Red;     // => main path
  [Red Yellow Green] ~> Off -> Red;  // ~> forced, -> legal
`;

-> is a legal transition. => is a legal transition that is also part of the main path. ~> is a transition that requires force_transition - useful for emergency stops, resets, and other rarities.

Hooks observe and gate transitions:

javascript
const m = sm`Red 'next' -> Green 'next' -> Yellow 'next' -> Red;`
  .hook('Red', 'Green', () => console.log('GO'))            // specific edge
  .hook_entry('Red', () => console.log('STOP'))             // entering a state
  .hook_action('Yellow', 'Red', 'next', () => allowed());   // gate a specific action; return false to block

Pre-hooks fire before the state changes and may return false to refuse the transition. Post-hooks fire after. Four *_everything hooks (hook_pre_everything, hook_everything, hook_pre_post_everything, hook_post_everything) bracket the entire pipeline if you want a single observation point.

Refusals and errors are deliberately different. An illegal transition returns false. An unknown state throws. Branching code can rely on the distinction.

Overlapping state groups let a state belong to several groups at once - something a strict hierarchy can't express. A group is declared with &, and the same &name then drives transitions, shared metadata, boundary hooks, and runtime queries:

javascript
const req = sm`
  &InProgress : [connecting sending receiving];
  &Receiving  : [receiving draining];

  idle 'send'    -> connecting 'open' -> sending 'reply' -> receiving;
  receiving 'eof' -> draining 'done'  -> idle;

  &InProgress 'abort' -> idle;        // a transition from every group member
  on enter &Receiving do 'log_rx';    // boundary hook fires crossing in
`;

req.action('send');
req.isIn('InProgress');     // true  - connecting is in &InProgress
req.groupsOf('receiving');  // Set { 'InProgress', 'Receiving' }  - overlap

receiving is in both groups simultaneously - it is in-progress and receiving. When two groups disagree about the same action, a CSS-like cascade decides: state-specific edges win, then the innermost (nearest) group, then the later-declared one. Groups render as nested Graphviz clusters, or as bracketed chips on the node label where memberships genuinely overlap.

See the cookbook's overlapping-groups recipes for fuller worked examples.

Why jssm

The big win: most state-machine libraries make you write a gargantuan JSON document, or call a builder API a few dozen times, to define a single machine. jssm machines are short, readable, arrow-driven strings - so they are easy to write, easy to read, easy to debug, and easy to share.

That decision shows up everywhere downstream:

  • A DSL with features other state-machine libraries don't have. Three arrow types distinguish legal, main-path, and forced transitions. Array notation collapses repeated edges - [Red Yellow Green] ~> Off replaces three lines. Named actions, per-state styling, named edges, validators, and live visualization all live in the same string the runtime parses.

  • Definition strings stay tiny, which makes machines easy to debug. The traffic light is one line; the full eight-step ATM walkthrough is thirty. Small enough to read top-to-bottom, diff in code review, paste into a bug report, or drop into the live editor for a rendered diagram you can step through.

  • Fast. Tens of millions of transitions per second on commodity hardware. See src/buildjs/benchmark.cjs or run npm run benny against your own machine.

  • More thoroughly tested than any other JavaScript state-machine library. 10,142 tests at 100.0% line coverage (report), plus fuzz testing via fast-check, with parser test data across ten natural languages and Emoji.

Documentation

  • What are state machines? - conceptual intro for newcomers
  • Getting started - install and use the library across Node, browser, Deno, ES5/ES6, CDN, and TypeScript
  • Using jssm in the browser - script tags, CDN, native ES modules, bundlers, and web components
  • Tutorial: a four-state traffic light - short walkthrough that introduces the three arrow types
  • Tutorial: building an ATM state machine - longer walkthrough that builds a real-world machine in nine incremental steps
  • Language reference - DSL reference for people already comfortable with state machines
  • Styling nodes and graphs - the built-in named color themes and how to select them from FSL source, code, Markdown fences, the CLI, and web components
  • Catalog of example machines - comparison table of worked examples (light switch, traffic light, intersection, vending machine, more)
  • Generated API reference - full surface, generated from the TypeScript source

API at a glance

| M

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptdslfinite-state-machineflowtypefsm

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言