@tinyactors/node 0.1.0 → 0.2.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.
@@ -0,0 +1,915 @@
1
+ // Type definitions for tinyactors (Node.js binding).
2
+ // The API follows xstate v5 where feasible. Context and event types flow from
3
+ // `types: {} as { context; events; input; output }` (or from `context`) into
4
+ // actions, guards, assigners and delays.
5
+
6
+ export interface EventObject {
7
+ type: string;
8
+ }
9
+ export type MachineContext = Record<string, any>;
10
+ export type StateValue = string | { [key: string]: StateValue };
11
+
12
+ /** Arguments passed to actions, guards, assigners, delays, inputs and outputs. */
13
+ export interface ActionArgs<TContext, TEvent extends EventObject> {
14
+ context: TContext;
15
+ event: TEvent;
16
+ /** The actor system the actor runs in (look up actors registered by systemID). */
17
+ system: SystemRef;
18
+ /** The actor running this code (put it in events so others can reply). */
19
+ self: AnyActorRef;
20
+ }
21
+
22
+ /** What actions and guards see of the actor system. */
23
+ export interface SystemRef {
24
+ get(systemID: string): AnyActor | undefined;
25
+ }
26
+
27
+ /** Something events can be sent to: a local actor or an ActorRef. */
28
+ export type AnyActorRef = AnyActor | ActorRef;
29
+
30
+ export type ActionFunction<TContext, TEvent extends EventObject, TParams = any> = (
31
+ args: ActionArgs<TContext, TEvent>,
32
+ params: TParams,
33
+ ) => void;
34
+
35
+ export type GuardPredicate<TContext, TEvent extends EventObject, TParams = any> = (
36
+ args: ActionArgs<TContext, TEvent>,
37
+ params: TParams,
38
+ ) => boolean;
39
+
40
+ /* ------------------------------------------------------------ action objects */
41
+
42
+ export type PartialAssigner<TContext, TEvent extends EventObject, K extends keyof TContext> =
43
+ | TContext[K]
44
+ | ((args: ActionArgs<TContext, TEvent>, params: any) => TContext[K]);
45
+
46
+ export type Assigner<TContext, TEvent extends EventObject> =
47
+ | ((args: ActionArgs<TContext, TEvent>, params: any) => Partial<TContext>)
48
+ | { [K in keyof TContext]?: PartialAssigner<TContext, TEvent, K> };
49
+
50
+ export interface AssignAction<TContext, TEvent extends EventObject> {
51
+ readonly type: 'xstate.assign';
52
+ readonly assignment: Assigner<TContext, TEvent>;
53
+ }
54
+
55
+ export type EventOrExpr<TContext, TEvent extends EventObject, TSent extends EventObject> =
56
+ | TSent
57
+ | ((args: ActionArgs<TContext, TEvent>) => TSent);
58
+
59
+ export type Delay<TContext, TEvent extends EventObject> =
60
+ | number
61
+ | string
62
+ | ((args: ActionArgs<TContext, TEvent>) => number);
63
+
64
+ export interface SendOptions<TContext, TEvent extends EventObject> {
65
+ delay?: Delay<TContext, TEvent>;
66
+ id?: string;
67
+ }
68
+
69
+ export interface RaiseAction<TContext, TEvent extends EventObject> {
70
+ readonly type: 'xstate.raise';
71
+ readonly event: EventOrExpr<TContext, TEvent, EventObject>;
72
+ readonly delay?: Delay<TContext, TEvent>;
73
+ readonly id?: string;
74
+ }
75
+ /** A child invoke id, another actor (local, or remote via an ActorRef), or a function returning one. */
76
+ export type SendTarget<TContext, TEvent extends EventObject> =
77
+ | string
78
+ | AnyActorRef
79
+ | ((args: ActionArgs<TContext, TEvent>) => string | AnyActorRef | undefined);
80
+
81
+ export interface SendToAction<TContext, TEvent extends EventObject> {
82
+ readonly type: 'xstate.sendTo';
83
+ readonly to: SendTarget<TContext, TEvent>;
84
+ readonly event: EventOrExpr<TContext, TEvent, EventObject>;
85
+ readonly delay?: Delay<TContext, TEvent>;
86
+ readonly id?: string;
87
+ }
88
+ export interface SendParentAction<TContext, TEvent extends EventObject> {
89
+ readonly type: 'xstate.sendParent';
90
+ readonly event: EventOrExpr<TContext, TEvent, EventObject>;
91
+ readonly delay?: Delay<TContext, TEvent>;
92
+ readonly id?: string;
93
+ }
94
+ export interface LogAction<TContext, TEvent extends EventObject> {
95
+ readonly type: 'xstate.log';
96
+ readonly value: string | ((args: ActionArgs<TContext, TEvent>) => unknown);
97
+ readonly label?: string;
98
+ }
99
+ export interface CancelAction {
100
+ readonly type: 'xstate.cancel';
101
+ readonly sendID: string;
102
+ }
103
+
104
+ /** A named action/guard reference, optionally with parameters. */
105
+ export interface ParameterizedObject {
106
+ type: string;
107
+ params?: unknown;
108
+ }
109
+
110
+ export type Action<TContext, TEvent extends EventObject> =
111
+ | string
112
+ | ParameterizedObject
113
+ | ActionFunction<TContext, TEvent>
114
+ | AssignAction<TContext, any>
115
+ | RaiseAction<TContext, any>
116
+ | SendToAction<TContext, any>
117
+ | SendParentAction<TContext, any>
118
+ | LogAction<TContext, any>
119
+ | CancelAction;
120
+
121
+ export type Actions<TContext, TEvent extends EventObject> =
122
+ | Action<TContext, TEvent>
123
+ | ReadonlyArray<Action<TContext, TEvent>>;
124
+
125
+ /* -------------------------------------------------------------------- guards */
126
+
127
+ export interface StateInGuard {
128
+ readonly type: 'xstate.stateIn';
129
+ readonly stateValue: string;
130
+ }
131
+ export interface CompositeGuard<TContext, TEvent extends EventObject> {
132
+ readonly type: 'xstate.and' | 'xstate.or' | 'xstate.not';
133
+ readonly guards: ReadonlyArray<Guard<TContext, TEvent>>;
134
+ }
135
+ export type Guard<TContext, TEvent extends EventObject> =
136
+ | string
137
+ | ParameterizedObject
138
+ | GuardPredicate<TContext, TEvent>
139
+ | StateInGuard
140
+ | CompositeGuard<TContext, TEvent>;
141
+
142
+ /* ------------------------------------------------------------------- configs */
143
+
144
+ export interface TransitionConfig<TContext, TEvent extends EventObject> {
145
+ target?: string | ReadonlyArray<string>;
146
+ guard?: Guard<TContext, TEvent>;
147
+ actions?: Actions<TContext, TEvent>;
148
+ /** Re-enter the source state when targeting itself or a descendant (default false). */
149
+ reenter?: boolean;
150
+ description?: string;
151
+ }
152
+
153
+ export type SingleOrArray<T> = T | ReadonlyArray<T>;
154
+
155
+ export type TransitionConfigOrTarget<TContext, TEvent extends EventObject> = SingleOrArray<
156
+ string | TransitionConfig<TContext, TEvent>
157
+ >;
158
+
159
+ export type TransitionsConfig<TContext, TEvent extends EventObject> = {
160
+ [K in TEvent['type'] | '*']?: TransitionConfigOrTarget<
161
+ TContext,
162
+ K extends '*' ? TEvent : Extract<TEvent, { type: K }>
163
+ >;
164
+ };
165
+
166
+ export interface DoneActorEvent<TOutput = unknown> extends EventObject {
167
+ output: TOutput;
168
+ }
169
+
170
+ export interface InvokeConfig<TContext, TEvent extends EventObject> {
171
+ /** A machine, or the name of one in `implementations.actors`. */
172
+ src: AnyStateMachine | string;
173
+ id?: string;
174
+ input?: unknown | ((args: ActionArgs<TContext, TEvent>) => unknown);
175
+ onDone?: TransitionConfigOrTarget<TContext, DoneActorEvent<any>>;
176
+ }
177
+
178
+ export interface StateNodeConfig<TContext, TEvent extends EventObject> {
179
+ id?: string;
180
+ type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';
181
+ initial?: string;
182
+ states?: { [key: string]: StateNodeConfig<TContext, TEvent> };
183
+ on?: TransitionsConfig<TContext, TEvent>;
184
+ always?: TransitionConfigOrTarget<TContext, TEvent>;
185
+ after?: { [delay: string | number]: TransitionConfigOrTarget<TContext, TEvent> };
186
+ entry?: Actions<TContext, TEvent>;
187
+ exit?: Actions<TContext, TEvent>;
188
+ invoke?: SingleOrArray<InvokeConfig<TContext, TEvent>>;
189
+ /** Final states: output of the parent's done event (or of the machine). */
190
+ output?: unknown | ((args: ActionArgs<TContext, TEvent>) => unknown);
191
+ tags?: SingleOrArray<string>;
192
+ /** History states. */
193
+ history?: 'shallow' | 'deep';
194
+ target?: string;
195
+ description?: string;
196
+ meta?: unknown;
197
+ }
198
+
199
+ export interface MachineTypes<TContext, TEvent extends EventObject, TInput, TOutput> {
200
+ context?: TContext;
201
+ events?: TEvent;
202
+ input?: TInput;
203
+ output?: TOutput;
204
+ }
205
+
206
+ export interface MachineConfig<
207
+ TContext extends MachineContext,
208
+ TEvent extends EventObject,
209
+ TInput = any,
210
+ TOutput = any,
211
+ > extends Omit<StateNodeConfig<TContext, TEvent>, 'output'> {
212
+ id?: string;
213
+ types?: MachineTypes<TContext, TEvent, TInput, TOutput>;
214
+ context?: TContext | ((args: { input: TInput }) => TContext);
215
+ output?: TOutput | ((args: ActionArgs<TContext, DoneActorEvent<any>>) => TOutput);
216
+ }
217
+
218
+ export interface MachineImplementations<TContext, TEvent extends EventObject> {
219
+ actions?: { [name: string]: ActionFunction<TContext, TEvent> | Action<TContext, TEvent> };
220
+ guards?: { [name: string]: GuardPredicate<TContext, TEvent> | Guard<TContext, TEvent> };
221
+ delays?: { [name: string]: number | ((args: ActionArgs<TContext, TEvent>) => number) };
222
+ actors?: { [name: string]: AnyStateMachine };
223
+ }
224
+
225
+ /* ------------------------------------------------------------------ machines */
226
+
227
+ export declare class StateMachine<
228
+ TContext extends MachineContext,
229
+ TEvent extends EventObject,
230
+ TInput = any,
231
+ TOutput = any,
232
+ > {
233
+ readonly id: string;
234
+ readonly config: MachineConfig<TContext, TEvent, TInput, TOutput>;
235
+ readonly implementations: Required<MachineImplementations<TContext, TEvent>>;
236
+ provide(implementations: MachineImplementations<TContext, TEvent>): StateMachine<TContext, TEvent, TInput, TOutput>;
237
+ /** The SCXML document the machine compiles to. It reads like hand-written
238
+ * SCXML: guards/actions by name, inline functions by their source, literals
239
+ * as JSON. */
240
+ toSCXML(): string;
241
+ /** @internal type carriers */
242
+ readonly __types?: { context: TContext; events: TEvent; input: TInput; output: TOutput };
243
+ }
244
+
245
+ export type AnyStateMachine = StateMachine<any, any, any, any>;
246
+
247
+ /* ----------------------------------------------------------- SCXML documents */
248
+
249
+ /** An SCXML event as sent to a document: `type` becomes `_event.name`; `data`
250
+ * (or, without it, the other properties) becomes `_event.data`. */
251
+ export interface SCXMLEvent extends EventObject {
252
+ data?: unknown;
253
+ [key: string]: unknown;
254
+ }
255
+
256
+ /**
257
+ * A W3C SCXML document as actor logic (fromSCXML). Its `datamodel` attribute
258
+ * picks the semantics: "ecmascript" (SCXML Appendix B.2) or "null".
259
+ */
260
+ export declare class SCXMLLogic<TContext = Record<string, any>, TEvent extends EventObject = SCXMLEvent> {
261
+ /** The document's `<scxml name>`, else "scxml" (or the `id` option). */
262
+ readonly id: string;
263
+ /** The document as given. */
264
+ toSCXML(): string;
265
+ /** @internal type carriers */
266
+ readonly __types?: { context: TContext; events: TEvent; input: Partial<TContext>; output: unknown };
267
+ }
268
+
269
+ export interface FromSCXMLOptions {
270
+ /** The logic's id (default: `<scxml name>`, else "scxml"). */
271
+ id?: string;
272
+ /** Further documents by name: `<invoke src>` documents (linked alongside) and
273
+ * any text a `src="..."` attribute names (e.g. `<data src>`). */
274
+ documents?: Record<string, string>;
275
+ }
276
+
277
+ /**
278
+ * Run an SCXML document. The snapshot's `context` is the datamodel's
279
+ * variables, its `value` the active states (by id) as a nested state value;
280
+ * `input` overrides `<data>` initial values; `<donedata>` is the output.
281
+ */
282
+ export declare function fromSCXML<TContext = Record<string, any>, TEvent extends EventObject = SCXMLEvent>(
283
+ xml: string,
284
+ options?: FromSCXMLOptions,
285
+ ): SCXMLLogic<TContext, TEvent>;
286
+
287
+ /* ------------------------------------------------------------- system images */
288
+
289
+ /**
290
+ * A compiled system image: charts plus the actors to boot (a `<system>`
291
+ * manifest). Store `bytes`; `loadImage()` reads it back, here or in a browser.
292
+ */
293
+ export declare class SystemImage {
294
+ /** The image's charts. */
295
+ readonly charts: ReadonlyArray<{ name: string; src: string; datamodel: string }>;
296
+ /** The actors `system.boot()` starts (chart: an index into `charts`). */
297
+ readonly actors: ReadonlyArray<{ name: string; chart: number }>;
298
+ /** The image as bytes. */
299
+ readonly bytes: Uint8Array;
300
+ /** Actor logic for one of its charts (by `<chart name>` or src), for createActor. */
301
+ chart(name: string): SCXMLLogic;
302
+ }
303
+
304
+ /**
305
+ * Compile a `<system>` manifest — `<chart name src/>` and `<actor name chart/>`
306
+ * elements — with the documents its `src` attributes name in `files`.
307
+ */
308
+ export declare function compileSystem(manifest: string, options?: { files?: Record<string, string> }): SystemImage;
309
+ /** A compiled image from bytes (`image.bytes`, or the C `tac` compiler's output). */
310
+ export declare function loadImage(bytes: Uint8Array): SystemImage;
311
+
312
+ /** Anything an actor can run: a machine or an SCXML document. */
313
+ export type AnyActorLogic = AnyStateMachine | SCXMLLogic<any, any>;
314
+ type TypesOf<M> = M extends { readonly __types?: infer T } ? NonNullable<T> : never;
315
+ export type ContextFrom<M> = TypesOf<M> extends { context: infer C } ? C : never;
316
+ export type EventFrom<M> = TypesOf<M> extends { events: infer E } ? E : never;
317
+ export type InputFrom<M> = TypesOf<M> extends { input: infer I } ? I : never;
318
+ export type OutputFrom<M> = TypesOf<M> extends { output: infer O } ? O : never;
319
+
320
+ export declare function createMachine<
321
+ TContext extends MachineContext = MachineContext,
322
+ TEvent extends EventObject = EventObject,
323
+ TInput = any,
324
+ TOutput = any,
325
+ >(
326
+ config: MachineConfig<TContext, TEvent, TInput, TOutput>,
327
+ implementations?: MachineImplementations<TContext, TEvent>,
328
+ ): StateMachine<TContext, TEvent, TInput, TOutput>;
329
+
330
+ export declare function setup<
331
+ TContext extends MachineContext = MachineContext,
332
+ TEvent extends EventObject = EventObject,
333
+ TInput = any,
334
+ TOutput = any,
335
+ >(
336
+ implementations: MachineImplementations<TContext, TEvent> & {
337
+ types?: MachineTypes<TContext, TEvent, TInput, TOutput>;
338
+ },
339
+ ): {
340
+ createMachine(
341
+ config: MachineConfig<TContext, TEvent, TInput, TOutput>,
342
+ ): StateMachine<TContext, TEvent, TInput, TOutput>;
343
+ };
344
+
345
+ /* -------------------------------------------------------------------- actors */
346
+
347
+ export interface Snapshot<TContext, TOutput = unknown> {
348
+ value: StateValue;
349
+ context: TContext;
350
+ status: 'active' | 'done' | 'stopped';
351
+ output?: TOutput;
352
+ /** Last error thrown by user code (reported to the chart as error.execution). */
353
+ error?: unknown;
354
+ matches(value: StateValue): boolean;
355
+ hasTag(tag: string): boolean;
356
+ toJSON(): { value: StateValue; context: TContext; status: string; output?: TOutput };
357
+ }
358
+
359
+ export interface Observer<T> {
360
+ next?: (value: T) => void;
361
+ error?: (err: unknown) => void;
362
+ complete?: () => void;
363
+ }
364
+ export interface Subscription {
365
+ unsubscribe(): void;
366
+ }
367
+
368
+ export interface ActorOptions<TInput> {
369
+ id?: string;
370
+ input?: TInput;
371
+ /** The system to start the actor in (default: the process-wide default system). */
372
+ system?: System;
373
+ /** Register the actor so other actors can find it with `system.get(systemID)`. */
374
+ systemID?: string;
375
+ /** Receives <log> output (default console.log). */
376
+ logger?: (...args: unknown[]) => void;
377
+ }
378
+
379
+ export declare class Actor<M extends AnyActorLogic> {
380
+ readonly id: string;
381
+ readonly logic: M;
382
+ readonly system: System;
383
+ /** This actor's address (`tinyactors://<system>/#_scxml_<session>`), the same across versions and reachable across links. */
384
+ readonly address: string | undefined;
385
+ /** True while the actor is hibernated (unloaded to the system's store); it wakes by itself when it gets work. */
386
+ readonly hibernated: boolean;
387
+ start(): this;
388
+ stop(): this;
389
+ send(event: EventFrom<M>): void;
390
+ getSnapshot(): Snapshot<ContextFrom<M>, OutputFrom<M>>;
391
+ subscribe(observer: Observer<Snapshot<ContextFrom<M>, OutputFrom<M>>>): Subscription;
392
+ subscribe(
393
+ next: (snapshot: Snapshot<ContextFrom<M>, OutputFrom<M>>) => void,
394
+ error?: (err: unknown) => void,
395
+ complete?: () => void,
396
+ ): Subscription;
397
+ }
398
+
399
+ export type AnyActor = Actor<AnyActorLogic>;
400
+
401
+ /** Statistics of one native segment of a system. */
402
+ export interface SegmentStats {
403
+ maxActors: number;
404
+ actors: number;
405
+ sessions: number;
406
+ payloads: number;
407
+ /** Actors currently hibernated. */
408
+ hibernated: number;
409
+ /** Totals for the whole system. */
410
+ hibernations: number;
411
+ wakes: number;
412
+ }
413
+
414
+ /**
415
+ * Where hibernated actors go. The system never does I/O itself: it hands the
416
+ * store opaque blobs and asks for them back when an actor gets work. Every
417
+ * method may return a promise (IndexedDB, files, Redis, a database, ...).
418
+ */
419
+ export interface HibernationStore {
420
+ get(key: string): Uint8Array | undefined | Promise<Uint8Array | undefined>;
421
+ set(key: string, blob: Uint8Array): void | Promise<void>;
422
+ delete(key: string): void | Promise<void>;
423
+ }
424
+
425
+ export interface HibernationOptions {
426
+ /** Default: an in-memory store (createMemoryStore()). */
427
+ store?: HibernationStore;
428
+ /** Unload actors idle for a whole sweep period, every `sweepMs` (default 30000; 0 = only on system.hibernate()). */
429
+ sweepMs?: number;
430
+ }
431
+
432
+ export interface SystemOptions {
433
+ /**
434
+ * This system's id in actor addresses, `tinyactors://<id>/...` (default: a
435
+ * random 12-character id). Lowercase a-z, 0-9, "-" and dots (see
436
+ * docs/protocol.md); set it explicitly when other systems address this one.
437
+ */
438
+ id?: string;
439
+ /** Unload idle actors (context, events and input must be encodable: no functions). */
440
+ hibernation?: HibernationOptions;
441
+ /**
442
+ * Restore a `system.snapshot()`: the same id, actors (find them with
443
+ * `get(systemID)`), timers and queued events. Machines are matched by id and
444
+ * the SCXML they compile to; ones defined in this process are found by
445
+ * themselves, `machines` names more. SCXML documents and images come from
446
+ * the snapshot.
447
+ */
448
+ restore?: Uint8Array;
449
+ machines?: AnyStateMachine[];
450
+ /**
451
+ * The system's clock in milliseconds (default: wall time). With a clock the
452
+ * system arms no timers of its own: advance your clock and call
453
+ * `system.flush()` — deterministic tests, simulations, replay.
454
+ */
455
+ clock?: () => number;
456
+ /** Receives <log> output of actors without their own `logger` (default console.log). */
457
+ logger?: (...args: unknown[]) => void;
458
+ }
459
+
460
+ /**
461
+ * A reference to an actor anywhere: this system, another segment, or another
462
+ * system across a link. Send to it from host code or use it as a sendTo()
463
+ * target; actor references inside events arrive as ActorRefs.
464
+ */
465
+ export declare class ActorRef {
466
+ readonly id: string;
467
+ readonly address: string;
468
+ readonly system: System;
469
+ send(event: EventObject | string): void;
470
+ }
471
+
472
+ /**
473
+ * An actor system: all its actors run inside one native tinyactors system
474
+ * (machines defined after it started are linked into an extra segment, which
475
+ * its actors reach transparently).
476
+ */
477
+ export declare class System implements SystemRef {
478
+ readonly id: string;
479
+ readonly options: SystemOptions;
480
+ get(systemID: string): AnyActor | undefined;
481
+ /** The actor at `address` (a local Actor if it is one of ours, else an ActorRef). */
482
+ ref(address: string): AnyActorRef;
483
+ /**
484
+ * Hand an envelope to the router as this system's host code (docs/protocol.md, "Envelope"):
485
+ * delivered to a local actor or sent to the peer its target routes to. "queued" when called
486
+ * from inside an action (it is handed over once the current step ends).
487
+ */
488
+ deliver(envelope: Envelope): 'delivered' | 'relayed' | 'duplicate' | 'refused' | 'queued';
489
+ stats(): SegmentStats[];
490
+ /**
491
+ * Hibernate `actor` now, or — without an argument — every actor that has
492
+ * been idle since the previous sweep. Returns how many were unloaded. An
493
+ * actor whose data cannot be stored throws (the message names the variable,
494
+ * and a function's line); the sweep leaves such actors resident.
495
+ */
496
+ hibernate(actor?: AnyActor): number;
497
+ /**
498
+ * Move `actor` out of this system, as bytes another system — in this or
499
+ * another process, Node or web — takes in with `adopt()`: its states,
500
+ * variables, delayed events with their data, the actors it invoked, and
501
+ * what it runs. The actor stops here, without a done event. It must be
502
+ * awake, not in a step, with nothing queued for it; data that cannot be
503
+ * stored throws, naming the variable.
504
+ */
505
+ export(actor: AnyActor): Uint8Array;
506
+ /**
507
+ * Take in an actor another system exported: the same session (its address
508
+ * under this system's id), states and variables; delayed events keep the
509
+ * time they had left at export. Machines are found as for
510
+ * `createSystem({ restore })`; SCXML documents and images travel with it.
511
+ */
512
+ adopt(bytes: Uint8Array, options?: { machines?: AnyStateMachine[] }): AnyActor;
513
+ /**
514
+ * Hot reload, CGI style: `machine` becomes the current version of the
515
+ * machines with its id (compiled and linked now, so errors throw here).
516
+ * Actors started afterwards run it; running actors finish on their version
517
+ * (or move with migrate()); versions without actors are freed. Addresses
518
+ * stay valid across versions. Returns the new version number (2, 3, ...).
519
+ */
520
+ reload(machine: AnyStateMachine | SCXMLLogic<any, any>): number;
521
+ /**
522
+ * Live migration to the current version: each actor moves at a stable
523
+ * point, states matched by id, history and context kept (properties the new
524
+ * machine does not declare are dropped, new ones initialized), same address.
525
+ * It then receives `{ type: 'error.platform.upgrade', data: previousContext }`.
526
+ * `target`: one actor, a machine (its actors), or all actors on old versions.
527
+ * Runs as a job in time slices (a few ms each, actors walked lazily), so the
528
+ * event loop stays responsive however many actors there are. Busy actors
529
+ * move at their next stable point; hibernated ones are loaded first when
530
+ * `wake` is on, else they move when they wake.
531
+ */
532
+ migrate(target?: AnyActor | AnyStateMachine, options?: MigrateOptions): Migration;
533
+ /**
534
+ * Send many events in one native call (batched per segment). `items`:
535
+ * [actor, event] pairs; returns how many were accepted (actors that ended
536
+ * are skipped).
537
+ */
538
+ sendMany(items: ReadonlyArray<readonly [AnyActor, EventObject | string]>): number;
539
+ /**
540
+ * The whole system as bytes: every actor (states, contexts and variables,
541
+ * queued events, timers) and what it runs (machine SCXML, documents,
542
+ * images). Restore with `createSystem({ restore })`. Not during a migration
543
+ * or inside an action; contexts must be encodable (no functions).
544
+ * Hibernated actors stay in the hibernation store: restore with the same store.
545
+ */
546
+ snapshot(): Uint8Array;
547
+ /**
548
+ * Run everything due now (events, eventless chains, timers due on the
549
+ * system's clock) until the system is idle; true when it is. With a `clock`
550
+ * option this is how time moves: advance the clock, then flush().
551
+ */
552
+ flush(maxSlices?: number): boolean;
553
+ /** Start the actors a system image declares; returns them by name (also `get(name)`). */
554
+ boot(image: SystemImage): Record<string, AnyActor>;
555
+ /** Stop every actor, close the system's links, end its timers and free its native memory. */
556
+ stop(): void;
557
+ }
558
+
559
+ export interface MigrateOptions {
560
+ /** Load hibernated actors to migrate them now (default: true when the system has a hibernation store). */
561
+ wake?: boolean;
562
+ /** End the job after this long; actors still busy (or asleep) stay on their version and are reported. */
563
+ timeoutMs?: number;
564
+ }
565
+
566
+ export interface MigrationResult {
567
+ /** Actors moved by the job. */
568
+ migrated: number;
569
+ /** Actors that could not be adopted by the new version (they stay, unchanged, where they were). */
570
+ failed: number;
571
+ /** Actors left on their version when the job ended (timeout, or the system stopped). */
572
+ pending: AnyActor[];
573
+ }
574
+
575
+ export interface Migration {
576
+ /** Actors moved during the call (the job's first slice). */
577
+ readonly migrated: AnyActor[];
578
+ /** Actors still on older versions (computed when read: a walk over the actors). */
579
+ readonly pending: AnyActor[];
580
+ /** Resolves when the job ends. */
581
+ readonly done: Promise<MigrationResult>;
582
+ }
583
+
584
+ /** A new, empty actor system (the default system is used otherwise). */
585
+ export declare function createSystem(options?: SystemOptions): System;
586
+
587
+ /** A hibernation store kept in memory. */
588
+ export declare function createMemoryStore(): HibernationStore & { readonly size: number };
589
+
590
+ /** The tagged-JSON encoding used for hibernation and links (keeps Date, Map, Set, BigInt, cycles; actors as addresses). */
591
+ export declare function encodeValue(value: unknown): Uint8Array;
592
+ export declare function decodeValue(bytes: Uint8Array, system?: System): unknown;
593
+
594
+ /** A JSON value with the protocol's extensions: {"$ref": address}, {"$bytes": base64}, {"$": {...}}. */
595
+ export type WireValue = null | boolean | number | string | WireValue[] | { [key: string]: WireValue };
596
+ /**
597
+ * A value as a neutral wire value (docs/protocol.md, "Values"): what systems in any language
598
+ * understand. Actors become {"$ref"}, bytes {"$bytes"}; undefined, functions and symbols are
599
+ * dropped, Map/Set become objects/arrays, Dates their JSON form; cycles throw.
600
+ */
601
+ export declare function encodeWire(value: unknown): WireValue;
602
+ /** A neutral wire value as a JS value ({"$ref"} becomes an ActorRef of `system`, if given). */
603
+ export declare function decodeWire(value: WireValue, system?: System): unknown;
604
+
605
+ /* --------------------------------------------------------------------- links */
606
+
607
+ /** A WebSocket-like duplex (the browser/Node WebSocket fits). */
608
+ export interface LinkTransport {
609
+ send(data: string): void;
610
+ close(): void;
611
+ onopen: ((ev?: unknown) => void) | null;
612
+ onmessage: ((ev: { data: unknown }) => void) | null;
613
+ onclose: ((ev?: unknown) => void) | null;
614
+ onerror?: ((ev?: unknown) => void) | null;
615
+ }
616
+
617
+ /** A Node-style stream of bytes (the shape links use: a net.Socket, process.stdin, a child's stdout). */
618
+ export interface NodeByteStream {
619
+ on(event: string, listener: (...args: any[]) => void): unknown;
620
+ off(event: string, listener: (...args: any[]) => void): unknown;
621
+ once(event: string, listener: (...args: any[]) => void): unknown;
622
+ write(chunk: Uint8Array): unknown;
623
+ end(): unknown;
624
+ destroy?(): unknown;
625
+ }
626
+ /**
627
+ * A byte stream as a link transport: length-prefixed frames (docs/protocol.md, "Framing").
628
+ * A duplex (a net.Socket) or a pair: `{ readable: child.stdout, writable: child.stdin }` in the
629
+ * parent, `{ readable: process.stdin, writable: process.stdout }` in the child.
630
+ */
631
+ export type ByteStream = NodeByteStream | { readable: NodeByteStream; writable: NodeByteStream };
632
+
633
+ /** A frame the decoder refused (above max_frame, or not UTF-8): skipped, the stream stays in step. */
634
+ export interface RefusedFrame {
635
+ reason: 'malformed';
636
+ /** The frame's length in bytes. */
637
+ length: number;
638
+ detail: string;
639
+ }
640
+ /** One length-prefixed frame (docs/protocol.md, "Framing"): a 4-byte big-endian length, then the UTF-8 text. */
641
+ export declare function encodeFrame(text: string): Uint8Array;
642
+ /** Bytes in, frames out: for byte-stream transports of your own. */
643
+ export declare class FrameDecoder {
644
+ /** `maxFrame`: frames above it are refused (default 1 MiB = 1048576). */
645
+ constructor(options?: { maxFrame?: number });
646
+ readonly maxFrame: number;
647
+ /** Feed bytes as they arrive (any split); returns the frames they complete, in order. */
648
+ push(chunk: Uint8Array): Array<string | RefusedFrame>;
649
+ }
650
+
651
+ export interface LinkOptions {
652
+ /** ws:// or wss:// URL of a system serving links. */
653
+ url?: string;
654
+ /** Or: open a transport yourself (called again on every reconnect): WebSocket-like, or a byte
655
+ * stream (e.g. a child process's stdio) that carries length-prefixed frames. */
656
+ transport?: () => LinkTransport | ByteStream;
657
+ /** Node: or connect over TCP (length-prefixed frames; host default 127.0.0.1). */
658
+ tcp?: { host?: string; port: number };
659
+ /** Largest frame accepted on a byte stream, announced in the hello (default 1 MiB). Envelopes
660
+ * that do not fit the other side's announced limit fail with error.communication (malformed). */
661
+ maxFrame?: number;
662
+ /** The remote system's id, used in addresses created by link.get() (default "remote"; if the
663
+ * server turns out to have another id, addresses with this name still reach it). */
664
+ name?: string;
665
+ /** Envelopes queued by the router while the link is down (default 1000; beyond that, or with 0
666
+ * = fail fast, sends raise error.communication in the sender). */
667
+ maxQueue?: number;
668
+ /** How long (ms) a queued envelope may wait for the link; then error.communication (default: no limit). */
669
+ queueTTLMs?: number;
670
+ /** Trust the remote system: it may send to any local actor and relay through us (default true). */
671
+ trusted?: boolean;
672
+ /** Announce the systems reachable through us to the remote side (relaying; default false; a list: only those). */
673
+ announce?: boolean | string[];
674
+ /** Opaque credential sent in the hello (the other side's `trust(hello)` may check it). */
675
+ credential?: unknown;
676
+ /** Value encoding: "js" (default; used if the other side announces it too, else neutral) or
677
+ * "neutral" (docs/protocol.md, "Values") — for peers in other languages. */
678
+ profile?: 'js' | 'neutral';
679
+ /** Ping interval for the round-trip time (default 5000 ms; 0 = off). */
680
+ pingMs?: number;
681
+ }
682
+
683
+ export type LinkStatus = 'connecting' | 'open' | 'reconnecting' | 'closed';
684
+
685
+ export interface LinkContext {
686
+ url: string | undefined;
687
+ /** Failed attempts since the link was last open. */
688
+ attempts: number;
689
+ /** Round-trip time of the last ping (ms). */
690
+ rtt: number | null;
691
+ /** Events waiting for the link to open. */
692
+ queued: number;
693
+ /** When the link opened (ms since the system started), or null. */
694
+ openedAt: number | null;
695
+ /** The remote system's id once connected. */
696
+ peer: string | null;
697
+ error: string | null;
698
+ }
699
+
700
+ export type LinkEvent =
701
+ | { type: 'OPENED'; peer: string; at: number }
702
+ | { type: 'DROPPED'; error?: string }
703
+ | { type: 'RTT'; ms: number }
704
+ | { type: 'QUEUED'; n: number }
705
+ | { type: 'CLOSE' };
706
+
707
+ export type LinkMachine = StateMachine<LinkContext, LinkEvent>;
708
+
709
+ /**
710
+ * A link to another actor system. The link itself is an actor: its snapshot
711
+ * value is the connection status (subscribe to show it), its context has
712
+ * attempts, round-trip time and queue length. Actors on either side reach each
713
+ * other transparently: `sendTo(link.get('lobby'), ...)`, replies to `self`
714
+ * references carried in events.
715
+ */
716
+ export interface Link extends Actor<LinkMachine> {
717
+ /** The remote actor registered with `systemID` on the other side. */
718
+ get(systemID: string): ActorRef;
719
+ /** Close for good (status becomes "closed"). */
720
+ close(): void;
721
+ /** The router's view of this link (null once closed). */
722
+ status(): PeerStatus | null;
723
+ }
724
+
725
+ /** One SCXML event on its way to one target (docs/protocol.md, "Envelope"). */
726
+ export interface Envelope {
727
+ target: string;
728
+ name: string;
729
+ data?: unknown;
730
+ /** Default: tinyactors://<this system>/@host */
731
+ origin?: string;
732
+ origintype?: string;
733
+ sendid?: string;
734
+ /** Unique per origin; errors and deduplication refer to it. */
735
+ msgid?: string;
736
+ /** A key to drop duplicates by instead of msgid (an idempotency key). */
737
+ dedup?: string;
738
+ hops?: number;
739
+ }
740
+
741
+ /** A route's status as the router sees it (docs/protocol.md, "Observability"). */
742
+ export interface PeerStatus {
743
+ /** The peer's system id. */
744
+ id: string;
745
+ state: 'connecting' | 'open' | 'reconnecting' | 'closed';
746
+ /** Envelopes waiting for the peer. */
747
+ queued: number;
748
+ /** Last measured round trip (ms; 0 = unknown). */
749
+ rtt: number;
750
+ /** How long the oldest queued envelope has waited (ms). */
751
+ lag: number;
752
+ sent: number;
753
+ received: number;
754
+ errors: number;
755
+ duplicates: number;
756
+ }
757
+
758
+ /** The first frame of the link protocol (docs/protocol.md, "Link protocol"). */
759
+ export interface LinkHello {
760
+ t: 'hello';
761
+ v: number;
762
+ id: string;
763
+ reach: string[];
764
+ caps?: { profile?: string; ordered?: boolean; acks?: boolean; max_frame?: number };
765
+ cred?: unknown;
766
+ }
767
+
768
+ /** A parsed actor address (docs/protocol.md, "Addresses"). Session ids are BigInt: exact up to 2^64-1. */
769
+ export type ParsedAddress =
770
+ | { system: string; local: string; kind: 'session'; session: bigint }
771
+ | { system: string; local: string; kind: 'name'; name: string; encoded: string };
772
+ /** Parse `tinyactors://<system>/<local>`; null if it is not an address. */
773
+ export declare function parseAddress(text: string): ParsedAddress | null;
774
+ /** `tinyactors://<system>/#_scxml_<id>` for a session id, `.../@<name>` (percent-encoded) for a name. */
775
+ export declare function formatAddress(system: string, local: bigint | number | string): string;
776
+ export declare function createLink(system: System, options: LinkOptions): Link;
777
+
778
+ export interface ServeLinksOptions {
779
+ /** Node: an http(s).Server to attach WebSocket upgrades to (with `path`, default "/link"). */
780
+ server?: unknown;
781
+ path?: string;
782
+ /** Node: or listen on this port. */
783
+ port?: number;
784
+ /** Node: or accept TCP connections (length-prefixed frames) on this port (0: any free one). */
785
+ tcp?: { port?: number; host?: string };
786
+ /** Any runtime: register a source of already-open transports (a WebSocket server, MessagePorts,
787
+ * byte streams such as a child process's stdio, ...). */
788
+ accept?: (onConnection: (transport: LinkTransport | ByteStream) => void) => void | (() => void);
789
+ /** Largest frame accepted on a byte stream, announced in the hello (default 1 MiB). */
790
+ maxFrame?: number;
791
+ /** What untrusted peers may send to: actor systemIDs ("*" = every name and session), optionally
792
+ * limited to event descriptors (`{ lobby: 'JOIN LEAVE' }`). Default: nothing. */
793
+ exports?: string[] | Record<string, string | string[]>;
794
+ /** Trust every peer (send anything, relay through us). Default false. */
795
+ trusted?: boolean;
796
+ /** Or decide per peer from its hello (e.g. check `hello.cred`). */
797
+ trust?: (hello: LinkHello) => boolean;
798
+ /** A peer that reconnects with the same id within this time resumes, and receives what was
799
+ * queued for it meanwhile (default 30000; 0 = fail fast as soon as it drops). Measured on
800
+ * the system's clock: with a `clock` option, simulated time. */
801
+ resumeMs?: number;
802
+ /** Envelopes queued per absent peer (default 1000). */
803
+ maxQueue?: number;
804
+ /** Announce the systems reachable through us to connecting peers (relaying; default false);
805
+ * a list announces only those (e.g. `[databaseID]`, not the other browsers). */
806
+ announce?: boolean | string[];
807
+ /** Value encoding offered to peers: "js" (default) or "neutral". */
808
+ profile?: 'js' | 'neutral';
809
+ }
810
+
811
+ export interface LinkServer {
812
+ /** Remote system ids currently connected. */
813
+ connections(): string[];
814
+ /** The router's view of the peer with this system id (also while it is away), or null. */
815
+ status(id: string): PeerStatus | null;
816
+ /** The port when listening (Node, `port` or `tcp` option). */
817
+ readonly port?: number;
818
+ close(): Promise<void>;
819
+ }
820
+
821
+ export interface StoreLinkOptions {
822
+ /** Run a statement with $1.. parameters; resolve to the rows (objects by column name). */
823
+ query(sql: string, params: unknown[]): Promise<Array<Record<string, unknown>>>;
824
+ /** Optional: subscribe to a NOTIFY channel; resolve to (or return) a function that unsubscribes. */
825
+ listen?(channel: string, onPayload: (payload: string) => void): Promise<() => unknown> | (() => unknown);
826
+ /** The database's system id (default: SELECT tinyactors.system_id()). */
827
+ id?: string;
828
+ /** How often to look for envelopes without a NOTIFY (default 1000 ms; 0 = only on NOTIFY). */
829
+ pollMs?: number;
830
+ /** Envelopes claimed per query (default 100). */
831
+ batch?: number;
832
+ /** This claimer's name in the outbox (default: <system id>/<random>). */
833
+ worker?: string;
834
+ /** Trust the database's actors: they may send to any local actor and relay through us (default true). */
835
+ trusted?: boolean;
836
+ /** Tell the database which systems we reach (browsers on our links), so their envelopes come to us (default true). */
837
+ announce?: boolean;
838
+ /** Envelopes the router keeps while the database is unreachable (default 10000). */
839
+ maxQueue?: number;
840
+ queueTTLMs?: number;
841
+ }
842
+
843
+ export interface StoreLink {
844
+ /** The database's system id (once known). */
845
+ readonly id: string | null;
846
+ /** Resolves once connected (rejects if the first query fails). */
847
+ readonly ready: Promise<void>;
848
+ /** Claim and deliver what the database has for us now. */
849
+ drain(): Promise<void>;
850
+ /** Resolves when everything handed to the link reached the database and nothing is being claimed. */
851
+ flush(): Promise<void>;
852
+ status(): (PeerStatus & { error: string | null; pending: number }) | null;
853
+ close(): Promise<void>;
854
+ }
855
+
856
+ /**
857
+ * Connect `system` to a database of actors (PostgreSQL with the tinyactors extension; docs/protocol.md,
858
+ * "Store links") through your own PostgreSQL client. With node-postgres:
859
+ * `createStoreLink(system, { query: (q, p) => pool.query(q, p).then((r) => r.rows) })`.
860
+ */
861
+ export declare function createStoreLink(system: System, options: StoreLinkOptions): StoreLink;
862
+
863
+ /** Accept links from other systems (e.g. browsers) into `system`. */
864
+ export declare function serveLinks(system: System, options: ServeLinksOptions): LinkServer;
865
+
866
+ export declare function createActor<M extends AnyActorLogic>(
867
+ logic: M,
868
+ options?: ActorOptions<InputFrom<M>>,
869
+ ): Actor<M>;
870
+
871
+ /* ---------------------------------------------------------- action creators */
872
+
873
+ export declare function assign<TContext extends MachineContext, TEvent extends EventObject = EventObject>(
874
+ assignment: Assigner<TContext, TEvent>,
875
+ ): AssignAction<TContext, TEvent>;
876
+ export declare function raise<
877
+ TSent extends EventObject,
878
+ TContext = any,
879
+ TEvent extends EventObject = EventObject,
880
+ >(
881
+ event: EventOrExpr<TContext, TEvent, TSent>,
882
+ options?: SendOptions<TContext, TEvent>,
883
+ ): RaiseAction<TContext, TEvent>;
884
+ export declare function sendTo<
885
+ TSent extends EventObject,
886
+ TContext = any,
887
+ TEvent extends EventObject = EventObject,
888
+ >(
889
+ to: SendTarget<TContext, TEvent>,
890
+ event: EventOrExpr<TContext, TEvent, TSent>,
891
+ options?: SendOptions<TContext, TEvent>,
892
+ ): SendToAction<TContext, TEvent>;
893
+ export declare function sendParent<
894
+ TSent extends EventObject,
895
+ TContext = any,
896
+ TEvent extends EventObject = EventObject,
897
+ >(
898
+ event: EventOrExpr<TContext, TEvent, TSent>,
899
+ options?: SendOptions<TContext, TEvent>,
900
+ ): SendParentAction<TContext, TEvent>;
901
+ export declare function log<TContext = any, TEvent extends EventObject = EventObject>(
902
+ value?: string | ((args: ActionArgs<TContext, TEvent>) => unknown),
903
+ label?: string,
904
+ ): LogAction<TContext, TEvent>;
905
+ export declare function cancel(sendID: string): CancelAction;
906
+ export declare function stateIn(stateValue: string): StateInGuard;
907
+ export declare function and<TContext = any, TEvent extends EventObject = EventObject>(
908
+ guards: ReadonlyArray<Guard<TContext, TEvent>>,
909
+ ): CompositeGuard<TContext, TEvent>;
910
+ export declare function or<TContext = any, TEvent extends EventObject = EventObject>(
911
+ guards: ReadonlyArray<Guard<TContext, TEvent>>,
912
+ ): CompositeGuard<TContext, TEvent>;
913
+ export declare function not<TContext = any, TEvent extends EventObject = EventObject>(
914
+ guard: Guard<TContext, TEvent>,
915
+ ): CompositeGuard<TContext, TEvent>;