@tinyactors/node 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts ADDED
@@ -0,0 +1,1221 @@
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.
74
+ *
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.
81
+ *
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.
122
+ *
123
+ * @example
124
+ * try { host.send(session, 'go'); }
125
+ * catch (error) { if (error instanceof TinyactorsError && error.status === 'TA_ERROR_STALE') ... }
126
+ */
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;
151
+ }
152
+
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;
164
+ readonly message: string;
165
+ }
166
+
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[];
173
+ }
174
+
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;
182
+ }
183
+
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. */
205
+ close(): void;
206
+ /** `close()`. */
207
+ [Symbol.dispose](): void;
208
+ }
209
+
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();
223
+ */
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') });
254
+ */
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;
290
+ }
291
+
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;
301
+ }
302
+
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[];
313
+ }
314
+
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;
318
+
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;
322
+
323
+ // ---- the clock ----------------------------------------------------------
324
+
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();
333
+ */
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' } } };
527
+ */
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;
553
+ }
554
+
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. */
731
+ traceparent?: string;
732
+ }
733
+
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;
757
+ }
758
+
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;
789
+ /**
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.
797
+ */
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;
829
+ /**
830
+ * Its pending delayed sends (`<send delay>` not yet due, not cancelled),
831
+ * earliest first, at most 32: `timersPending` says how many it has.
832
+ */
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. */
844
+ readonly due: number;
845
+ }
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;
896
+ };
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;
945
+ }
946
+ /** The params of `traceUnwatch`. */
947
+ export interface TraceUnwatchParams {
948
+ id: number;
949
+ }
950
+ /** The params of `traceSpansDecode`. */
951
+ export interface TraceSpansDecodeParams {
952
+ /** An OTLP traces request, as the telemetry handler gets it. */
953
+ traces: Uint8Array;
954
+ }
955
+ /** A span event. */
956
+ export interface SpanEvent {
957
+ readonly name: string;
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;
968
+ readonly name: string;
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.
992
+ *
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();
1005
+ */
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.
1048
+ *
1049
+ * @example
1050
+ * host.addCharts({ 'order.scxml': text });
1051
+ * const order = host.spawnChart('order');
1052
+ */
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. */
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>;
1221
+ }