@tinyactors/node 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,31 @@
1
- # tinyactors for Node.js
2
-
3
- xstate-style machines and actors running on the tinyactors SCXML runtime.
4
- The addon is written against the **Node-API C API** (`node_api.h`, no C++
5
- wrapper) and links the tinyactors static libraries. The JavaScript API lives
6
- in `bindings/shared/core.mjs` and is shared with the
7
- [web binding](../web) (same `index.d.ts`), so the same code runs in Node.js and
8
- in browsers. Node.js ≥ 22.12 (`require()` of the ES-module core).
1
+ # @tinyactors/node
2
+
3
+ Run statecharts as actors in Node.js and Bun.
4
+
5
+ Much of a program's logic is a lifecycle: an order is open, then paying,
6
+ then paid or timed out; a connection is dialing, up, or backing off. Written
7
+ as flags and callbacks, a lifecycle spreads over a codebase, and the states
8
+ it may be in are nowhere written down. A **statechart** writes them down:
9
+ the states, the events that move between them, and what happens on the
10
+ way. This package runs statecharts written in
11
+ [SCXML](https://www.w3.org/TR/scxml/), the W3C's XML language for them,
12
+ with JavaScript for their data and expressions.
13
+
14
+ Each running statechart is an **actor**: it has its own data and a queue
15
+ of events, and it talks to the world only by sending and receiving events.
16
+ A **host** runs many of them, from a handful to millions, on your
17
+ program's event loop. The host does no I/O of its own. When an actor sends
18
+ something out (a payment request, a log line, an email), your handler gets
19
+ it, does the I/O, and answers with an event. So the logic stays in the
20
+ charts, testable on a simulated clock, and the I/O stays in your code.
21
+
22
+ Use it when your program keeps many long-lived things that each have a
23
+ lifecycle (orders, sessions, devices, workflows), when you want timeouts
24
+ and retries written as states rather than timers, or when the same logic
25
+ must run in tests without the network.
26
+
27
+ This README describes the package as it is built from `main`. The last
28
+ version on npm, 0.2.0, is an earlier binding with another API.
9
29
 
10
30
  ## Install
11
31
 
@@ -13,389 +33,631 @@ in browsers. Node.js ≥ 22.12 (`require()` of the ES-module core).
13
33
  npm install @tinyactors/node # or: pnpm add, bun add
14
34
  ```
15
35
 
16
- The package carries no compiler step: each supported platform has a
17
- prebuilt addon in its own package (`@tinyactors/node-darwin-arm64`,
18
- `-darwin-x64`, `-linux-x64`, `-linux-arm64`), an optional dependency that
19
- npm, pnpm and Bun install only where it matches. The Linux addon serves
20
- glibc and musl alike. Development builds are under the `next` dist-tag
21
- (`npm install @tinyactors/node@next`).
22
-
23
- In this repository, `mise run node:build` (in `tinyactors-core`) builds the
24
- addon into `bindings/node/build/tinyactors.node`, which `index.js` loads
25
- before any installed platform package. Packaging and releasing are in
26
- [distribution](../../docs/distribution.md).
36
+ It runs on Node.js 22.3 or later and on Bun (tested on 1.4), on macOS
37
+ (arm64, x64) and Linux (x64, arm64; glibc or musl). Nothing compiles on
38
+ install: the addon is prebuilt, one per platform, in
39
+ `@tinyactors/node-darwin-arm64`, `-darwin-x64`, `-linux-x64` and
40
+ `-linux-arm64`, which the main package lists as optional dependencies, so
41
+ the package manager installs only the one that matches. A Linux addon
42
+ links no C library, so one file serves glibc and musl. The macOS addons
43
+ are cross-built from Linux and checked by their symbols; no Mac has run
44
+ them yet. An install that left out optional dependencies
45
+ (`--no-optional`, `--omit=optional`) fails at import, naming the package
46
+ it needs.
47
+
48
+ For a browser, or a platform with no addon (Windows), the same API is
49
+ `@tinyactors/wasm`, core compiled to WebAssembly: see
50
+ [In the browser](docs/guide/browser.md), which says what differs.
51
+
52
+ Development builds of `main` are published under the `next` dist-tag
53
+ (`npm install @tinyactors/node@next`), versioned
54
+ `<next minor>-dev.<date>.<n>.g<commit>`. Releases, their tarballs and
55
+ `SHA256SUMS` are on
56
+ [tinyactors-dev/tinyactors-napi](https://github.com/tinyactors-dev/tinyactors-napi/releases).
57
+
58
+ ## A first program
59
+
60
+ An order collects items, then asks a payment service to charge the total,
61
+ and is paid when the service answers. Save this as `order.mjs` and run it
62
+ with `node order.mjs` or `bun order.mjs`:
27
63
 
28
64
  ```js
29
- const { createMachine, createActor, assign } = require('@tinyactors/node');
30
-
31
- const toggle = createMachine({
32
- id: 'toggle',
33
- initial: 'inactive',
34
- context: { count: 0 },
35
- states: {
36
- inactive: { on: { TOGGLE: { target: 'active', actions: assign({ count: ({ context }) => context.count + 1 }) } } },
37
- active: { on: { TOGGLE: 'inactive' }, after: { 1000: 'inactive' } },
65
+ import { compileCharts, Host } from '@tinyactors/node';
66
+
67
+ // 1. The chart: the order's states and what moves between them.
68
+ const chart = `
69
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
70
+ datamodel="ecmascript" name="order" initial="open">
71
+ <datamodel>
72
+ <data id="total" expr="0"/>
73
+ </datamodel>
74
+ <state id="open">
75
+ <transition event="add">
76
+ <assign location="total" expr="total + _event.data.price"/>
77
+ </transition>
78
+ <transition event="checkout" target="paying"/>
79
+ </state>
80
+ <state id="paying">
81
+ <onentry>
82
+ <send type="urn:payments" event="charge" target="card">
83
+ <param name="amount" expr="total"/>
84
+ </send>
85
+ </onentry>
86
+ <transition event="charged" target="paid"/>
87
+ </state>
88
+ <final id="paid">
89
+ <onentry><log label="order" expr="'paid ' + total"/></onentry>
90
+ </final>
91
+ </scxml>`;
92
+
93
+ // 2. Compile it into an image the host can load.
94
+ const compiled = compileCharts([{ name: 'order.scxml', text: chart }]);
95
+
96
+ // 3. A host, with a handler for what the chart sends to urn:payments.
97
+ const host = new Host(
98
+ { systemID: 'shop', ioProcessors: [{ type: 'urn:payments' }] },
99
+ {
100
+ ioProcessors: {
101
+ 'urn:payments': (host, send) => {
102
+ console.log(`charging ${send.data.amount} to ${send.target}`);
103
+ send.answer('charged');
104
+ },
105
+ },
106
+ log: (host, entry) => console.log(`${entry.label}: ${entry.text}`),
38
107
  },
39
- });
40
-
41
- const actor = createActor(toggle).start();
42
- actor.subscribe((s) => console.log(s.value, s.context));
43
- actor.send({ type: 'TOGGLE' });
108
+ );
109
+ host.addImage(compiled.image);
110
+ compiled.close();
111
+
112
+ // 4. An actor of the chart, and three events for it.
113
+ const order = host.spawn(host.chart('order'));
114
+ host.send(order, 'add', { price: 4 });
115
+ host.send(order, 'add', { price: 7 });
116
+ host.send(order, 'checkout');
117
+
118
+ // 5. Let it run, then stop.
119
+ await host.idle();
120
+ host.close();
44
121
  ```
45
122
 
46
- ## How it works
47
-
48
- - `createMachine(config)` compiles the config to SCXML that reads like
49
- hand-written SCXML (`machine.toSCXML()`): named guards and actions appear by
50
- name (`cond="isAdult"`, `<script>track({"tag":"t"})</script>`), inline
51
- functions by their source, literals as JSON, `stateIn` as `In('a.b')`,
52
- combinators as `and(isAdult, not(above({"min":30})))`, assigns as
53
- `<assign location="count" expr="..."/>`, raises as `<raise event="X"/>`.
54
- - The context is SCXML data: one `<data id="prop">` per property, for object
55
- literals and for factories `({ input }) => ({ a: input.a, b: [] })` alike
56
- (each `<data>` shows its property's source; the factory still runs once per
57
- actor). `assign()` becomes one `<assign location="prop">` per property; the
58
- computed properties are evaluated together against the previous context
59
- (xstate semantics), constants follow. Sequential steps read best as
60
- sequential assigns: `[assign({ pos: ... }), assign({ status: ({ context })
61
- => status(context.pos) })]`. Only a function the compiler cannot split (a
62
- block body, spreads, computed keys) falls back to a single
63
- `<data id="context">` / `<assign location="context">`.
64
- - Each machine keeps a registry from that text to the JavaScript function
65
- implementing it. When a chart is attached to a native system, the datamodel
66
- resolves every expression of the chart once and stores the functions in a
67
- table indexed by the image's expression ids — evaluation is an indexed
68
- call, and the index never appears in the chart. Two different functions
69
- with the same source text are told apart by a trailing comment
70
- (`... /* 2 */`).
71
- - **One native system per `System`, not per actor.** Actors started with
72
- `createActor()` live in the process-wide default system (or the one given
73
- as `createActor(machine, { system: createSystem() })`). The machines known
74
- when the system starts are linked into one image; a machine defined later
75
- is linked into an additional *segment* (as is each reloaded version). All
76
- segments share one base URI, `tinyactors://<system id>/`, and each creates
77
- sessions from its own range; a send to a session in another segment goes
78
- through the runtime's remote I/O processor (`TA_IO_PROCESSOR_SCXML_SHARED`), so
79
- `sendTo(actor, ...)` and
80
- `sendTo(({ system }) => system.get('id'), ...)` work across them. The
81
- native region grows by relocation (thousands of actors per system).
82
- - Context, events and payloads are napi references owned by the system's
83
- datamodel host; they live as long as the system (payloads are refcounted
84
- and recycled).
85
- - Events are processed synchronously on `send()`; long-running work yields
86
- cooperatively (`setImmediate`) so even a runaway eventless loop cannot block
87
- the event loop or starve other actors. Delayed events use the host clock via
88
- `setTimeout`. Calls made from inside actions (e.g. `actor.send()`) are
89
- queued until the current run returns. A system runs on the JavaScript
90
- thread; for more cores, run systems in worker threads and link them —
91
- [docs/concurrency.md](../../docs/concurrency.md) explains what runs when.
92
-
93
- ## Hibernation
94
-
95
- Idle actors can be unloaded and brought back on demand. The system never does
96
- I/O itself: you hand it a store.
123
+ It prints:
97
124
 
98
- ```js
99
- const system = createSystem({
100
- hibernation: {
101
- store: { get: (k) => db.get(k), set: (k, blob) => db.put(k, blob), delete: (k) => db.del(k) }, // may be async
102
- sweepMs: 30_000, // unload actors idle for a whole sweep period (0 = only system.hibernate())
103
- },
104
- });
105
- system.hibernate(actor); // or system.hibernate() for every idle actor
106
- actor.hibernated; // true; getSnapshot() is answered from cache
107
- actor.send({ type: 'X' }); // the event waits, the blob is loaded, the actor carries on
125
+ ```output
126
+ charging 11 to card
127
+ order: paid 11
108
128
  ```
109
129
 
110
- Context, events and input travel through a tagged-JSON codec (`encodeValue` /
111
- `decodeValue`). It keeps `undefined`, `Date`, `Map`, `Set`, `BigInt`, shared
112
- references and cycles, and encodes actors as their addresses. Actors whose
113
- context holds functions stay resident (the sweep skips them;
114
- `system.hibernate(actor)` throws, naming what cannot be stored). Pending
115
- delayed events wake the actor when they fire. `createMemoryStore()` is a
116
- store in memory.
117
-
118
- ### Moving an actor to another system
119
-
120
- `system.export(actor)` takes an actor out of its system as bytes — states,
121
- context or variables, delayed events with their data, the actors it invoked,
122
- and what it runs. `system.adopt(bytes)` takes it in anywhere: another system
123
- in this process, another process, Node or web. It keeps its session (its
124
- address under the new system's id), and its delayed events keep the time
125
- they had left.
130
+ What happened, step by step:
131
+
132
+ 1. **The chart** has three states. In `open`, each `add` event adds its
133
+ price to the variable `total`; `checkout` moves to `paying`. Entering
134
+ `paying` sends a `charge` event to `urn:payments`, which is not
135
+ another actor but something outside the host. The answer `charged`
136
+ moves to `paid`, a final state, which logs the total.
137
+ 2. **`compileCharts`** checks the chart and compiles it. A mistake in the
138
+ XML, an unknown state id or a malformed attribute throws a
139
+ `CompileError` here, before anything runs. JavaScript that does not
140
+ parse is a warning in `compiled.diagnostics` (SCXML makes it an
141
+ `error.execution` when it runs), and an error with
142
+ `compileCharts(sources, undefined, { warningsAsErrors: true })`.
143
+ 3. **`new Host(config, options)`** makes a host. The config names this
144
+ system (`systemID`) and the I/O processors its charts may send to; the
145
+ options hold your handlers. The `urn:payments` handler gets each send
146
+ to that type: its data, its target, and `answer()`, which sends an
147
+ event back to the actor that sent it.
148
+ 4. **`host.spawn`** starts an actor of the chart and returns its session
149
+ id, a `bigint`. `host.send` puts an event in its queue.
150
+ 5. **`await host.idle()`** waits until the host has nothing left to do.
151
+ The actor runs on the event loop on its own; `idle()` only watches.
152
+ `host.close()` frees the host.
153
+
154
+ ## Concepts
155
+
156
+ Read these in order the first time. Each builds on the one before.
157
+
158
+ ### Charts
159
+
160
+ A chart is an SCXML document. Its parts, from the outside in:
161
+
162
+ - **`<scxml>`** names the chart (`name`), its first state (`initial`) and
163
+ its language for data and expressions. Write `datamodel="ecmascript"`,
164
+ JavaScript, on every chart. A chart without the attribute gets SCXML's
165
+ null datamodel, which evaluates no expression and says nothing about it:
166
+ its `<log>`s and `<data>` do nothing. Another value is refused when the
167
+ image is added (`host.addImage` throws `TA_ERROR_INVALID`).
168
+ - **`<state id>`** is a state the actor can be in. States nest (a
169
+ compound state has children, one of them active), and `<parallel>`
170
+ holds regions that are all active at once. **`<final>`** ends the
171
+ actor.
172
+ - **`<transition event cond target>`** leaves the state when an event
173
+ whose name matches `event` arrives and the expression `cond` is true.
174
+ Without `target` it runs its actions and stays.
175
+ - **Actions** run on a transition and in `<onentry>` and `<onexit>`:
176
+ `<assign>`, `<script>`, `<log>`, `<send>`, `<raise>`, `<cancel>`,
177
+ `<if>` and `<foreach>`.
178
+ - **`<datamodel>`** declares the actor's variables, one `<data id expr>`
179
+ each. Every expression in the chart sees them as plain variables, and
180
+ sees the event being handled as `_event` (`_event.name`, `_event.data`).
181
+
182
+ An event's name is matched by prefix, word by word: `event="error"` and
183
+ `event="error.*"` match `error.execution` and `error.communication`;
184
+ `event="a b"` matches either name; `event="*"` matches any event. An
185
+ event no transition matches is dropped.
186
+
187
+ The prefix rule also matches an answer whose name starts with the
188
+ request's: `event="join"` takes `join.refused` too. A chart that asks a
189
+ peer again on `join`, and a peer that answers with `join.refused`, then
190
+ answer each other for ever, and `await host.idle()` never resolves. Name
191
+ an answer so that it does not extend the request (`refused.join`), and
192
+ see [Inspecting a host](docs/guide/inspection.md#two-actors-that-never-rest)
193
+ for how such a loop shows in the host's counters.
194
+
195
+ [Writing charts](docs/guide/charts.md) covers the JavaScript a chart may
196
+ hold, `<script>`, XML data, several charts in one image (and
197
+ `host.addCharts`, `host.spawnChart` and `directoryResolver`, which save
198
+ the steps), and `<invoke>`.
199
+
200
+ ### Starting an actor with data
201
+
202
+ `spawn`'s `params` set the new actor's variables: each key that names a
203
+ top-level `<data>` replaces that variable's initial value, keys that name
204
+ no `<data>` are left out, and the variables you do not name keep the
205
+ chart's `expr`.
126
206
 
127
207
  ```js
128
- const bytes = here.export(actor); // it stops here (no done event)
129
- // ... another process ...
130
- const actor = there.adopt(bytes); // machines are found as for restore
208
+ import { compileCharts, Host } from '@tinyactors/node';
209
+
210
+ const compiled = compileCharts([{ name: 'greeter.scxml', text: `
211
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
212
+ datamodel="ecmascript" name="greeter" initial="ready">
213
+ <datamodel>
214
+ <data id="greeting" expr="'Hello'"/>
215
+ <data id="who" expr="'world'"/>
216
+ </datamodel>
217
+ <state id="ready">
218
+ <onentry><log expr="greeting + ', ' + who + '!'"/></onentry>
219
+ </state>
220
+ </scxml>` }]);
221
+
222
+ const host = new Host({ systemID: 'demo' }, { log: (host, entry) => console.log(entry.text) });
223
+ host.addImage(compiled.image);
224
+ compiled.close();
225
+
226
+ host.spawn(host.chart('greeter'));
227
+ host.spawn(host.chart('greeter'), { params: { who: 'Ada' } });
228
+ host.spawn(host.chart('greeter'), { params: { greeting: 'Hi', who: 'Bob', mood: 'ignored' } });
229
+ await host.idle();
230
+ host.close();
131
231
  ```
132
232
 
133
- ## Hot reload and live migration
134
-
135
- ```js
136
- system.reload(counterV2); // CGI style: returns 2; new actors run it, running ones keep theirs
137
- const { done } = system.migrate(); // move running actors (a job in time slices)
138
- const { migrated, failed, pending } = await done; // pending: left behind (timeout)
139
- system.migrate(counter, { wake: false, timeoutMs: 5000 }); // options
140
- // in counterV2: on: { 'error.platform.upgrade': { actions: assign({ total: ({ event }) => event.data.count }) } }
233
+ ```output
234
+ Hello, world!
235
+ Hello, Ada!
236
+ Hi, Bob!
141
237
  ```
142
238
 
143
- `reload(machine)` makes `machine` the current version of the machines with its
144
- id (compiled right away, so errors throw there). A version whose actors are
145
- all gone is freed. Addresses stay valid: all actors of a system share one base
146
- URI and sessions are found wherever they live. `migrate(target?)` moves actors
147
- of older versions (one actor, a machine's actors, or all) at a stable point:
148
- states are matched by id, the context is kept (properties the new machine does
149
- not declare are dropped, new ones initialized), timers keep running, and the
150
- actor receives `{ type: 'error.platform.upgrade', data: previousContext }`.
151
- Migration is a job advanced in time slices of a few ms, walking the actors
152
- lazily, so the event loop stays responsive with any number of actors (100,000
153
- actors: the call takes ~5 ms, each slice ~5 ms). Busy actors move at their next
154
- stable point. Hibernated actors are loaded from the store first (`wake`, on by
155
- default when the system has a hibernation store), or move once they wake.
156
- `timeoutMs` ends the job and reports who was left behind. `done` resolves once
157
- the moved actors have processed their upgrade event. There is deliberately no
158
- "force": an actor mid-macrostep or with a pending request cannot move without
159
- changing SCXML semantics, and an actor with running invocations waits until
160
- they finish (its invoked sessions run charts of its old version, which are not
161
- translated). Sends to an address
162
- nobody has raise `error.communication` in the sender.
163
-
164
- ## SCXML documents
165
-
166
- `fromSCXML(xml, { documents })` runs a W3C SCXML document as actor logic, in
167
- the same system as your machines (they message each other directly). The
168
- `ecmascript` datamodel (SCXML Appendix B.2) runs in JavaScript with the same
169
- semantics as the C datamodel; `null` works too. The W3C IRP suite passes
170
- through this binding (158/158 mandatory; `mise run w3c:js`).
239
+ ### The host and its event loop
240
+
241
+ A host holds actors and runs them on your program's event loop. There is
242
+ no `run()` to call. An input (`spawn`, `send`, `terminate`) is taken at
243
+ once (the event is in the actor's queue when `send` returns, or the call
244
+ throws), but nothing runs yet: it schedules a turn with `setImmediate`,
245
+ and in its turns the host runs
246
+ every actor that has an event, calls your handlers with what the actors
247
+ sent out, and runs again until nothing is left. A turn does a bounded
248
+ amount of work and then yields, so a busy host never starves your I/O.
249
+
250
+ `await host.idle()` resolves at the next turn that finds nothing to do
251
+ while no promise one of your handlers returned is pending (a promise a
252
+ handler starts and does not return is not waited for). It is for tests, scripts and an orderly shutdown; a server never needs to
253
+ call it. A handler may call the host (send an event, spawn an actor): the
254
+ input applies at once, and the actors run in the same or a later turn.
255
+
256
+ Each `addImage` makes a **segment**: the host's memory for that image's
257
+ actors, numbered from 0, which `addImage` returns. A host runs many
258
+ segments as one; you need the number for `boot` and see it in the host's
259
+ statistics.
260
+
261
+ A host also keeps time. A delayed `<send>` or a timeout is a deadline,
262
+ and an idle host arms one `setTimeout` for its next one. That timer keeps
263
+ the process alive while the host is open, as any `setTimeout` does, and
264
+ it is the only thing the host keeps the process alive with: an open host
265
+ with no deadline lets the process exit, even with actors that wait for an
266
+ answer (below, "Before you use it"). `host.close()` clears the timer,
267
+ frees the host, and drops every handler that was still waiting.
268
+
269
+ ### Actors, sessions and addresses
270
+
271
+ `spawn` returns the actor's **session**, a `bigint` unique in its host.
272
+ Inputs take it back: `host.send(session, event, data)`,
273
+ `host.terminate(session)`. They also take a number that is a safe
274
+ integer, since that is what a database or JSON gives back. The calls and
275
+ views return sessions as `bigint`s (`console.log` prints `1n`, and
276
+ `JSON.stringify` refuses one: convert with `String()` or `Number()`
277
+ yourself), while the results of the typed methods
278
+ ([Inspecting a host](docs/guide/inspection.md)) hold them as numbers. So
279
+ compare with `Number(session) === listed`, never `===` across the two;
280
+ either kind may be passed back to an input.
171
281
 
172
282
  ```js
173
- const { fromSCXML, createActor } = require('@tinyactors/node');
174
-
175
- const counter = fromSCXML(`
176
- <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" datamodel="ecmascript" initial="idle">
177
- <datamodel><data id="count" expr="0"/></datamodel>
178
- <state id="idle">
179
- <transition event="inc"><assign location="count" expr="count + (_event.data.by || 1)"/></transition>
180
- <transition event="done" target="end"/>
181
- </state>
182
- <final id="end"><donedata><param name="total" expr="count"/></donedata></final>
183
- </scxml>`);
184
-
185
- const a = createActor(counter, { input: { count: 10 } }).start(); // input overrides <data>
186
- a.send({ type: 'inc', by: 2 }); // _event.name = 'inc', _event.data = { by: 2 }
187
- a.getSnapshot().context; // { count: 12 } — the datamodel's variables
283
+ import { Host } from '@tinyactors/node';
284
+
285
+ const host = new Host({ systemID: 'demo' });
286
+ host.addCharts({ 'idle.scxml': `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
287
+ datamodel="ecmascript" name="idle"><state id="s"/></scxml>` });
288
+ const session = host.spawnChart('idle', { name: 'first' });
289
+ const { sessions } = await host.actorList();
290
+ console.log(typeof session, typeof sessions[0]);
291
+ console.log(sessions.includes(Number(session)), sessions.map(BigInt).includes(session));
292
+ const byKey = new Map([[String(session), 'kept under its text']]);
293
+ console.log(byKey.get(String(sessions[0])), host.actorByName('first') === session);
294
+ host.close();
188
295
  ```
189
296
 
190
- - Events: `type` becomes `_event.name`; `data` (or, without it, the event's
191
- other properties) becomes `_event.data`.
192
- - The snapshot's `value` is the active states (by id) as a nested state value;
193
- `context` the datamodel variables; `output` the `<donedata>`.
194
- - `documents` maps names to further documents: `<invoke src="child.scxml">`
195
- children and anything a `src="..."` names (`<data src>`).
196
- - Expressions are compiled with `new Function` (a browser CSP must allow
197
- `'unsafe-eval'` for SCXML documents; machines do not need it).
198
- - `<script>`s that declare top-level names (`var`, `let`, `const`,
199
- `function`, `class` — as the JS engine sees them: names in blocks or nested
200
- functions do not count) make those names the session's, as in the C
201
- datamodel. Such actors hibernate, snapshot, export and migrate: variables
202
- and `let`/`const` bindings keep their values (`const` stays constant),
203
- top-level function declarations are re-created. Anything else that cannot
204
- be stored is refused naming the variable and line, e.g. `variable 'helper'
205
- cannot be stored: it holds a function (line 12); only top-level function
206
- declarations are stored ...`.
207
-
208
- ## System images
209
-
210
- A `<system>` manifest names charts and the actors to start; compiled, it is
211
- one immutable image you can ship as bytes (also produced by the C `tac`
212
- compiler) and boot anywhere — Node, a browser, a C host.
213
-
214
- ```js
215
- const { compileSystem, loadImage, createSystem } = require('@tinyactors/node');
216
-
217
- const image = compileSystem(`
218
- <system>
219
- <chart name="pinger" src="ping.scxml"/>
220
- <actor name="server" chart="pinger"/>
221
- </system>`, { files: { 'ping.scxml': pingXML } });
222
-
223
- fs.writeFileSync('app.tai', image.bytes);
224
- const { server } = createSystem().boot(loadImage(fs.readFileSync('app.tai')));
225
- createActor(image.chart('pinger')).start(); // more actors of an image's chart
297
+ ```output
298
+ bigint number
299
+ true true
300
+ kept under its text true
226
301
  ```
227
302
 
228
- ## Snapshots and deterministic time
229
-
230
- `system.snapshot()` returns the whole system as bytes: every actor's
231
- configuration, context or datamodel variables, queued events and pending
232
- timers, plus what it runs (the SCXML of each machine, documents, images).
233
- `createSystem({ restore: bytes })` brings it back — same system id, so
234
- addresses stay valid; find actors with `system.get(systemID)`. Machines are
235
- matched by id and the SCXML they compile to (ones defined in the process are
236
- found automatically; pass more in `machines`). Contexts must be encodable (no
237
- functions); hibernated actors stay in the hibernation store, so restore with
238
- the same store.
303
+ `sessions.includes(session)` would be `false` (TypeScript refuses it),
304
+ and a `Map` keyed by the `bigint` misses the number: key it by
305
+ `String(session)`, which is the same for both kinds.
306
+
307
+ An actor may also have a **name**, given at spawn, and
308
+ `host.actorByName(name)` finds it. An actor that reaches a `<final>`
309
+ state, or is terminated, ends: its session is refused from then on with
310
+ `TA_ERROR_STALE`, and its name finds nothing. The events still in its
311
+ queue when it ends are dropped, as SCXML ends a session at its top-level
312
+ `<final>`: a `host.send` that returned before the end is never handled,
313
+ and nothing tells the application. A chart whose events stand for
314
+ requests your program holds (an HTTP response, a promise) tells your
315
+ program from its `<final>` first:
316
+ [I/O processors](docs/guide/io-processors.md#when-the-sender-ends) has the
317
+ pattern.
318
+
319
+ Actors find each other by **address**. Every system has its `systemID`,
320
+ and an actor's address is `tinyactors://<systemID>/#_scxml_<session>`, or
321
+ `tinyactors://<systemID>/@<name>` for a named one. A chart sends to
322
+ another actor with `<send target="tinyactors://shop/@pong" event="ping"/>`,
323
+ and the receiver answers to `_event.origin`. The `Address` class reads
324
+ and makes them:
239
325
 
240
326
  ```js
241
- const bytes = system.snapshot(); // e.g. on shutdown
242
- // ... a new process ...
243
- const system = createSystem({ restore: bytes, hibernation: { store } });
244
- system.get('lobby').send({ type: 'PING' });
327
+ import { compileCharts, Host, Address } from '@tinyactors/node';
328
+
329
+ const pong = `
330
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
331
+ datamodel="ecmascript" name="pong" initial="waiting">
332
+ <state id="waiting">
333
+ <transition event="ping">
334
+ <log expr="'pong got ' + _event.name"/>
335
+ <send event="pong" targetexpr="_event.origin"/>
336
+ </transition>
337
+ </state>
338
+ </scxml>`;
339
+ const ping = `
340
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
341
+ datamodel="ecmascript" name="ping" initial="asking">
342
+ <state id="asking">
343
+ <onentry><send event="ping" target="tinyactors://demo/@pong"/></onentry>
344
+ <transition event="pong" target="done"><log expr="'ping got ' + _event.name"/></transition>
345
+ </state>
346
+ <final id="done"/>
347
+ </scxml>`;
348
+
349
+ const compiled = compileCharts([{ name: 'ping.scxml', text: ping }, { name: 'pong.scxml', text: pong }]);
350
+ const host = new Host({ systemID: 'demo' }, { log: (host, entry) => console.log(entry.text) });
351
+ host.addImage(compiled.image);
352
+ compiled.close();
353
+
354
+ const pongSession = host.spawn(host.chart('pong'), { name: 'pong' });
355
+ const pingSession = host.spawn(host.chart('ping'));
356
+ await host.idle();
357
+
358
+ console.log(Address.fromSession('demo', pongSession).text);
359
+ console.log(new Address('tinyactors://demo/@pong').name);
360
+ console.log(host.actorByName('pong') === pongSession);
361
+ host.terminate(pongSession);
362
+ await host.idle();
363
+ console.log(host.actorByName('pong'), pingSession);
364
+ host.close();
245
365
  ```
246
366
 
247
- `createSystem({ clock })` makes the system run on your clock instead of wall
248
- time: it arms no timers itself; advance the clock and call
249
- `system.flush()`, which runs everything that is due until the system is
250
- idle — for deterministic tests, simulations and replays.
251
-
252
- ```js
253
- let now = 0;
254
- const system = createSystem({ clock: () => now });
255
- createActor(machineWithAfter1000, { system }).start();
256
- now += 1000;
257
- system.flush(); // the `after: 1000` transition has been taken
367
+ ```output
368
+ pong got ping
369
+ ping got pong
370
+ tinyactors://demo/#_scxml_1
371
+ pong
372
+ true
373
+ undefined 2n
258
374
  ```
259
375
 
260
- ## Links: actors across systems
261
-
262
- `createLink(system, { url })` connects to another system (`serveLinks` on the
263
- other side). The link is itself an actor: its snapshot value is the
264
- connection status (`connecting`, `open`, `reconnecting`, `closed`); its context
265
- holds `rtt`, `attempts`, `queued` and `peer`. Subscribe to it to show the status.
376
+ ### Effects and handlers
377
+
378
+ What an actor does toward the outside is an **effect**, and each kind has
379
+ a handler you give the host in its options:
380
+
381
+ | The chart does | Your handler | Guide |
382
+ |---|---|---|
383
+ | `<send type="urn:x">` to an I/O processor the config lists | `ioProcessors: { 'urn:x': (host, send) => ... }` | [I/O processors](docs/guide/io-processors.md) |
384
+ | `<send>` to an actor of another system | `transport: (host, send) => ...` | [Other systems](docs/guide/other-systems.md) |
385
+ | `<invoke type="urn:y">` of a service you run | `services: { 'urn:y': (host, invocation) => service }` | [Invoked services](docs/guide/services.md) |
386
+ | `<log>` | `log: (host, entry) => ...` | this README |
387
+ | spans, logs and metrics as OpenTelemetry (OTLP) | `telemetry: (host, signal, data) => ...` | [Telemetry](docs/guide/telemetry.md) |
388
+ | an event for an actor you took out of memory | `wake: (host, session, migration) => ...` | [Hibernation](docs/guide/hibernation.md) |
389
+
390
+ A send to an I/O processor the config lists but no handler serves is
391
+ failed: the sender gets the event `error.communication`, so a chart can
392
+ always react. A send to a type the config does not list at all raises
393
+ `error.execution` in the chart. `<log>` lines without
394
+ a `log` handler are dropped.
395
+
396
+ **A handler's argument is a view, valid while the handler runs.** The
397
+ `send` an I/O processor gets reads each field from the host's memory when
398
+ you first read it. After the handler returns, the host moves on and the
399
+ view is stale: reading it then throws `TA_ERROR_STALE`. Copy out what you
400
+ keep (`const { data } = send`). A handler that returns a promise (an
401
+ `async` function) is the exception: the host fills its view with every
402
+ field before moving on, so it may `await` and answer later.
403
+
404
+ ### Values
405
+
406
+ What crosses between your program and a chart (event data, spawn params,
407
+ results) is a value of one table: `undefined`, `null`, booleans, numbers,
408
+ `bigint`s up to 64 bits, strings, `Uint8Array`s, arrays and plain
409
+ objects. A function, a `Map`, a `Date` or a class's instance is refused
410
+ with `TA_ERROR_UNSUPPORTED`, and a value is copied when it crosses, so a
411
+ chart never holds your object, and what a chart hands you (`send.data`,
412
+ `invocation.data`) is made with your realm's constructors: its arrays are
413
+ `instanceof Array`, and `assert.deepStrictEqual` compares it with a
414
+ literal. `undefined` and `null` stay apart; a
415
+ whole number past 2^53 comes back as a `bigint`.
416
+
417
+ `encode(value)` and `decode(bytes)` give that table as CBOR bytes, the
418
+ form a value takes when you store or send it:
266
419
 
267
420
  ```js
268
- // server
269
- const system = createSystem({ id: 'chess' });
270
- createActor(lobby, { system, systemID: 'lobby' }).start();
271
- // browsers are untrusted peers: they may send only what is exported
272
- serveLinks(system, { server: httpServer, path: '/link', exports: { lobby: 'JOIN LEAVE' } }); // or { port }, { tcp }, or { accept }
273
-
274
- // client (Node or the web binding); name: the server's system id
275
- const link = createLink(createSystem(), { url: 'ws://localhost:8080/link', name: 'chess' });
276
- createActor(player, { input: { lobby: link.get('lobby') } }); // an ActorRef to the remote lobby
277
- // in the player: sendTo(({ context }) => context.lobby, ({ self }) => ({ type: 'JOIN', player: self }))
278
- // in the lobby: sendTo(({ event }) => event.player, { type: 'WELCOME' }) — the reply crosses back
421
+ import { encode, decode } from '@tinyactors/node';
422
+
423
+ const bytes = encode({ sku: 'tea', qty: 2, big: 2n ** 60n, gone: undefined });
424
+ const value = decode(bytes);
425
+ console.log(bytes.length, 'bytes');
426
+ console.log(value.sku, value.qty, value.big, 'gone' in value, value.gone);
427
+ ```
428
+
429
+ ```output
430
+ 33 bytes
431
+ tea 2 1152921504606846976n true undefined
279
432
  ```
280
433
 
281
- Every actor has an `address` (`tinyactors://<system id>/#_scxml_<session>`)
282
- and `self` in action arguments. An actor reference sent in an event arrives as
283
- an `ActorRef` (with `send()`) that works as a `sendTo` target. `system.ref(address)`
284
- creates one. `system.stop()` stops all actors, closes the system's links and
285
- frees its native memory.
286
-
287
- Routing is done by the native router (`ta_host`, docs/protocol.md), not in
288
- JS: every link connection is one router *peer*, and the binding only moves
289
- frames (link protocol v1: `hello`, `ev`, `err`, `ping`/`pong`). What that
290
- gives you:
291
-
292
- - **Policy.** A served peer is untrusted unless `trusted: true` or
293
- `trust(hello)` says so: it may send only to the `exports` (`['lobby']`,
294
- `{ lobby: 'JOIN LEAVE' }`, `'*'` for every name and session). Everything
295
- else, and every forged `origin`, is refused.
296
- - **No silent drops.** A refused or undeliverable send — unknown name, ended
297
- session, no route, denied, queue full, expired — raises
298
- `error.communication` (with the `sendid`) in the sending actor, across any
299
- number of hops.
300
- - **Queues and resumption.** While a link is down the router queues for it
301
- (`maxQueue`, default 1000; `queueTTLMs` to expire them; `maxQueue: 0` to fail
302
- fast). On the server, a peer that reconnects with the same system id within
303
- `resumeMs` (default 30 s, on the system's clock: with a `clock` option,
304
- simulated time) gets what was queued for it, in order.
305
- - **Relaying.** With `announce: true` a system tells its peers which other
306
- systems it reaches, and forwards their envelopes (for trusted peers): a
307
- browser can reach a backend behind its server.
308
- - **Values.** Between two JS systems values keep their types (`js` profile:
309
- `Date`, `Map`, `Set`, `BigInt`, cycles, actor refs). With a peer in another
310
- language they travel as neutral values (JSON plus `{"$ref"}` and
311
- `{"$bytes"}`; `encodeWire` / `decodeWire`); `profile: 'neutral'` forces that.
312
- - **Status.** `link.status()` and `server.status(systemID)` report the route:
313
- state, queued, lag, rtt, sent/received/errors/duplicates.
314
- - `system.deliver(envelope)` hands an envelope to the router from host code
315
- (any transport you write yourself starts there).
316
-
317
- ### Byte streams: TCP, stdio, serial
318
-
319
- On byte streams the link protocol travels in length-prefixed frames (a 4-byte
320
- big-endian length, then UTF-8 JSON; docs/protocol.md, "Framing"):
434
+ `encode` also writes an `Address` (from "Actors, sessions and
435
+ addresses"), as CBOR's tag 32, and `decode` reads one back as an
436
+ `Address`: that is how a transport's message keeps its addresses
437
+ ([Other systems](docs/guide/other-systems.md)).
438
+ [docs/values.md](docs/values.md) has every row of the table and every
439
+ refusal.
440
+
441
+ ### Time and the SimulatedClock
442
+
443
+ Time in this API is milliseconds, with two exceptions that the host's
444
+ config and the trace methods inherit from core: `telemetry.flushInterval`
445
+ counts the host's clock ticks, and `traceWatch` takes `seconds`. In a
446
+ chart, `<send event="timeout" delay="30s"/>` sends an event to the actor
447
+ itself 30 seconds later, and `<cancel sendid>` takes it back. A delay is
448
+ written in seconds or milliseconds (`30s`, `1.5s`, `500ms`), and any
449
+ other form (`10`, `1m`) is a compile error. `delayexpr` computes one, and
450
+ must give such a string: `delayexpr="timeoutMs + 'ms'"`, not
451
+ `delayexpr="timeoutMs"`. A number, or a string without its unit, raises
452
+ `error.execution` with no `_event.data` (the delay is the host's check,
453
+ not code that threw, so there is no reason to give), and nothing is sent.
454
+ By default the host reads the runtime's
455
+ clock. A test gives it a `SimulatedClock` instead, which moves only when
456
+ you move it, so a test of a 30-second timeout takes no time:
321
457
 
322
458
  ```js
323
- // TCP
324
- const served = serveLinks(server, { tcp: { port: 7000 }, exports: ['echo'] }); // served.port
325
- const link = createLink(client, { tcp: { host: 'db-1', port: 7000 }, name: 'srv' });
326
-
327
- // any duplex stream: `transport` and `accept` take byte streams as well as WebSocket-like objects
328
- const child = spawn('node', ['worker.js'], { stdio: ['pipe', 'pipe', 'inherit'] });
329
- serveLinks(system, { trusted: true, accept: (on) => on({ readable: child.stdout, writable: child.stdin }) });
330
- // in worker.js (stdout carries the link: log with createSystem({ logger }) to stderr)
331
- createLink(system, { name: 'parent', transport: () => ({ readable: process.stdin, writable: process.stdout }) });
459
+ import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
460
+
461
+ const compiled = compileCharts([{ name: 'door.scxml', text: `
462
+ <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
463
+ datamodel="ecmascript" name="door" initial="open">
464
+ <state id="open">
465
+ <onentry><send event="close" delay="30s"/></onentry>
466
+ <transition event="close" target="closed"/>
467
+ </state>
468
+ <final id="closed"><onentry><log expr="'closed'"/></onentry></final>
469
+ </scxml>` }]);
470
+
471
+ const clock = new SimulatedClock();
472
+ const host = new Host({ systemID: 'demo' }, { clock, log: (host, entry) => console.log(entry.text, 'at', clock.now) });
473
+ host.addImage(compiled.image);
474
+ compiled.close();
475
+
476
+ host.spawn(host.chart('door'));
477
+ await host.idle();
478
+ console.log('next deadline in', host.nextDeadline, 'ms');
479
+ clock.increment(29_999);
480
+ await host.idle();
481
+ clock.increment(1);
482
+ await host.idle();
483
+ host.close();
332
484
  ```
333
485
 
334
- A byte stream is a Node-style duplex (a `net.Socket`) or a `{ readable,
335
- writable }` pair. `maxFrame` (default 1 MiB, both functions) is the largest
336
- frame this side accepts and is announced in its hello. Frames above it are
337
- skipped unread. An envelope that does not fit the other side's `maxFrame` is
338
- not sent: its sender gets `error.communication`. `encodeFrame(text)` and
339
- `new FrameDecoder({ maxFrame }).push(chunk)` (frames out; a refused one as
340
- `{ reason: 'malformed', length }`) frame streams of your own. C hosts use
341
- `ta_frame_header` / `ta_frame_read` (`include/tinyactors/frame.h`).
342
-
343
- ### Store links: actors in PostgreSQL
486
+ ```output
487
+ next deadline in 30000 ms
488
+ closed at 30000
489
+ ```
344
490
 
345
- `createStoreLink(system, { query, listen })` connects the system to a
346
- database of actors (the PostgreSQL extension, bindings/postgres) through any
347
- PostgreSQL client. The database becomes a peer: actors here and there send to
348
- each other by address, replies included, and the database can reach the
349
- browsers on your links (the link tells it which ones).
491
+ `host.now()` reads the host's clock in milliseconds (the simulated
492
+ clock's time, or the runtime's), the clock its deadlines and snapshots
493
+ use. `clock.increment(ms)` moves the clock and schedules a turn on every host
494
+ made with it; `await host.idle()` then sees what ran. One increment past
495
+ several deadlines does not replay each of them: what is due runs once, at
496
+ the new time, and a delay it starts counts from there. Step the clock one
497
+ deadline at a time to see each. An input runs at the host's next turn, so
498
+ one given just before an `increment` is handled at the new time: `await
499
+ host.idle()` between them when it should run first. A host on a
500
+ `SimulatedClock` arms no timer.
501
+
502
+ On the runtime's clock a delay counts from the step that armed it, which
503
+ runs a little after its timer fired (the timer's and the turn's latency).
504
+ So a chart that re-arms `<send event="tick" delay="20ms"/>` at each tick
505
+ falls behind by that latency every tick: 24 ms after 40 ticks alone, 136
506
+ ms beside a CPU-bound job, in the repository's job-scheduler example. A
507
+ chart cannot read the host's clock, so a job that must keep its cadence
508
+ is given its schedule as absolute times by your program, and asks your
509
+ program for the time (an I/O processor) before it arms each delay. [Testing your charts](docs/guide/testing.md)
510
+ has more.
511
+
512
+ ### Errors
513
+
514
+ Errors surface in four places:
515
+
516
+ - **At compile time,** `compileCharts` throws a `CompileError` whose
517
+ message is the first error as `file:line:column: error: message`, and
518
+ whose `diagnostics` holds them all.
519
+ - **At a call,** the host throws a `TinyactorsError` for what it refuses
520
+ at once: a chart it does not have, a session that ended or never was, a
521
+ config it does not take. Branch on `error.status` (`'TA_ERROR_STALE'`,
522
+ `'TA_ERROR_INVALID'`, ...); the message is for people. A refused config
523
+ also has `error.path`, the key it is about (`system.maxActors`), and
524
+ `error.reason`. Arguments of the
525
+ wrong JavaScript type throw a `TypeError`.
526
+ - **In a chart,** an expression that throws, or an `<assign>` to a
527
+ variable the chart does not declare, raises the event `error.execution`
528
+ for that actor, and a send that cannot be delivered raises
529
+ `error.communication`. These are events, not exceptions. A failed action
530
+ also stops the rest of its block: the actions after it in the same
531
+ `<onentry>`, `<onexit>` or transition do not run. The actor goes on,
532
+ and a transition on `error` handles both; without one the error event
533
+ is dropped like any event no transition matches. When the chart's code
534
+ failed, `_event.data` says why: `{ reason, message }`, `reason`
535
+ `'exception'` (code that threw; `message` is its text, as `String(e)`
536
+ gives it, such as `'Error: boom'`), `'fuel'` (it ran past QuickJS's
537
+ `maxOps`) or `'memory'` (past QuickJS's `memoryLimit`); a failure the
538
+ host decides (an unknown `<send>` type) has no data. To learn which
539
+ action failed, turn on [telemetry](docs/guide/telemetry.md), whose spans
540
+ and log records mark the failed action.
541
+ - **In your handlers,** an error a handler throws is reported after its
542
+ turn: it rejects a waiting `host.idle()`, or, with none waiting, is
543
+ thrown as an uncaught exception (below).
350
544
 
351
545
  ```js
352
- const pool = new pg.Pool();
353
- const client = await pool.connect(); // a connection for LISTEN
354
- const store = createStoreLink(system, {
355
- query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
356
- listen: async (channel, fn) => { client.on('notification', (n) => n.channel === channel && fn(n.payload));
357
- await client.query(`LISTEN ${channel}`); return () => client.query(`UNLISTEN ${channel}`); },
358
- });
359
- await store.ready; // store.id: the database's system id
360
- sendTo(system.ref(`tinyactors://${store.id}/@ledger`), { type: 'add', amount: 5 });
546
+ import { compileCharts, CompileError, Host, TinyactorsError } from '@tinyactors/node';
547
+
548
+ try {
549
+ compileCharts([{ name: 'bad.scxml', text: `<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" name="bad">
550
+ <state id="s"><transition event="go" target="nowhere"/></state>
551
+ </scxml>` }]);
552
+ } catch (error) {
553
+ if (!(error instanceof CompileError)) throw error;
554
+ console.log(error.message);
555
+ }
556
+
557
+ const host = new Host({ systemID: 'demo' });
558
+ try {
559
+ host.chart('missing');
560
+ } catch (error) {
561
+ if (!(error instanceof TinyactorsError)) throw error;
562
+ console.log(error.status, '-', error.message);
563
+ }
564
+ host.close();
361
565
  ```
362
566
 
363
- Envelopes go in with `tinyactors.deliver` (in order, retried until taken;
364
- the database drops repeats), come out of the outbox with `claim_for` on
365
- NOTIFY (and every `pollMs`), and errors travel both ways as
366
- `error.communication`. Values travel as neutral values. `store.flush()`
367
- waits until everything was handed over; `store.status()` is the route's
368
- status.
369
-
370
- ## Supported (xstate v5 subset)
371
-
372
- `createMachine`, `setup({ actions, guards, delays, actors })`, `createActor`
373
- (`start`, `stop`, `send`, `getSnapshot`, `subscribe`, `address`, `hibernated`,
374
- options `input`, `systemID`, `system`, `logger`),
375
- `createSystem({ id, hibernation, clock, logger, restore, machines })`,
376
- `system.get()`, `system.ref()`, `system.sendMany()`, `system.hibernate()`,
377
- `system.reload()`, `system.migrate()`, `system.snapshot()`, `system.boot()`,
378
- `system.export()`, `system.adopt()`,
379
- `system.flush()`, `system.stop()`, `fromSCXML`, `compileSystem`, `loadImage`,
380
- `machine.provide()`, `createLink`, `serveLinks`, `encodeFrame`, `FrameDecoder`, `createMemoryStore`;
381
- states (`initial`, nested, `parallel`, `final` with `output`, `history`),
382
- `on` (including `'*'`), `always`, `after`, `entry`/`exit`, `invoke` of child
383
- machines (`input`, `onDone`), `tags`; actions: functions, named actions with
384
- `params`, `assign`, `raise` (optionally delayed), `sendTo`, `sendParent`,
385
- `log`, `cancel`; guards: functions, named guards with `params`, `and`, `or`,
386
- `not`, `stateIn`. Snapshots: `value`, `context`, `status`, `output`,
387
- `error`, `matches()`, `hasTag()`.
388
-
389
- Not supported: promise/callback/observable actors, `spawn`, `emit`,
390
- `enqueueActions`, `onError`, `can()`, inspection API.
391
-
392
- Semantics follow SCXML where they differ from xstate: an exception in user
393
- code raises `error.execution` (the actor keeps running; see
394
- `snapshot.error`), and external events wait while a macrostep is still
395
- running.
396
-
397
- ## Build & test
398
-
399
- ```sh
400
- mise run node:test # npm ci, build the addon, node --test, bun test, tsc
567
+ ```output
568
+ bad.scxml:2:17: error: unknown state id 'nowhere'
569
+ TA_ERROR_INVALID - the host has no chart of that name
401
570
  ```
571
+
572
+ ## Before you use it
573
+
574
+ - **Chart code is trusted code.** On the native datamodel (the default)
575
+ a chart's expressions and scripts run in `node:vm` contexts of your own
576
+ engine, and a `vm` context is not a security boundary. Run charts you do
577
+ not trust on quickjs, the sandbox: `new Host(config, { datamodel:
578
+ 'quickjs', quickjs: { maxOps, memoryLimit } })`
579
+ ([the quickjs sandbox](docs/guide/quickjs.md)).
580
+ - **An open host with a pending deadline keeps the process alive, and
581
+ only then** (a delayed `<send>`, a timeout, the telemetry flush): the host arms one
582
+ timer at its next deadline, as `setTimeout` does, and `host.close()`
583
+ clears it. Nothing else holds the event loop: an open host with no
584
+ deadline lets the process exit, its actors still waiting, and so does an
585
+ actor that waits for an answer from a handler whose promise has no I/O
586
+ behind it. Give a chart that waits for an answer a timeout of its own,
587
+ and keep the process alive with your server, socket or timer.
588
+ - **A handler's error ends the process by default.** An error thrown by
589
+ a handler (an I/O processor's, the log handler, the result handler of
590
+ a typed method, one of the host's queries in
591
+ [Inspecting a host](docs/guide/inspection.md))
592
+ rejects a waiting `host.idle()`; with none waiting it is thrown from the
593
+ host's turn as an uncaught exception, and a handler's promise that
594
+ rejects is an unhandled rejection, as is a typed method's promise
595
+ (`await host.actorState(...)`) that rejects with no `catch`. Either
596
+ ends a Node.js or Bun process unless the application handles
597
+ `uncaughtException` and `unhandledRejection`. Only a turn's first error is reported; the others
598
+ of that turn are lost.
599
+ - **`using host = new Host(...)` needs a runtime that parses `using`:**
600
+ Bun 1.4 does, Node.js 22 does not. `Symbol.dispose` and
601
+ `Symbol.asyncDispose` call `close()`, which works everywhere.
602
+ - **A `<script>` that declares top-level names gives each session a
603
+ context of its own.** A chart whose scripts declare `var` or `function`,
604
+ or whose chart-level scripts declare `let`, `const` or `class`, at their
605
+ top level runs each of its sessions
606
+ in a `vm` context of its own (about 143 KB a session on Node.js, 60 KB
607
+ on Bun), so the script's functions close over its own variables. A
608
+ chart that declares nothing shares one context per host: declare the
609
+ function as a `<data>` and assign it in the script
610
+ (`<data id="price"/>`, `price = (sku) => ...`)
611
+ ([Writing charts](docs/guide/charts.md#scripts)).
612
+ - **A chart whose chart-level scripts declare with `let`, `const` or
613
+ `class` keeps its sessions resident** (in a transition's script they
614
+ are the script's own, each run). Hibernation, migration and snapshots refuse its
615
+ sessions (`TA_ERROR_UNSUPPORTED`): a new context cannot be given those
616
+ bindings back. Declare with `var` and `function`, or hold the values in
617
+ `<data>`, for a chart whose sessions should hibernate.
618
+ - **The charts of a host share the builtins of its shared context.** On
619
+ the native datamodel the charts that declare nothing run in one `vm`
620
+ context per host, so a chart that changes a builtin (`Math.random = ...`,
621
+ `Array.prototype.sum = ...`) changes it for the host's other charts
622
+ there; its sessions' own variables stay apart. On quickjs the same holds,
623
+ unless `quickjs: { realm: 'isolated' }` gives each session a context of
624
+ its own ([the quickjs sandbox](docs/guide/quickjs.md#realms)).
625
+
626
+ ## Guides
627
+
628
+ One per feature, each with complete examples that run as written. They
629
+ are in the package too, under `docs/guide/` in
630
+ `node_modules/@tinyactors/node`, so these links work after an install:
631
+
632
+ - [Writing charts](docs/guide/charts.md): JavaScript in charts, scripts,
633
+ XML data, several charts, `<invoke>` of a chart, systems and `boot`.
634
+ - [I/O processors](docs/guide/io-processors.md): your code as a chart's
635
+ output: answering, failing, answering later.
636
+ - [Invoked services](docs/guide/services.md): long-running things a chart
637
+ starts and stops, such as a connection or a subprocess.
638
+ - [Inspecting a host](docs/guide/inspection.md): an actor's state and
639
+ variables, listing actors, the host's counters.
640
+ - [Telemetry](docs/guide/telemetry.md): traces, logs and metrics as
641
+ OpenTelemetry, and trace context across your services.
642
+ - [Hibernation](docs/guide/hibernation.md): millions of actors, most of
643
+ them in your database.
644
+ - [Migration](docs/guide/migration.md): moving running actors to a new
645
+ version of their chart.
646
+ - [Snapshots](docs/guide/snapshots.md): the whole host as one blob, and a
647
+ host restored from it.
648
+ - [Other systems](docs/guide/other-systems.md): actors of two hosts
649
+ talking through your transport, and SCXML's BasicHTTP.
650
+ - [The quickjs sandbox](docs/guide/quickjs.md): charts you do not trust.
651
+ - [Capacity and memory](docs/guide/capacity.md): sizing a host, how it
652
+ grows, and what an actor costs.
653
+ - [Testing your charts](docs/guide/testing.md): a simulated clock,
654
+ `idle()`, and asserting on an actor's state.
655
+ - [In the browser](docs/guide/browser.md): `@tinyactors/wasm`, the same
656
+ API in a page or a Worker: loading, the CSP, IndexedDB as the store,
657
+ liveness, memory, and what differs.
658
+
659
+ The reference is the doc comment of each export in
660
+ [index.d.ts](index.d.ts), which an editor shows on hover. In TypeScript
661
+ the types need the `es2022` lib and a `URL` (the `dom` lib or
662
+ @types/node); they declare `Symbol.dispose` and `Disposable` themselves,
663
+ so no `esnext` lib is needed.