@tinyactors/node 0.1.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.
Files changed (43) hide show
  1. package/README.md +648 -154
  2. package/docs/guide/browser.md +494 -0
  3. package/docs/guide/capacity.md +202 -0
  4. package/docs/guide/charts.md +578 -0
  5. package/docs/guide/hibernation.md +201 -0
  6. package/docs/guide/inspection.md +381 -0
  7. package/docs/guide/io-processors.md +269 -0
  8. package/docs/guide/migration.md +323 -0
  9. package/docs/guide/other-systems.md +275 -0
  10. package/docs/guide/quickjs.md +135 -0
  11. package/docs/guide/services.md +317 -0
  12. package/docs/guide/snapshots.md +186 -0
  13. package/docs/guide/telemetry.md +265 -0
  14. package/docs/guide/testing.md +272 -0
  15. package/docs/values.md +107 -0
  16. package/index.d.ts +1166 -1820
  17. package/index.mjs +6 -0
  18. package/lib/convenience.mjs +162 -0
  19. package/lib/direct.mjs +65 -0
  20. package/package.json +29 -16
  21. package/index.js +0 -34
  22. package/lib/actor.js +0 -85
  23. package/lib/debug/breakpoints.js +0 -349
  24. package/lib/debug/console.js +0 -149
  25. package/lib/debug/expressions.js +0 -133
  26. package/lib/debug/frames.js +0 -119
  27. package/lib/debug/labels.js +0 -142
  28. package/lib/debug/macrosteps.js +0 -207
  29. package/lib/debug/protocol.js +0 -186
  30. package/lib/debug/sources.js +0 -218
  31. package/lib/debug/variables.js +0 -265
  32. package/lib/debug.js +0 -1434
  33. package/lib/definition.js +0 -139
  34. package/lib/errors.js +0 -24
  35. package/lib/events.js +0 -56
  36. package/lib/image.js +0 -90
  37. package/lib/loader.js +0 -68
  38. package/lib/metrics.js +0 -333
  39. package/lib/native.js +0 -8
  40. package/lib/otlp.js +0 -332
  41. package/lib/statechart.js +0 -768
  42. package/lib/system.js +0 -2183
  43. package/lib/tracing.js +0 -164
package/index.d.ts CHANGED
@@ -1,1875 +1,1221 @@
1
- /**
2
- * @file The desired public API of tinyactors: the design target, not a
3
- * description of what is built.
1
+ // The types of @tinyactors/node and @tinyactors/wasm, one API (docs/api-map.md
2
+ // says where @tinyactors/wasm differs today). Every export has a doc comment, which an
3
+ // editor shows on hover; README.md and docs/guide/ teach the same API in
4
+ // order, with examples. Each declaration is a row of docs/api-map.md,
5
+ // which names the core behind it.
6
+ //
7
+ // Units: time is milliseconds (but telemetry.flushInterval, in the host's
8
+ // clock ticks, and traceWatch's seconds); sessions are bigints (inputs also
9
+ // take a safe integer from 1, and typed methods' results hold numbers);
10
+ // bytes the host hands out are Uint8Arrays (Buffers in @tinyactors/node),
11
+ // copied once, yours to keep.
12
+
13
+ // ---- disposal ------------------------------------------------------------
14
+
15
+ // `Symbol.dispose`, `Symbol.asyncDispose`, `Disposable` and
16
+ // `AsyncDisposable`, which a `Host` and a compile result implement, as
17
+ // TypeScript's `esnext.disposable` lib and @types/node declare them: a
18
+ // project need not add that lib, and these merge with it where it does.
19
+ declare global {
20
+ interface SymbolConstructor {
21
+ readonly dispose: unique symbol;
22
+ readonly asyncDispose: unique symbol;
23
+ }
24
+ interface Disposable {
25
+ [Symbol.dispose](): void;
26
+ }
27
+ interface AsyncDisposable {
28
+ [Symbol.asyncDispose](): PromiseLike<void>;
29
+ }
30
+ }
31
+
32
+ // ---- values -------------------------------------------------------------
33
+
34
+ /** An actor's session, as an input takes it: a `bigint` from 1 to
35
+ * 2^64-1, or a number that is a safe integer from 1 (as a database or
36
+ * JSON gives one back). Anything else is a `TypeError`. The calls and
37
+ * views return a `bigint`; a typed method's result holds a number, so
38
+ * compare with `Number(session) === listed`. */
39
+ export type Session = bigint | number;
40
+
41
+ /** A value that crosses between your program and a chart: event data,
42
+ * spawn params, a typed method's result, and what `encode` and `decode`
43
+ * convert. Numbers that are safe integers stay integers; integers past
44
+ * 2^53 are `bigint`s (up to 64 bits). Plain objects only: a function, a
45
+ * `Map`, a `Date` or a class's instance is refused. Values are copied when
46
+ * they cross. Inside a value an actor's address is its text. */
47
+ export type Value =
48
+ | undefined
49
+ | null
50
+ | boolean
51
+ | number
52
+ | bigint
53
+ | string
54
+ | Uint8Array
55
+ | Value[]
56
+ | { [key: string]: Value };
57
+
58
+ /** A {@link Value} the host hands you (`send.data`, `invocation.data`,
59
+ * `decode`, a typed method's variables), typed `any` as `JSON.parse`'s
60
+ * result is: it holds whatever a chart put there, so you read its fields
61
+ * without narrowing first. What it holds at run time is a `Value`. */
62
+ export type ReceivedValue = any;
63
+
64
+ /** What `encode` writes: a {@link Value}, or one holding `Address`es,
65
+ * which it writes as CBOR's tag 32 (an actor reference). */
66
+ export type Encodable =
67
+ | Value
68
+ | Address
69
+ | Encodable[]
70
+ | { [key: string]: Encodable };
71
+
72
+ /** A value as CBOR bytes, the form to store or send it in. An `Address`
73
+ * is tag 32 on its text.
4
74
  *
5
- * Parts of this file are knowingly not implemented yet. Each declaration
6
- * that lib/ does not implement carries a marker on the line directly above
7
- * it (after its JSDoc, if it has one):
75
+ * Throws a `TinyactorsError`: `TA_ERROR_UNSUPPORTED` for what is not a
76
+ * {@link Value} (a function, a symbol, a `Date`, a `Map`, a class's
77
+ * instance, a typed array other than `Uint8Array`), `TA_ERROR_INVALID` for
78
+ * what a value cannot hold (a string with a lone surrogate, a `bigint` past
79
+ * 64 bits, a cycle or nesting deeper than 64). A getter's exception passes
80
+ * through.
8
81
  *
9
- * // status: unimplemented
10
- * // status: partial: <what is missing>
82
+ * @example
83
+ * const bytes = encode({ sku: 'tea', qty: 2 });
84
+ * decode(bytes); // { sku: 'tea', qty: 2 }
85
+ */
86
+ export function encode(value: Encodable): Uint8Array;
87
+
88
+ /** The value of the one CBOR item that fills `bytes`: the inverse of
89
+ * {@link encode}, tag 32 an `Address`. Throws a `TinyactorsError` (`TA_ERROR_INVALID`) for bytes
90
+ * that are not one such item, a `TypeError` for an argument that is not
91
+ * bytes. */
92
+ export function decode(bytes: Uint8Array | ArrayBuffer): ReceivedValue;
93
+
94
+ // ---- errors -------------------------------------------------------------
95
+
96
+ /** The reason a call was refused, as `TinyactorsError.status` names it:
97
+ * - `TA_ERROR_INVALID`: an argument the host does not take (a chart it
98
+ * does not have, a config key, malformed bytes);
99
+ * - `TA_ERROR_STALE`: something that ended or never was (a session, a
100
+ * view read after its handler returned, a closed compile result);
101
+ * - `TA_ERROR_STATE`: not now (a snapshot from a handler, a second
102
+ * answer, hibernating an actor that is not at rest);
103
+ * - `TA_ERROR_UNSUPPORTED`: a value outside the value table;
104
+ * - `TA_ERROR_NO_MEMORY`: a pool at its largest size, or the system
105
+ * allocator refused. */
106
+ export type Status =
107
+ | 'TA_ERROR_INVALID'
108
+ | 'TA_ERROR_NO_MEMORY'
109
+ | 'TA_ERROR_STATE'
110
+ | 'TA_ERROR_STALE'
111
+ | 'TA_ERROR_UNSUPPORTED'
112
+ | 'TA_ERROR_EXECUTION'
113
+ | 'TA_ERROR_COMMUNICATION'
114
+ | 'TA_ERROR_ABORTED'
115
+ | 'TA_ERROR_FATAL'
116
+ | (string & {});
117
+
118
+ /** An error the host reported. A refused call has a `status` to branch
119
+ * on; a typed method's error, and a refused config, have `code`, `reason`
120
+ * and `path`, as the host wrote them. The message is for
121
+ * people: do not match on it.
11
122
  *
12
- * Do not delete a declaration because lib/ lacks it: implement it, or
13
- * leave it marked. `mise run check-api-status` (part of `mise run test`)
14
- * keeps the markers honest where the runtime can answer: a marked
15
- * declaration that exists fails, and an unmarked one that is missing
16
- * fails. `grep -n "// status:" index.d.ts` lists what is outstanding.
123
+ * @example
124
+ * try { host.send(session, 'go'); }
125
+ * catch (error) { if (error instanceof TinyactorsError && error.status === 'TA_ERROR_STALE') ... }
17
126
  */
18
-
19
- /** The package version. */
20
- export const version: string;
21
-
22
- /* --------------------------------------------------------------------------
23
- * Systems and scheduling
24
- * -------------------------------------------------------------------------- */
25
-
26
- export interface SystemOptions {
27
- /**
28
- * "realtime" (the default) follows a monotonic clock read natively; one
29
- * unreferenced timer fires due sends, so an idle system does not keep the
30
- * process alive. "manual" time moves only with advanceTo()/advanceBy()
31
- * (ADR 0007 point 3).
32
- */
33
- clock?: "realtime" | "manual";
34
- /** Core's logical time at creation, in milliseconds; default 0. */
35
- initialTime?: number;
36
- scheduling?: SchedulingOptions;
37
- /**
38
- * What happens to an actor that reaches a top-level final state (ADR 0012):
39
- * "destroy" (the default) destroys it after the `done` hook returns;
40
- * "retain" keeps it inspectable until it is destroyed.
41
- */
42
- finished?: "destroy" | "retain";
43
- /** Called at the end of the pump turn in which an actor finished. */
44
- done?: (record: DoneRecord) => void;
45
- /** Called at the end of the pump turn in which an actor faulted (ADR 0008). */
46
- fault?: (record: FaultRecord) => void;
47
- /**
48
- * Called for a message whose target is gone, finished, or refused it, at
49
- * most `messageBudget` times per pump turn (ADR 0008). Without a hook,
50
- * dead letters are only counted in stats().
51
- */
52
- deadLetter?: (record: DeadLetterRecord) => void;
53
- io?: Readonly<Record<string, IOProcessor>>;
54
- invokers?: Readonly<Record<string, Invoker>>;
55
- log?: LogSink;
56
- /**
57
- * How unload() keeps an actor's JavaScript values: "serialize" (the
58
- * default) writes them with v8.serialize, "handles" keeps each value by
59
- * handle in this process. unload() throws `unsupported` for a value it
60
- * can do neither with.
61
- */
62
- unloadValues?: "serialize" | "handles";
63
- }
64
-
65
- /** An actor finished (ADR 0012). The actor is still resident while the hook runs. */
66
- export interface DoneRecord<Data = unknown> {
67
- readonly actor: Actor;
68
- /** The top-level final state it reached (core ADR 0056). */
69
- readonly finalState: string;
70
- /** Its completion data (<donedata>), or undefined. */
71
- readonly data: Data | undefined;
127
+ export class TinyactorsError extends Error {
128
+ constructor(
129
+ message?: string,
130
+ options?: { code?: number; reason?: string; path?: string; status?: Status },
131
+ );
132
+ /** A typed method's error: its JSON-RPC code (`-32001` for a session that
133
+ * does not exist, `-32602` for a param it does not take, ...). */
134
+ readonly code: number | undefined;
135
+ /** A typed method's error: a word for its cause (`stale`, `type`,
136
+ * `unknown`, `range`, `missing`, `state`, ...). */
137
+ readonly reason: string | undefined;
138
+ /** A typed method's error: the param it is about (`params.session`). */
139
+ readonly path: string | undefined;
140
+ /** A refused call's reason. */
141
+ readonly status: Status | undefined;
142
+ }
143
+
144
+ // ---- compiling ----------------------------------------------------------
145
+
146
+ /** A document to compile: its name, which error messages and `src`
147
+ * attributes name, and its text. */
148
+ export interface Source {
149
+ name: string;
150
+ text: string;
72
151
  }
73
152
 
74
- /**
75
- * A core call for an actor failed; the actor is quarantined (ADR 0008). An
76
- * invoked child's parent also gets error.communication.invoke.<id>.quarantined
77
- * with `{ code, message }` from this record (napi ADR 0025).
78
- */
79
- export interface FaultRecord {
80
- readonly actor: Actor;
81
- readonly operation: string;
82
- readonly code: string;
153
+ /** One message of the compiler about a document. */
154
+ export interface Diagnostic {
155
+ readonly severity: 'error' | 'warning' | 'note';
156
+ /** The compiler's code for the kind of problem. */
157
+ readonly code: number;
158
+ /** The document's name, as its {@link Source} gave it. */
159
+ readonly file: string;
160
+ /** From 1. */
161
+ readonly line: number;
162
+ /** From 1. */
163
+ readonly column: number;
83
164
  readonly message: string;
84
165
  }
85
166
 
86
- /**
87
- * A message that could not be delivered (ADR 0008). `target` is the actor it
88
- * was for, or the address when it was sent to a name with no resident actor
89
- * (ADR 0006).
90
- */
91
- export interface DeadLetterRecord {
92
- readonly target: ActorID | ActorAddress;
93
- readonly event: EventName;
94
- /** The message's data, absent when it had none: post it again with it. */
95
- readonly data?: unknown;
96
- /** The message's traceparent, absent when it was not traced. */
97
- readonly traceparent?: string;
98
- /**
99
- * `unloaded`: a name whose actor is unloaded and whose family has no
100
- * loader (setLoader), or mail left for an actor unloaded through the raw
101
- * layer. Mail that waited for a loader (napi ADR 0020) ends as `rejected`
102
- * (the loader said "not now"), `load-failed`, `load-timeout`, or
103
- * `waiting-full` (the address already had maxWaiting messages waiting).
104
- */
105
- readonly reason:
106
- | "not-found"
107
- | "done"
108
- | "destroyed"
109
- | "refused"
110
- | "unloaded"
111
- | "rejected"
112
- | "load-failed"
113
- | "load-timeout"
114
- | "waiting-full";
115
- /** Why the load failed: the rejection's reason, the loader's error, or the timeout. */
116
- readonly detail?: string;
117
- }
118
-
119
- /** Why a loader is called (setLoader). */
120
- export type LoadReason = "mail" | "timer";
121
-
122
- /**
123
- * What a loader returns (setLoader, napi ADR 0020). Session images are
124
- * process-local: after a process exit, rebuild an actor from the data the
125
- * application stored ({ spawn, binding }), or replay a log.
126
- */
127
- export type LoadResult<Data extends object = object> =
128
- | SessionImage<Data>
129
- | { readonly image: SessionImage<Data>; readonly restore?: (actor: ActorID) => unknown }
130
- | "offloaded"
131
- | {
132
- readonly spawn: Definition<Data>;
133
- readonly binding?: Partial<Data> | Data;
134
- readonly pendingSends?: readonly DelayedSendInspection[];
135
- }
136
- | "not-found"
137
- | "reject"
138
- | { readonly reject: unknown };
139
-
140
- export interface LoaderOptions {
141
- /** Milliseconds the loader may take; after that its mail is `load-timeout` (default 5000). */
142
- readonly timeout?: number;
143
- /** Messages that may wait for one address; the rest are `waiting-full` (default 1000). */
144
- readonly maxWaiting?: number;
167
+ /** A compilation found an error, and compiled nothing. Its message is the
168
+ * first error as a compiler prints it, `file:line:column: error:
169
+ * message`; its status is `TA_ERROR_INVALID`. */
170
+ export class CompileError extends TinyactorsError {
171
+ /** Every diagnostic of the compilation: errors, warnings and notes. */
172
+ readonly diagnostics: readonly Diagnostic[];
145
173
  }
146
174
 
147
- export interface SchedulingOptions {
148
- /** Microsteps one resume may run before the actor yields (core's `budget`); default 64. */
149
- resumeBudget?: number;
150
- /**
151
- * Units of executable content one resume may run before the actor pauses
152
- * inside a microstep (core ADR 0061); 0 means no limit; default 1024.
153
- */
154
- actionBudget?: number;
155
- /** Runnable actors resumed in one pump turn; default 1024. */
156
- resumesPerTurn?: number;
157
- /** Maximum due sends dispatched during one pump turn; at least 1, default 1024. */
158
- dueBudget?: number;
159
- /**
160
- * Microsteps one macrostep may run before its actor is quarantined with
161
- * fault code `runaway` (core ADR 0075); 0 for no limit, default 100000. A
162
- * tenth of it writes a `tinyactors.macrostep.long` log. `release()` lets a
163
- * runaway finish its macrostep; the next one has the limit again.
164
- */
165
- microstepLimit?: number;
166
- /**
167
- * Deliveries started during one pump turn, and dead letters reported in
168
- * one turn; at least 1, default 1024.
169
- */
170
- messageBudget?: number;
171
- /**
172
- * Maximum accepted messages not yet delivered or reported; post() throws
173
- * `queue-full` beyond it. 0 or absent: no limit.
174
- */
175
- maxQueuedMessages?: number;
176
- /**
177
- * Maximum retained-bytes estimate of the data of accepted messages not yet
178
- * delivered or reported (ADR 0005 point 9); 0 or absent: no limit. The
179
- * estimate: `options.bytes`, or 2 bytes per string code unit, byteLength
180
- * for buffers, 64 for other objects, 0 for primitives. Mail between actors
181
- * carries no estimate.
182
- */
183
- maxRetainedBytes?: number;
175
+ /** Thrown by a {@link Resolver} to refuse a document: the refusal becomes
176
+ * a compile error of the resolved file, at `line` and `column` when given,
177
+ * and the compile call throws a `CompileError`. */
178
+ export class ResolveError extends TinyactorsError {
179
+ constructor(message: string, options?: { line?: number; column?: number });
180
+ readonly line: number | undefined;
181
+ readonly column: number | undefined;
184
182
  }
185
183
 
186
- export declare function createSystem(options?: SystemOptions): System;
187
-
188
- export interface System {
189
- /** The one member besides close() that works after close(); the others throw `closed`. */
190
- readonly closed: boolean;
191
- readonly clock: "realtime" | "manual";
192
- readonly time: number;
193
-
194
- /**
195
- * Compile and register a chart: a statechart() builder, or a spec in the
196
- * generated shape (the shape core's definition export returns). A refused
197
- * chart throws `invalid` or `unsupported`, with core's compile error as
198
- * `detail` (ChartRefusal). `options.microstepLimit` overrides the system's
199
- * `scheduling.microstepLimit` for this definition; 0 for no limit.
200
- */
201
- define<Data extends object = Record<string, unknown>>(
202
- source: DefinitionSpec | DefinitionBuilder<Data>,
203
- options?: { microstepLimit?: number },
204
- ): Definition<Data>;
205
- /**
206
- * Import an SCXML document (napi ADR 0019). Its `<scxml name>` is the
207
- * definition's family and is required; the revision is a hash of the
208
- * document. Its `datamodel` attribute picks `javascript` (also for a
209
- * document without one) or a data model registerDatamodel() registered;
210
- * `datamodel="null"` opts into core's null data model, which keeps no
211
- * data. lib/ ships no ECMAScript compiler, so under `javascript` an
212
- * expression may only be `In(state)` or a data name: register a data
213
- * model to compile others. A refused document throws `invalid` or
214
- * `unsupported` with ImportRefusal as `detail`, which says where.
215
- */
216
- define<Data extends object = Record<string, unknown>>(
217
- source: string | Uint8Array,
218
- options: {
219
- format: "scxml";
220
- /**
221
- * Fetches `<data src>` and `<script src>` while the document is
222
- * defined: the content as a string or a Uint8Array, or undefined for a
223
- * src it does not know, which refuses the document there. It also
224
- * fetches a literal `<invoke type="scxml" src>`, whose child chart is
225
- * compiled with the parent (napi ADR 0024). The definition keeps it
226
- * for children compiled at invoke time from `srcexpr`, and its
227
- * children inherit it.
228
- */
229
- resolve?: (src: string) => string | Uint8Array | undefined;
230
- /**
231
- * What the document is called, such as its path or a file:// URL: the
232
- * source its spans name (core ADR 0085), which sourceOf() answers and
233
- * a debugger opens (napi ADR 0026). Without it the spans name no
234
- * source, and a debug session shows the chart as SCXML it writes from
235
- * the definition, by `sourceReference`. A child fetched by `src` or `srcexpr` is named by
236
- * that src; a child inline in `<content>` has no name, since its lines
237
- * count from the start of its content.
238
- */
239
- name?: string;
240
- microstepLimit?: number;
241
- },
242
- ): Definition<Data>;
243
-
244
- /**
245
- * Register a data model for imported documents (ADR 0019): `compile`
246
- * turns each source expression into what a builder chart would pass, and
247
- * the built-in data model runs it. `javascript` and `null` are reserved.
248
- */
249
- registerDatamodel(name: string, datamodel: DatamodelCompiler): void;
250
-
251
- /**
252
- * The unretired definition with this identity. define() of an identity
253
- * already registered returns that definition and takes another hold;
254
- * different content under it throws `definition-mismatch`.
255
- */
256
- findDefinition(identity: DefinitionIdentity): Definition | undefined;
257
-
258
- spawn<Data extends object>(
259
- definition: Definition<Data>,
260
- options?: SpawnOptions<Data>,
261
- ): Actor<Data>;
262
-
263
- /** The resident actor the directory has at `address`, or undefined (ADR 0006). */
264
- findActor(address: ActorAddress): Actor | undefined;
265
-
266
- /** A snapshot of core's view of `actor`. Throws `not-found` once it is gone. */
267
- inspect<Data extends object>(actor: ActorID): ActorInspection<Data>;
268
- /** True while a resident actor has this ID. */
269
- exists(actor: ActorID): boolean;
270
- /** Terminate `actor`. Throws `not-found` once it is gone. */
271
- destroy(actor: ActorID): void;
272
- /** Put an actor that faulted back into scheduling (ADR 0008). */
273
- release(actor: ActorID): void;
274
-
275
- /** The messages waiting in `actor`'s mailbox, oldest first, at most `limit` (default 100). */
276
- mailbox(actor: ActorID, options?: { readonly limit?: number }): readonly QueuedMessage[];
277
- /**
278
- * Abandon `actor`'s macrostep (core ADR 0082): the actor keeps the
279
- * configuration after its last completed microstep, and the send() that
280
- * follows the macrostep rejects with `abandoned`. `busy` while it is
281
- * paused inside a microstep (the pump finishes that microstep in its next
282
- * turns) or before its bootstrap finished; `invalid` with no macrostep in
283
- * progress.
284
- */
285
- abandon(actor: ActorID): void;
286
- /**
287
- * Withdraw `actor`'s pending delayed sends with this ID (core ADR 0084),
288
- * the `id` DelayedSendInspection shows. `not-found` when it has none;
289
- * `done` when the only ones were refused once and belong to their
290
- * receiver now.
291
- */
292
- withdrawSend(actor: ActorID, sendID: string): void;
293
-
294
- /**
295
- * Capture `actor` in memory (core ADR 0013), with the data-model root it
296
- * has now. `busy` for an unpublished (prepared) actor.
297
- */
298
- capture<Data extends object>(actor: ActorID): SessionImage<Data>;
299
-
300
- /**
301
- * Offload a stable named actor from memory (core ADR 0074): its data,
302
- * history and pending delayed sends go to bytes this system keeps, and
303
- * mail to its address or its own next delayed send loads it back (the
304
- * family's loader decides when it has one; see setLoader). Throws `busy`
305
- * while it has mail waiting, is inside a macrostep or is quarantined. The
306
- * bytes are for this process only: to survive a restart, store its data
307
- * and inspect().delayedSends, and spawn it again with
308
- * { binding, pendingSends }.
309
- */
310
- unload(actor: ActorID): void;
311
-
312
- /**
313
- * Bring an unloaded named actor back: from the bytes unload() kept for an
314
- * address, or from a SessionImage; the same session ID, a new runtime ID
315
- * (core ADR 0066). `binding` replaces the data root outright, it is not
316
- * merged: for an address it replaces the data the actor was unloaded
317
- * with, which it keeps without one; from an image it defaults to the
318
- * image's root. A chart on the null data model has no root, and a binding
319
- * for it throws `unsupported`. An invocation active at capture is
320
- * reported to the actor as `error.communication.invoke.<id>.unavailable`
321
- * (core ADR 0038).
322
- */
323
- load<Data extends object>(
324
- target: SessionImage<Data> | ActorAddress,
325
- options?: { readonly binding?: Partial<Data> | Data },
326
- ): Actor<Data>;
327
-
328
- /**
329
- * Restore an image under a fresh runtime ID without touching the directory
330
- * (core ADR 0052). `binding` defaults to the root the image kept, which is
331
- * shared with the captured actor if it still runs.
332
- */
333
- reconstruct<Data extends object>(
334
- image: SessionImage<Data>,
335
- options?: { readonly binding?: Partial<Data> | Data },
336
- ): Actor<Data>;
337
-
338
- /** Release the address of an actor that stays unloaded; load() of its image then fails with `stale`. */
339
- removeUnloaded(address: ActorAddress): void;
340
-
341
- /**
342
- * Bring actors of `family` back when mail arrives for them (napi ADR
343
- * 0020). Mail for a name in `family` with no resident actor (unloaded, or
344
- * never seen here: the family is virtual) waits while the loader runs,
345
- * and is delivered first, in order, once it has loaded or spawned the
346
- * actor. One load runs per address. `why` is "timer" when an unloaded
347
- * actor's own delayed send is due. `null` removes the loader.
348
- */
349
- setLoader(
350
- family: string,
351
- loader:
352
- | ((
353
- address: ActorAddress,
354
- why: LoadReason,
355
- load: { readonly offloaded: boolean },
356
- ) => LoadResult | Promise<LoadResult>)
357
- | null,
358
- options?: LoaderOptions,
359
- ): void;
360
-
361
- /**
362
- * Wake the unloaded actor at `address` through its family's loader at
363
- * `time` (core's clock). unload() does this for the image's next deadline.
364
- * Nothing happens at `time` for an address with no unloaded actor and no
365
- * loader.
366
- */
367
- wakeAt(address: ActorAddress, time: number): void;
368
-
369
- /** Create an unpublished replacement for the named actor `incumbent` (Actor.prepareReplacement). */
370
- prepareReplacement<Data extends object>(
371
- incumbent: ActorID,
372
- definition: Definition<Data>,
373
- options?: ReplacementOptions<Data>,
374
- ): PreparedActor<Data>;
375
-
376
- /** Publish a prepared actor and destroy its incumbent (PreparedActor.activate). */
377
- activate<Data extends object>(prepared: PreparedActor<Data>): Actor<Data>;
378
-
379
- registerIO(type: string, processor: IOProcessor, options?: IOProcessorOptions): void;
380
- /** Open a scope that stores `uri` once, for a connection or a session (core ADR 0068). */
381
- openScope(type: string, uri: string): IOScope;
382
- /** Close a scope; events naming it then carry no origin. Idempotent. */
383
- closeScope(scope: IOScope): void;
384
- registerInvoker(type: string, invoker: Invoker): void;
385
- setLogSink(sink?: LogSink): void;
386
- /**
387
- * Hand traces to `sink` as OTLP protobuf (napi ADR 0016): once per pump
388
- * turn, one Uint8Array holding one ExportTraceServiceRequest with the
389
- * spans that ended. Post it to an OTLP/HTTP `/v1/traces` endpoint as it
390
- * is, or read it with decodeTraces(). Without a sink core builds no record.
391
- */
392
- setTraceSink(sink?: (traces: Uint8Array, logs?: Uint8Array) => void, options?: TraceSinkOptions): void;
393
- /** Changes `detail`, `kinds` and `sample` of the installed sink in place; open spans are kept. */
394
- configureTraces(options: TraceConfiguration): void;
395
- /**
396
- * Traces matching deliveries in full, sampled whatever the ratio, until
397
- * stop(): to these sessions (IDs or actors), to the actors at these
398
- * addresses, and to the actors of these definition families. What a
399
- * watched delivery causes is watched too. An address is resolved once,
400
- * now, to its resident actor's session: an address with none throws
401
- * `not-found`, and a later session at it is not watched.
402
- */
403
- watchTraces(watch: {
404
- sessions?: (bigint | number | ActorID)[];
405
- families?: string[];
406
- addresses?: { family: string; name: string }[];
407
- }): { stop(): void };
408
- /** Metrics as plain data: core's counters and occupancy, and napi's messages and memory. */
409
- metrics(): MetricsSnapshot;
410
-
411
- /**
412
- * Queue a message and return; a later pump turn delivers it (ADR 0005).
413
- * Messages to one target are delivered in the order they were accepted.
414
- * Mail for an actor that is gone is a dead letter, not an error. An
415
- * address is resolved through the directory when the post is accepted; a
416
- * name with no resident actor is a dead letter too (ADR 0006). Throws
417
- * `queue-full` at maxQueuedMessages or maxRetainedBytes. `data` is any JavaScript value, shared
418
- * with the receiver, not copied (ADR 0011); the receiver's expressions see
419
- * it as `context.event.data`.
420
- */
421
- post(target: ActorTarget, event: EventName, data?: unknown, options?: PostOptions): void;
422
-
423
- /**
424
- * Queue a message and return a promise (ADR 0005 point 11). With
425
- * `until: "completed"` (the default) it resolves once the macrostep the
426
- * message starts has ended, with the actor stable or done; with
427
- * `until: "accepted"` once the message is queued. It rejects when the
428
- * message becomes a dead letter, when its macrostep faults, on `signal`
429
- * (`aborted`), after `timeout` (`timeout`), when the queue is full
430
- * (`queue-full`), and on close() (`closed`) while it is pending. Abort
431
- * and timeout withdraw a message still queued; a delivered one is not
432
- * undone. Only misuse throws, and a call after close() throws `closed`.
433
- * A send() whose message becomes a dead letter rejects with the reason's
434
- * code: `not-found` (also for `destroyed`), `done`, `unloaded`,
435
- * `rejected`, `load-failed`, `load-timeout`, `waiting-full`, or `invalid`
436
- * for `refused`; a macrostep quarantined as a runaway rejects with
437
- * `runaway`.
438
- */
439
- send(
440
- target: ActorTarget,
441
- event: EventName,
442
- data?: unknown,
443
- options?: SendOptions,
444
- ): Promise<SendResult>;
445
-
446
- /** Resolve after all currently reachable work is quiescent. */
447
- flush(): Promise<void>;
448
-
449
- /**
450
- * Available only with a manual clock; throws `invalid` otherwise, or when
451
- * time would move backwards. Resolves once everything due has been
452
- * dispatched and the system is quiet.
453
- */
454
- advanceTo(time: number): Promise<void>;
455
- advanceBy(milliseconds: number): Promise<void>;
456
-
457
- /**
458
- * Resident actors as pages of IDs: each page is a Uint32Array of
459
- * interleaved [slot, generation] pairs (ADR 0003). Pages continue from
460
- * core's cursor, in slot order; a page is a snapshot (core ADR 0062).
461
- * This and actors() and definitions() are generators: `reentrant` inside
462
- * a core call, and an invalid `pageSize`, throw from the first next(),
463
- * not from the call.
464
- */
465
- actorIDs(options?: PageOptions): IterableIterator<Uint32Array>;
466
- /**
467
- * Resident actors' inspections, taken when the iterator reaches each
468
- * actor. Holds one page of IDs at a time; an actor destroyed after its
469
- * page was taken is skipped.
470
- */
471
- actors(options?: PageOptions): IterableIterator<ActorInspection>;
472
- /**
473
- * Every definition the system holds, as inspections, one page of IDs at
474
- * a time (core ADR 0078): builder and imported charts, their nested
475
- * inline children, and children compiled when an <invoke> ran. Retired
476
- * definitions still in use are included. A definition freed after its
477
- * page was taken is skipped.
478
- */
479
- definitions(options?: PageOptions): IterableIterator<DefinitionInspection>;
480
-
481
- /** Memory by category and allocator calls (ADRs 0009, 0014). Throws `closed` after close(). */
482
- stats(): SystemStats;
483
-
484
- /**
485
- * Stop scheduling, reject pending sends, destroy the native system, and
486
- * release every retained JavaScript value. Idempotent.
487
- */
184
+ /** Reads a document a chart names with `src` (`<invoke src>`, `<script
185
+ * src>`, `<data src>`, a manifest's `<chart src>`): the text of `source`,
186
+ * named by the document `base`. Called during the compile call only.
187
+ * Throw a `ResolveError` to refuse; any other error is thrown from the
188
+ * compile call as it is.
189
+ *
190
+ * @example
191
+ * const resolver = (base, source) => readFileSync(join(root, source), 'utf8');
192
+ */
193
+ export type Resolver = (base: string, source: string) => string;
194
+
195
+ /** What a compile call returns: the image and the compiler's warnings. */
196
+ export interface Compiled extends Disposable {
197
+ /** The compiled image, for `host.addImage`: a `Uint8Array`, copied on the
198
+ * first read and yours from then on (write it to a file, load it
199
+ * elsewhere). A first read after `close()` throws `TA_ERROR_STALE`. */
200
+ readonly image: Uint8Array;
201
+ /** The warnings and notes of the compilation. */
202
+ readonly diagnostics: readonly Diagnostic[];
203
+ /** Frees the compiler's memory now; the garbage collector does it
204
+ * otherwise. Read `image` first. */
488
205
  close(): void;
206
+ /** `close()`. */
489
207
  [Symbol.dispose](): void;
490
208
  }
491
209
 
492
- export interface MemoryCounters {
493
- readonly bytesInUse: number;
494
- /** High-water mark of bytesInUse. */
495
- readonly peakBytes: number;
496
- /** The largest single allocation so far; in `total`, the largest of any category. */
497
- readonly largestBlock: number;
498
- readonly allocations: number;
499
- readonly frees: number;
500
- }
501
-
502
- export interface PageOptions {
503
- /** Items per page; default 1024, at most 65536. */
504
- readonly pageSize?: number;
505
- }
506
-
507
- export interface SystemStats {
508
- readonly memory: {
509
- readonly total: MemoryCounters;
510
- readonly core: MemoryCounters;
511
- readonly envelopes: MemoryCounters;
512
- readonly scheduling: MemoryCounters;
513
- readonly values: MemoryCounters;
514
- readonly directory: MemoryCounters;
515
- readonly scratch: MemoryCounters;
516
- readonly other: MemoryCounters;
517
- };
518
- /** Allocations plus frees: zero growth in steady state is the test signal. */
519
- readonly allocatorCalls: number;
520
- readonly messages: {
521
- /** Accepted messages not yet delivered or reported as dead letters. */
522
- readonly queued: number;
523
- readonly delivered: number;
524
- readonly deadLetters: number;
525
- };
526
- /** JavaScript values core and the mailboxes hold (ADR 0011). */
527
- readonly values: {
528
- /** Value boxes live now; numbers, booleans, null and undefined need none. */
529
- readonly live: number;
530
- /** Value boxes made since the system was created. */
531
- readonly made: number;
532
- };
533
- }
534
-
535
- export type EventName = string;
536
- export type ActorTarget = Actor | ActorID | ActorAddress;
537
-
538
- export interface ActorAddress {
539
- readonly family: string;
540
- readonly name: string;
541
- }
542
-
543
- declare const definitionIDBrand: unique symbol;
544
- declare const invocationIDBrand: unique symbol;
545
-
546
- /**
547
- * An actor's ID: its slot and generation in the actor table, two small
548
- * integers (ADR 0002). Equality is by value; among live actors the slot alone
549
- * is unique.
550
- */
551
- export interface ActorID {
552
- readonly system: System;
553
- readonly slot: number;
554
- readonly generation: number;
555
- }
556
- export type DefinitionID = bigint & { readonly [definitionIDBrand]: true };
557
- export type InvocationID = bigint & { readonly [invocationIDBrand]: true };
558
-
559
- export interface PostOptions {
560
- /** A W3C traceparent: the macrostep this message starts runs under it (ADR 0015). */
561
- traceparent?: string;
562
- /**
563
- * post() only checks it when called, throwing `aborted` if it already
564
- * aborted; send() also withdraws a message still queued when it aborts.
565
- */
566
- signal?: AbortSignal;
567
- /** The retained-bytes estimate of `data`, instead of the default (ADR 0005 point 9). */
568
- bytes?: number;
569
- /**
570
- * Who the receiver answers with `event.origin` and `event.originType`
571
- * (core ADR 0068): an I/O processor's type plus one request's reply URI,
572
- * a scope from openScope(), or a token its origin template renders.
573
- */
574
- origin?: IOOrigin;
575
- /**
576
- * An operator transition (core ADR 0082, ADR 0026): the message is taken
577
- * by a transition to `targets`, states of the target actor's chart, from
578
- * the active state `source` or the root, instead of by the chart's
579
- * transitions, with every exit, entry, history and invocation a chart
580
- * transition would have. It queues behind the mail before it. When it
581
- * arrives, an actor whose `source` is no longer active, or that runs
582
- * another revision by then, refuses it: a dead letter with reason
583
- * `refused` (a send() rejects with `invalid`), and the actor is not
584
- * quarantined. Only for an ActorID target.
585
- */
586
- transition?: { readonly targets: readonly string[]; readonly source?: string };
587
- }
588
-
589
- /** A message waiting in a mailbox (System.mailbox). */
590
- export interface QueuedMessage {
591
- readonly event: EventName;
592
- readonly data?: unknown;
593
- /** A send() waits for it. */
594
- readonly awaited: boolean;
595
- /** Its origin's scope, when it was posted with `origin: { type, scope }`. */
596
- readonly scope?: { readonly index: number; readonly generation: number };
597
- /** The operator transition it carries, by state names; `source` null is the root. */
598
- readonly transition?: { readonly source: string | null; readonly targets: readonly string[] };
599
- }
600
-
601
- export type IOOrigin =
602
- | { readonly type: string; readonly uri: string }
603
- | { readonly type: string; readonly scope: IOScope }
604
- | { readonly type: string; readonly token: number | bigint };
605
-
606
- /** A scope from System.openScope(); stale once closed. */
607
- export interface IOScope {
608
- readonly type: string;
609
- readonly uri: string;
610
- readonly index: number;
611
- readonly generation: number;
612
- }
613
-
614
- /**
615
- * Templates the native adapter renders without running JavaScript (core ADR
616
- * 0068): `location` is this session's address through the processor,
617
- * listed in `ioProcessors` ({session}, {family}, {name}); `origin` is the
618
- * URI of a computed origin ({token}).
619
- */
620
- export interface IOProcessorOptions {
621
- location?: string;
622
- origin?: string;
623
- }
624
-
625
- export interface SendOptions extends PostOptions {
626
- /** "completed" (default): the message's macrostep ended; "accepted": it is queued. */
627
- until?: "completed" | "accepted";
628
- /** Reject with `timeout`, and withdraw the message if still queued, after this many milliseconds. */
629
- timeout?: number;
630
- }
631
-
632
- export interface SendResult {
633
- /** The actor that ran the macrostep; for "accepted", the target when it was an ActorID. */
634
- readonly actor?: Actor;
635
- readonly status: "accepted" | "stable" | "done";
636
- /** "done": the actor's done data. */
637
- readonly completion?: unknown;
638
- }
639
-
640
- /* --------------------------------------------------------------------------
641
- * Definitions
642
- * -------------------------------------------------------------------------- */
643
-
644
- /**
645
- * A revision is stored as bytes. It reads back as a string when the bytes are
646
- * valid UTF-8, and as a Uint8Array otherwise.
210
+ /** Compiles SCXML documents into one image. Each chart is known by its
211
+ * `<scxml name>`. A `src` is answered by a source of that name or by
212
+ * `resolver`. The first source is the boot chart, which `host.boot`
213
+ * spawns. Throws `CompileError` with every diagnostic. Every expression
214
+ * and script of an `"ecmascript"` chart is parsed by the engine, running
215
+ * nothing: a syntax error is a warning in `diagnostics` (`cond:
216
+ * SyntaxError: ...`, at its element's line and column, a script's own
217
+ * line), and an error with `warningsAsErrors`.
218
+ *
219
+ * @example
220
+ * const compiled = compileCharts([{ name: 'order.scxml', text }]);
221
+ * const segment = host.addImage(compiled.image);
222
+ * compiled.close();
647
223
  */
648
- export interface DefinitionIdentity {
649
- readonly family: string;
650
- readonly revision: string | Uint8Array;
651
- }
652
-
653
- /** How the chart uses a source expression (core ADR 0076). */
654
- export type ExpressionRole = "value" | "condition" | "location" | "script";
655
-
656
- /**
657
- * A data model for imported documents (napi ADR 0019). For "value",
658
- * "condition" and "script", compile returns a function called with `this` =
659
- * the data and one argument, the context; for "location", a data name or
660
- * `{ get(context), set(value, context) }`. Throwing refuses the chart; an
661
- * error with numeric `offset` and `length` points into `source`.
224
+ export function compileCharts(sources: readonly Source[], resolver?: Resolver, options?: CompileOptions): Compiled;
225
+
226
+ /** The options of `compileCharts` and `compileSystem`. */
227
+ export interface CompileOptions {
228
+ /** Every warning is an error, and the compile throws `CompileError`:
229
+ * the compiler's own warnings and the syntax errors of the charts'
230
+ * ECMAScript, which are warnings otherwise, since SCXML makes such an
231
+ * expression an `error.execution` when it is evaluated. */
232
+ readonly warningsAsErrors?: boolean;
233
+ }
234
+
235
+ /** Compiles a system manifest: a `<system>` document of `<chart name
236
+ * src>`s, read through `resolver`, and `<actor name chart>`s, which
237
+ * `host.boot` spawns with their names. Throws `CompileError`. */
238
+ export function compileSystem(manifest: Source, resolver?: Resolver, options?: CompileOptions): Compiled;
239
+
240
+ /** A {@link Resolver} that reads each `src` as a file under `root`,
241
+ * relative to the directory of the document that names it (`base`): a
242
+ * document named `orders/order.scxml` asking for `payment.scxml` reads
243
+ * `<root>/orders/payment.scxml`. It refuses with a `ResolveError` (a
244
+ * compile error) a path that leaves `root` (`..` past it, an absolute
245
+ * path, a symbolic link that points outside), a file that does not exist,
246
+ * and text that is not UTF-8; another error of the file system is thrown
247
+ * from the compile call as it is. `root` is resolved through its links
248
+ * once, here: one that does not exist throws now. A document it read is
249
+ * named by its `src` as written. (The convenience layer: JavaScript over
250
+ * `node:fs`.)
251
+ *
252
+ * @example
253
+ * host.addCharts({ 'orders/order.scxml': text }, { resolver: directoryResolver('charts') });
662
254
  */
663
- export interface DatamodelCompiler {
664
- compile(
665
- source: string,
666
- role: ExpressionRole,
667
- ): ((this: any, context: any) => unknown) | string | { get(this: any, context: any): unknown; set(this: any, value: unknown, context: any): void };
255
+ export function directoryResolver(root: string | URL): Resolver;
256
+
257
+ // ---- addresses ----------------------------------------------------------
258
+
259
+ /** An actor's address: `tinyactors://<system>/#_scxml_<session>`, or
260
+ * `tinyactors://<system>/@<name>` for a named actor. Immutable. Its parts
261
+ * are read from the text on each access, `undefined` for a part the text
262
+ * lacks (any text makes an `Address`; one that is not an address has no
263
+ * parts). */
264
+ export class Address {
265
+ constructor(text: string);
266
+ /** The address of a session of system `system`. */
267
+ static fromSession(system: string, session: Session): Address;
268
+ /** The address of the actor named `name` in system `system`; the name is
269
+ * percent-encoded. */
270
+ static fromName(system: string, name: string): Address;
271
+ readonly text: string;
272
+ /** The system id. */
273
+ readonly system: string | undefined;
274
+ readonly session: bigint | undefined;
275
+ /** The actor's name, decoded. */
276
+ readonly name: string | undefined;
277
+ /** The text. */
278
+ toString(): string;
279
+ /** The text, so `JSON.stringify` writes an address as a string, which
280
+ * `new Address(text)` and `host.send` read back. */
281
+ toJSON(): string;
282
+ }
283
+
284
+ // ---- BasicHTTP ----------------------------------------------------------
285
+
286
+ /** A form field of a BasicHTTP message. */
287
+ export interface HTTPField {
288
+ name: string;
289
+ value: string;
668
290
  }
669
291
 
670
- /** Why define(xml, { format: "scxml" }) refused a document, as `detail`. */
671
- export interface ImportRefusal {
672
- /** "decode": the document is not SCXML the codec reads; "compile": core refused the chart. */
673
- readonly stage: "decode" | "compile";
674
- readonly message: string;
675
- /** Where in the document, 1-based, when the refusal names a place. */
676
- readonly line?: number;
677
- readonly column?: number;
678
- /** The byte offset in the UTF-8 document. */
679
- readonly offset?: number;
292
+ /** A BasicHTTP POST, the request SCXML's HTTP processor makes for a send. */
293
+ export interface HTTPPost {
294
+ /** `http://host[:port]/path`. */
295
+ url: string;
296
+ /** Written as the `_scxmleventname` field. */
297
+ event?: string;
298
+ fields?: readonly HTTPField[];
299
+ /** The body, used when there are no fields; percent-encoded. */
300
+ body?: string;
680
301
  }
681
302
 
682
- /** Core's compile error, attached as `detail` when define() refuses a chart. */
683
- export interface ChartRefusal {
684
- /** The compile error code, e.g. "expression_rejected" or "unknown_state". */
685
- readonly code: string;
686
- /** Where in the spec, e.g. "states[0].transitions[1].condition". */
687
- readonly path: string;
688
- /** Core's compile error as the generated layer returns it. */
689
- readonly error: {
690
- readonly code: string;
691
- readonly path: readonly { readonly member: string; readonly index: number }[];
692
- readonly subject?: string;
693
- readonly related?: string;
694
- readonly message: string;
695
- };
303
+ /** An incoming BasicHTTP request, read. */
304
+ export interface HTTPRequest {
305
+ readonly method: string;
306
+ readonly target: string;
307
+ /** The body as received. */
308
+ readonly body: string;
309
+ /** The `_scxmleventname` field, else `HTTP.<METHOD>`. */
310
+ readonly event: string;
311
+ /** The decoded form fields, but `_scxmleventname`. */
312
+ readonly fields: readonly HTTPField[];
696
313
  }
697
314
 
698
- export interface Definition<Data extends object = Record<string, unknown>> {
699
- readonly system: System;
700
- readonly id: DefinitionID;
701
- readonly identity: DefinitionIdentity;
702
- /**
703
- * True once retire() has run. Core frees a retired definition when no
704
- * actor uses it; a freed definition still reads as retired.
705
- */
706
- readonly retired: boolean;
707
-
708
- /** Read from core. Throws `not-found` once a retired definition is freed. */
709
- inspect(): DefinitionInspection;
710
-
711
- /**
712
- * Where element `id` of `kind` was written (core ADR 0085), or undefined
713
- * when the definition keeps no span for it. statechart() records the file,
714
- * line and column of the call that wrote each state, transition, initial
715
- * transition and action.
716
- */
717
- sourceOf(kind: ElementKind, id: number): SourcePlace | undefined;
315
+ /** The bytes of a BasicHTTP POST, to write to a socket. A URL that is not
316
+ * `http://host[:port]/path` throws `TA_ERROR_INVALID`. */
317
+ export function encodeHTTPPost(post: HTTPPost): Uint8Array;
718
318
 
719
- /** Prevent new actors from using this definition. Existing actors continue. */
720
- retire(): void;
721
- }
319
+ /** Reads an incoming BasicHTTP request: its event and form fields, for
320
+ * `host.send`. A malformed request throws `TA_ERROR_INVALID`. */
321
+ export function parseHTTPRequest(message: Uint8Array | ArrayBuffer): HTTPRequest;
722
322
 
723
- /** The kinds of compiled element core numbers, as trace records name them. */
724
- export type ElementKind = "state" | "transition" | "action" | "expression";
323
+ // ---- the clock ----------------------------------------------------------
725
324
 
726
- /**
727
- * A place in a source. Lines and columns count from 1; a column is the
728
- * engine's (UTF-16 code units in JavaScript). The column, the end and the
729
- * byte range are present when the front end knew them: statechart() and a
730
- * document codec record the column; a spec's span may give only a line.
731
- */
732
- export interface SourcePlace {
733
- /** The source's name: a file, a URL, or "" when the spec named none. */
734
- readonly source: string;
735
- readonly line: number;
736
- readonly column?: number;
737
- readonly endLine?: number;
738
- readonly endColumn?: number;
739
- readonly offset?: number;
740
- readonly length?: number;
741
- }
742
-
743
- export interface DefinitionInspection {
744
- readonly id: DefinitionID;
745
- readonly identity: DefinitionIdentity;
746
- /** StatechartOptions.name, or an imported document's `<scxml name>`. */
747
- readonly name?: string;
748
- /** The data model the chart was compiled against, e.g. "javascript". */
749
- readonly datamodel: string;
750
- readonly binding: "early" | "late";
751
- readonly retired: boolean;
752
- readonly actorCount: number;
753
- readonly stateCount: number;
754
- readonly actorFixedBytes: number;
755
- readonly definitionBytes: number;
756
- /** Holds taken by define() and not given back (core ADR 0077). */
757
- readonly holds: number;
758
- /** How many definitions nest this one as an inline child. */
759
- readonly nestedBy: number;
760
- /** The children this chart's <invoke>s nest, when it has any (core ADR 0078). */
761
- readonly nested?: readonly DefinitionID[];
762
- }
763
-
764
- /* --------------------------------------------------------------------------
765
- * Fluent definition builder
766
- * -------------------------------------------------------------------------- */
767
-
768
- export interface StatechartOptions extends DefinitionIdentity {
769
- readonly name?: string;
770
- readonly binding?: "early" | "late";
771
- }
772
-
773
- /**
774
- * Begin an ordered JavaScript-authored statechart definition. The builder is
775
- * mutable until build() or System.define() consumes it.
325
+ /** A clock for tests and simulations, which moves only when you move it.
326
+ * Give it to a host as `options.clock`; a host on it arms no timer.
327
+ *
328
+ * @example
329
+ * const clock = new SimulatedClock();
330
+ * const host = new Host(config, { clock });
331
+ * clock.increment(30_000); // a 30-second timeout, at once
332
+ * await host.idle();
776
333
  */
777
- export declare function statechart<Data extends object>(
778
- options: StatechartOptions,
779
- ): DefinitionBuilder<Data>;
780
-
781
- export type Target = string | readonly string[];
782
- declare const literalValueBrand: unique symbol;
783
- export interface LiteralValue<Value> {
784
- readonly [literalValueBrand]: true;
785
- readonly value: Value;
786
- }
787
-
788
- /** Force a callable JavaScript value to be data rather than an expression. */
789
- export declare function literal<Value>(value: Value): LiteralValue<Value>;
790
-
791
- declare const contentValueBrand: unique symbol;
792
- export interface ContentValue {
793
- readonly [contentValueBrand]: true;
794
- /** The content's bytes: a string's UTF-8, or a copy of the Uint8Array. */
795
- readonly bytes: Uint8Array;
796
- readonly mediaType?: string;
797
- }
798
-
799
- /**
800
- * Literal SCXML `<content>`, kept in the definition as bytes with an
801
- * optional media type; accepted wherever a value is. A send's data reaches
802
- * its I/O processor, and an invoke's content its invoker, as text with
803
- * `contentType` (IORequest, InvokeRequest). Anywhere else the content is a
804
- * value: parsed as JSON when it parses, otherwise the text with each run of
805
- * whitespace made one space and none leading or trailing (SCXML B.2.2).
334
+ export class SimulatedClock {
335
+ constructor();
336
+ /** Milliseconds since the clock was made. */
337
+ readonly now: number;
338
+ /** Moves the clock `ms` forward and schedules a turn on every host made
339
+ * with it; `await host.idle()` to see what ran. What is due runs once, at
340
+ * the new time, and a delay it starts counts from there: to see each of
341
+ * several deadlines, step to each. */
342
+ increment(ms: number): void;
343
+ }
344
+
345
+ // ---- what handlers get ----------------------------------------------------
346
+
347
+ /** One `<send>` of a chart, as an I/O processor's handler, the transport
348
+ * or a service's `receive` gets it. A view of the host's memory: each
349
+ * field is read on first access, while the handler runs; after the
350
+ * handler returned, a read throws `TA_ERROR_STALE`. When the handler
351
+ * returns a promise, every field is read before the host moves on, and
352
+ * the view stays valid, `answer` and `fail` included, while the host is
353
+ * open. */
354
+ export interface Send {
355
+ /** The sender. */
356
+ readonly session: bigint;
357
+ /** The event's name. */
358
+ readonly event: string;
359
+ /** `<send target>`: a string; an `Address` for the transport's sends;
360
+ * `undefined` when the send has none. */
361
+ readonly target: string | Address | undefined;
362
+ /** `<send id>`, or the id the host generated; `undefined` when none. A
363
+ * generated id is unique in the sender's session only (each session's
364
+ * first is `send.1`): key by `session` and `sendid` together. */
365
+ readonly sendid: string | undefined;
366
+ /** The `<param>`s as an object, or the `<content>`'s value. */
367
+ readonly data: ReceivedValue;
368
+ /** The I/O processor's type; `undefined` for the transport and a service. */
369
+ readonly type: string | undefined;
370
+ /** The sender's address. */
371
+ readonly origin: Address | undefined;
372
+ /** The sending step's trace as W3C `traceparent` text, for the header of
373
+ * the request you make; `undefined` when untraced. */
374
+ readonly traceparent: string | undefined;
375
+ /** The outgoing half, `{ target, event, data, sendid, origin,
376
+ * traceparent }`: what `host.send(message)` takes on the other side,
377
+ * unchanged. The transport's reason to exist; present on every send. A
378
+ * text field the send lacks (`sendid`, `origin`, `traceparent`) is
379
+ * `null`, as in a Python host's message, so encoded it is absent to
380
+ * every binding. Its addresses are `Address`es, which `JSON.stringify` writes as their text
381
+ * (`toJSON`) and `encode` as tag 32. */
382
+ readonly message: SendMessage;
383
+ /** Sends `event` back to the sender, with this send's `sendid`. It
384
+ * continues the send's trace unless `options.traceparent` is given
385
+ * (`null`: a new trace). Once: a second answer, or one after `fail()`,
386
+ * throws `TA_ERROR_STATE`, as does a closed host. Returns `true` when the
387
+ * sender gets it, `false` when the sender ended meanwhile (an answer
388
+ * given after the handler returned): nothing is delivered. */
389
+ answer(event: string, data?: Value, options?: AnswerOptions): boolean;
390
+ /** Gives the sender `error.communication` with this send's `sendid`:
391
+ * the request could not be done. Returns `true` when the sender gets it,
392
+ * `false` when it ended meanwhile, as `answer`. */
393
+ fail(): boolean;
394
+ }
395
+
396
+ /** The options of `send.answer`. */
397
+ export interface AnswerOptions {
398
+ /** The answer's trace: W3C text, or `null` for a new trace. Absent: the
399
+ * send's. */
400
+ traceparent?: string | null;
401
+ /** The answer's `_event.origin`. */
402
+ origin?: string | Address;
403
+ /** The message as you read it, for the chart's `_event.raw`. */
404
+ raw?: string;
405
+ }
406
+
407
+ /** An event for `host.send(message)` and `host.sendMany(items)`, in the
408
+ * shape `send.message` has. Keys it does not know are ignored. */
409
+ export interface SendMessage {
410
+ /** A session, or an address (string or `Address`); a local address is
411
+ * resolved to its actor. */
412
+ target: Session | string | Address;
413
+ event: string;
414
+ data?: Value;
415
+ /** The event's `_event.sendid`. */
416
+ sendid?: string | null;
417
+ /** The event's `_event.origin`: where an answer goes. */
418
+ origin?: string | Address | null;
419
+ /** The trace the event continues, as W3C text; text that does not parse
420
+ * starts a new one. */
421
+ traceparent?: string | null;
422
+ }
423
+
424
+ /** A `<log>` line: a view, valid while the log handler runs. */
425
+ export interface LogEntry {
426
+ /** The actor that logged. */
427
+ readonly session: bigint;
428
+ /** `<log label>`; `''` when it has none. */
429
+ readonly label: string;
430
+ /** The value of `<log expr>`, as text. */
431
+ readonly text: string;
432
+ }
433
+
434
+ /** An actor a migration moved: a view, valid while the handler runs. */
435
+ export interface Migrated {
436
+ readonly session: bigint;
437
+ /** The segment of its new version. */
438
+ readonly segment: number;
439
+ /** The chart's name. */
440
+ readonly chart: string;
441
+ /** The migration's id, as `host.migrate` returned it. */
442
+ readonly migration: number;
443
+ }
444
+
445
+ /** A session a migration could not move: it stays on its version.
446
+ * `reason` names core's status, `'TA_ERROR_UNSUPPORTED'` when its state
447
+ * cannot be written out (a value outside the value table). */
448
+ export interface MigrationFailure {
449
+ readonly session: bigint;
450
+ readonly reason: string;
451
+ }
452
+
453
+ /** A migration's end: how many actors it moved, the ones it could not move
454
+ * and why (they stay on their version), and the sessions its timeout left
455
+ * behind. */
456
+ export interface MigrationResult {
457
+ readonly migration: number;
458
+ readonly migrated: number;
459
+ readonly failed: readonly MigrationFailure[];
460
+ readonly pending: readonly bigint[];
461
+ }
462
+
463
+ /** An `<invoke>` of a service your program runs, as a service handler
464
+ * gets it. A record: keep it and use it while the service runs. */
465
+ export interface Invocation {
466
+ /** The invoking actor. */
467
+ readonly session: bigint;
468
+ /** The `<invoke id>`, or the id the host generated. */
469
+ readonly invokeid: string;
470
+ /** `<invoke type>`. */
471
+ readonly type: string;
472
+ /** `<invoke src>`. */
473
+ readonly src: string;
474
+ /** The `<param>`s as an object, or the `<content>`'s value. */
475
+ readonly data: ReceivedValue;
476
+ /** The invoking step's trace, as W3C text. */
477
+ readonly traceparent: string | undefined;
478
+ /** True when a restored host announces an invocation that was running
479
+ * at its snapshot: start it again, or a stand-in. */
480
+ readonly restored: boolean;
481
+ /** False once the invocation ended (done, cancelled, failed) or the host
482
+ * closed. */
483
+ readonly running: boolean;
484
+ /** Sends `event` to the invoker, with `_event.invokeid` set. Continues
485
+ * the invoke's trace unless given one (`null`: a new trace). Throws
486
+ * `TA_ERROR_STALE` once the invocation ended. */
487
+ sendBack(event: string, data?: Value, options?: { traceparent?: string | null }): void;
488
+ /** Ends the service: the invoker gets `done.invoke.<invokeid>` with
489
+ * `data`, and the service is dropped without `stop`. Throws
490
+ * `TA_ERROR_STALE` once the invocation ended. */
491
+ done(data?: Value, options?: { traceparent?: string | null }): void;
492
+ }
493
+
494
+ /** What a service handler returns: any object, kept by the host until the
495
+ * invocation ends, whose methods the host calls. At `host.close()` a
496
+ * running service is dropped, not stopped. */
497
+ export interface Service {
498
+ /** A send of the invoker to the service (`<send target="#_<invokeid>">`,
499
+ * or an autoforwarded event); `send.type` is `undefined`. A throw, or a
500
+ * promise that rejects, is a crash: the invoker gets
501
+ * `error.communication` and the service is dropped. */
502
+ receive?(host: Host, send: Send): void | Promise<void>;
503
+ /** The invoker left the state, which cancels the invocation. */
504
+ stop?(host: Host): void;
505
+ }
506
+
507
+ // ---- the host -----------------------------------------------------------
508
+
509
+ /** A chart's current version in a host, from `host.chart(name)`, for
510
+ * `host.spawn`. */
511
+ export interface ChartRef {
512
+ /** The segment of the image that holds it. */
513
+ readonly segment: number;
514
+ /** Its index in that image. */
515
+ readonly chart: number;
516
+ }
517
+
518
+ /** The host's config: plain values, checked by the host, every absent key
519
+ * a default (the host's, never the package's). A key the host does not
520
+ * take, or a value of the wrong type, throws a `TinyactorsError`
521
+ * (`TA_ERROR_INVALID`) at `new Host`, with the host's `reason` and the key
522
+ * as `path` (`system.maxActors`). `host.hostConfig()` answers the
523
+ * config with every default filled in, as {@link EffectiveHostConfig}.
524
+ *
525
+ * @example
526
+ * const config = { systemID: 'orders', system: { maxActors: 10_000 }, telemetry: { resource: { 'service.name': 'orders' } } };
806
527
  */
807
- export declare function content(
808
- body: string | Uint8Array,
809
- options?: { readonly mediaType?: string },
810
- ): ContentValue;
811
-
812
- export type ValueInput<Data extends object, Value = unknown> =
813
- | (Value extends (...arguments_: never[]) => unknown ? never : Value)
814
- | LiteralValue<Value>
815
- | ContentValue
816
- | Expression<Data, Value>;
817
-
818
- export interface DefinitionBuilder<Data extends object>
819
- extends StateContainerBuilder<Data, DefinitionBuilder<Data>> {
820
- /** `initial` is data even when it is a function; content() is parsed (see content()). */
821
- data<Key extends keyof Data & string>(name: Key, initial: Data[Key] | ContentValue): this;
822
- dataExpression<Key extends keyof Data & string>(
823
- name: Key,
824
- initial: Expression<Data, Data[Key]>,
825
- ): this;
826
- initial(target: Target, actions?: ActionBlock<Data>): this;
827
- /** A script run once at initialization, after early-bound data (SCXML 3.2.2). */
828
- script(run: Script<Data>): this;
829
- build(): DefinitionSpec;
830
- }
831
-
832
- export type ActionBlock<Data extends object> = (
833
- actions: ActionBuilder<Data>,
834
- ) => void;
835
-
836
- export type StateBlock<Data extends object> = (
837
- state: StateBuilder<Data>,
838
- ) => void;
839
-
840
- export interface StateContainerBuilder<Data extends object, Self> {
841
- state(id: string, build?: StateBlock<Data>): Self;
842
- parallel(id: string, build: StateBlock<Data>): Self;
843
- final(id: string, build?: StateBlock<Data>): Self;
844
- /**
845
- * A history state. `build` gives it its default transition, which it
846
- * needs exactly one of, with always(): `h => h.always(t => t.target("a"))`.
847
- */
848
- history(
849
- id: string,
850
- depth: "shallow" | "deep",
851
- build: StateBlock<Data>,
852
- ): Self;
853
- }
854
-
855
- export interface StateBuilder<Data extends object>
856
- extends StateContainerBuilder<Data, StateBuilder<Data>> {
857
- /** Override the kind normally inferred from the builder method and children. */
858
- kind(kind: StateKind): this;
859
- initial(target: Target, actions?: ActionBlock<Data>): this;
860
-
861
- /** `initial` is data even when it is a function; content() is parsed (see content()). */
862
- data<Key extends keyof Data & string>(name: Key, initial: Data[Key] | ContentValue): this;
863
- dataExpression<Key extends keyof Data & string>(
864
- name: Key,
865
- initial: Expression<Data, Data[Key]>,
866
- ): this;
867
-
868
- /** Each call creates one separately-failing executable-content block. */
869
- entry(build: ActionBlock<Data>): this;
870
- exit(build: ActionBlock<Data>): this;
871
-
872
- /** Add an external transition in document order. */
873
- on(event: EventName, build?: TransitionBlock<Data>): this;
874
- /** Add an eventless transition in document order. */
875
- always(build: TransitionBlock<Data>): this;
876
- invoke(build: InvokeBlock<Data>): this;
877
- doneData(build: DoneDataBlock<Data>): this;
878
- }
879
-
880
- export type TransitionBlock<Data extends object> = (
881
- transition: TransitionBuilder<Data>,
882
- ) => void;
883
-
884
- export interface TransitionBuilder<Data extends object>
885
- extends ActionSequenceBuilder<Data, TransitionBuilder<Data>> {
886
- /** A function, or source text: "In('s')" or a data name. */
887
- when(condition: Condition<Data> | string): this;
888
- target(target: Target): this;
889
- internal(): this;
890
- external(): this;
891
- }
892
-
893
- export interface ActionBuilder<Data extends object>
894
- extends ActionSequenceBuilder<Data, ActionBuilder<Data>> {}
895
-
896
- export interface ActionSequenceBuilder<Data extends object, Self> {
897
- raise(event: EventName, data?: ValueInput<Data>): Self;
898
-
899
- send(event: StringSpec<Data>, build?: SendBlock<Data>): Self;
900
- cancel(sendID: StringSpec<Data>): Self;
901
-
902
- /** Assign a declared top-level data property. */
903
- assign<Key extends keyof Data & string>(
904
- location: Key,
905
- value: ValueInput<Data, Data[Key]>,
906
- ): Self;
907
- /** Assign through an explicit location, for nested or computed storage. */
908
- assignAt<Value>(
909
- location: Location<Data, Value>,
910
- value: ValueInput<Data, Value>,
911
- ): Self;
912
-
913
- script(run: Script<Data>): Self;
914
- log(label?: string, value?: Expression<Data> | string): Self;
915
-
916
- choose(
917
- condition: Condition<Data> | string,
918
- then: ActionBlock<Data>,
919
- otherwise?: ActionBlock<Data>,
920
- ): Self;
921
-
922
- forEach<Item>(
923
- array: Expression<Data, readonly Item[]> | (keyof Data & string) | LiteralValue<readonly Item[]>,
924
- item: keyof Data & string,
925
- build: ActionBlock<Data>,
926
- index?: keyof Data & string,
927
- ): Self;
928
- }
929
-
930
- export type SendBlock<Data extends object> = (send: SendBuilder<Data>) => void;
931
-
932
- export interface SendBuilder<Data extends object> {
933
- to(target: StringSpec<Data>): this;
934
- via(ioType: StringSpec<Data>): this;
935
- after(delay: DelaySpec<Data>): this;
936
- /** id() and idLocation() replace each other: the last one called wins. */
937
- id(id: string): this;
938
- idLocation(location: keyof Data & string | Location<Data, string>): this;
939
- data(value: ValueInput<Data>): this;
940
- param(name: string, value: ValueInput<Data>): this;
941
- }
942
-
943
- export type InvokeBlock<Data extends object> = (
944
- invoke: InvokeBuilder<Data>,
945
- ) => void;
946
-
947
- export interface InvokeBuilder<Data extends object> {
948
- /** id() and idLocation() replace each other: the last one called wins. */
949
- id(id: string): this;
950
- idLocation(location: keyof Data & string | Location<Data, string>): this;
951
- type(type: StringSpec<Data>): this;
952
- source(source: StringSpec<Data>): this;
953
- content(value: ValueInput<Data>): this;
954
- param(name: string, value: ValueInput<Data>): this;
955
- autoforward(enabled?: boolean): this;
956
- finalize(build: ActionBlock<Data>): this;
957
- }
958
-
959
- export type DoneDataBlock<Data extends object> = (
960
- done: DoneDataBuilder<Data>,
961
- ) => void;
962
-
963
- export interface DoneDataBuilder<Data extends object> {
964
- content(value: ValueInput<Data>): this;
965
- param(name: string, value: ValueInput<Data>): this;
528
+ export interface HostConfig {
529
+ /** Required: this system's id, part of every address it hands out
530
+ * (`tinyactors://<systemID>/...`). No two systems that talk may share
531
+ * one. */
532
+ systemID: string;
533
+ /** The capacities of each new segment, each its first size, not a cap
534
+ * (a pool that fills grows its segment). */
535
+ system?: SystemConfig;
536
+ /** The I/O processors the charts may send to (`<send type>`), at most
537
+ * 16; each needs a handler in `options.ioProcessors`. Sends to another
538
+ * system need none: they go to `options.transport`. */
539
+ ioProcessors?: readonly IOProcessorConfig[];
540
+ /** Actors a migration looks at per run (default 256). */
541
+ migrateQuantum?: number;
542
+ /** Present: the host has an OTLP encoder, and `options.telemetry` gets
543
+ * its requests. Absent: none, and nothing is paid for it. */
544
+ telemetry?: TelemetryConfig;
545
+ }
546
+
547
+ /** An I/O processor of the config. */
548
+ export interface IOProcessorConfig {
549
+ /** The `<send type>` it serves. */
550
+ type: string;
551
+ /** Its location, which `_ioprocessors` shows the charts. */
552
+ location?: string;
966
553
  }
967
554
 
968
- /* --------------------------------------------------------------------------
969
- * Actors and lifecycle
970
- * -------------------------------------------------------------------------- */
971
-
972
- export interface SpawnOptions<Data extends object> {
973
- /** A W3C traceparent: the bootstrap runs under it (ADR 0015). */
555
+ /** Each new segment's first sizes: unsigned integers, 0 or absent for the
556
+ * host's default; larger values are clamped to the host's limits. */
557
+ export interface SystemConfig {
558
+ /** Default 64, at most 8388606. */
559
+ maxActors?: number;
560
+ /** Queued events; default 256. */
561
+ maxEvents?: number;
562
+ /** Delayed sends and timeouts; default 64. */
563
+ maxTimers?: number;
564
+ /** Actors that may be in a step at once; default 4. */
565
+ workspaces?: number;
566
+ /** Default 16. */
567
+ maxRequests?: number;
568
+ /** Default 64. */
569
+ outbox?: number;
570
+ /** Default 1000. */
571
+ quantum?: number;
572
+ /** Default 0: derived from the image and `maxActors`. */
573
+ instanceBytes?: number;
574
+ /** Default 16384 + 16 per actor of `maxActors`. */
575
+ stringBytes?: number;
576
+ /** The host's clock rate; default 1e9 (nanoseconds). */
577
+ ticksPerSecond?: number;
578
+ /** The trace journal; default 131072, at least 65536. */
579
+ traceBytes?: number;
580
+ /** Default `maxEvents`. */
581
+ traceContexts?: number;
582
+ /** Default 16, at most 255. */
583
+ traceRules?: number;
584
+ /** The seed of the trace IDs: the same seed gives the same IDs. Without
585
+ * one, each new host draws a random seed (`crypto.getRandomValues`);
586
+ * set it to reproduce a test's traces. */
587
+ traceSeed?: number;
588
+ /** Write trace records (default true), so export or a watch can be
589
+ * turned on later. */
590
+ tracing?: boolean;
591
+ }
592
+
593
+ /** The OTLP encoder: unsigned integers, 0 or absent for its default. */
594
+ export interface TelemetryConfig {
595
+ /** Default 1048576, from 65536 to 1073741824. */
596
+ stagingBytes?: number;
597
+ /** Default a quarter of `stagingBytes`. */
598
+ logBytes?: number;
599
+ /** Default 1024. */
600
+ openSpans?: number;
601
+ /** Default 8 per open span. */
602
+ chunks?: number;
603
+ /** Default 64. */
604
+ scopes?: number;
605
+ /** Default 256. */
606
+ valueLimit?: number;
607
+ /** Default 16384. */
608
+ renderBytes?: number;
609
+ /** Default 4096. */
610
+ resourceBytes?: number;
611
+ /** Default 65536. */
612
+ metricBytes?: number;
613
+ /** Default 64. */
614
+ spanMetricCharts?: number;
615
+ /** A request is ready this long after its first record, in the host's
616
+ * clock ticks; 0 or absent: only when the staging is full. */
617
+ flushInterval?: number;
618
+ /** A macrostep is a root span linked to its cause (default false). */
619
+ linkParents?: boolean;
620
+ /** Event data and assigned values in the spans (default false: they may
621
+ * hold personal data). */
622
+ values?: boolean;
623
+ /** `<log>`s and failed actions as log records (default true). */
624
+ logs?: boolean;
625
+ /** Attributes on every request (`service.name`, ...), at most 32. */
626
+ resource?: { readonly [key: string]: string };
627
+ }
628
+
629
+ /** The config a host runs with, every key present, as `hostConfig`
630
+ * answers it: a host made from it answers the same. */
631
+ export interface EffectiveHostConfig {
632
+ readonly systemID: string;
633
+ readonly system: Readonly<Required<SystemConfig>>;
634
+ readonly ioProcessors: readonly Readonly<IOProcessorConfig>[];
635
+ readonly migrateQuantum: number;
636
+ /** Only when the host has an encoder. */
637
+ readonly telemetry?: Readonly<Required<TelemetryConfig>>;
638
+ }
639
+
640
+ /** What a handler returns: nothing, or a promise (typed `unknown`, so a
641
+ * handler that returns another value, as `(host, send) => sent.push(send)`
642
+ * does, is one too; the host ignores it). A send whose handler returns a
643
+ * promise is read in full before the host moves on, and may be answered
644
+ * when the promise gets there. */
645
+ export type Handled = unknown;
646
+
647
+ /** The handlers and choices of a host. A handler's error is reported after
648
+ * its turn: it rejects a waiting `host.idle()`, or else is thrown as an
649
+ * uncaught exception. */
650
+ export interface HostOptions {
651
+ /** The handler of each I/O processor type the config lists. A listed
652
+ * type without a handler fails each send to it; a handler for a type the
653
+ * config does not list is a `TypeError`. */
654
+ ioProcessors?: { [type: string]: (host: Host, send: Send) => Handled };
655
+ /** Sends to another system's address. Pass `send.message` to the other
656
+ * side's `host.send`. Without one, each such send is failed. */
657
+ transport?: (host: Host, send: Send) => Handled;
658
+ /** `<log>` lines; without one they are dropped. */
659
+ log?: (host: Host, entry: LogEntry) => void;
660
+ /** A `SimulatedClock`; without one the host reads the runtime's clock
661
+ * and arms a timer at its next deadline. */
662
+ clock?: SimulatedClock;
663
+ /** Your exporter: each OTLP traces or logs request the encoder wrote
664
+ * (protobuf, for a collector's `/v1/traces` or `/v1/logs`), as a
665
+ * `Uint8Array`. Needs `telemetry` in the config; without a handler the
666
+ * requests are dropped. It runs in the host's turn: start the post and
667
+ * return. At `close()` it gets the last requests; the promises it
668
+ * returns then are awaited by `[Symbol.asyncDispose]`. */
669
+ telemetry?: (host: Host, signal: 'traces' | 'logs', data: Uint8Array) => Handled;
670
+ /** A hibernated actor has work: an event or a due delayed send
671
+ * (`migration` undefined), or a migration asks for it (its id). Load its
672
+ * blob and call `host.wake`, now or later. Called once per hibernation;
673
+ * without it the actor stays hibernated, and its events wait, until
674
+ * `host.wake`. */
675
+ wake?: (host: Host, session: bigint, migration: number | undefined) => Handled;
676
+ /** Each actor a migration moved. */
677
+ migrated?: (host: Host, migrated: Migrated) => void;
678
+ /** The end of each migration. */
679
+ migrationDone?: (host: Host, result: MigrationResult) => void;
680
+ /** The handler of each `<invoke type>` your program runs: it returns the
681
+ * service, or a promise of it. Until the promise settles the sends to
682
+ * the invocation wait, in order; a rejection is a failed start, and the
683
+ * invoker gets `error.communication`. */
684
+ services?: { [type: string]: (host: Host, invocation: Invocation) => Service | void | PromiseLike<Service | void> };
685
+ /** Where chart code runs: `'native'` (the default), your own engine
686
+ * (`node:vm` contexts in @tinyactors/node), for trusted charts; or
687
+ * `'quickjs'`, the sandbox, for charts you do not trust (in
688
+ * @tinyactors/wasm the datamodel for a page whose policy forbids
689
+ * `'unsafe-eval'`). */
690
+ datamodel?: 'native' | 'quickjs';
691
+ /** The sandbox's limits, with `datamodel: 'quickjs'` only (else a
692
+ * `TypeError`). */
693
+ quickjs?: QuickJSOptions;
694
+ }
695
+
696
+ /** The quickjs sandbox's limits. Absent: the engine's default. */
697
+ export interface QuickJSOptions {
698
+ /** Interrupt checks one evaluation may make before it is stopped with
699
+ * `error.execution` (default 1,000,000, which lets a busy loop run for
700
+ * many seconds). */
701
+ maxOps?: number;
702
+ /** Bytes for the whole engine, every actor together (default 1 GiB,
703
+ * `2 ** 30`; `Number.MAX_SAFE_INTEGER` is as good as none). An
704
+ * evaluation that needs more is stopped with `error.execution`, reason
705
+ * `'memory'`. */
706
+ memoryLimit?: number;
707
+ /** Bytes of native stack for JavaScript. */
708
+ stackLimit?: number;
709
+ /** `'auto'` (the default): the actors of a chart that declares no
710
+ * top-level names share one context and its builtins; `'isolated'`: a
711
+ * context per actor. */
712
+ realm?: 'auto' | 'isolated';
713
+ }
714
+
715
+ /** The options of `host.addCharts`. */
716
+ export interface AddChartsOptions {
717
+ /** The compile call's resolver, for each `src` the documents do not
718
+ * answer. */
719
+ resolver?: Resolver;
720
+ }
721
+
722
+ /** The options of `host.spawn`. */
723
+ export interface SpawnOptions {
724
+ /** The actor's name: `host.actorByName` finds it, `_name` holds it, and
725
+ * its address is `tinyactors://<system>/@<name>`. */
726
+ name?: string;
727
+ /** Initial values: each key that names a top-level `<data>` replaces that
728
+ * variable's initial value; keys that name none are left out. */
729
+ params?: Value;
730
+ /** The trace the actor's start continues, as W3C text. */
974
731
  traceparent?: string;
975
- /** Omit both name and address for an anonymous actor. */
976
- readonly name?: string;
977
- readonly address?: ActorAddress;
978
- readonly binding?: Partial<Data>;
979
- /**
980
- * Delayed sends to re-arm before the actor bootstraps (core ADR 0074
981
- * section 8): entries of inspect().delayedSends from an earlier session
982
- * of this actor, stored with its data; they survive JSON and structured
983
- * clone, and may be re-armed in another system or process. They keep
984
- * their IDs, due times and traces; a due time already past fires on the
985
- * next dispatch. A `destination` of "self" goes to this new actor, and an
986
- * address to whatever actor has that address when the send is due. An
987
- * ActorID destination (a send to an unnamed other actor) re-arms only as
988
- * a live ActorID of this system; any other form of it throws `invalid`
989
- * naming the entry, since a stored slot and generation would name
990
- * whichever actor holds that slot by then.
991
- */
992
- readonly pendingSends?: readonly DelayedSendInspection[];
993
- }
994
-
995
- /**
996
- * The view spawn() returns (ADR 0002): an ActorID with methods that ask the
997
- * system. It holds no native resource and no finalizer.
998
- */
999
- export interface Actor<Data extends object = Record<string, unknown>> extends ActorID {
1000
- /**
1001
- * True once no resident actor has this ID: destroyed, finished and
1002
- * destroyed, or unloaded. Throws `closed` after close() of its system.
1003
- */
1004
- readonly destroyed: boolean;
1005
- equals(other: ActorID): boolean;
1006
-
1007
- post(event: EventName, data?: unknown, options?: PostOptions): void;
1008
- send(event: EventName, data?: unknown, options?: SendOptions): Promise<SendResult>;
1009
- inspect(): ActorInspection<Data>;
1010
-
1011
- /** A retained reference to the actor's live data-model root. */
1012
- data(): Data;
1013
-
1014
- /** Capture Tinyactors-owned state and the data-model root in memory (System.capture). */
1015
- capture(): SessionImage<Data>;
1016
-
1017
- /** Offload this stable named actor from memory (System.unload, core ADR 0074). */
1018
- unload(): void;
1019
-
1020
- /**
1021
- * Prepare a fresh unpublished actor of `definition` to replace this named
1022
- * actor in place. It bootstraps like a spawned actor, and core holds its
1023
- * visible bootstrap effects until activation. `binding` defaults to this
1024
- * actor's live data root when `definition` uses the JavaScript data model.
1025
- */
1026
- prepareReplacement(
1027
- definition: Definition<Data>,
1028
- options?: ReplacementOptions<Data>,
1029
- ): PreparedActor<Data>;
1030
-
1031
- /**
1032
- * Terminate this interpreter. Its active invocations are cancelled: an
1033
- * in-system SCXML child is destroyed with it, and a JavaScript invoker's
1034
- * service gets cancel().
1035
- */
1036
- destroy(): void;
1037
- [Symbol.dispose](): void;
1038
- }
1039
-
1040
- export interface PreparedActor<Data extends object> extends Actor<Data> {
1041
- /** False until activate() publishes it. */
1042
- readonly published: boolean;
1043
- readonly incumbent: ActorID;
1044
-
1045
- /**
1046
- * Publish this actor at the incumbent's address, then destroy the
1047
- * incumbent. Mail still waiting for the incumbent, and the send()s it
1048
- * carries, move in order to the front of this actor's mailbox, so nothing
1049
- * accepted for the address is lost; the incumbent's delayed sends are
1050
- * discarded. Throws `busy` while the incumbent is inside a macrostep. If
1051
- * activation fails, the incumbent keeps the address and this actor is left
1052
- * for the caller to destroy.
1053
- */
1054
- activate(): Actor<Data>;
1055
732
  }
1056
733
 
1057
- export interface ReplacementOptions<Data extends object> {
1058
- /** Defaults to the incumbent actor's current data-model root. */
1059
- readonly binding?: Partial<Data> | Data;
734
+ /** The options of `host.send(target, event, data, options)`. */
735
+ export interface SendOptions {
736
+ /** The event's `_event.sendid`. */
737
+ sendid?: string;
738
+ /** The trace the event continues, as W3C text; text that does not parse
739
+ * starts a new one. */
740
+ traceparent?: string;
741
+ /** The event's `_event.origin`. */
742
+ origin?: string | Address;
743
+ }
744
+
745
+ /** The options of `host.migrate`. */
746
+ export interface MigrateOptions {
747
+ /** A chart's name; none: every chart. */
748
+ chart?: string;
749
+ /** One actor. */
750
+ session?: Session;
751
+ /** Ask the `wake` handler for the hibernated actors, with the
752
+ * migration's id. */
753
+ wake?: boolean;
754
+ /** Milliseconds of the host's clock from now, rounded up to its next
755
+ * tick; 0 or none: no timeout. */
756
+ timeout?: number;
1060
757
  }
1061
758
 
1062
- /**
1063
- * Core's residency: "idle" between macrosteps, "running" inside one, "done"
1064
- * once finished. An unloaded actor is not resident: inspecting it throws
1065
- * `not-found`.
1066
- */
1067
- export type ActorResidency = "idle" | "running" | "done";
1068
-
1069
- /**
1070
- * A snapshot of core's view of one actor (ADR 0054: O(size of the actor)).
1071
- */
1072
- export interface ActorInspection<Data = unknown> {
1073
- readonly actor: Actor;
1074
- /** Stable across unload and load; the runtime ID is not (core ADR 0066). */
1075
- readonly sessionID: bigint;
1076
- readonly definition: DefinitionIdentity;
1077
- /** The definition's ID (Definition.id), which names its compiled states, transitions and actions. */
1078
- readonly definitionID: DefinitionID;
1079
- readonly residency: ActorResidency;
1080
- readonly published: boolean;
1081
- readonly activeStates: readonly string[];
1082
- readonly macrostepInProgress: boolean;
1083
- /** Paused inside a microstep, in executable content (core ADR 0061). */
1084
- readonly microstepInProgress: boolean;
1085
- /**
1086
- * The step key of where a paused macrostep stands (core ADR 0083);
1087
- * (session, 0, 0) outside a macrostep and before one begins.
1088
- */
1089
- readonly step: { readonly session: bigint; readonly macrostep: number; readonly microstep: number };
759
+ /** A typed method's params, passed to the host as given (the host checks
760
+ * them); `undefined` for none. Each method has its own type below. */
761
+ export type Params = { [key: string]: Value } | undefined;
762
+ /** The params of a method that takes none: `undefined` or `{}`. */
763
+ export type NoParams = undefined | { readonly [key: string]: never };
764
+ /** A typed method's result handler, called once, in a later turn, with the
765
+ * method's result. */
766
+ export type OnResult<R = Value> = (host: Host, result: R) => void;
767
+ /** A typed method's error handler. Without one, the error rejects a
768
+ * waiting `idle()` or is thrown as an uncaught exception. */
769
+ export type OnError = (host: Host, error: TinyactorsError) => void;
770
+
771
+ // ---- the typed methods' params and results ---------------------------
772
+ //
773
+ // As the host writes them (each method of the host's control plane). A
774
+ // session or a count in a result is a number; an integer past 2^53 would
775
+ // be a bigint, which only `trace.spans.decode`'s nanosecond times reach.
776
+
777
+ /** An active configuration, as xstate's `value`: an atomic state is its
778
+ * id (`'s'`), a compound state `{ [state]: its active child }`, a parallel
779
+ * state `{ [state]: { [region]: ... } }`, an atomic region `{}`. */
780
+ export type StateValue = string | { readonly [state: string]: StateValue };
781
+
782
+ /** The params of `actorState`, `actorContext` and `actorGet`. */
783
+ export interface SessionParams {
784
+ session: Session;
785
+ }
786
+ /** `actorState`'s result. */
787
+ export interface ActorStateResult {
788
+ readonly value: StateValue;
1090
789
  /**
1091
- * The unit a paused macrostep runs next (core ADR 0083): `at` is "none"
1092
- * between microsteps and outside a macrostep; otherwise the phase, the
1093
- * state, and the transition and action by compiled ID (core ADR 0071).
790
+ * Where each history state the actor has recorded would return, by its
791
+ * id: its parent state as it would be entered again, in the shape of
792
+ * `value` (a deep history down to the atomic states it recorded; a
793
+ * shallow one names the child it recorded). A history state records when
794
+ * its parent is exited; one that has recorded nothing is absent, so this
795
+ * is `{}` before any exit. A hibernated actor's state is refused
796
+ * (`reason` `'state'`): wake it first.
1094
797
  */
1095
- readonly position: TracePosition;
1096
- /** The external event of the macrostep in progress, or null. */
1097
- readonly currentEvent: InspectedEvent | null;
1098
- /** The internal queue, oldest first. */
1099
- readonly internalEvents: readonly InspectedEvent[];
1100
- readonly internalEventCount: number;
1101
- /** Active and finished invocations of active states. */
1102
- readonly invocations: readonly InvocationInspection[];
1103
- readonly delayedSendCount: number;
1104
- /** Pending delayed sends, by due time then send order (core ADR 0054). */
1105
- readonly delayedSends: readonly DelayedSendInspection[];
1106
- /** The addon's scheduling state (ADR 0005). */
1107
- readonly scheduling: "none" | "idle" | "ready" | "runnable" | "quarantined";
1108
- /** The top-level final state it reached, or null (core ADR 0056). */
1109
- readonly finalState: string | null;
1110
- readonly allocatedBytes: number;
1111
- /** The live data object (JavaScript data model), shared, not copied; undefined under the null data model. */
1112
- readonly data?: Data;
1113
- /** A finished actor's completion data (<donedata>), or undefined. */
1114
- readonly completion?: unknown;
1115
- }
1116
-
1117
- export interface InvocationInspection {
1118
- readonly id: InvocationID;
1119
- readonly type: string;
1120
- readonly active: boolean;
1121
- readonly autoforward: boolean;
798
+ readonly history: { readonly [history: string]: StateValue };
799
+ }
800
+ /** `actorContext`'s result: each `<data>`, in the chart's order. */
801
+ export interface ActorContextResult {
802
+ readonly variables: { readonly [id: string]: ReceivedValue };
803
+ }
804
+ /** The params of `actorList`. */
805
+ export interface ActorListParams {
806
+ /** From the previous page; absent: the first. */
807
+ cursor?: number;
808
+ /** 1 to 512, default 256. */
809
+ limit?: number;
810
+ }
811
+ /** `actorList`'s result: a page of sessions. */
812
+ export interface ActorListResult {
813
+ readonly sessions: readonly number[];
814
+ /** The next page's cursor, opaque; `null` after the last page. */
815
+ readonly cursor: number | null;
816
+ }
817
+ /** `actorGet`'s result. */
818
+ export interface ActorGetResult {
819
+ readonly session: number;
820
+ readonly segment: number;
821
+ /** The chart's name. */
822
+ readonly chart: string;
823
+ /** The session that invoked it; `null` for a root actor. */
824
+ readonly parent: number | null;
825
+ /** Events waiting for it. */
826
+ readonly mailbox: number;
827
+ /** Services it runs. */
828
+ readonly invocations: number;
1122
829
  /**
1123
- * The invoker's handle for the service. For the in-system SCXML invoker,
1124
- * the child's runtime ID as one integer, (generation << 32) | slot: it
1125
- * matches no actor once the child is unloaded or reconstructed.
830
+ * Its pending delayed sends (`<send delay>` not yet due, not cancelled),
831
+ * earliest first, at most 32: `timersPending` says how many it has.
1126
832
  */
1127
- readonly serviceHandle: bigint;
1128
- }
1129
-
1130
- export interface TracePosition {
1131
- readonly at: "none" | "select" | "exit" | "transition" | "enter" | "bootstrap" | "finalize" | "invoke";
1132
- readonly state: string | null;
1133
- readonly transition: number | null;
1134
- readonly action: number | null;
1135
- readonly iteration: number;
1136
- }
1137
-
1138
- /** An event as inspection reports it. */
1139
- export interface InspectedEvent {
1140
- readonly name: EventName;
1141
- readonly type: "external" | "internal" | "platform";
1142
- readonly sendID?: string;
1143
- /** Who sent it; absent when it has no origin, as after a post() without `origin`. */
1144
- readonly origin?: EventOrigin;
1145
- readonly data?: unknown;
1146
- }
1147
-
1148
- /**
1149
- * Who sent an event (core ADR 0068). `type` and `uri` are what the
1150
- * receiver's expressions see as `event.originType` and `event.origin`, so a
1151
- * reply can go to them; `uri` is absent once the origin's scope is closed.
1152
- * `invocation` is the InvocationInspection.id of the invocation whose
1153
- * service sent it; `scope` is the IOScope it was posted through.
1154
- */
1155
- export type EventOrigin = { readonly type: string; readonly uri?: string } & (
1156
- | { readonly kind: "actor"; readonly actor: ActorID | ActorAddress }
1157
- | { readonly kind: "invocation"; readonly invocation: InvocationID }
1158
- | { readonly kind: "io"; readonly scope?: { readonly index: number; readonly generation: number } }
1159
- );
1160
-
1161
- /** One pending delayed send; `delayedSends` is ordered by due time, then send order. */
1162
- export interface DelayedSendInspection {
1163
- /** The send ID as the chart names it (core ADR 0048), or null when it has none. */
1164
- readonly id: string | null;
833
+ readonly timers: readonly PendingSend[];
834
+ /** How many delayed sends it has pending: more than `timers` holds when the list was cut. */
835
+ readonly timersPending: number;
836
+ }
837
+ /** A pending delayed send, in `actorGet`'s `timers`. */
838
+ export interface PendingSend {
839
+ /** The send's id (its `id`, or the one `idlocation` was given); `null` when it has none. */
840
+ readonly sendid: string | null;
841
+ /** The event's name. */
842
+ readonly event: string;
843
+ /** When it fires: milliseconds on the clock `host.now()` reads. */
1165
844
  readonly due: number;
1166
- readonly event: EventName;
1167
- readonly ioType: string;
1168
- /**
1169
- * The resolved receiver for the built-in SCXML processor: "self" for the
1170
- * actor itself (a send without a target, or to its own session), an
1171
- * address for a named receiver, or an ActorID for an unnamed other actor.
1172
- * null for custom processors, which use `target`.
1173
- */
1174
- readonly destination: "self" | ActorAddress | ActorID | null;
1175
- readonly target: unknown;
1176
- readonly data: unknown;
1177
- /** The router refused this send once; it is waiting to be offered again. */
1178
- readonly submitted: boolean;
1179
- /** A literal target's content ID in the definition, or null (core ADR 0074 section 8). */
1180
- readonly targetContent: number | null;
1181
- /** A literal <content>'s ID in the definition, or null. */
1182
- readonly content: number | null;
1183
- /** The sending step's trace, or null. */
1184
- readonly traceparent: string | null;
1185
- }
1186
-
1187
- /* --------------------------------------------------------------------------
1188
- * In-memory capture, unload, and reconstruction
1189
- * -------------------------------------------------------------------------- */
1190
-
1191
- /**
1192
- * A capture held in memory (ROADMAP step 14). Its handle is destroyed by
1193
- * destroy(), by its finalizer, or by close() of its system, whichever comes
1194
- * first; it never outlives its system (ADR 0012). Serializing it across
1195
- * processes is not supported: model network handoff with I/O processors.
1196
- */
1197
- export interface SessionImage<Data extends object = Record<string, unknown>> {
1198
- readonly origin: System;
1199
- /** The actor at capture; its ID is stale once the actor is unloaded. */
1200
- readonly actor: ActorID;
1201
- /** Stable across unload and load (core ADR 0066). */
1202
- readonly sessionID: bigint;
1203
- readonly definition: DefinitionIdentity;
1204
- readonly address?: ActorAddress;
1205
- /** The data-model root at capture (shared, not copied), or undefined under the null data model. */
1206
- readonly data?: Data;
1207
- /** The earliest pending delayed send's due time, or undefined. */
1208
- readonly nextDeadline?: number;
1209
- /** True after destroy() or close() of its system. */
1210
- readonly destroyed: boolean;
1211
-
1212
- destroy(): void;
1213
- [Symbol.dispose](): void;
1214
- }
1215
-
1216
- /* --------------------------------------------------------------------------
1217
- * JavaScript data-model callbacks
1218
- * -------------------------------------------------------------------------- */
1219
-
1220
- export interface EvaluationContext<Data extends object> {
1221
- readonly data: Data;
1222
- readonly event?: ActorEvent;
1223
- readonly sessionID: string;
1224
- readonly name?: string;
1225
- readonly ioProcessors: Readonly<Record<string, { readonly location: string }>>;
1226
- inState(state: string): boolean;
1227
- }
1228
-
1229
- export type Expression<Data extends object, Result = unknown> = (
1230
- this: Data,
1231
- context: EvaluationContext<Data>,
1232
- ) => Result;
1233
-
1234
- export type Condition<Data extends object> = Expression<Data, unknown>;
1235
-
1236
- export type Script<Data extends object> = (
1237
- this: Data,
1238
- context: EvaluationContext<Data>,
1239
- ) => void;
1240
-
1241
- export interface Location<Data extends object, Value = unknown> {
1242
- get(this: Data, context: EvaluationContext<Data>): Value;
1243
- set(this: Data, value: Value, context: EvaluationContext<Data>): void;
1244
845
  }
1245
-
1246
- export type StringSpec<Data extends object> = string | Expression<Data, string>;
1247
-
1248
- /**
1249
- * A number is milliseconds, written as `${number}ms` for core, which takes
1250
- * an SCXML duration: a non-negative decimal without an exponent, so a
1251
- * number JavaScript prints with one (1e21, 1e-7) is refused at define(). A
1252
- * function's result is checked only when the send runs; a negative or NaN
1253
- * delay then raises `error.execution`.
1254
- */
1255
- export type DelaySpec<Data extends object> =
1256
- | number
1257
- | `${number}ms`
1258
- | `${number}s`
1259
- | Expression<Data, number | string>;
1260
-
1261
- /**
1262
- * The event an expression sees as `context.event` (SCXML _event). `origin`
1263
- * is a URI a send can target: `#_scxml_<sessionID>` or
1264
- * `#_actor_<family>/<name>` (core ADR 0044), so replying is
1265
- * `send("reply").to(({ event }) => event.origin)`.
1266
- */
1267
- export interface ActorEvent<Data = unknown> {
1268
- readonly name: EventName;
1269
- readonly type: "external" | "internal" | "platform";
1270
- readonly sendID?: string;
1271
- readonly origin?: string;
1272
- readonly originType?: string;
1273
- readonly invocationID?: string;
1274
- readonly data: Data;
1275
- }
1276
-
1277
- /* --------------------------------------------------------------------------
1278
- * Statechart specs: the generated shape (ADR 0013)
1279
- *
1280
- * System.define() accepts this shape as a plain object; statechart() emits
1281
- * it; core's definition export returns it. Member names follow core's C
1282
- * spelling, and a tagged union is { kind, <member>: ... }.
1283
- *
1284
- * An expression is a JavaScript function (a condition, value or script,
1285
- * called with `this` bound to the actor's data), a literal() value, or source
1286
- * text: `In(state)`, or a data name, which reads that property (ADR 0011). A
1287
- * location is a data name or a { get, set } object. A spec compiles against
1288
- * the JavaScript data model ("javascript") unless it opts into core's null
1289
- * data model with `datamodel: "null"`. A script, unlike other expressions,
1290
- * must be a function.
1291
- * -------------------------------------------------------------------------- */
1292
-
1293
- /** A function, a literal(), or source text (In(state) or a data name). */
1294
- export type ExpressionSpec =
1295
- | string
1296
- | ((this: any, context: EvaluationContext<any>) => unknown)
1297
- | LiteralValue<unknown>;
1298
- /**
1299
- * A script. Source text and literal() compile, but running them fails with
1300
- * an internal `error.execution` (a script must be a function).
1301
- */
1302
- export type ScriptSpec = (this: any, context: EvaluationContext<any>) => void;
1303
- /** A data name, or a { get, set } location. */
1304
- export type LocationSpec = string | Location<any, unknown>;
1305
-
1306
- export type StateKind =
1307
- | "atomic"
1308
- | "compound"
1309
- | "parallel"
1310
- | "final"
1311
- | "history_shallow"
1312
- | "history_deep";
1313
-
1314
- export interface DefinitionSpec {
1315
- /** The statechart document name. */
1316
- readonly name?: string;
1317
- /**
1318
- * "javascript" when absent. "null" opts into core's null data model: no
1319
- * data, no functions, and content that cannot become a value. define()
1320
- * compiles every other name as "javascript", which core then refuses: a
1321
- * data model registerDatamodel() registered is only for imported SCXML.
1322
- */
1323
- readonly datamodel?: "null" | "javascript";
1324
- readonly identity?: {
1325
- readonly family: { readonly name: string };
1326
- readonly revision: string | Uint8Array;
846
+ /** A pool of a segment: its size, what it holds, the most it held. */
847
+ export interface Pool {
848
+ readonly capacity: number;
849
+ readonly used: number;
850
+ readonly highWater: number;
851
+ }
852
+ /** One live segment's pools, in `host.stats`. */
853
+ export interface SegmentPools {
854
+ /** The segment, as `addImage` returned it. */
855
+ readonly segment: number;
856
+ readonly actors: Pool;
857
+ readonly events: Pool;
858
+ readonly timers: Pool;
859
+ readonly workspaces: Pool;
860
+ readonly requests: Pool;
861
+ /** The slab of instances and strings, in bytes. */
862
+ readonly slabBytes: Pool;
863
+ }
864
+ /** One chart's counters, summed over every segment, retired versions
865
+ * included. */
866
+ export interface ChartStats {
867
+ readonly name: string;
868
+ readonly actors: number;
869
+ readonly hibernated: number;
870
+ readonly spawned: number;
871
+ readonly ended: number;
872
+ readonly turns: number;
873
+ readonly macrosteps: number;
874
+ readonly fuel: number;
875
+ readonly errorsExecution: number;
876
+ readonly errorsCommunication: number;
877
+ readonly errorsPlatform: number;
878
+ readonly faults: number;
879
+ }
880
+ /** `hostStats`'s result. */
881
+ export interface HostStatsResult {
882
+ readonly host: {
883
+ readonly segments: number;
884
+ readonly actors: number;
885
+ readonly hibernated: number;
886
+ readonly runnable: number;
887
+ readonly migrations: number;
888
+ /** The live segments' regions; the host's copies of the images are not
889
+ * in it. */
890
+ readonly regionBytes: number;
891
+ readonly delivered: number;
892
+ readonly routed: number;
893
+ readonly migrated: number;
894
+ readonly retired: number;
895
+ readonly fuelClock: number;
1327
896
  };
1328
- /** "default" is early binding: inspection reports it as "early". */
1329
- readonly binding?: "default" | "early" | "late";
1330
- readonly initial?: InitialSpec;
1331
- /** Document order is semantically significant. */
1332
- readonly states?: readonly StateSpec[];
1333
- readonly data?: readonly DataSpec[];
1334
- readonly script?: ScriptSpec;
1335
- /** Where the script was written: an index into `spans`, from 1. */
1336
- readonly script_span?: number;
1337
- /**
1338
- * Where elements were written (core ADR 0085): each element's `span` is an
1339
- * index into this list, from 1, and each span's `source` an index into
1340
- * `sources`. None of it changes the revision. statechart() fills them in.
1341
- */
1342
- readonly spans?: readonly SpanSpec[];
1343
- readonly sources?: readonly { readonly name: string }[];
1344
- }
1345
-
1346
- export interface SpanSpec {
1347
- readonly source?: number;
1348
- readonly line: number;
1349
- readonly column?: number;
1350
- readonly end_line?: number;
1351
- readonly end_column?: number;
1352
- readonly offset?: bigint;
1353
- readonly length?: number;
1354
- }
1355
-
1356
- export interface StateSpec {
1357
- readonly kind: StateKind;
1358
- readonly span?: number;
1359
- readonly id: string;
1360
- readonly states?: readonly StateSpec[];
1361
- readonly initial?: InitialSpec;
1362
- readonly transitions?: readonly TransitionSpec[];
1363
- /** Each handler is one separately-failing executable-content block. */
1364
- readonly onentry?: readonly HandlerSpec[];
1365
- readonly onexit?: readonly HandlerSpec[];
1366
- readonly data?: readonly DataSpec[];
1367
- readonly invokes?: readonly InvokeSpec[];
1368
- readonly done_data?: DoneDataSpec;
1369
- }
1370
-
1371
- export interface InitialSpec {
1372
- readonly targets: readonly string[];
1373
- readonly actions?: readonly ActionSpec[];
1374
- readonly span?: number;
897
+ /** One entry per live segment, in segment order. */
898
+ readonly pools: readonly SegmentPools[];
899
+ readonly charts: readonly ChartStats[];
900
+ }
901
+ /** A trace rule of `traceConfigure` and `traceWatch`: each absent field
902
+ * matches anything. */
903
+ export interface TraceRule {
904
+ at?: 'start' | 'take';
905
+ chart?: string;
906
+ /** An actor's name; a trailing `*` makes it a prefix. */
907
+ actor?: string;
908
+ /** An event descriptor, SCXML's prefix rule. */
909
+ event?: string;
910
+ session?: Session;
911
+ from?: readonly ('host' | 'actor' | 'timer' | 'spawn' | 'sampled' | 'unsampled')[];
912
+ /** What a match decides (default `'keep'`); a number samples that share
913
+ * of trace IDs. */
914
+ sample?: 'keep' | 'sample' | 'drop' | number;
915
+ detail?: TraceDetail;
916
+ values?: boolean;
917
+ perSecond?: number;
918
+ burst?: number;
919
+ }
920
+ /** How much a trace records. */
921
+ export type TraceDetail = 'summary' | 'decisions' | 'full' | 'off';
922
+ /** The params of `traceConfigure`, which replace the last ones. */
923
+ export interface TraceConfigureParams {
924
+ /** Default `'summary'`. */
925
+ detail?: TraceDetail;
926
+ /** Default false. */
927
+ values?: boolean;
928
+ /** The share of new traces sampled, 0 to 1 (default 1). */
929
+ sample?: number;
930
+ /** False writes no records; traceparents still flow (default true). */
931
+ records?: boolean;
932
+ /** At most 32. */
933
+ rules?: readonly TraceRule[];
934
+ }
935
+ /** The params of `traceWatch`. */
936
+ export interface TraceWatchParams {
937
+ /** At least one. */
938
+ rules: readonly TraceRule[];
939
+ /** On the host's clock; `null`: no end (default 900). */
940
+ seconds?: number | null;
941
+ }
942
+ /** `traceWatch`'s result. */
943
+ export interface TraceWatchResult {
944
+ readonly id: number;
1375
945
  }
1376
-
1377
- export interface TransitionSpec {
1378
- readonly kind: "external" | "internal";
1379
- readonly span?: number;
1380
- /** Omit for an eventless transition. Wildcard segments are supported. */
1381
- readonly event?: string;
1382
- readonly condition?: ExpressionSpec;
1383
- readonly targets?: readonly string[];
1384
- readonly actions?: readonly ActionSpec[];
946
+ /** The params of `traceUnwatch`. */
947
+ export interface TraceUnwatchParams {
948
+ id: number;
1385
949
  }
1386
-
1387
- export interface HandlerSpec {
1388
- readonly actions: readonly ActionSpec[];
950
+ /** The params of `traceSpansDecode`. */
951
+ export interface TraceSpansDecodeParams {
952
+ /** An OTLP traces request, as the telemetry handler gets it. */
953
+ traces: Uint8Array;
1389
954
  }
1390
-
1391
- export interface DataSpec {
955
+ /** A span event. */
956
+ export interface SpanEvent {
1392
957
  readonly name: string;
1393
- readonly initializer?: ValueSourceSpec;
1394
- }
1395
-
1396
- export type ValueSourceSpec =
1397
- | { readonly kind: "expr"; readonly expr: ExpressionSpec }
1398
- | { readonly kind: "location"; readonly location: LocationSpec }
1399
- | { readonly kind: "content"; readonly content: { readonly media_type?: string; readonly bytes: Uint8Array } };
1400
-
1401
- /** An `x` / `xexpr` attribute pair. */
1402
- export type StringAttributeSpec =
1403
- | { readonly kind: "literal"; readonly literal: string }
1404
- | { readonly kind: "expr"; readonly expr: ExpressionSpec };
1405
-
1406
- export type ActionSpec = { readonly span?: number } & (
1407
- | { readonly kind: "raise"; readonly raise: { readonly event: string; readonly data?: ValueSourceSpec } }
1408
- | { readonly kind: "send"; readonly send: SendSpec }
1409
- | { readonly kind: "cancel"; readonly cancel: { readonly sendid: StringAttributeSpec } }
1410
- | { readonly kind: "assign"; readonly assign: { readonly location: LocationSpec; readonly value?: ValueSourceSpec } }
1411
- | { readonly kind: "script"; readonly script: { readonly script: ScriptSpec } }
1412
- | { readonly kind: "log"; readonly log: { readonly label?: string; readonly expr?: ExpressionSpec } }
1413
- | {
1414
- readonly kind: "if";
1415
- readonly conditional: {
1416
- readonly condition: ExpressionSpec;
1417
- readonly then_actions?: readonly ActionSpec[];
1418
- readonly else_actions?: readonly ActionSpec[];
1419
- };
1420
- }
1421
- | {
1422
- readonly kind: "foreach";
1423
- readonly foreach: {
1424
- readonly array: ExpressionSpec;
1425
- readonly item: string;
1426
- readonly index?: string;
1427
- readonly body?: readonly ActionSpec[];
1428
- };
1429
- }
1430
- );
1431
-
1432
- export interface SendSpec {
1433
- readonly id?: { readonly kind: "literal"; readonly literal: string } | { readonly kind: "location"; readonly location: LocationSpec };
1434
- readonly type?: StringAttributeSpec;
1435
- readonly event?: { readonly kind: "name"; readonly name: string } | { readonly kind: "expr"; readonly expr: ExpressionSpec };
1436
- readonly target?: StringAttributeSpec;
1437
- /** A literal delay is an SCXML duration such as "500ms" or "5s". */
1438
- readonly delay?: StringAttributeSpec;
1439
- readonly data?: ValueSourceSpec;
1440
- readonly params?: readonly ParamSpec[];
1441
- }
1442
-
1443
- export interface ParamSpec {
958
+ readonly time: number | bigint;
959
+ readonly attributes: { readonly [key: string]: ReceivedValue };
960
+ }
961
+ /** A span of `traceSpansDecode`. */
962
+ export interface Span {
963
+ /** Lowercase hex. */
964
+ readonly trace: string;
965
+ readonly span: string;
966
+ /** `null` for a root span. */
967
+ readonly parent: string | null;
1444
968
  readonly name: string;
1445
- readonly value?: ValueSourceSpec;
1446
- }
1447
-
1448
- export interface InvokeSpec {
1449
- readonly kind: "invoke";
1450
- readonly id?: { readonly kind: "literal"; readonly literal: string } | { readonly kind: "location"; readonly location: LocationSpec };
1451
- readonly type?: StringAttributeSpec;
1452
- readonly src?: StringAttributeSpec;
1453
- readonly data?: ValueSourceSpec;
1454
- readonly autoforward?: boolean;
1455
- readonly params?: readonly ParamSpec[];
1456
- readonly finalize?: readonly ActionSpec[];
1457
- }
1458
-
1459
- export interface DoneDataSpec {
1460
- readonly content?: ValueSourceSpec;
1461
- readonly params?: readonly ParamSpec[];
1462
- }
1463
-
1464
- /* --------------------------------------------------------------------------
1465
- * Host extensions
1466
- * -------------------------------------------------------------------------- */
1467
-
1468
- /**
1469
- * An I/O processor for `<send type>` (ROADMAP step 13). Core calls it while an
1470
- * actor runs, so the call is queued and send() runs at the end of that pump
1471
- * turn, never inside core. A reply is an event the processor posts, now or
1472
- * later. Throwing, or returning a promise that rejects, fails the send: the
1473
- * sender gets an external `error.communication` event with data
1474
- * { sendID, type, error }.
1475
- */
1476
- export interface IOProcessor extends IOProcessorOptions {
1477
- send(request: IORequest, context: EffectContext): void | Promise<void>;
1478
- }
1479
-
1480
- export interface IORequest {
1481
- /** The sending actor: an ActorID, or its address when it is named. */
1482
- readonly source: ActorID | ActorAddress;
1483
- /** The send's ID text (`<send id>` or core's generated one), or null for a send without one. */
1484
- readonly sendID: string | null;
1485
- readonly event: EventName;
1486
- readonly type: string;
1487
- readonly target: unknown;
1488
- readonly data: unknown;
1489
- /** A literal <content>, as text, with its media type. */
1490
- readonly content?: string;
1491
- readonly contentType?: string;
1492
- }
1493
-
1494
- /**
1495
- * One per system, except that a request carrying a traceparent gets its
1496
- * own, whose post() carries that traceparent unless given another.
1497
- * `signal` aborts on close().
1498
- */
1499
- export interface EffectContext {
1500
- readonly system: System;
1501
- readonly signal: AbortSignal;
1502
- post(target: ActorTarget, event: EventName, data?: unknown, options?: PostOptions): void;
1503
- }
1504
-
1505
- /**
1506
- * An invoker for `<invoke type>` (ROADMAP step 13). start() runs at the end
1507
- * of the pump turn in which core started the invocation; the service's
1508
- * cancel() runs when the invoking state exits, and forward() gets
1509
- * autoforwarded events.
1510
- */
1511
- export interface Invoker {
1512
- start(request: InvokeRequest, reporter: InvocationReporter): InvokedService | void;
1513
- }
1514
-
1515
- export interface InvokeRequest {
1516
- readonly system: System;
1517
- readonly parent: Actor;
1518
- readonly invocationID: InvocationID;
1519
- /** The invoke ID's text: `<invoke id>` or the one core generated. */
1520
- readonly invokeID?: string;
1521
- readonly type: string;
1522
- /**
1523
- * A literal `<invoke src>` as the text the chart wrote, never imported into
1524
- * the data model, so a chart on the null data model can name one; or
1525
- * `srcexpr`'s value.
1526
- */
1527
- readonly source?: unknown;
1528
- /** `<content expr>`'s value, or a literal <content> as text (then `contentType` is set). */
1529
- readonly content?: unknown;
1530
- readonly contentType?: string;
1531
- readonly params?: unknown;
1532
- readonly autoforward: boolean;
1533
- }
1534
-
1535
- export interface InvokedService {
1536
- cancel?(reason?: unknown): void | Promise<void>;
1537
- forward?(event: { readonly name: EventName; readonly data?: unknown }): void | Promise<void>;
1538
- }
1539
-
1540
- /**
1541
- * Reports from an invocation to its parent. event() and done() arrive as
1542
- * external events (done as done.invoke.<id>); unavailable() retires the
1543
- * invocation and the parent gets error.communication. Each returns true
1544
- * when the report was taken, and false once the invocation has ended (done,
1545
- * unavailable, cancelled, closed) or its parent is gone.
969
+ /** OTLP's span kind. */
970
+ readonly kind: number;
971
+ /** Nanoseconds since the Unix epoch (a bigint past 2^53). */
972
+ readonly start: number | bigint;
973
+ readonly end: number | bigint;
974
+ /** OTLP's status code. */
975
+ readonly status: number;
976
+ readonly statusMessage: string;
977
+ readonly attributes: { readonly [key: string]: ReceivedValue };
978
+ readonly events: readonly SpanEvent[];
979
+ }
980
+ /** `traceSpansDecode`'s result. */
981
+ export interface TraceSpansDecodeResult {
982
+ readonly spans: readonly Span[];
983
+ }
984
+ /** The result of the methods that answer nothing: `{}`. */
985
+ export type EmptyResult = { readonly [key: string]: never };
986
+
987
+ /** Runs actors: many charts, many images, from a handful of actors to
988
+ * millions, on the runtime's event loop. Inputs (`spawn`, `send`, ...)
989
+ * apply at once and schedule a turn; in its turns the host runs the actors
990
+ * and calls your handlers with what they sent out. There is no `run()`:
991
+ * `await host.idle()` waits until there is nothing left to do.
1546
992
  *
1547
- * A report that could not be taken throws and changes nothing: event() and
1548
- * done() throw `queue-full` when the parent's mailbox is at
1549
- * maxQueuedMessages or maxRetainedBytes, and any report throws
1550
- * `out-of-memory` when the addon or core cannot allocate. The invocation
1551
- * stays alive and its signal unaborted, so the service can report again,
1552
- * for example once the parent has drained its mailbox.
1553
- */
1554
- export interface InvocationReporter {
1555
- /** Aborts when the invocation ends: cancel, a taken done() or unavailable(), or close(). */
1556
- readonly signal: AbortSignal;
1557
- event(name: EventName, data?: unknown): boolean;
1558
- /** Ends the invocation once the report is taken. */
1559
- done(data?: unknown): boolean;
1560
- /** Ends the invocation once the report is taken. */
1561
- unavailable(error?: unknown): boolean;
1562
- }
1563
-
1564
- export interface LogRecord {
1565
- readonly source: ActorID | ActorAddress;
1566
- readonly label?: string;
1567
- readonly hasValue: boolean;
1568
- readonly value?: unknown;
1569
- }
1570
-
1571
- export type LogSink = (record: LogRecord) => void;
1572
-
1573
- /* --------------------------------------------------------------------------
1574
- * Public errors
1575
- * -------------------------------------------------------------------------- */
1576
-
1577
- export type TinyactorsErrorCode =
1578
- | "done"
1579
- | "invalid"
1580
- | "out-of-memory"
1581
- | "not-found"
1582
- | "busy"
1583
- | "unsupported"
1584
- | "definition-mismatch"
1585
- | "unloaded"
1586
- | "stale"
1587
- | "queue-full"
1588
- | "closed"
1589
- | "reentrant"
1590
- | "aborted"
1591
- | "timeout"
1592
- | "abandoned"
1593
- | "runaway"
1594
- /** A send()'s message became a dead letter with this reason (DeadLetterRecord). */
1595
- | "rejected"
1596
- | "load-failed"
1597
- | "load-timeout"
1598
- | "waiting-full";
1599
-
1600
- export class TinyactorsError extends Error {
1601
- readonly code: TinyactorsErrorCode;
1602
- readonly detail?: unknown;
1603
- }
1604
-
1605
- // ---------------------------------------------------------------------------
1606
- // Tracing (core ADR 0067, napi ADR 0016). OTLP bytes and a decoder; no
1607
- // telemetry dependency.
1608
-
1609
- /**
1610
- * Core's trace record kinds, in core's order (TRACE_KINDS). The three
1611
- * `definition*` kinds (core ADR 0080) are for hosts that follow core's
1612
- * record stream; the addon's OTLP output reports definitions through the
1613
- * `tinyactors.definition.*` logs instead, so no detail preset asks for them,
1614
- * and naming them in `kinds` adds nothing to the output.
1615
- */
1616
- export type TraceKind =
1617
- | 'spawned' | 'loaded' | 'unloaded' | 'finished' | 'destroyed'
1618
- | 'macrostepBegin' | 'macrostepEnd' | 'condition' | 'microstep' | 'raised'
1619
- | 'dataInit' | 'assign' | 'script' | 'foreach' | 'actionFailed'
1620
- | 'sent' | 'cancelled' | 'invoked' | 'invokeCancelled'
1621
- | 'paused' | 'resumed' | 'stopped' | 'ignored' | 'forwarded' | 'longMacrostep' | 'runaway'
1622
- | 'definitionRegistered' | 'definitionRetired' | 'definitionFreed'
1623
- | 'abandoned' | 'withdrawn';
1624
-
1625
- export declare const TRACE_KINDS: readonly TraceKind[];
1626
-
1627
- export interface TraceConfiguration {
1628
- /**
1629
- * "summary" (default): a span per macrostep, lifecycle spans, failures
1630
- * (`actionFailed`, `stopped`, `longMacrostep`, `runaway`) and an
1631
- * operator's interventions (`abandoned`, `withdrawn`); "decisions": adds
1632
- * microsteps, conditions and raised events; "full": every kind. Watched
1633
- * actors (watchTraces) always get every kind.
1634
- */
1635
- detail?: 'summary' | 'decisions' | 'full';
1636
- /** The record kinds wanted, overriding `detail`. Core builds no other record. */
1637
- kinds?: TraceKind[];
1638
- /**
1639
- * The ratio (0 to 1, default 1) of the traces this system starts that are
1640
- * sampled, decided as OpenTelemetry's TraceIDRatioBased does. A
1641
- * traceparent keeps its caller's decision. Lifecycle spans (spawned,
1642
- * loaded, unloaded, finished, destroyed) are kept whatever the decision.
1643
- */
1644
- sample?: number;
1645
- }
1646
-
1647
- export interface TraceSinkOptions extends TraceConfiguration {
1648
- /** Failures and <log> as OTLP log records, the sink's second argument (default true). */
1649
- logs?: boolean;
1650
- /** At most this many logs per definition and name per second (default 20). */
1651
- logLimit?: number;
1652
- /** Also trace macrosteps whose traceparent is not sampled. */
1653
- unsampled?: boolean;
1654
- /** Resource attributes every request carries, such as `service.name`. */
1655
- resource?: Record<string, string>;
1656
- /** Event data and assigned values as JSON attributes, cut at `valueLimit` (default 256, at most 1023). */
1657
- values?: boolean;
1658
- valueLimit?: number;
1659
- /** "cause" (default): a macrostep's parent is its cause; "link": a root, linked to its cause. */
1660
- parent?: 'cause' | 'link';
1661
- /** Trace IDs the system starts become a fixed sequence (tests). */
1662
- seed?: bigint;
1663
- }
1664
-
1665
- export interface MetricPoint {
1666
- attributes: Record<string, string>;
1667
- value: number;
1668
- }
1669
-
1670
- /** A bucket's latest sample, with the sampled trace step it happened in. */
1671
- export interface Exemplar {
1672
- /** The bucket's index in `buckets`. */
1673
- bucket: number;
1674
- value: number;
1675
- /** Milliseconds since the epoch. */
1676
- time: number;
1677
- traceID: string;
1678
- spanID: string;
1679
- }
1680
-
1681
- /** A distribution with explicit bucket bounds (OTLP Histogram). */
1682
- export interface HistogramPoint {
1683
- attributes: Record<string, string>;
1684
- count: number;
1685
- sum: number;
1686
- /** Present once something was recorded. */
1687
- min?: number;
1688
- max?: number;
1689
- /** Inclusive upper bounds; `buckets` has one more entry, for the rest. */
1690
- bounds: number[];
1691
- buckets: number[];
1692
- exemplars: Exemplar[];
1693
- }
1694
-
1695
- /** One metric: a cumulative monotonic sum, a gauge, or a histogram. */
1696
- export type Metric =
1697
- | { name: string; unit: string; kind: 'sum' | 'gauge'; points: MetricPoint[] }
1698
- | { name: string; unit: string; kind: 'histogram'; points: HistogramPoint[] };
1699
-
1700
- export interface MetricsSnapshot {
1701
- /** Milliseconds since the epoch: when the system started counting, and now. */
1702
- startTime: number;
1703
- time: number;
1704
- /** Core's totals, freed definitions included (core ADR 0072). */
1705
- system: Record<string, number>;
1706
- metrics: Metric[];
1707
- }
1708
-
1709
- /** One OTLP ExportMetricsServiceRequest, to post to `/v1/metrics`. */
1710
- export declare function metricsToOTLP(
1711
- snapshot: MetricsSnapshot,
1712
- options?: { resource?: Record<string, string>; version?: string },
1713
- ): Uint8Array;
1714
-
1715
- /**
1716
- * A span as decodeTraces() reads it. IDs are lowercase hex. The addon's own
1717
- * spans are all `internal`, with status `unset` or `error` (no message) and
1718
- * links without attributes; the other values come from other producers'
1719
- * bytes.
1720
- */
1721
- export interface DecodedSpan {
1722
- traceID: string;
1723
- spanID: string;
1724
- parentSpanID?: string;
1725
- name: string;
1726
- kind: 'unspecified' | 'internal' | 'server' | 'client' | 'producer' | 'consumer';
1727
- /** Milliseconds since the epoch. */
1728
- startTime: number;
1729
- endTime: number;
1730
- startTimeUnixNano: bigint;
1731
- endTimeUnixNano: bigint;
1732
- attributes: Record<string, unknown>;
1733
- events: { name: string; time: number; timeUnixNano: bigint; attributes: Record<string, unknown> }[];
1734
- links: { traceID: string; spanID: string; attributes: Record<string, unknown> }[];
1735
- status: { code: 'unset' | 'ok' | 'error'; message?: string };
1736
- /** Shared by the spans of one resource. */
1737
- resource: { attributes: Record<string, unknown> };
1738
- scope: { name: string; version: string };
1739
- }
1740
-
1741
- /** Reads OTLP protobuf trace bytes; throws on a malformed message. */
1742
- export declare function decodeTraces(bytes: Uint8Array): DecodedSpan[];
1743
-
1744
- /**
1745
- * A W3C `traceparent` header's fields, or undefined when it is not a valid
1746
- * one; parsed by core, as a traceparent given to post(), send() or spawn()
1747
- * is. Spaces and tabs around it are ignored and hex is lowercase. Version
1748
- * ff, an all-zero trace or parent ID, and version 00 with anything after
1749
- * the flags are refused. A later version is read by its first four fields,
1750
- * ignoring what follows a dash after the flags (W3C Trace Context,
1751
- * "Versioning of traceparent").
1752
- */
1753
- export declare function parseTraceparent(header: string | undefined):
1754
- { traceID: string; parentSpanID: string; flags: number; sampled: boolean } | undefined;
1755
- export declare function formatTraceparent(span: { traceID: string; spanID: string; sampled?: boolean; flags?: number }): string;
1756
- export declare function stepSpanID(session: bigint | number, macrostep: bigint | number, microstep?: number): string;
1757
-
1758
- // ---------------------------------------------------------------------------
1759
- // The debug adapter (napi ADR 0026)
1760
-
1761
- /**
1762
- * A poke a debug session may be allowed on the live actor: `send` an event,
1763
- * `set` its data model, `goto` (operator transitions, abandon, cancel and
1764
- * replace), and `evaluate` expressions. With none, the session only watches.
993
+ * An open host with a pending deadline keeps the process alive, as a
994
+ * `setTimeout` does; `close()` ends it. With no deadline it keeps nothing
995
+ * alive: the process may exit with the host open and actors waiting, for
996
+ * an answer included.
997
+ *
998
+ * @example
999
+ * const host = new Host({ systemID: 'shop' }, { log: (host, entry) => console.log(entry.text) });
1000
+ * host.addImage(compileCharts([{ name: 'order.scxml', text }]).image);
1001
+ * const order = host.spawn(host.chart('order'));
1002
+ * host.send(order, 'checkout');
1003
+ * await host.idle();
1004
+ * host.close();
1765
1005
  */
1766
- export type DebugPermission = 'send' | 'set' | 'goto' | 'evaluate';
1767
-
1768
- /** One record for the audit hook. `time` is milliseconds since the epoch. */
1769
- export type DebugAuditEntry = {
1770
- time: number;
1771
- /** DebugSession.id. */
1772
- session: number;
1773
- /** While attached: the actor's label and its session ID. */
1774
- actor?: string;
1775
- /** In decimal. */
1776
- sessionID?: string;
1777
- } & (
1778
- | { type: 'attach'; allow: DebugPermission[]; [detail: string]: unknown }
1779
- | { type: 'detach'; reason: string }
1780
- /** A line breakpoint's source is `path`, or `sourceReference` for SCXML the session wrote. */
1781
- | { type: 'breakpoints'; kind: 'line' | 'function' | 'data' | 'exception'; [detail: string]: unknown }
1782
- /** A console line, before it runs. */
1783
- | { type: 'command'; text: string }
1784
- | { type: 'evaluate'; context: string; expression: string }
1785
- /** A poke: send, set, goto, abandon, cancel, replace. */
1786
- | { type: 'mutation'; operation: string; [detail: string]: unknown }
1787
- );
1788
-
1789
- export interface DebugSessionOptions {
1790
- /**
1791
- * The pokes an attach may ask for (default none: watch only).
1006
+ export class Host implements Disposable, AsyncDisposable {
1007
+ /** A host for `config`, with the handlers and choices of `options`.
1008
+ * Throws `TinyactorsError` (`TA_ERROR_INVALID`) for a config the host
1009
+ * does not take, `TypeError` for options it does not take. */
1010
+ constructor(config: HostConfig, options?: HostOptions);
1011
+ /** A new host running a snapshot `host.snapshot()` gave, with the config
1012
+ * it was taken with (its `systemID` is checked) and the options `new Host`
1013
+ * takes, its `datamodel` the snapshot's. Every session stays the same, and
1014
+ * its clock goes on from the snapshot's time, whatever clock reads it.
1015
+ * Invocations that were running are announced again to `services`, with
1016
+ * `invocation.restored` true. A snapshot of a build whose layout differs
1017
+ * throws `TA_ERROR_INVALID`. */
1018
+ static restore(snapshot: Uint8Array | ArrayBuffer, config: HostConfig, options?: HostOptions): Host;
1019
+
1020
+ /** The host's clock rate, `system.ticksPerSecond`. */
1021
+ readonly ticksPerSecond: number;
1022
+ /** True once `close()` ran; every input of a closed host throws. */
1023
+ readonly closed: boolean;
1024
+ /** Milliseconds from the last idle turn to the next deadline (a delayed
1025
+ * send, a timeout, or the telemetry encoder's flush once records are
1026
+ * staged); `undefined` for none. An input given since that turn has not
1027
+ * run yet, so its deadlines are not in it. */
1028
+ readonly nextDeadline: number | undefined;
1029
+ /** The quickjs engine's heap in bytes, every actor's together, read on
1030
+ * each access (cheap): what `quickjs.memoryLimit` bounds. `undefined` on
1031
+ * a native host and once closed. */
1032
+ readonly quickjsHeapBytes: number | undefined;
1033
+
1034
+ /** Loads a compiled image, which it copies, and returns its segment, a
1035
+ * number. A chart whose name the host already has gets a new version:
1036
+ * new actors are of it, running ones stay on theirs until `migrate`.
1037
+ * Throws `TA_ERROR_INVALID` for bytes that are not an image. */
1038
+ addImage(image: Uint8Array | ArrayBuffer): number;
1039
+ /** The current version of chart `name`, for `spawn`. Throws
1040
+ * `TA_ERROR_INVALID` when the host has no chart of that name. */
1041
+ chart(name: string): ChartRef;
1042
+ /** Compiles the documents of `charts` (`{ [name]: text }`, the first
1043
+ * key the boot chart), adds the image and closes the compile result, in
1044
+ * one call: `compileCharts`, `addImage` and `close()`. Returns the
1045
+ * segment. Throws `compileCharts`'s `CompileError`, with every
1046
+ * diagnostic, and adds nothing; `TypeError` for `charts` that is not an
1047
+ * object or an option it does not take.
1792
1048
  *
1793
- * `evaluate` runs arbitrary JavaScript in this process: watch, hover and
1794
- * console expressions, breakpoint conditions and logpoint `{expression}`
1795
- * parts. Grant it only to someone who may run code on the host. Without
1796
- * it the Variables pane, the console commands and setVariable still work.
1797
- * Each evaluation checks the permissions of the attach it runs under: a
1798
- * condition set before an attach that did not keep `evaluate` never runs,
1799
- * and the client hears that breakpoint changed to unverified; a logpoint's
1800
- * parts are then written as they are.
1049
+ * @example
1050
+ * host.addCharts({ 'order.scxml': text });
1051
+ * const order = host.spawnChart('order');
1801
1052
  */
1802
- allow?: DebugPermission[];
1803
- /**
1804
- * Hears every attach, detach, breakpoint change (exception filters
1805
- * included), console command, evaluation and mutation before it happens;
1806
- * throwing refuses it. Evaluations include a breakpoint condition and a
1807
- * logpoint part at each hit (context "condition", "logpoint"), and a
1808
- * setVariable or setExpression value that is not JSON (context
1809
- * "setVariable", "setExpression"), before it runs. A refused condition
1810
- * does not fire, a refused logpoint part is written as `<refused>`, and
1811
- * the console says why. A detach is recorded after it happens and cannot
1812
- * be refused.
1813
- */
1814
- audit?: (entry: DebugAuditEntry) => void;
1815
- /** Takes each outgoing DAP message (an object). */
1816
- send: (message: DAPMessage) => void;
1817
- }
1818
-
1819
- /** A Debug Adapter Protocol message: a request, response or event. */
1820
- export interface DAPMessage {
1821
- seq: number;
1822
- type: 'request' | 'response' | 'event';
1823
- [field: string]: unknown;
1824
- }
1825
-
1826
- /**
1827
- * A DAP session over one attached actor, which it watches and pokes and
1828
- * never stops (ADR 0026): the client hears it stopped on entry, and after
1829
- * each of its macrosteps a stop that keeps the focus and an `invalidated`
1830
- * event for the variables; breakpoints are
1831
- * tracepoints. It opens no socket and checks no credentials: put it behind
1832
- * the application's transport and authentication, and decide each user's
1833
- * permissions before creating it.
1834
- */
1835
- export interface DebugSession {
1836
- readonly id: number;
1837
- readonly allow: DebugPermission[];
1838
- /** True while an actor is attached. */
1839
- readonly attached: boolean;
1840
- /**
1841
- * Takes one incoming message. Requests are answered in the order they
1842
- * arrive; the promise settles once this one is answered.
1843
- */
1844
- receive(message: DAPMessage): Promise<void>;
1845
- /** The transport closed: detach without answering. */
1053
+ addCharts(charts: { readonly [name: string]: string }, options?: AddChartsOptions): number;
1054
+ /** Spawns the boot actors of the image of `segment`: a system manifest's
1055
+ * `<actor>`s, or an actor of `compileCharts`' first chart. */
1056
+ boot(segment: number): void;
1057
+ /** Starts an actor of `ref` and returns its session. It runs in a later
1058
+ * turn. */
1059
+ spawn(ref: ChartRef, options?: SpawnOptions): bigint;
1060
+ /** Starts an actor of the current version of chart `name`:
1061
+ * `host.spawn(host.chart(name), options)`. */
1062
+ spawnChart(name: string, options?: SpawnOptions): bigint;
1063
+ /** Puts `event`, with `data`, in the queue of the actor `target` names (a
1064
+ * session or an address). Throws `TA_ERROR_STALE` for an actor that
1065
+ * ended. */
1066
+ send(target: Session | string | Address, event: string, data?: Value, options?: SendOptions): void;
1067
+ /** The same, from a `SendMessage` (the transport's `send.message`). */
1068
+ send(message: SendMessage): void;
1069
+ /** Tells a sender that its send could not be delivered: the actor
1070
+ * `sender` (a session or its address, the send's `origin`) gets
1071
+ * `error.communication` with `sendid`. */
1072
+ fail(sender: Session | string | Address, sendid?: string): void;
1073
+ /** Sends each of `items` in order, and returns how many were taken: the
1074
+ * rest, from the first one refused, were not sent. */
1075
+ sendMany(items: readonly SendMessage[]): number;
1076
+ /** Ends the actor. Throws `TA_ERROR_STALE` for one that already ended. */
1077
+ terminate(session: Session): void;
1078
+ /** The running actor spawned with `name`, newest segment first, or
1079
+ * `undefined`. */
1080
+ actorByName(name: string): bigint | undefined;
1081
+
1082
+ /** Resolves at the next turn that finds nothing to do while no promise a
1083
+ * handler returned is pending (an I/O processor's, a service's or its
1084
+ * `receive`'s, a wake, telemetry, log, migration or typed-method
1085
+ * handler's): the same promise to every caller until then. A handler's
1086
+ * promise that never settles keeps it pending, and so does a handler
1087
+ * that awaits `idle()` itself. Rejects with the turn's first error (a
1088
+ * handler's, a typed method's without `onError`), or with
1089
+ * `TA_ERROR_STATE` when the host is closed first; on a closed host it
1090
+ * returns a promise rejected so. It does not wait for promises your
1091
+ * handlers start and do not return. */
1092
+ idle(): Promise<void>;
1093
+ /** The host's clock in milliseconds, read now: a `SimulatedClock`'s
1094
+ * time, or the runtime's monotonic clock, on the scale the host's
1095
+ * deadlines and `snapshot()` use, so a restored host's goes on from its
1096
+ * snapshot's. A journal of inputs records it beside each input, and a
1097
+ * replay on a restored host moves its clock to each reading. It reads
1098
+ * and advances nothing; a closed host throws `TA_ERROR_STATE`. */
1099
+ now(): number;
1100
+
1101
+ // The typed methods. Each has two forms. Given handlers, `onResult` or
1102
+ // `onError` is called once, in a later turn, and the call returns
1103
+ // nothing; an error with no `onError` is the turn's (`idle()` rejects
1104
+ // with it). Given no handler, the call returns a promise that resolves
1105
+ // with the result and rejects with the `TinyactorsError` (`code`,
1106
+ // `reason`, `path`); a refusal at the call rejects too. A rejection is
1107
+ // yours: without a `catch` it is an unhandled rejection, and `idle()`
1108
+ // does not see it. Each reads the host when called; `close()` drops a
1109
+ // pending method uncalled, and its promise never settles.
1110
+
1111
+ /** An actor's active states, `{ value, history }`: a state id, or `{
1112
+ * parent: child }` for compound states. Params `{ session }`. `const {
1113
+ * value } = await host.actorState({ session })`. */
1114
+ actorState(params: SessionParams, onResult: OnResult<ActorStateResult>, onError?: OnError | null): void;
1115
+ /** `actorState` given no handler: a promise of `{ value, history }`. */
1116
+ actorState(params: SessionParams): Promise<ActorStateResult>;
1117
+ /** An actor's variables, `{ variables }`. Params `{ session }`; refused
1118
+ * for a hibernated actor. A variable that holds `undefined` reads
1119
+ * `undefined`, apart from `null`; before the actor's first turn every
1120
+ * variable is `undefined`, its spawn params included. */
1121
+ actorContext(params: SessionParams, onResult: OnResult<ActorContextResult>, onError?: OnError | null): void;
1122
+ /** `actorContext` given no handler: a promise of `{ variables }`. */
1123
+ actorContext(params: SessionParams): Promise<ActorContextResult>;
1124
+ /** The host's sessions a page at a time, `{ sessions, cursor }`, `cursor`
1125
+ * `null` after the last page. Params `{ cursor?, limit? }` (1 to 512,
1126
+ * default 256). */
1127
+ actorList(params: ActorListParams | undefined, onResult: OnResult<ActorListResult>, onError?: OnError | null): void;
1128
+ /** `actorList` given no handler: a promise of a page, `{ sessions, cursor }`. */
1129
+ actorList(params?: ActorListParams): Promise<ActorListResult>;
1130
+ /** One actor, `{ session, segment, chart, parent, mailbox, invocations,
1131
+ * timers, timersPending }`. Params `{ session }`. */
1132
+ actorGet(params: SessionParams, onResult: OnResult<ActorGetResult>, onError?: OnError | null): void;
1133
+ /** `actorGet` given no handler: a promise of the actor. */
1134
+ actorGet(params: SessionParams): Promise<ActorGetResult>;
1135
+ /** The host's counters, `{ host, pools, charts }`: `pools` has one entry
1136
+ * per live segment with each pool's `capacity`, `used` and `highWater`.
1137
+ * No params: `await host.hostStats()`. */
1138
+ hostStats(params: NoParams, onResult: OnResult<HostStatsResult>, onError?: OnError | null): void;
1139
+ /** `hostStats` given no handler: a promise of the counters. */
1140
+ hostStats(params?: NoParams): Promise<HostStatsResult>;
1141
+ /** The config the host runs with, every default filled in. No params. */
1142
+ hostConfig(params: NoParams, onResult: OnResult<EffectiveHostConfig>, onError?: OnError | null): void;
1143
+ /** `hostConfig` given no handler: a promise of the effective config. */
1144
+ hostConfig(params?: NoParams): Promise<EffectiveHostConfig>;
1145
+ /** Sets what every actor traces: `{ detail, values, sample, records,
1146
+ * rules }`. */
1147
+ traceConfigure(params: TraceConfigureParams | undefined, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
1148
+ /** `traceConfigure` given no handler: a promise of `{}`. */
1149
+ traceConfigure(params?: TraceConfigureParams): Promise<EmptyResult>;
1150
+ /** Adds trace rules for a while: `{ rules, seconds }` (default 900);
1151
+ * answers `{ id }`. */
1152
+ traceWatch(params: TraceWatchParams, onResult: OnResult<TraceWatchResult>, onError?: OnError | null): void;
1153
+ /** `traceWatch` given no handler: a promise of `{ id }`. */
1154
+ traceWatch(params: TraceWatchParams): Promise<TraceWatchResult>;
1155
+ /** Ends a watch early: `{ id }`. */
1156
+ traceUnwatch(params: TraceUnwatchParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
1157
+ /** `traceUnwatch` given no handler: a promise of `{}`. */
1158
+ traceUnwatch(params: TraceUnwatchParams): Promise<EmptyResult>;
1159
+ /** Ends every open span now, marked incomplete, for the telemetry handler.
1160
+ * Refused without `telemetry` in the config. */
1161
+ traceEnd(params: NoParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
1162
+ /** `traceEnd` given no handler: a promise of `{}`. */
1163
+ traceEnd(params?: NoParams): Promise<EmptyResult>;
1164
+ /** The spans of a traces request: `{ traces }` (the bytes) answers `{
1165
+ * spans }`, each with `trace`, `span`, `parent`, `name`, `start`, `end`,
1166
+ * `attributes`, ... */
1167
+ traceSpansDecode(params: TraceSpansDecodeParams, onResult: OnResult<TraceSpansDecodeResult>, onError?: OnError | null): void;
1168
+ /** `traceSpansDecode` given no handler: a promise of `{ spans }`. */
1169
+ traceSpansDecode(params: TraceSpansDecodeParams): Promise<TraceSpansDecodeResult>;
1170
+
1171
+ /** The host's counters now as an OTLP metrics request (a `Uint8Array`, for a
1172
+ * collector's `/v1/metrics`). `TA_ERROR_STATE` without `telemetry` in the
1173
+ * config. */
1174
+ metrics(): Uint8Array;
1175
+ /** Finds cold actors: at most `limit` sessions that did not run since
1176
+ * the previous sweep and can be hibernated now, looking at most at `maxScan`
1177
+ * actors (each an integer from 0 to 2^32-1). The first sweep after an
1178
+ * actor ran skips it. */
1179
+ sweep(maxScan: number, limit: number): bigint[];
1180
+ /** Takes the actor out of memory and returns its blob (a `Uint8Array`) for
1181
+ * your store. `TA_ERROR_STATE` when it is not at rest (events waiting, a
1182
+ * step not over, running an invoked child or service) and when it is not
1183
+ * resident (already hibernated, its wake asked for and not given): the
1184
+ * status does not tell the two apart. `TA_ERROR_STALE` for a session that
1185
+ * ended or never was, `TA_ERROR_UNSUPPORTED` when a variable holds what
1186
+ * the datamodel cannot store (the message names it); it stays where it
1187
+ * is then. */
1188
+ hibernate(session: Session): Uint8Array;
1189
+ /** Puts a hibernated actor back from the blob `hibernate` gave; its
1190
+ * waiting events run at the next turn. Only its latest blob: one of an
1191
+ * earlier hibernation (a store that fell behind) throws `TA_ERROR_STALE`,
1192
+ * another session's `TA_ERROR_INVALID`, and the actor stays hibernated.
1193
+ * On a restored host a blob of a hibernation made after the snapshot is
1194
+ * taken too. */
1195
+ wake(session: Session, blob: Uint8Array | ArrayBuffer): void;
1196
+ /** Starts moving running actors (every chart's, `chart`'s, or one
1197
+ * `session`) to the current version of their chart, in later turns; each
1198
+ * gets `error.platform.upgrade` with its old variables. Returns the
1199
+ * migration's id, which `migrated`, `migrationDone` and the wake handler
1200
+ * name. Throws `TA_ERROR_INVALID` for a chart the host does not have and
1201
+ * `TA_ERROR_STALE` for a session that ended. */
1202
+ migrate(options?: MigrateOptions): number;
1203
+ /** The whole host as one `Uint8Array`: every segment, the images, the system
1204
+ * id, the host's time (its clocks advanced first: the time of the call,
1205
+ * as `now()` reads it) and the datamodel's state, for `Host.restore` on the
1206
+ * same build of the package. Only when quiescent: from a handler, with an
1207
+ * effect or a reply pending, or during a migration it throws
1208
+ * `TA_ERROR_STATE`; a value outside the value table throws
1209
+ * `TA_ERROR_UNSUPPORTED`. */
1210
+ snapshot(): Uint8Array;
1211
+
1212
+ /** Frees the host: the last telemetry requests go to the handler, the
1213
+ * timer is cleared, pending typed methods and running services are
1214
+ * dropped without being called. From a handler it waits for the end of
1215
+ * the turn. Again: nothing. */
1846
1216
  close(): void;
1217
+ /** `close()`. */
1218
+ [Symbol.dispose](): void;
1219
+ /** `close()`, then the promises the telemetry handler returned at it. */
1220
+ [Symbol.asyncDispose](): Promise<void>;
1847
1221
  }
1848
-
1849
- export declare function createDebugSession(system: System, options: DebugSessionOptions): DebugSession;
1850
-
1851
- /**
1852
- * The base protocol's framing for a byte stream (stdio, a TCP socket):
1853
- * push() each chunk; `onMessage` gets each whole message in order. Chunks
1854
- * may split a header, a body or a UTF-8 sequence anywhere, and a string
1855
- * chunk may split a surrogate pair. Header fields other than
1856
- * Content-Length are ignored.
1857
- *
1858
- * A malformed stream throws an `invalid` TinyactorsError from push(), and
1859
- * every later push() throws `invalid` too: a stream cannot be
1860
- * resynchronized once a length is in doubt, so close the connection.
1861
- * Malformed is: headers that are not UTF-8, longer than 8 KiB without the
1862
- * blank line, or with a line that is not `Name: value`; no Content-Length,
1863
- * two, or one that is not a decimal number of at most 64 MiB; a body that
1864
- * is not UTF-8 JSON, or not an object with an integer `seq` and a `type`
1865
- * of "request", "response" or "event". An exception from `onMessage`
1866
- * propagates from push() but leaves the reader usable; messages already
1867
- * buffered behind it arrive with the next push().
1868
- */
1869
- export declare class DAPReader {
1870
- constructor(onMessage: (message: DAPMessage) => void);
1871
- push(chunk: Uint8Array | string): void;
1872
- }
1873
-
1874
- /** One message as bytes: the Content-Length header, then its JSON. */
1875
- export declare function encodeDAPMessage(message: object): Uint8Array;