<!-- https://tinyactors.dev/guides/charts/ -->
# Writing charts

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Write an actor's behaviour as an SCXML chart in JavaScript, and compile your charts into one image a host runs.

A chart's conditions, data and scripts are plain JavaScript that reads the actor's variables by name. Your charts compile into one image: bytes a host runs, in this process or another.

<a id="first-chart"></a>

## Install the package and run a chart

Install `@tinyactors/node`, which runs on Node.js and Bun:

- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi#readme))

This program runs an order: it waits for payment, then for shipping, and logs each state it enters:

```javascript title="order.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'order.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="pending">
  <state id="pending">
    <onentry><log expr="'pending'"/></onentry>
    <transition event="paid" target="paid"/>
    <transition event="cancel" target="cancelled"/>
  </state>
  <state id="paid">
    <onentry><log expr="'paid'"/></onentry>
    <transition event="shipped" target="shipped"/>
  </state>
  <final id="shipped">
    <onentry><log expr="'shipped'"/></onentry>
  </final>
  <final id="cancelled"/>
</scxml>` }]);

const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();

const order = host.spawn('order');
host.send(order, 'paid');
host.send(order, 'shipped');
await host.idle();
host.close();
```

```text title="output"
pending
paid
shipped
```

`host.spawn` starts an actor of the chart, and each `host.send` gives it an event. The actor handles its events one at a time, in order.

<a id="variables-and-expressions"></a>

## Declare variables and read the event

Declare an actor's variables with `<data>`. Each `expr` is evaluated once, when the actor starts, unless `spawn`'s `params` give [another value](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#starting-an-actor-with-data).

Every `cond`, `expr`, `<log expr>` and `<script>` reads the variables by name, beside the names the host sets:

| Name | What it holds |
|---|---|
| `_event` | the event being handled: `name`, `data`, `type` (`'external'`, `'internal'` or `'platform'`), `sendid`, `origin`, `origintype`, `invokeid`, and `raw` when an I/O processor's answer gave one |
| `_sessionid` | the actor's session, as a string |
| `_name` | the actor's name, or its chart's name when it has none |
| `_ioprocessors` | the I/O processors, by type; `_ioprocessors.scxml.location` is the actor's address |
| `In(id)` | whether state `id` is active |

An expression is ordinary JavaScript, such as the spread and `slice` that keep the thermostat's last three readings below.

An assignment to an undeclared name, to `_event` or to a system variable raises `error.execution`, as a throwing expression does.

One region of this thermostat switches the heater while the other logs readings. Its `typo` event assigns to a name it never declared:

```javascript title="thermostat.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="thermostat" initial="running">
  <datamodel>
    <data id="readings" expr="[]"/>
    <data id="target" expr="20"/>
  </datamodel>
  <parallel id="running">
    <state id="heater" initial="off">
      <state id="off">
        <onentry><log expr="'heater off'"/></onentry>
        <transition event="reading" cond="_event.data.celsius &lt; target" target="on"/>
      </state>
      <state id="on">
        <onentry><log expr="'heater on'"/></onentry>
        <transition event="reading" cond="_event.data.celsius &gt;= target" target="off"/>
      </state>
    </state>
    <state id="recorder">
      <transition event="reading">
        <assign location="readings" expr="[...readings, _event.data.celsius].slice(-3)"/>
        <log expr="_event.data.celsius + '°C, last ' + readings.join(' ') + ', heating: ' + In('on')"/>
      </transition>
      <transition event="typo"><assign location="tagret" expr="21"/></transition>
      <transition event="error.execution"><log expr="'that was an error.execution'"/></transition>
    </state>
  </parallel>
</scxml>`;

const compiled = compileCharts([{ name: 'thermostat.scxml', text: chart }]);
const host = new Host(compiled, { system: 'home', log: (entry) => console.log(entry.text) });
compiled.close();

const thermostat = host.spawn('thermostat');
for (const celsius of [18, 19, 21]) host.send(thermostat, 'reading', { celsius });
host.send(thermostat, 'typo');
await host.idle();
host.close();
```

```text title="output"
heater off
18°C, last 18, heating: false
heater on
19°C, last 18 19, heating: true
21°C, last 18 19 21, heating: false
heater off
that was an error.execution
```

Inside an attribute, XML needs `&lt;` for `<` and `&amp;` for `&`.

Both regions of the `<parallel>` handle a `reading` in one step. The states it leaves are exited first, then every transition's actions run, then the new states are entered.

So `In('on')` in the recorder is true only when the heater stays on. At 18°C the recorder logs `heating: false` before the heater logs `heater on`.

<a id="scripts"></a>

## Define helper functions once per chart

A `function` in a chart-level `<script>` is a helper, made once for the chart and callable from its actors' expressions. This basket prices its items with one:

```javascript title="basket.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="basket" initial="open">
  <datamodel>
    <data id="items" expr="[]"/>
  </datamodel>
  <script>
    function price(sku) { return ({ tea: 4, cake: 7 })[sku] ?? 0; }
  </script>
  <state id="open">
    <transition event="add"><script>items.push(_event.data.sku)</script></transition>
    <transition event="checkout" target="closed">
      <log expr="'total ' + items.map(price).reduce((a, b) => a + b, 0)"/>
    </transition>
  </state>
  <final id="closed"/>
</scxml>`;

const compiled = compileCharts([{ name: 'basket.scxml', text: chart }]);
const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();

const basket = host.spawn('basket');
for (const sku of ['tea', 'cake', 'tea']) host.send(basket, 'add', { sku });
host.send(basket, 'checkout');
await host.idle();
host.close();
```

```text title="output"
total 15
```

A helper sees no actor's variables by name, so pass it what it reads, as the basket passes each `sku`. Another chart cannot call it.

A hibernated, migrated or snapshotted actor gets its helpers back from its chart, not from its blob.

A function held in a variable is not a value, so it keeps its actor in memory. Declare it with `function` in a chart-level script instead.

`<script>` also runs statements in a transition, in `<onentry>` or `<onexit>`. A chart-level script's other statements run once, when an actor starts.

A host runs chart code in one engine, its datamodel: `native` by default, or [quickjs](https://tinyactors.dev/guides/quickjs/index.md). On native, a host's actors share one context, and a script's top-level declarations mean this:

- **`function` in a chart-level script**: a helper of the chart, as above.
- **`function` in executable content**: that run's own, gone when the script ends.
- **`var`**: a variable of the actor, as a `<data>` is. It is read before the script runs and written back after, so it keeps its value between runs and is hibernated with the actor.
- **`let`, `const` and `class`**: refused: the script is `error.execution` each time it runs. Inside a block or a function they are fine.

`compileCharts` warns of every top-level `var`, `let`, `const` and `class` at the script's line, an error with `{warningsAsErrors: true}`.

The warning names the `<data id>` to declare instead, which other SCXML tools read. It is the same whichever datamodel a host runs the chart on.

On quickjs a chart-level script runs as global code in the actor's own context, which [costs memory](https://tinyactors.dev/guides/quickjs/index.md#realms). All its declarations are the actor's, and its functions see its variables.

<a id="sending-events"></a>

## Send an event to any actor

`<send>` sends an event to the actor itself, to another actor, or out of the host to your program. Each attribute has an `...expr` form that computes it:

| Attribute | What it gives | Default |
|---|---|---|
| `event`, `eventexpr` | the event's name | required |
| `target`, `targetexpr` | where it goes: an address, `#_scxml_<session>`, `#_parent`, `#_<invokeid>`, `#_internal` | the actor itself, at the back of its queue |
| `type`, `typeexpr` | the I/O processor ([I/O processors](https://tinyactors.dev/guides/io-processors/index.md)) | SCXML's own, between actors |
| `id`, `idlocation` | the send's id, for `<cancel>` and the answer's `_event.sendid`; `idlocation` names a declared `<data>` that gets a generated id, unique in the actor's session only (every session's first is `send.1`) | none |
| `delay`, `delayexpr` | when: `500ms`, `1.5s`, `30s` | now |
| `namelist` | variables whose names and values become the data | none |

The data is `<param name expr>`s and `namelist`, as an object, or one `<content expr>`, any value.

`#_internal` puts the event in the actor's internal queue, which runs before anything waiting outside, as `<raise>` does.

This sender sends an order to itself, a note to its internal queue, and a greeting to a target it computes. The note runs before the order sent ahead of it:

```javascript title="send.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const sender = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="sender" initial="s">
  <datamodel>
    <data id="qty" expr="2"/>
    <data id="sku" expr="'tea'"/>
    <data id="lastid"/>
    <data id="peer" expr="'#_scxml_2'"/>
  </datamodel>
  <state id="s">
    <onentry>
      <send event="self.order" namelist="qty sku" idlocation="lastid"/>
      <send event="self.note" target="#_internal"/>
      <send eventexpr="'hello.' + sku" targetexpr="peer"/>
      <log expr="'the order went out as ' + lastid"/>
    </onentry>
    <transition event="self.*"><log expr="_event.name + ' (' + _event.type + ') ' + JSON.stringify(_event.data)"/></transition>
  </state>
</scxml>`;
const receiver = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="receiver" initial="s">
  <state id="s"><transition event="hello"><log expr="'receiver got ' + _event.name"/></transition></state>
</scxml>`;

const compiled = compileCharts([{ name: 'sender.scxml', text: sender }, { name: 'receiver.scxml', text: receiver }]);
const host = new Host(compiled, { system: 'demo', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('sender');
host.spawn('receiver');
await host.idle();
host.close();
```

```text title="output"
the order went out as send.1
receiver got hello.tea
self.note (internal) undefined
self.order (external) {"qty":2,"sku":"tea"}
```

`idlocation` must name a declared `<data>`, as every assignment must. Otherwise the `<send>` fails with `error.execution` and nothing is sent.

<a id="xml-data"></a>

## Keep XML data in a variable

A `<data>` whose content is XML holds a document. Node.js and Bun have no `DOMParser`, so the package builds a small DOM of its own:

- **Every node**: has `nodeType`, `nodeName`, `nodeValue`, `attributes`, `childNodes`, `firstChild`, `lastChild`, `parentNode` and `textContent`, and the methods `getElementsByTagName(name)` (an array, `'*'` for every element), `getAttribute(name)` and `hasAttribute(name)`.
- **A document**: has `documentElement` too.

This menu walks its catalog's `price` elements with `<foreach>` and logs each one's `sku` and text:

```javascript title="menu.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const chart = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="menu" initial="s">
  <datamodel>
    <data id="catalog">
      <prices xmlns=""><price sku="tea">4</price><price sku="cake">7</price></prices>
    </data>
  </datamodel>
  <state id="s">
    <onentry>
      <foreach array="catalog.getElementsByTagName('price')" item="node" index="i">
        <log expr="(i + 1) + '. ' + node.getAttribute('sku') + ' ' + node.textContent"/>
      </foreach>
    </onentry>
  </state>
</scxml>`;

const compiled = compileCharts([{ name: 'menu.scxml', text: chart }]);
const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('menu');
await host.idle();
host.close();
```

```text title="output"
1. tea 4
2. cake 7
```

An actor whose variable holds a DOM stays in memory: hibernation and snapshots refuse it.

A DOM reaches your program as XML text, in a send's `<content>` or from `actorContext`, on both datamodels. A document arrives as the text it was read from, a node written out.

<a id="a-chart-that-starts-another"></a>

## Start a child actor from a state

`<invoke src>` starts a child, an actor of another chart, when its state is entered. Leaving the state stops it.

The `<param>`s set the child's variables, as `spawn`'s `params` do. The child sends to its parent with `target="#_parent"`.

A child's events carry the invoke's `id` as `_event.invokeid`. When the child reaches a final state, the parent gets `done.invoke.<id>` with its `<donedata>`.

This parent passes its worker 21; the worker reports progress, then finishes with twice that:

```javascript title="invoke.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const parent = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="parent" initial="waiting">
  <state id="waiting">
    <invoke id="worker" src="worker.scxml"><param name="n" expr="21"/></invoke>
    <transition event="progress"><log expr="'progress from ' + _event.invokeid + ': ' + _event.data.step"/></transition>
    <transition event="done.invoke.worker" target="done">
      <log expr="'the worker answered ' + _event.data.answer"/>
    </transition>
  </state>
  <final id="done"/>
</scxml>`;

const worker = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="worker" initial="working">
  <datamodel><data id="n" expr="0"/></datamodel>
  <state id="working">
    <onentry><send event="progress" target="#_parent"><param name="step" expr="'halfway'"/></send></onentry>
    <transition target="finished"/>
  </state>
  <final id="finished">
    <donedata><param name="answer" expr="n * 2"/></donedata>
  </final>
</scxml>`;

const compiled = compileCharts([{ name: 'parent.scxml', text: parent }, { name: 'worker.scxml', text: worker }]);
const host = new Host(compiled, { system: 'demo', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('parent');
await host.idle();
host.close();
```

```text title="output"
progress from worker: halfway
the worker answered 42
```

A parent sends to its child with `target="#_worker"`: `#_` and the invoke's id. An `<invoke>` of a type other than SCXML is a service your program runs ([Invoked services](https://tinyactors.dev/guides/services/index.md)).

<a id="when-the-child-exists"></a>

## Wait for the child before sending to it

A child starts at the end of the macrostep that entered its state, once the actor settles, as SCXML starts invocations.

Until then a send to the child gets `error.communication`. That covers the state's own `<onentry>`, and anything else in the same macrostep:

- a `<raise>`d event's transition;
- an eventless transition;
- a history state that re-enters several states at once.

Send once the child's first message arrives, such as `ready` below. Pass what the child needs at its start as a `<param>`, evaluated when it starts.

This parent sends `hello` from its `<onentry>`, from a raised event and after `ready`. Only the last arrives:

```javascript title="child-ready.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const parent = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="parent" initial="running">
  <state id="running">
    <onentry>
      <send event="hello" target="#_kid"/>
      <raise event="soon"/>
    </onentry>
    <invoke id="kid" src="kid.scxml"/>
    <transition event="soon"><send event="hello" target="#_kid"/></transition>
    <transition event="error.communication"><log expr="'no child yet: error.communication'"/></transition>
    <transition event="ready"><send event="hello" target="#_kid"/></transition>
  </state>
</scxml>`;
const kid = `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="kid" initial="s">
  <state id="s">
    <onentry><send event="ready" target="#_parent"/></onentry>
    <transition event="hello"><log expr="'the child got hello'"/></transition>
  </state>
</scxml>`;

const compiled = compileCharts([{ name: 'parent.scxml', text: parent }, { name: 'kid.scxml', text: kid }]);
const host = new Host(compiled, { system: 'demo', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('parent');
await host.idle();
host.close();
```

```text title="output"
no child yet: error.communication
no child yet: error.communication
the child got hello
```

<a id="several-charts-in-one-image"></a>

## Put several charts in one image

`compileCharts` takes a list of documents, each `{ name, text }`, and compiles them into one image.

Each chart is known by its `<scxml name>`: `host.spawn(name)` starts one, and `host.chart(name)` finds its current version. A document's `name` is what error messages and `src` attributes name.

A chart may read another document through `src`: `<invoke src>`, `<script src>` or `<data src>`. A document in the list answers a `src` with its name.

For any other `src`, give `compileCharts` a resolver, a function `(base, source) => text` the compile calls. `base` is the document that names the `src`.

A resolver may read a file or a database; this one reads a map. Its `ResolveError` becomes a compile error at the line and column it gives:

```javascript title="resolver.mjs"
import { compileCharts, CompileError, ResolveError } from '@tinyactors/node';

const files = { 'child.scxml': '<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="child"><final id="f"/></scxml>' };
const resolver = (base, source) => {
  if (!(source in files)) throw new ResolveError(`${base} asks for ${source}, which is not in the store`, { line: 1, column: 1 });
  return files[source];
};

const parent = (src) => `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="parent">
  <state id="s"><invoke src="${src}"/></state>
</scxml>`;

const compiled = compileCharts([{ name: 'parent.scxml', text: parent('child.scxml') }], { resolver });
console.log('compiled', compiled.image.length > 0);
compiled.close();

try {
  compileCharts([{ name: 'parent.scxml', text: parent('missing.scxml') }], { resolver });
} catch (error) {
  if (!(error instanceof CompileError)) throw error;
  console.log(error.message);
}
```

```text title="output"
compiled true
missing.scxml:1:1: error: parent.scxml asks for missing.scxml, which is not in the store
```

Any other error a resolver throws, such as a file it cannot read, is thrown from `compileCharts` as it is.

<a id="charts-in-a-directory"></a>

## Compile a whole directory of charts

`compileDir(dir)` compiles every `*.scxml` file under `dir` into one image. `dir` is a path, or a `file:` URL such as `new URL('./charts/', import.meta.url)`.

Each chart is named by its path under `dir`, `/`-separated, and the list is sorted by name. So the first is the image's default boot chart.

A `src` that names no file of the list is read relative to the directory of the document that names it. `orders/order.scxml` asking for `payment.scxml` reads `<dir>/orders/payment.scxml`.

`compileDir` reads each such `src` with a resolver confined to `dir`, which reports these as compile errors:

- a path that leaves `dir`: `..` past it, an absolute path, or a symbolic link that points outside;
- a file that does not exist;
- a file that is not UTF-8.

Another error of the file system, such as no permission, is thrown as it is. A directory with no chart is refused with `InvalidError`.

`compileDir(dir, { resolver })` reads each `src` with your resolver instead.

An order here invokes the payment chart beside it. Rewritten to reach outside the directory, it no longer compiles:

```javascript title="compile-dir.mjs"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { CompileError, compileDir, Host } from '@tinyactors/node';

const root = mkdtempSync(join(tmpdir(), 'charts-'));
mkdirSync(join(root, 'orders'));
writeFileSync(join(root, 'orders', 'order.scxml'), `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
    datamodel="ecmascript" name="order">
  <state id="s"><invoke src="payment.xml"/></state>
</scxml>`);
writeFileSync(join(root, 'orders', 'payment.xml'), `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
    datamodel="ecmascript" name="payment">
  <state id="s"><onentry><log expr="'paying'"/></onentry></state>
</scxml>`);

const compiled = compileDir(root);
const host = new Host(compiled, { system: 'demo', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('order');
await host.idle();
host.close();

writeFileSync(join(root, 'orders', 'order.scxml'), `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="order">
  <state id="s"><invoke src="../../etc/passwd"/></state>
</scxml>`);
try {
  compileDir(root);
} catch (error) {
  if (!(error instanceof CompileError)) throw error;
  console.log(error.diagnostics[0].message);
}
rmSync(root, { recursive: true });
```

```text title="output"
paying
../../etc/passwd (from orders/order.scxml) leaves the charts' directory
```

A document the resolver read is named by its `src` as written. A `src` inside it is read relative to that name's directory.

<a id="the-compile-result"></a>

## Save an image to run it elsewhere

`compileCharts` returns an object whose `image` is a `Buffer`, copied out at its first read and then yours. Its `diagnostics` lists the compiler's warnings.

Write the image to a file and give it to a host in another process: `new Host(readFileSync(path), options)`.

`new Host(compiled, options)` copies the image, so `close()` may free the compiler's memory at once. The garbage collector frees it otherwise.

`new Host` takes one image or a list, compile results and bytes alike. Each becomes a segment, the number the host knows it by, in order.

`host.addImage(bytes)` adds an image to a running host. It copies the bytes and returns the image's segment.

<a id="a-system-that-starts-its-own-actors"></a>

## Boot named actors from a manifest

When a system starts the same actors every time, list them in a manifest, so your program need not know which.

A manifest is a `<system>` document. Its charts are `<chart name src>`, read through the resolver, and its actors `<actor name chart>`.

`compileSystem` compiles it, and `host.boot(segment)` spawns its actors, each with its name. The image `new Host` was given first is segment 0.

```javascript title="boot.mjs"
import { compileSystem, Host } from '@tinyactors/node';

const files = {
  'counter.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
      datamodel="ecmascript" name="counter" initial="s">
    <datamodel><data id="n" expr="0"/></datamodel>
    <state id="s">
      <transition event="tick"><assign location="n" expr="n + 1"/><log expr="_name + ' ' + n"/></transition>
    </state>
  </scxml>`,
};
const manifest = `<system>
  <chart name="counter" src="counter.scxml"/>
  <actor name="left" chart="counter"/>
  <actor name="right" chart="counter"/>
</system>`;

const compiled = compileSystem({ name: 'system.xml', text: manifest }, { resolver: (base, source) => files[source] });
const host = new Host(compiled, { system: 'demo', log: (entry) => console.log(entry.text) });
compiled.close();

host.boot(0);
host.actor('left').send('tick');
host.actor('right').send('tick');
host.actor('left').send('tick');
await host.idle();
host.close();
```

```text title="output"
left 1
right 1
left 2
```

A program that spawns its own actors can skip `boot`. An image from `compileCharts` has one boot actor too, of its first chart, named after its `<scxml name>`.
