CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

statelyai/model-based-testing

Write model-based tests with @xstate/test 2.0 beta, replace end-to-end tests with model-based tests without losing coverage, and visualize the model in Stately. Use for model-based testing, @xstate/test, generating tests from a state machine, testing every path, replacing Playwright, Cypress, Vitest, or Jest end-to-end tests with a model, coverage parity, or migrating from @xstate/test 0.x or 1.0 beta.

Quality

100%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Medium

Suggest reviewing before use

Overview
Quality
Evals
Security
Files

coverage-viewer.mjsscripts/

#!/usr/bin/env node
// Shows a model in a Stately embed. State nodes and transitions turn green
// when a reported run covers them and red when no run has.
//
// Usage:
//   node coverage-viewer.mjs --machine <file> [--sdk <dir>] [--viz <url>] [--port <n>]
//
// Tests report each run with:
//   POST http://127.0.0.1:<port>/coverage
//   { "coverage": testCoverageToJSON(coverage), "label": "<test id>",
//     "paths": [[{ "event": "<type>", "value": <state value after it> }, ...], ...] }
//
// `paths` picks the branch of a function transition that each step took.
// Without it, a transition with several drawn branches stays uncovered.
//
// --sdk is the @statelyai/sdk dist directory (default: resolved from the cwd).
// --viz is the editor base URL (default: https://editor.stately.ai, which needs
// sign-in or STATELY_API_KEY).

import { createServer } from 'node:http';
import { readFileSync, statSync } from 'node:fs';
import { join, resolve, extname, dirname, sep } from 'node:path';
import { createRequire } from 'node:module';

function arg(name, fallback) {
  const i = process.argv.indexOf(`--${name}`);
  return i === -1 ? fallback : process.argv[i + 1];
}

const machinePath = arg('machine');
if (!machinePath) {
  console.error('usage: coverage-viewer.mjs --machine <file> [--sdk <dir>] [--viz <url>] [--port <n>]');
  process.exit(2);
}
// Loopback only: the page can contain STATELY_API_KEY.
const host = '127.0.0.1';
const port = Number(arg('port', '5173'));
const viz = arg('viz', 'https://editor.stately.ai').replace(/\/+$/, '');
let sdkDir = arg('sdk');
if (!sdkDir) {
  const require = createRequire(join(process.cwd(), 'package.json'));
  try {
    sdkDir = join(dirname(require.resolve('@statelyai/sdk/package.json')), 'dist');
  } catch {
    console.error('coverage-viewer: @statelyai/sdk not found. Run `npm i -D @statelyai/sdk` or pass --sdk <dist dir>.');
    process.exit(2);
  }
}
sdkDir = resolve(sdkDir);

// Every reported run, replayed to each page. The page resolves ids against the
// diagram, so the server keeps no coverage state of its own.
const runs = [];
const clients = new Set();

function send(res, msg) {
  res.write(`data: ${JSON.stringify(msg)}\n\n`);
}

const page = `<!doctype html>
<meta charset="utf-8">
<title>Model coverage</title>
<style>
  html, body { margin: 0; height: 100%; font: 13px system-ui, sans-serif; background: #111; color: #ddd; }
  #bar { padding: 6px 10px; display: flex; gap: 16px; align-items: center; }
  #bar b { color: #22c55e; }
  #last { opacity: .7; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1; }
  iframe { border: 0; width: 100%; height: calc(100% - 30px); }
</style>
<div id="bar"><span>states <b id="s">0/0</b></span><span>transitions <b id="t">0/0</b></span><span id="last"></span><button id="reset">Reset</button></div>
<iframe id="viz"></iframe>
<script type="module">
  import { createStatelyEmbed } from '/sdk/embed.mjs';
  const machine = await (await fetch('/machine')).text();
  let graph;
  const pending = [];
  const covered = new Set();
  const known = new Set();
  // Edge id -> source of a transition the runs report as "unknown".
  const unknown = new Map();
  const embed = createStatelyEmbed({
    baseUrl: ${JSON.stringify(viz)},
    apiKey: ${JSON.stringify(process.env.STATELY_API_KEY)},
    iframe: document.getElementById('viz'),
    theme: 'dark',
    onLoaded: (g) => { graph = window.graph = g; pending.splice(0).forEach(apply); render(); }
  });
  window.embed = embed;
  embed.init({ machine, format: 'xstate', mode: 'view', settings: { validation: { showValidations: false } } });

  const parse = (id) => { try { return JSON.parse(id); } catch { return []; } };
  const edgesOf = (source, event) =>
    graph.edges.filter((e) => e.sourceId === source && e.data?.eventType === event);
  const all = (d) => [...(d?.coveredIds ?? []), ...(d?.uncovered ?? [])];

  // State value -> ids of its active state nodes, root included.
  function activeIds(value) {
    const root = graph.nodes.find((n) => !n.parentId).id;
    const ids = [root];
    const walk = (prefix, v) => {
      if (typeof v === 'string') ids.push(prefix + '.' + v);
      else if (v && typeof v === 'object') for (const [k, c] of Object.entries(v)) { ids.push(prefix + '.' + k); walk(prefix + '.' + k, c); }
    };
    walk(root, value);
    return ids;
  }

  // A transition id names source, event and the transition's index, not the
  // branch a function transition took. Stately draws each branch as an edge,
  // so a branch counts as covered only when a step reached its target. A
  // targetless branch counts when no drawn target was reached.
  function apply(run) {
    if (!graph) return pending.push(run);
    const dims = run.coverage?.dimensions ?? {};
    for (const id of all(dims.stateNodes)) known.add(id);
    for (const id of dims.stateNodes?.coveredIds ?? []) covered.add(id);
    const branched = new Set();
    for (const id of all(dims.transitions)) {
      const [kind, source, event] = parse(id);
      if (kind !== 'transition') continue;
      const edges = edgesOf(source, event);
      edges.forEach((e) => known.add(e.id));
      if (edges.length > 1) branched.add(source + '\\n' + event);
      else if (dims.transitions.coveredIds.includes(id)) edges.forEach((e) => covered.add(e.id));
    }
    // @xstate/test finds reachable states from static targets, and a function
    // transition has none, so transitions out of states reached only through
    // one are "unknown". Once a run covers such a source, they are uncovered.
    for (const id of dims.transitions?.unknown ?? []) {
      const [kind, source, event] = parse(id);
      if (kind === 'transition') edgesOf(source, event).forEach((e) => unknown.set(e.id, source));
    }
    for (const steps of run.paths ?? []) {
      let before;
      for (const { event, value } of steps) {
        const after = activeIds(value);
        for (const key of branched) {
          const [source, type] = key.split('\\n');
          if (type !== event || (before && !before.includes(source))) continue;
          const edges = edgesOf(source, type);
          const hit = edges.find((e) => e.data?.transitionType !== 'targetless' && after.includes(e.targetId))
            ?? edges.find((e) => e.data?.transitionType === 'targetless');
          if (hit) covered.add(hit.id);
        }
        before = after;
      }
    }
    document.getElementById('last').textContent = 'last: ' + run.label;
    render();
  }

  async function render() {
    if (!graph) return;
    for (const [id, source] of unknown) if (covered.has(source)) known.add(id);
    const edges = new Set(graph.edges.map((e) => e.id));
    const count = (inEdges) => [...covered].filter((id) => edges.has(id) === inEdges).length + '/' + [...known].filter((id) => edges.has(id) === inEdges).length;
    document.getElementById('s').textContent = count(false);
    document.getElementById('t').textContent = count(true);
    const uncovered = [...known].filter((id) => !covered.has(id));
    const highlights = [];
    if (covered.size) highlights.push({ kind: 'entities', ids: [...covered], color: '#22c55e', label: 'Covered' });
    if (uncovered.length) highlights.push({ kind: 'entities', ids: uncovered, color: '#ef4444', label: 'Not covered' });
    const result = await embed.setSession({ highlights, showLegend: true });
    if (result.diagnostics?.length) console.warn('session diagnostics', result.diagnostics);
  }

  new EventSource('/events').onmessage = (e) => {
    const msg = JSON.parse(e.data);
    if (msg.reset) { covered.clear(); known.clear(); unknown.clear(); pending.length = 0; document.getElementById('last').textContent = ''; render(); }
    else apply(msg);
  };
  document.getElementById('reset').onclick = () => fetch('/reset', { method: 'POST' });
</script>`;

const types = { '.mjs': 'text/javascript', '.js': 'text/javascript', '.map': 'application/json' };

// No CORS headers: the page is same-origin and tests post from Node. `/` can
// contain STATELY_API_KEY, so other origins must not read it.
createServer((req, res) => {
  const url = new URL(req.url, `http://${host}`);
  if (url.pathname === '/') return res.end(page);
  if (url.pathname === '/machine') return res.end(readFileSync(machinePath, 'utf8'));
  if (url.pathname.startsWith('/sdk/')) {
    const file = join(sdkDir, url.pathname.slice(5));
    try {
      if (!file.startsWith(sdkDir + sep) || !statSync(file).isFile()) return res.writeHead(404).end();
      const body = readFileSync(file);
      res.setHeader('Content-Type', types[extname(file)] ?? 'application/octet-stream');
      return res.end(body);
    } catch {
      return res.writeHead(404).end();
    }
  }
  if (url.pathname === '/events') {
    res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
    for (const run of runs) send(res, run);
    clients.add(res);
    return req.on('close', () => clients.delete(res));
  }
  if (url.pathname === '/reset' && req.method === 'POST') {
    runs.length = 0;
    for (const client of clients) send(client, { reset: true });
    return res.end();
  }
  if (url.pathname === '/coverage' && req.method === 'POST') {
    let body = '';
    req.on('data', (c) => (body += c));
    req.on('end', () => {
      try {
        const msg = JSON.parse(body);
        const run = { coverage: msg.coverage, paths: msg.paths, label: msg.label ?? `run ${runs.length + 1}` };
        runs.push(run);
        for (const client of clients) send(client, run);
        res.end();
      } catch (error) {
        res.writeHead(400).end(String(error));
      }
    });
    return;
  }
  res.writeHead(404).end();
}).listen(port, host, () => console.log(`coverage viewer: http://${host}:${port}`));

LICENSE

README.md

SKILL.md

tile.json