@tinyactors/wasm 0.0.0-stage → 0.4.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,876 @@
1
+ // The application layer of @tinyactors/node and @tinyactors/wasm, in
2
+ // JavaScript over the direct layer's exports only (AGENTS.md, "Layers and
3
+ // the resolver"): the API applications use. It imports nothing but
4
+ // `#direct`, the package's direct exports (the lint rule
5
+ // convenience-imports-the-direct-layer): package.json's `imports` maps it
6
+ // to the addon's lib/direct.mjs, and under the export condition
7
+ // `tinyactors-wasm` to the wasm package's wasm/lib/direct.mjs
8
+ // (docs/browser.md, "One API"), so the two packages share this file and
9
+ // present one API. The package's entries export what this module exports,
10
+ // and nothing else.
11
+ //
12
+ // The direct layer mirrors core: its Host takes a host config and
13
+ // handlers. This layer's Host is that class extended in place (ROADMAP.md,
14
+ // 8.6: no second class, no second signature), and the direct class is not
15
+ // exported:
16
+ //
17
+ // - new Host(charts, {system, ioProcessors, config, ...}) builds the
18
+ // config from its options (ioProcessors in the order given, each a
19
+ // processor object with receive(send)), makes the host, then adds the
20
+ // charts' images in order; Host.restore(snapshot, charts, options) adds
21
+ // only the images the snapshot does not hold;
22
+ // - spawn returns an Actor, a small immutable handle by session;
23
+ // host.actor(session, name or address) and await host.actors() find
24
+ // them; send.sender is one;
25
+ // - store and resident hibernate the actors past the bound after a turn
26
+ // and load a WAKE's blob (the direct layer's idle and wake hooks);
27
+ // - onDone and onError get each top-level actor that ends (its done and
28
+ // error hooks), actor.done its donedata;
29
+ // - Actor.ask sends with an origin of the system the binding reserves,
30
+ // tinyactors-ask, and takes the chart's reply out of the transport.
31
+ //
32
+ // The direct layer's helpers the API is built on (actorByName,
33
+ // holdsImage, residentCount, actorInfo, askOpen, askClose) are taken off
34
+ // its prototype here, so an application sees only this layer's names.
35
+ //
36
+ // The typed methods return promises when given no handler (the
37
+ // maintainer, 2026-11-18): `host.actorState(params)` returns a promise that
38
+ // resolves with the result and rejects with the TinyactorsError, while
39
+ // `host.actorState(params, onResult, onError?)` is the direct method's call
40
+ // and returns nothing. A refusal at the call rejects too. A method still
41
+ // pending at `close()` never settles: the direct layer drops its handlers
42
+ // uncalled. A `session` param may be an Actor.
43
+ //
44
+ // compileDir, SQLiteStore and directory reads reach node:fs, node:path,
45
+ // node:url and the runtime's SQLite through process.getBuiltinModule: a
46
+ // runtime without them (a browser) refuses them with TA_ERROR_UNSUPPORTED.
47
+ import {
48
+ Address,
49
+ CompileError,
50
+ compileCharts,
51
+ compileSystem,
52
+ decode,
53
+ decodeTraces,
54
+ encode,
55
+ encodeHTTPPost,
56
+ Host as DirectHost,
57
+ InvalidError,
58
+ parseHTTPRequest,
59
+ ResolveError,
60
+ Send,
61
+ SimulatedClock,
62
+ StaleError,
63
+ StateError,
64
+ TinyactorsError,
65
+ UnsupportedError,
66
+ } from './direct.mjs';
67
+ export { version } from './version.mjs';
68
+ export {
69
+ Address,
70
+ CompileError,
71
+ compileCharts,
72
+ compileSystem,
73
+ decode,
74
+ decodeTraces,
75
+ encode,
76
+ encodeHTTPPost,
77
+ InvalidError,
78
+ parseHTTPRequest,
79
+ ResolveError,
80
+ SimulatedClock,
81
+ StaleError,
82
+ StateError,
83
+ TinyactorsError,
84
+ UnsupportedError,
85
+ };
86
+
87
+ // ---- the direct layer's helpers ----------------------------------------------
88
+
89
+ /** Takes method `name` off the direct Host's prototype: the application
90
+ * layer calls it, an application does not see it. */
91
+ function taken(name) {
92
+ const method = DirectHost.prototype[name];
93
+ if (typeof method !== 'function') throw new Error(`@tinyactors/node: the direct layer has no Host method ${name}`);
94
+ delete DirectHost.prototype[name];
95
+ return method;
96
+ }
97
+
98
+ const actorByName = taken('actorByName');
99
+ const holdsImage = taken('holdsImage');
100
+ const residentCount = taken('residentCount');
101
+ const actorInfo = taken('actorInfo');
102
+ const askOpen = taken('askOpen');
103
+ const askClose = taken('askClose');
104
+
105
+ /** Defines `value` on `target` as a class's method is: writable,
106
+ * configurable, not enumerable, its `name` the property's. */
107
+ function method(target, name, value) {
108
+ Object.defineProperty(value, 'name', { value: name });
109
+ Object.defineProperty(target, name, { value, writable: true, configurable: true, enumerable: false });
110
+ }
111
+
112
+ /** A plain object (an object literal, Object.create(null)), not an array,
113
+ * a class's instance or a function. */
114
+ function plain(value) {
115
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
116
+ const prototype = Object.getPrototypeOf(value);
117
+ return prototype === null || prototype === Object.prototype;
118
+ }
119
+
120
+ /** Refuses a key of `object` that is not in `known`, naming it. */
121
+ function onlyKnown(object, known, what) {
122
+ for (const key of Object.keys(object)) if (!known.has(key)) throw new TypeError(`unknown ${what}: ${key}`);
123
+ }
124
+
125
+ // ---- the typed methods: a promise when given no handler ------------------------
126
+
127
+ /** The direct typed method `direct` as one that returns a promise of its
128
+ * result when it is given no handler; a `session` param may be an Actor. */
129
+ function promising(direct) {
130
+ return function (params, onResult, onError) {
131
+ const session = params !== null && typeof params === 'object' ? Object.getOwnPropertyDescriptor(params, 'session') : undefined;
132
+ if (session !== undefined && session.value instanceof Actor) params = { ...params, session: session.value.id };
133
+ if (onResult !== undefined || (onError !== undefined && onError !== null)) return direct.call(this, params, onResult, onError);
134
+ return new Promise((resolve, reject) => {
135
+ direct.call(this, params, resolve, reject);
136
+ });
137
+ };
138
+ }
139
+
140
+ /** The direct typed methods of Host. */
141
+ const TYPED_METHODS = [
142
+ 'actorState', 'actorContext', 'actorList', 'actorGet', 'hostStats', 'hostConfig',
143
+ 'traceConfigure', 'traceWatch', 'traceUnwatch', 'traceEnd', 'traceSpansDecode',
144
+ ];
145
+
146
+
147
+ // ---- the host's construction ------------------------------------------------------
148
+
149
+ // The system id the binding reserves for ask()'s reply addresses: a host
150
+ // may not take it as its own.
151
+ const ASK_SYSTEM = 'tinyactors-ask';
152
+
153
+ const HOST_OPTIONS = new Set([
154
+ 'system', 'ioProcessors', 'config', 'clock', 'store', 'resident', 'log', 'telemetry', 'services', 'transport',
155
+ 'onDone', 'onError', 'onHandlerError', 'migrated', 'migrationDone', 'datamodel', 'quickjs',
156
+ ]);
157
+
158
+ // The direct options a Host's options pass on as given.
159
+ const PASSED = ['clock', 'log', 'telemetry', 'services', 'migrated', 'migrationDone', 'datamodel', 'quickjs'];
160
+
161
+ /** The images of `charts`: a compile result (its `image`), an image's
162
+ * bytes, or an array of them, in order. */
163
+ function imagesOf(charts) {
164
+ const list = Array.isArray(charts) ? charts : [charts];
165
+ return list.map((item) => {
166
+ if (item instanceof Uint8Array || item instanceof ArrayBuffer) return item;
167
+ if (item !== null && typeof item === 'object' && !Array.isArray(item) && 'image' in item) return item.image;
168
+ throw new TypeError('a Host\'s charts are a compile result, an image\'s bytes (a Uint8Array or an ArrayBuffer), or an array of them');
169
+ });
170
+ }
171
+
172
+ /** A Host's options as the direct layer takes them: the host config, the
173
+ * direct options, and the application layer's state (`app`), its `host`
174
+ * set once the host is made. */
175
+ function shape(charts, options, restoring) {
176
+ if (options === undefined) options = {};
177
+ if (!plain(options)) throw new TypeError('a Host\'s options are an object');
178
+ onlyKnown(options, HOST_OPTIONS, 'Host option');
179
+ const images = imagesOf(charts);
180
+ const { system, config, ioProcessors, store, resident } = options;
181
+ if (system === undefined && restoring) throw new TypeError('restore needs options.system, the system id the snapshot was taken with');
182
+ if (system === ASK_SYSTEM) throw new InvalidError(`the system id ${ASK_SYSTEM} is reserved for ask()'s replies`);
183
+ if (config !== undefined && !plain(config)) {
184
+ throw new TypeError('config is an object of the host config\'s system, migrateQuantum and telemetry');
185
+ }
186
+ for (const key of ['systemID', 'ioProcessors']) {
187
+ if (config !== undefined && Object.hasOwn(config, key)) {
188
+ throw new TypeError(`config has no ${key}: a Host takes it as options.${key === 'systemID' ? 'system' : 'ioProcessors'}`);
189
+ }
190
+ }
191
+ const full = system === undefined ? { ...config } : { systemID: system, ...config };
192
+ const direct = {};
193
+ if (ioProcessors !== undefined) {
194
+ if (!plain(ioProcessors)) throw new TypeError('ioProcessors is an object of a type -> its processor');
195
+ const entries = [];
196
+ for (const [type, processor] of Object.entries(ioProcessors)) {
197
+ if (processor === null || typeof processor !== 'object' || typeof processor.receive !== 'function') {
198
+ throw new TypeError(`the I/O processor ${type} is not an object with receive(send)`);
199
+ }
200
+ const entry = { type };
201
+ if (processor.location !== undefined) entry.location = processor.location;
202
+ entries.push(entry);
203
+ }
204
+ if (entries.length > 0) {
205
+ full.ioProcessors = entries;
206
+ direct.ioProcessors = ioProcessors;
207
+ }
208
+ }
209
+ for (const name of PASSED) if (options[name] !== undefined) direct[name] = options[name];
210
+ for (const name of ['transport', 'onDone', 'onError', 'onHandlerError']) {
211
+ if (options[name] !== undefined && typeof options[name] !== 'function') throw new TypeError(`${name} is a function`);
212
+ }
213
+ if (store !== undefined) {
214
+ for (const name of ['save', 'load', 'delete']) {
215
+ if (store === null || typeof store !== 'object' || typeof store[name] !== 'function') {
216
+ throw new TypeError(`store is an object with save(session, blob), load(session) and delete(session): it has no ${name}`);
217
+ }
218
+ }
219
+ }
220
+ if (resident !== undefined) {
221
+ if (!Number.isSafeInteger(resident) || resident < 1) throw new TypeError('resident is the most actors kept in memory, an integer from 1');
222
+ if (store === undefined) throw new TypeError('resident needs a store to hibernate the other actors into');
223
+ }
224
+ const app = {
225
+ host: undefined,
226
+ system,
227
+ transport: options.transport,
228
+ onDone: options.onDone,
229
+ onError: options.onError,
230
+ store,
231
+ resident,
232
+ dones: new Map(), // session -> the waiter of actor.done
233
+ deferred: new Set(), // migrations' WAKEs waiting for room (resident)
234
+ saving: new Map(), // session -> its blob, while a save that returned a promise is pending
235
+ unsaved: new Set(), // sessions whose last save failed: the next trim leaves them resident
236
+ };
237
+ direct.transport = (send) => transported(app, send);
238
+ direct.done = (session, donedata) => ended(app, session, { donedata });
239
+ direct.error = (session, fault) => ended(app, session, { fault });
240
+ if (options.onHandlerError !== undefined) direct.handlerError = options.onHandlerError;
241
+ if (store !== undefined) direct.wake = (session, migration) => woken(app, session, migration);
242
+ if (resident !== undefined) direct.idle = () => trimmed(app);
243
+ return { config: full, direct, app, images };
244
+ }
245
+
246
+ // What Host.restore passes the constructor: taken at its entry.
247
+ let restoring = null;
248
+
249
+ let appOf;
250
+
251
+ /** Runs actors: many charts, many images, from a handful of actors to
252
+ * millions, on the runtime's event loop (index.d.ts has the whole API). */
253
+ export class Host extends DirectHost {
254
+ #app;
255
+
256
+ static {
257
+ appOf = (host) => {
258
+ if (host === null || typeof host !== 'object' || !(#app in host)) throw new TypeError('not a Host');
259
+ return host.#app;
260
+ };
261
+ }
262
+
263
+ constructor(charts, options) {
264
+ const restore = restoring;
265
+ restoring = null;
266
+ const made = restore ?? shape(charts, options, false);
267
+ super(made.config, made.direct);
268
+ made.app.host = this;
269
+ this.#app = made.app;
270
+ try {
271
+ for (const image of made.images) if (restore === null || !holdsImage.call(this, image)) this.addImage(image);
272
+ } catch (error) {
273
+ this.close();
274
+ throw error;
275
+ }
276
+ }
277
+
278
+ /** Host.restore(snapshot, charts, options): a new Host running the
279
+ * snapshot, with the images of `charts` it does not hold added. */
280
+ static restore(snapshot, charts, options) {
281
+ const made = shape(charts, options, true);
282
+ const outer = restoring;
283
+ restoring = made;
284
+ try {
285
+ return super.restore(snapshot, made.config, made.direct);
286
+ } finally {
287
+ restoring = outer;
288
+ }
289
+ }
290
+
291
+ /** The host's system id, `options.system`. */
292
+ get system() { return appOf(this).system; }
293
+
294
+ /** spawn(chart, options?) -> Actor: an actor of `chart`, a chart's name
295
+ * (its current version) or a ChartRef. */
296
+ spawn(chart, options) {
297
+ const ref = typeof chart === 'string' ? this.chart(chart) : chart;
298
+ return new Actor(this, super.spawn(ref, options));
299
+ }
300
+
301
+ /** actor(which) -> Actor: a live actor by its session (a bigint or a
302
+ * safe integer), an Actor, the name it was spawned with, or an address
303
+ * of this system (a string or an Address); StaleError for none. */
304
+ actor(which) {
305
+ let session;
306
+ if (which instanceof Actor) session = which.id;
307
+ else if (typeof which === 'bigint' || typeof which === 'number') session = which;
308
+ else if (typeof which === 'string' && !which.startsWith('tinyactors://')) return this.#named(which);
309
+ else if (typeof which === 'string' || which instanceof Address) {
310
+ const address = which instanceof Address ? which : new Address(which);
311
+ if (address.system !== this.system) throw new InvalidError(`${address.text} is an address of another system`);
312
+ if (address.session !== undefined) session = address.session;
313
+ else if (address.name !== undefined) return this.#named(address.name);
314
+ else throw new InvalidError(`${address.text} names no actor`);
315
+ } else throw new TypeError('actor takes a session, an Actor, a name or an address');
316
+ if (actorInfo.call(this, session) === undefined) throw new StaleError(`no live actor has the session ${session}`);
317
+ return new Actor(this, BigInt(session));
318
+ }
319
+
320
+ #named(name) {
321
+ const session = actorByName.call(this, name);
322
+ if (session === undefined) throw new StaleError(`no live actor is named ${name}`);
323
+ return new Actor(this, session);
324
+ }
325
+
326
+ /** actors({chart}?) -> Promise<Actor[]>: every live actor of the host
327
+ * (actor.list, a page at a time), or those of the chart named `chart`. */
328
+ async actors(options) {
329
+ if (options !== undefined) {
330
+ if (!plain(options)) throw new TypeError('actors\' options are an object: {chart}');
331
+ onlyKnown(options, new Set(['chart']), 'actors option');
332
+ }
333
+ const chart = options?.chart;
334
+ if (chart !== undefined && typeof chart !== 'string') throw new TypeError('chart is a chart\'s name, a string');
335
+ const found = [];
336
+ let cursor = 0;
337
+ for (;;) {
338
+ const page = await this.actorList({ cursor, limit: 512 });
339
+ for (const listed of page.sessions) {
340
+ const session = BigInt(listed);
341
+ if (chart === undefined || (!this.closed && actorInfo.call(this, session)?.chart === chart)) found.push(new Actor(this, session));
342
+ }
343
+ if (page.cursor === null) return found;
344
+ cursor = page.cursor;
345
+ }
346
+ }
347
+ }
348
+
349
+ for (const name of TYPED_METHODS) {
350
+ const direct = taken(name);
351
+ const wrapped = promising(direct);
352
+ method(Host.prototype, name, wrapped);
353
+ // the direct method's length (index.d.ts declares it)
354
+ Object.defineProperty(wrapped, 'length', { value: direct.length });
355
+ }
356
+
357
+ // ---- actors ------------------------------------------------------------------
358
+
359
+ /** An actor of a host: what spawn and actor() return, what send.sender
360
+ * and onDone get. A small immutable value made where the API returns one:
361
+ * keeping one keeps nothing alive in the host, and two for one actor are
362
+ * equal by `equals` (or by `id`, the key to use in a Map). */
363
+ export class Actor {
364
+ constructor(host, id) {
365
+ if (!(host instanceof Host)) throw new TypeError('an Actor is of a Host: new Actor(host, id)');
366
+ if (typeof id !== 'bigint' || id < 1n || id > 0xFFFFFFFFFFFFFFFFn) {
367
+ throw new TypeError('an Actor\'s id is its session, a bigint from 1 to 2^64-1');
368
+ }
369
+ Object.defineProperty(this, 'host', { value: host, enumerable: false });
370
+ Object.defineProperty(this, 'id', { value: id, enumerable: true });
371
+ Object.freeze(this);
372
+ }
373
+
374
+ /** tinyactors://<system>/#_scxml_<id>, the full form: what another
375
+ * system sends to. A chart sees this actor's sends' _event.origin
376
+ * either in it or as its fragment, #_scxml_<id>, so compare by the
377
+ * fragment. */
378
+ get address() { return Address.fromSession(this.host.system, this.id); }
379
+
380
+ /** send(event, data?, options?): host.send to the actor. */
381
+ send(event, data, options) {
382
+ this.host.send(this.id, event, data, options);
383
+ }
384
+
385
+ /** Ends the actor now (host.terminate). */
386
+ terminate() {
387
+ this.host.terminate(this.id);
388
+ }
389
+
390
+ /** A promise of the actor's active states (actorState). */
391
+ state() { return this.host.actorState({ session: this.id }); }
392
+ /** A promise of the actor's variables (actorContext). */
393
+ context() { return this.host.actorContext({ session: this.id }); }
394
+ /** A promise of what the host knows of the actor (actorGet). */
395
+ get() { return this.host.actorGet({ session: this.id }); }
396
+
397
+ /** ask(event, data?, {signal}?) -> Promise<[event, data]>: sends the
398
+ * event with an origin the host answers itself; the chart replies with
399
+ * <send targetexpr="_event.origin">. */
400
+ ask(event, data, options) { return asked(this.host, this.id, event, data, options); }
401
+
402
+ /** A promise of the actor's donedata, settled when it reaches a
403
+ * top-level final state (or rejected with the error it ended with). */
404
+ get done() { return doneOf(this.host, this.id); }
405
+
406
+ /** Whether `other` is an Actor of the same host and session. */
407
+ equals(other) { return other instanceof Actor && other.host === this.host && other.id === this.id; }
408
+
409
+ toString() { return `Actor(${this.id})`; }
410
+ }
411
+
412
+ // send.sender: the sending actor, an Actor (the view's session).
413
+ Object.defineProperty(Send.prototype, 'sender', {
414
+ get() { return new Actor(this.host, this.session); },
415
+ configurable: true,
416
+ enumerable: false,
417
+ });
418
+
419
+ /** The waiter of actor.done, kept in the host's map until the actor ends;
420
+ * one that ended already is StaleError, a closed host StateError. */
421
+ function doneOf(host, id) {
422
+ const app = appOf(host);
423
+ const kept = app.dones.get(id);
424
+ if (kept !== undefined) return kept.promise;
425
+ if (host.closed) return Promise.reject(new StateError('the Host is closed'));
426
+ if (actorInfo.call(host, id) === undefined) return Promise.reject(new StaleError(`actor ${id} ended: its donedata is gone`));
427
+ const waiter = {};
428
+ waiter.promise = new Promise((resolve, reject) => {
429
+ waiter.resolve = resolve;
430
+ waiter.reject = reject;
431
+ });
432
+ app.dones.set(id, waiter);
433
+ return waiter.promise;
434
+ }
435
+
436
+ /** A top-level actor ended (the direct layer's done or error hook): its
437
+ * actor.done settles, then onDone(actor, donedata) or onError(actor, error). */
438
+ function ended(app, session, how) {
439
+ const failed = how.fault !== undefined;
440
+ const error = failed
441
+ ? new TinyactorsError(`actor ${session} faulted (fault ${how.fault}) and ended`, { status: 'TA_ERROR_FATAL' })
442
+ : undefined;
443
+ const waiter = app.dones.get(session);
444
+ if (waiter !== undefined) {
445
+ app.dones.delete(session);
446
+ if (failed) waiter.reject(error);
447
+ else waiter.resolve(how.donedata);
448
+ }
449
+ const handler = failed ? app.onError : app.onDone;
450
+ if (handler === undefined) return undefined;
451
+ return handler(new Actor(app.host, session), failed ? error : how.donedata);
452
+ }
453
+
454
+ // ---- ask: a request and its reply over a send ------------------------------------
455
+
456
+ const ASK_PREFIX = `tinyactors://${ASK_SYSTEM}/@`;
457
+
458
+ /** Actor.ask: a row of the host's pending table holds the ask's settle
459
+ * function; the event goes with origin tinyactors://tinyactors-ask/@<the
460
+ * row's handle>. */
461
+ function asked(host, id, event, data, options) {
462
+ if (options !== undefined) {
463
+ if (!plain(options)) return Promise.reject(new TypeError('ask\'s options are an object: {signal}'));
464
+ try {
465
+ onlyKnown(options, new Set(['signal']), 'ask option');
466
+ } catch (error) {
467
+ return Promise.reject(error);
468
+ }
469
+ }
470
+ if (typeof event !== 'string') return Promise.reject(new TypeError('ask(event, data?, options?): the event is a string'));
471
+ const signal = options?.signal;
472
+ if (signal !== undefined && (signal === null || typeof signal.addEventListener !== 'function')) {
473
+ return Promise.reject(new TypeError('signal is an AbortSignal'));
474
+ }
475
+ if (signal?.aborted) return Promise.reject(signal.reason);
476
+ let resolve, reject, aborted;
477
+ const promise = new Promise((yes, no) => {
478
+ resolve = yes;
479
+ reject = no;
480
+ });
481
+ const settle = (name, value) => {
482
+ if (aborted !== undefined) signal.removeEventListener('abort', aborted);
483
+ resolve([name, value]);
484
+ };
485
+ let handle;
486
+ try {
487
+ handle = askOpen.call(host, settle);
488
+ host.send(id, event, data, { origin: `${ASK_PREFIX}${handle}` });
489
+ } catch (error) {
490
+ if (handle !== undefined) askClose.call(host, handle); // refused: no reply comes
491
+ return Promise.reject(error);
492
+ }
493
+ if (signal !== undefined) {
494
+ aborted = () => {
495
+ if (askClose.call(host, handle) !== undefined) reject(signal.reason);
496
+ };
497
+ signal.addEventListener('abort', aborted, { once: true });
498
+ }
499
+ return promise;
500
+ }
501
+
502
+ /** The host's transport (the direct layer's): a send to an ask's reply
503
+ * address settles the ask, and never reaches the application's transport;
504
+ * any other goes to it, or fails without one. */
505
+ function transported(app, send) {
506
+ const target = send.target;
507
+ if (target !== undefined && target.system === ASK_SYSTEM) {
508
+ let handle;
509
+ try {
510
+ handle = BigInt(target.name ?? '');
511
+ } catch {
512
+ return undefined; // not an ask's address: dropped
513
+ }
514
+ const settle = askClose.call(app.host, handle);
515
+ if (settle !== undefined) settle(send.event, send.data); // a stale handle: dropped
516
+ return undefined;
517
+ }
518
+ if (app.transport === undefined) {
519
+ send.fail(); // no transport: a failed completion, error.communication for the sender
520
+ return undefined;
521
+ }
522
+ return app.transport(send);
523
+ }
524
+
525
+ // ---- the store: hibernation the host does itself ------------------------------------
526
+
527
+ /** Whether `value` is a thenable. */
528
+ function thenable(value) {
529
+ return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
530
+ }
531
+
532
+ /** A WAKE (the direct layer's wake hook): the session's blob loaded from
533
+ * the store and woken; a migration's WAKE waits while the resident bound
534
+ * is reached, for trimmed() to load as room allows. */
535
+ function woken(app, session, migration) {
536
+ if (!actorInfo.call(app.host, session)?.hibernated) return undefined; // woken already by the application, or gone
537
+ if (migration !== undefined && app.resident !== undefined && residentCount.call(app.host) >= app.resident) {
538
+ app.deferred.add(session);
539
+ return undefined;
540
+ }
541
+ return loaded(app, session);
542
+ }
543
+
544
+ /** The blob of `session` loaded and woken, then deleted from the store; a
545
+ * load (or delete) that returns a promise is followed. */
546
+ function loaded(app, session) {
547
+ const saving = app.saving.get(session);
548
+ if (saving !== undefined) { // its save is pending: woken once it settled, if still hibernated
549
+ return saving.then(() => {
550
+ if (actorInfo.call(app.host, session)?.hibernated) return loaded(app, session);
551
+ return undefined;
552
+ });
553
+ }
554
+ const blob = app.store.load(session);
555
+ if (thenable(blob)) return blob.then((bytes) => wokenWith(app, session, bytes));
556
+ return wokenWith(app, session, blob);
557
+ }
558
+
559
+ function wokenWith(app, session, blob) {
560
+ if (!(blob instanceof Uint8Array || blob instanceof ArrayBuffer)) {
561
+ throw new StaleError(`the store has no blob of actor ${session}: it stays hibernated`);
562
+ }
563
+ app.host.wake(session, blob);
564
+ return app.store.delete(session); // the blob is spent
565
+ }
566
+
567
+ // Sessions swept at once: one sweep's slice.
568
+ const SLICE = 1024;
569
+ const MAX_SCAN = 0xFFFFFFFF;
570
+
571
+ /** A turn went idle (the direct layer's idle hook): the actors past the
572
+ * resident bound hibernated into the store (room made first for the
573
+ * migrations' WAKEs that wait), then those WAKEs loaded while there is
574
+ * room. Saves that return promises are followed, together. */
575
+ function trimmed(app) {
576
+ const host = app.host;
577
+ const waiting = app.deferred.size;
578
+ const pending = [];
579
+ let first = null;
580
+ const failed = (error) => {
581
+ if (first === null) first = [error];
582
+ };
583
+ // a session whose save failed was woken back, which made this turn: it
584
+ // stays resident now, or saving it again would turn without end
585
+ const skip = app.unsaved;
586
+ app.unsaved = new Set();
587
+ hibernateSurplus(app, waiting < app.resident ? app.resident - waiting : 0, { pending, failed, skip });
588
+ while (app.deferred.size > 0 && residentCount.call(host) < app.resident) {
589
+ const [session] = app.deferred;
590
+ app.deferred.delete(session);
591
+ if (!actorInfo.call(host, session)?.hibernated) continue;
592
+ try {
593
+ const result = loaded(app, session);
594
+ if (thenable(result)) pending.push(result);
595
+ } catch (error) {
596
+ failed(error);
597
+ }
598
+ }
599
+ if (first !== null) throw first[0];
600
+ if (pending.length > 0) return Promise.all(pending).then(() => undefined);
601
+ return undefined;
602
+ }
603
+
604
+ /** Down to `target` resident actors: the CLOCK sweep takes the actors that
605
+ * did not run since the last one, so a revolution marks the others, a
606
+ * second finds them, a third whatever ran in between. */
607
+ function hibernateSurplus(app, target, report) {
608
+ const host = app.host;
609
+ const start = residentCount.call(host);
610
+ const sweeps = start > target ? 3 + Math.floor((start - target) / SLICE) : 0;
611
+ for (let sweep = 0; sweep < sweeps; sweep++) {
612
+ const resident = sweep === 0 ? start : residentCount.call(host);
613
+ if (resident <= target) return;
614
+ const surplus = resident - target;
615
+ for (const session of host.sweep(MAX_SCAN, Math.min(surplus, SLICE))) {
616
+ if (!report.skip.has(session)) stored(app, session, report);
617
+ }
618
+ }
619
+ }
620
+
621
+ /** One session hibernated into the store: an actor that cannot hibernate
622
+ * now (not at rest, a value outside the table) stays. A save that throws,
623
+ * or whose promise rejects, wakes the actor back from its blob. */
624
+ function stored(app, session, report) {
625
+ const host = app.host;
626
+ let blob;
627
+ try {
628
+ blob = host.hibernate(session);
629
+ } catch (error) {
630
+ if (error instanceof StateError || error instanceof UnsupportedError) return; // it stays resident
631
+ report.failed(error);
632
+ return;
633
+ }
634
+ let saved;
635
+ try {
636
+ saved = app.store.save(session, blob);
637
+ } catch (error) {
638
+ host.wake(session, blob); // back from the blob, or the actor would have none anywhere
639
+ app.unsaved.add(session);
640
+ report.failed(error);
641
+ return;
642
+ }
643
+ if (!thenable(saved)) return;
644
+ const settled = Promise.resolve(saved).then(
645
+ () => {
646
+ app.saving.delete(session);
647
+ },
648
+ (error) => {
649
+ app.saving.delete(session);
650
+ if (!host.closed && actorInfo.call(host, session)?.hibernated) {
651
+ host.wake(session, blob);
652
+ app.unsaved.add(session);
653
+ }
654
+ throw error;
655
+ },
656
+ );
657
+ app.saving.set(session, settled.then(undefined, () => undefined));
658
+ report.pending.push(settled);
659
+ }
660
+
661
+ /** A store of hibernated actors' blobs in a Map: Host's store saves an
662
+ * actor's blob here when it hibernates the actor, loads it when an event
663
+ * comes for it, and deletes it once the actor is back or ended. */
664
+ export class MemoryStore {
665
+ constructor() {
666
+ /** The blobs by session: what a test reads to see what was stored. */
667
+ this.blobs = new Map();
668
+ }
669
+
670
+ save(session, blob) {
671
+ this.blobs.set(session, blob);
672
+ }
673
+
674
+ load(session) {
675
+ const blob = this.blobs.get(session);
676
+ if (blob === undefined) throw new StaleError(`no blob of actor ${session}`);
677
+ return blob;
678
+ }
679
+
680
+ delete(session) {
681
+ this.blobs.delete(session);
682
+ }
683
+ }
684
+
685
+ /** A session id (to 2^64 - 1) as SQLite's signed 64-bit integer. */
686
+ const signed = (session) => BigInt.asIntN(64, BigInt(session));
687
+
688
+ /** The runtime's SQLite, synchronous: node:sqlite's DatabaseSync, bun's
689
+ * Database; a runtime without either refuses. */
690
+ function sqlite() {
691
+ const process = globalThis.process;
692
+ const name = globalThis.Bun ? 'bun:sqlite' : 'node:sqlite';
693
+ let module;
694
+ try {
695
+ if (typeof process?.getBuiltinModule !== 'function') module = undefined;
696
+ else module = globalThis.Bun ? process.getBuiltinModule('bun:sqlite') : process.getBuiltinModule('node:sqlite');
697
+ } catch {
698
+ module = undefined;
699
+ }
700
+ const Database = module?.DatabaseSync ?? module?.Database;
701
+ if (typeof Database !== 'function') {
702
+ throw new TinyactorsError(`SQLiteStore needs the runtime's SQLite (${name}), which this runtime does not have`, {
703
+ status: 'TA_ERROR_UNSUPPORTED',
704
+ });
705
+ }
706
+ return { Database, bun: globalThis.Bun !== undefined };
707
+ }
708
+
709
+ /** A store of hibernated actors' blobs in an SQLite database file, one row
710
+ * per actor in the table tinyactors_blobs (session, blob), through the
711
+ * runtime's own SQLite (node:sqlite, bun:sqlite), synchronously. */
712
+ export class SQLiteStore {
713
+ #insert;
714
+ #select;
715
+ #delete;
716
+
717
+ constructor(path) {
718
+ if (typeof path !== 'string') throw new TypeError('SQLiteStore takes the database file\'s path (":memory:" for none)');
719
+ const { Database, bun } = sqlite();
720
+ const db = new Database(path);
721
+ const run = (sql) => (bun ? db.run(sql) : db.exec(sql));
722
+ run('PRAGMA journal_mode=WAL');
723
+ run('PRAGMA synchronous=NORMAL');
724
+ run('CREATE TABLE IF NOT EXISTS tinyactors_blobs (session INTEGER PRIMARY KEY, blob BLOB NOT NULL)');
725
+ /** The database, for an application that reads the table itself. */
726
+ this.database = db;
727
+ this.#insert = db.prepare('INSERT OR REPLACE INTO tinyactors_blobs VALUES (?, ?)');
728
+ this.#select = db.prepare('SELECT blob FROM tinyactors_blobs WHERE session = ?');
729
+ this.#delete = db.prepare('DELETE FROM tinyactors_blobs WHERE session = ?');
730
+ }
731
+
732
+ save(session, blob) {
733
+ this.#insert.run(signed(session), blob);
734
+ }
735
+
736
+ load(session) {
737
+ const row = this.#select.get(signed(session));
738
+ if (row === undefined || row === null) throw new StaleError(`no blob of actor ${session}`);
739
+ return row.blob;
740
+ }
741
+
742
+ delete(session) {
743
+ this.#delete.run(signed(session));
744
+ }
745
+
746
+ /** Closes the database; the file keeps the blobs saved. */
747
+ close() {
748
+ this.database.close();
749
+ }
750
+ }
751
+
752
+ // ---- Spawner: spawning from a chart ------------------------------------------------
753
+
754
+ /** An I/O processor that spawns actors for charts: give it to the host
755
+ * under a type you name, `ioProcessors: { spawn: new Spawner() }`, and a
756
+ * chart sends `{chart, name, params}` with `<send type="spawn">`. It
757
+ * spawns the chart's current version under the name, and the sender gets
758
+ * `spawned` with `{name, address}` (the new actor's session address) and
759
+ * the send's sendid, or error.communication when the host cannot spawn
760
+ * it. It does not look names up: a name has one owner, the collection
761
+ * actor that spawns it and records the spawns it asked for. */
762
+ export class Spawner {
763
+ receive(send) {
764
+ const data = send.data;
765
+ let actor;
766
+ try {
767
+ if (!plain(data) || typeof data.chart !== 'string') throw new TypeError('a Spawner\'s data is {chart, name, params}');
768
+ actor = send.host.spawn(data.chart, { name: data.name ?? undefined, params: data.params ?? undefined });
769
+ } catch (error) {
770
+ if (error instanceof TinyactorsError || error instanceof TypeError || error instanceof RangeError) {
771
+ send.fail();
772
+ return;
773
+ }
774
+ throw error;
775
+ }
776
+ send.answer('spawned', { name: data.name ?? null, address: actor.address });
777
+ }
778
+ }
779
+
780
+ // ---- a directory of charts ---------------------------------------------------------
781
+
782
+ const UTF8 = new TextDecoder('utf-8', { fatal: true });
783
+
784
+ /** node:fs, node:path and node:url, from the runtime (node, bun); a
785
+ * runtime without them refuses. */
786
+ function builtins(what) {
787
+ const process = globalThis.process;
788
+ if (typeof process?.getBuiltinModule !== 'function') {
789
+ throw new TinyactorsError(`${what} reads files with node:fs, which this runtime does not have`, { status: 'TA_ERROR_UNSUPPORTED' });
790
+ }
791
+ return {
792
+ fs: process.getBuiltinModule('node:fs'),
793
+ path: process.getBuiltinModule('node:path'),
794
+ url: process.getBuiltinModule('node:url'),
795
+ };
796
+ }
797
+
798
+ /** Whether `file`, absolute, is under `root` (`path`: node:path). */
799
+ function inside(path, root, file) {
800
+ const rest = path.relative(root, file);
801
+ return rest !== '' && rest !== '..' && !rest.startsWith(`..${path.sep}`) && !path.isAbsolute(rest);
802
+ }
803
+
804
+ /** Text as UTF-8, refused when it is not. */
805
+ function utf8(bytes, what) {
806
+ try {
807
+ return UTF8.decode(bytes);
808
+ } catch {
809
+ throw new ResolveError(`${what} is not UTF-8`);
810
+ }
811
+ }
812
+
813
+ /** compileDir's resolver: `source` read under `root`, relative to the
814
+ * document `base` that names it, refused when it leaves `root`, symbolic
815
+ * links included. */
816
+ function confined({ fs, path }, top) {
817
+ return function resolve(base, source) {
818
+ const file = path.resolve(top, path.dirname(base), source);
819
+ if (!inside(path, top, file)) throw new ResolveError(`${source} (from ${base}) leaves the charts' directory`);
820
+ let real;
821
+ try {
822
+ real = fs.realpathSync(file);
823
+ } catch (error) {
824
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') throw new ResolveError(`no file ${source} (from ${base}) under the charts' directory`);
825
+ throw error;
826
+ }
827
+ if (!inside(path, top, real)) throw new ResolveError(`${source} (from ${base}) leaves the charts' directory through a symbolic link`);
828
+ if (!fs.statSync(real).isFile()) throw new ResolveError(`${source} (from ${base}) is not a file`);
829
+ return utf8(fs.readFileSync(real), `${source} (from ${base})`);
830
+ };
831
+ }
832
+
833
+ /** compileDir(dir, {resolver}?) -> Compiled: every *.scxml file under the
834
+ * directory `dir` (a path, or a file: URL) compiled into one image, named
835
+ * by its path under it (sorted; the first is the image's default boot
836
+ * chart), a `src` read from under `dir` by a resolver confined to it. */
837
+ export function compileDir(dir, options) {
838
+ if (options !== undefined) {
839
+ if (!plain(options)) throw new TypeError('compileDir\'s options are an object: {resolver}');
840
+ onlyKnown(options, new Set(['resolver']), 'compileDir option');
841
+ }
842
+ const modules = builtins('compileDir');
843
+ const { fs, path, url } = modules;
844
+ const given = dir instanceof URL || (typeof dir === 'string' && dir.startsWith('file:')) ? url.fileURLToPath(dir) : dir;
845
+ if (typeof given !== 'string') throw new TypeError('compileDir takes a directory: a path or a file: URL');
846
+ const top = fs.realpathSync(given);
847
+ if (!fs.statSync(top).isDirectory()) throw new InvalidError(`compileDir takes a directory: ${given} is not one`);
848
+ const files = [];
849
+ const walk = (directory) => {
850
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
851
+ const full = path.join(directory, entry.name);
852
+ if (entry.isDirectory()) walk(full);
853
+ else if (entry.name.endsWith('.scxml') && (entry.isFile() || entry.isSymbolicLink())) files.push(full);
854
+ }
855
+ };
856
+ walk(top);
857
+ const sources = [];
858
+ for (const file of files) {
859
+ const real = fs.realpathSync(file);
860
+ if (!fs.statSync(real).isFile()) continue;
861
+ if (!inside(path, top, real)) throw new InvalidError(`the chart ${file} leaves ${top}`);
862
+ const name = path.relative(top, file).split(path.sep).join('/');
863
+ sources.push({ name, text: utf8(fs.readFileSync(real), name) });
864
+ }
865
+ if (sources.length === 0) throw new InvalidError(`no *.scxml file under ${top}`);
866
+ sources.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
867
+ return compileCharts(sources, { resolver: options?.resolver ?? confined(modules, top) });
868
+ }
869
+
870
+ // ---- Address ---------------------------------------------------------------------------
871
+
872
+ // Address.prototype.toJSON: its text, so JSON.stringify writes an address
873
+ // as the string an Address is made from (new Address(text) reads it back).
874
+ method(Address.prototype, 'toJSON', function () {
875
+ return this.text;
876
+ });