@tinyactors/wasm 0.0.0-stage → 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.
@@ -0,0 +1,1341 @@
1
+ // The native "ecmascript" datamodel of @tinyactors/wasm (docs/browser.md,
2
+ // "The native datamodel without node:vm"; the addon's src/datamodel/,
3
+ // translated): the vtable's entries, which wasm/src/datamodel.c forwards
4
+ // to the import ta_web.datamodel, done in JavaScript with the host's realm
5
+ // (realms.mjs) and the realm's script (the addon's src/datamodel/realm.js).
6
+ //
7
+ // Rows are the host's tables in C (charts, sessions, payloads, loops); the
8
+ // value of each is at its row's slot in an array of this file's: a
9
+ // chart's record, a session's scope or declaring session, a payload's
10
+ // value, a loop's items.
11
+ //
12
+ // Where a chart evaluates (decision M2):
13
+ //
14
+ // - a chart whose scripts declare nothing at their top level (and whose
15
+ // scripts of executable content declare no var): a scope object per
16
+ // session, made by the chart's constructor in the host's realm, and
17
+ // each expression one function of the scope, compiled at its first
18
+ // evaluation, sloppy outside (`with (scope)`) and strict inside: the
19
+ // addon's code path;
20
+ // - a declaring chart: one session function per chart, made at attach
21
+ // from its chart-level scripts' text with the realm's Function (the
22
+ // engine compiles it; no parser of ours), a generator called once per
23
+ // session, whose bindings are the session's: its `var`, `function`,
24
+ // `let`, `const` and `class` declarations, the <data> ids, the names a
25
+ // <foreach> binds and the vars its scripts of executable content
26
+ // declare. It stops before each chart-level script and after the last
27
+ // one, and at each stop runs the session's evaluations as direct evals
28
+ // in its own scope, so closures and lexical bindings work as in the
29
+ // addon's context per session, at a few hundred bytes a session.
30
+ //
31
+ // Which kind a chart is, and the names it declares, is asked of the engine
32
+ // at attach: a candidate name (an identifier of the script's text) is
33
+ // declared when the script followed by `let <name>` does not parse, and
34
+ // declared lexically when the script followed by `var <name>` does not
35
+ // either. Where the session function cannot do what the addon's context
36
+ // does, it refuses at attach or reports, never differs silently:
37
+ // declaring `eval`, `arguments` or a `__tinyactors_` name, a chart-level
38
+ // script with a 'use strict' directive, or a strict script of executable
39
+ // content that declares a var, refuse the chart; a chart-level script that
40
+ // throws stops the ones after it (the session's error.execution says so);
41
+ // an undeclared assignment in a sloppy script lands on the host's realm,
42
+ // and hibernation and snapshots refuse naming it.
43
+ import * as cbor from './cbor.mjs';
44
+ import { TinyactorsError } from './errors.mjs';
45
+ import { application, makeRealm } from './realms.mjs';
46
+
47
+ // The entries (wasm/src/datamodel.c).
48
+ const DM = {
49
+ ATTACH: 1, DETACH: 2, CREATE: 3, DESERIALIZE: 4, DESTROY: 5, INIT_DATA: 6, BIND_EVENT: 7, DETACH_EVENT: 8,
50
+ EVAL_CONDITION: 9, EVAL_STRING: 10, ASSIGN: 11, ASSIGN_STRING: 12, SCRIPT: 13, LOG: 14, FOREACH_BEGIN: 15,
51
+ FOREACH_ITEM: 16, FOREACH_END: 17, CAPTURE: 18, DROP: 19, CUSTOM: 20, SERIALIZE: 21, MIGRATE: 22, TO_WIRE: 23,
52
+ FROM_WIRE: 24, PAYLOAD_SERIALIZE: 25, PAYLOAD_DESERIALIZE: 26, VARIABLE: 27, FAILURE: 28,
53
+ };
54
+ const TA_OK = 0, TA_ERROR_EXECUTION = -1, TA_ERROR_INVALID = -3, TA_ERROR_NO_MEMORY = -4, TA_ERROR_STALE = -5;
55
+ const TA_ERROR_STATE = -6, TA_ERROR_UNSUPPORTED = -7;
56
+ const NIL = 0xFFFFFFFF;
57
+ const FAILURE_NONE = 0, FAILURE_EXCEPTION = 1;
58
+ // TA_EXPRESSION_* (tinyactors/image.h)
59
+ const KIND = { CONDITION: 1, VALUE: 2, LOCATION: 3, SCRIPT: 4, STRING: 5, CONTENT: 6, ITEM: 7, GLOBAL_SCRIPT: 8 };
60
+ const TYPES = ['platform', 'internal', 'external'];
61
+ const EVENT_FIELDS = ['name', 'type', 'sendid', 'origin', 'origintype', 'invokeid', 'data', 'raw'];
62
+ const PREFIX = '__tinyactors_';
63
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
64
+ // Candidate names of a script: what may be an identifier in its text.
65
+ const CANDIDATES = /[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*/gu;
66
+ const SPACE = /[ \t\n\r]/;
67
+
68
+ // The shapes an expression is compiled in (the addon's expressions.c).
69
+ const SHARED_VALUE = ["(function(__s){with(__s){return (function(){'use strict';return (\n", "\n);})();}})"];
70
+ const SHARED_SCRIPT = ["(function(__s){with(__s){(function(){'use strict';\n", '\n})();}})'];
71
+ const SHARED_SETTER = ["(function(__s,__v){with(__s){(function(){'use strict';(\n", '\n) = __v;})();}})'];
72
+ const OWN_VALUE = ["(function(){'use strict';return (\n", '\n);})'];
73
+ const OWN_SETTER = ["(function(__tinyactors_v){'use strict';(\n", '\n) = __tinyactors_v;})'];
74
+
75
+ const encoder = new TextEncoder();
76
+
77
+ function strictDirective(source) {
78
+ const match = /^[ \t\n\r]*(['"])use strict\1/.exec(source);
79
+ return match !== null;
80
+ }
81
+
82
+ // A value's source without a trailing `;` (expr="new Foo();").
83
+ function trimmed(source) {
84
+ let end = source.length;
85
+ while (end > 0 && (source[end - 1] === ';' || SPACE.test(source[end - 1]))) end--;
86
+ return source.slice(0, end);
87
+ }
88
+
89
+ // The identifier a location starts with (ASCII; empty for anything else).
90
+ function leadingName(source) {
91
+ const match = /^[ \t\n\r]*([A-Za-z_$][A-Za-z0-9_$]*)/.exec(source);
92
+ return match === null ? '' : match[1];
93
+ }
94
+
95
+ function trim(text) { return text.replace(/^[ \t\n\r]+|[ \t\n\r]+$/g, ''); }
96
+
97
+ // A refusal the datamodel answers core with, carrying its status.
98
+ class Refused extends Error {
99
+ constructor(status, message) {
100
+ super(message);
101
+ this.status = status;
102
+ }
103
+ }
104
+
105
+ // ---- a declaring chart's session function ------------------------------------------------------
106
+
107
+ // One stop of the session's generator: it runs each evaluation it is given
108
+ // as a direct eval in the generator's own scope, until it is told to go on
109
+ // to the next chart-level script.
110
+ const STOP = 'for (;;) { __tinyactors_in = yield __tinyactors_out; if (__tinyactors_in === __tinyactors_session.next) break; ' +
111
+ 'try { __tinyactors_out = [true, eval(__tinyactors_in)]; } catch (__tinyactors_e) { __tinyactors_out = [false, __tinyactors_e]; } }';
112
+
113
+ // The factory of a declaring chart's sessions: called with a session's
114
+ // scope (its system variables and _event, read through `with`), it answers
115
+ // the session's generator function.
116
+ function factorySource({ vars, names, scripts }) {
117
+ const cases = names.map((name) => `case ${JSON.stringify(name)}: `);
118
+ const get = names.map((name, i) => `${cases[i]}return ${name};`).join(' ');
119
+ const set = names.map((name, i) => `${cases[i]}${name} = __tinyactors_v; return true;`).join(' ');
120
+ const body = [
121
+ 'let arguments;',
122
+ vars.length ? `var ${vars.join(', ')};` : '',
123
+ `function __tinyactors_get(__tinyactors_n) { switch (__tinyactors_n) { ${get} } return __tinyactors_session.none; }`,
124
+ `function __tinyactors_set(__tinyactors_n, __tinyactors_v) { switch (__tinyactors_n) { ${set} } return false; }`,
125
+ 'function* __tinyactors_loop() { var __tinyactors_in = yield; for (;;) { var __tinyactors_out; ' +
126
+ 'try { __tinyactors_out = [true, eval(__tinyactors_in)]; } catch (__tinyactors_e) { __tinyactors_out = [false, __tinyactors_e]; } ' +
127
+ '__tinyactors_in = yield __tinyactors_out; } }',
128
+ '__tinyactors_session.get = __tinyactors_get; __tinyactors_session.set = __tinyactors_set;',
129
+ '__tinyactors_session.loop = __tinyactors_loop(); __tinyactors_session.loop.next();',
130
+ 'var __tinyactors_in, __tinyactors_out;',
131
+ STOP,
132
+ ];
133
+ for (const script of scripts) body.push(script, STOP);
134
+ return `with (__tinyactors_system) return function* (__tinyactors_session) {\n${body.join('\n')}\n};`;
135
+ }
136
+
137
+ // A declaring session: its scope (the system variables and _event, read
138
+ // through `with`), its generator, and the handle the generator fills (get,
139
+ // set, and the loop it runs on after a chart-level script threw).
140
+ class Declaring {
141
+ constructor(scope, handle, generator) {
142
+ this.scope = scope;
143
+ this.handle = handle;
144
+ this.generator = generator;
145
+ this.stop = 0;
146
+ this.dead = false;
147
+ this.getters = undefined;
148
+ this.setters = undefined;
149
+ this.odd = undefined;
150
+ }
151
+ }
152
+
153
+ // ---- the datamodel -----------------------------------------------------------------------------
154
+
155
+ export class NativeDatamodel {
156
+ constructor(state) {
157
+ this.state = state;
158
+ this.module = state.module;
159
+ this.fn = state.fn;
160
+ this.realm = null;
161
+ this.charts = [];
162
+ this.sessions = [];
163
+ // per session slot: its chart's slot and core's ids of its _event's name, invoke and origintype
164
+ this.meta = new Uint32Array(64);
165
+ this.values = [];
166
+ this.loops = [];
167
+ this.strings = null;
168
+ this.failed = false;
169
+ this.message = '';
170
+ this.evaluating = -1; // the chart slot of the session evaluating, for In()
171
+ this.current = -1; // the slot of the session evaluating
172
+ this.attachError = null; // why the last chart was refused at attach
173
+ }
174
+
175
+ // The host's pointer and arena: during the host's making (a restore
176
+ // attaches its charts) JavaScript has neither yet.
177
+ get pointer() { return this.state.pointer || (this.fn.ta_web_host_making(this.module.env) >>> 0); }
178
+ get scratch() { return this.state.scratch || (this.fn.ta_web_host_scratch(this.pointer) >>> 0); }
179
+
180
+ // ---- the realm ----
181
+
182
+ kit() { return this.ensureRealm().kit; }
183
+
184
+ ensureRealm() {
185
+ if (this.realm === null) this.realm = makeRealm((state) => this.in(state));
186
+ return this.realm;
187
+ }
188
+
189
+ free() {
190
+ const realm = this.realm;
191
+ this.realm = null;
192
+ this.charts = [];
193
+ this.sessions = [];
194
+ this.values = [];
195
+ this.loops = [];
196
+ realm?.free();
197
+ }
198
+
199
+ // SCXML In() of the evaluating session (5.9.1).
200
+ in(state) {
201
+ if (this.evaluating < 0 || this.pointer === 0) return false;
202
+ const name = `${state}`;
203
+ const module = this.module;
204
+ return module.scoped(this.scratch, () => {
205
+ const [at, length] = module.text(this.scratch, name);
206
+ module.setWord(0, at);
207
+ module.setWord(1, length);
208
+ const index = this.fn.ta_web_chart_state(this.pointer, this.evaluating) >>> 0;
209
+ return index !== NIL && this.fn.ta_web_dm_in(this.pointer, index) !== 0;
210
+ });
211
+ }
212
+
213
+ // ---- the record and the output ----
214
+
215
+ words(n) { return this.module.words().slice(this.module.record, this.module.record + n); }
216
+
217
+ text(pointer, length) { return this.module.string(pointer >>> 0, length); }
218
+
219
+ // The output room of at least `size` bytes: its address.
220
+ room(size) {
221
+ const at = this.fn.ta_web_dm_output(this.pointer, size) >>> 0;
222
+ if (at === 0) throw new Refused(TA_ERROR_NO_MEMORY, 'no memory for the datamodel\'s output');
223
+ return at;
224
+ }
225
+
226
+ // A string in the output room; its length in the record's word 0.
227
+ putText(text) {
228
+ const at = this.room(3 * text.length + 1);
229
+ const { written } = encoder.encodeInto(text, this.module.bytes().subarray(at, at + 3 * text.length + 1));
230
+ this.module.setWord(0, written);
231
+ }
232
+
233
+ // Bytes at [pointer, length] of linear memory copied into the output room;
234
+ // the length in the record's word 0.
235
+ putBytes(pointer, length) {
236
+ const at = this.room(length || 1);
237
+ const bytes = this.module.bytes();
238
+ bytes.copyWithin(at, pointer, pointer + length);
239
+ this.module.setWord(0, length);
240
+ }
241
+
242
+ // `value` as CBOR (the value table's, or to_wire's with `wire`) in the
243
+ // output room.
244
+ putValue(value, wire) {
245
+ const module = this.module, scratch = this.scratch;
246
+ module.scoped(scratch, () => {
247
+ const [at, length] = cbor.write(module, scratch, value, { realms: true, wire });
248
+ this.putBytes(at, length);
249
+ });
250
+ }
251
+
252
+ // The value of the CBOR at [pointer, length], made in the application's realm.
253
+ readValue(pointer, length) {
254
+ const module = this.module;
255
+ return cbor.read(module, this.scratch, pointer, length);
256
+ }
257
+
258
+ // ---- the import ----
259
+
260
+ // One entry, as the import ta_web.datamodel gives it: its status. What it
261
+ // throws is its error.execution (kept for `failure`), or the refusal's
262
+ // status.
263
+ entry(entry, slot) {
264
+ if (entry === DM.FAILURE) return this.failure();
265
+ if (entry === DM.DROP) {
266
+ this.values[slot] = undefined;
267
+ return TA_OK;
268
+ }
269
+ this.failed = false;
270
+ const outer = this.evaluating, current = this.current;
271
+ try {
272
+ return this.dispatch(entry, slot) ?? TA_OK;
273
+ } catch (error) {
274
+ if (error instanceof Refused) {
275
+ if (error.reason !== undefined) this.state.reason = error.reason;
276
+ if (entry === DM.ATTACH) this.attachError = error.message;
277
+ return error.status;
278
+ }
279
+ this.fail(error);
280
+ if (entry === DM.ATTACH) this.attachError = this.message;
281
+ return entry === DM.ATTACH ? TA_ERROR_INVALID : TA_ERROR_EXECUTION;
282
+ } finally {
283
+ this.evaluating = outer;
284
+ this.current = current;
285
+ }
286
+ }
287
+
288
+ fail(error) {
289
+ this.failed = true;
290
+ try {
291
+ this.message = String(error);
292
+ } catch {
293
+ this.message = '';
294
+ }
295
+ }
296
+
297
+ failure() {
298
+ if (!this.failed) {
299
+ this.module.setWord(0, FAILURE_NONE);
300
+ return TA_OK;
301
+ }
302
+ this.failed = false;
303
+ this.putText(this.message);
304
+ const length = this.module.word(0);
305
+ this.module.setWord(0, FAILURE_EXCEPTION);
306
+ this.module.setWord(1, length);
307
+ return TA_OK;
308
+ }
309
+
310
+ dispatch(entry, slot) {
311
+ switch (entry) {
312
+ case DM.ATTACH: return this.attach(slot);
313
+ case DM.DETACH: this.charts[slot] = undefined; return TA_OK;
314
+ case DM.CREATE: return this.create(slot);
315
+ case DM.DESERIALIZE: return this.deserialize(slot);
316
+ case DM.DESTROY: this.sessions[slot] = undefined; return TA_OK;
317
+ case DM.INIT_DATA: return this.initData(slot);
318
+ case DM.BIND_EVENT: return this.bindEvent(slot);
319
+ case DM.DETACH_EVENT: return TA_OK; // SCXML keeps _event bound to the last event (5.10)
320
+ case DM.EVAL_CONDITION: {
321
+ const e = this.module.word(0);
322
+ const value = this.evaluate(this.session(slot, true), e);
323
+ this.module.setWord(0, value ? 1 : 0);
324
+ return TA_OK;
325
+ }
326
+ case DM.EVAL_STRING: {
327
+ const e = this.module.word(0);
328
+ this.putText(`${this.evaluate(this.session(slot, true), e)}`);
329
+ return TA_OK;
330
+ }
331
+ case DM.ASSIGN: {
332
+ const [location, e] = this.words(2);
333
+ const session = this.session(slot, true);
334
+ this.assign(session, location, this.evaluate(session, e));
335
+ return TA_OK;
336
+ }
337
+ case DM.ASSIGN_STRING: {
338
+ const [location, at, length] = this.words(3);
339
+ const text = this.text(at, length);
340
+ this.assign(this.session(slot, true), location, text);
341
+ return TA_OK;
342
+ }
343
+ case DM.SCRIPT: {
344
+ const e = this.module.word(0);
345
+ this.evaluate(this.session(slot, true), e);
346
+ return TA_OK;
347
+ }
348
+ case DM.LOG: return this.log(slot);
349
+ case DM.FOREACH_BEGIN: return this.foreachBegin(slot);
350
+ case DM.FOREACH_ITEM: return this.foreachItem(slot);
351
+ case DM.FOREACH_END: this.loops[this.module.word(0)] = undefined; return TA_OK;
352
+ case DM.CAPTURE: return this.capture(slot);
353
+ case DM.CUSTOM: return TA_ERROR_UNSUPPORTED;
354
+ case DM.SERIALIZE: return this.serialize(slot);
355
+ case DM.MIGRATE: return this.migrate(slot);
356
+ case DM.TO_WIRE: return this.payloadOut(slot, true);
357
+ case DM.PAYLOAD_SERIALIZE: return this.payloadOut(slot, false);
358
+ case DM.FROM_WIRE:
359
+ case DM.PAYLOAD_DESERIALIZE: return this.fromWire(slot);
360
+ case DM.VARIABLE: return this.variable(slot);
361
+ default: return TA_ERROR_UNSUPPORTED;
362
+ }
363
+ }
364
+
365
+ // ---- charts ----
366
+
367
+ // Expression `e` of the chart at `slot`, from the image: {kind, line, column, source}.
368
+ expressionOf(chart, e) {
369
+ let info = chart.expressions[e];
370
+ if (info !== undefined) return info;
371
+ const status = this.fn.ta_web_chart_expression(this.pointer, chart.slot, e);
372
+ const w = this.words(6);
373
+ info = status === TA_OK ? { kind: w[1], line: w[2], column: w[3], source: this.text(w[4], w[5]) } : null;
374
+ chart.expressions[e] = info;
375
+ return info;
376
+ }
377
+
378
+ attach(slot) {
379
+ const [index, segment, binding] = this.words(3);
380
+ const realm = this.ensureRealm();
381
+ const chart = {
382
+ slot, index, segment, binding, expressions: [], getters: [], setters: [], names: [], invokeids: [], origins: [],
383
+ leading: [], declaring: null, Scope: undefined, data: [],
384
+ };
385
+ const pointer = this.pointer;
386
+ const dataCount = this.fn.ta_web_chart_data_count(pointer, slot);
387
+ for (let i = 0; i < dataCount; i++) {
388
+ if (this.fn.ta_web_chart_data(pointer, slot, i) !== TA_OK) continue;
389
+ const w = this.words(5);
390
+ chart.data.push({ id: this.text(w[1], w[2]), expression: w[3] });
391
+ }
392
+ const count = this.fn.ta_web_chart_expression_count(pointer, slot);
393
+ const names = chart.data.map((d) => d.id);
394
+ const scripts = [];
395
+ for (let e = 0; e < count; e++) {
396
+ const info = this.expressionOf(chart, e);
397
+ if (info === null) continue;
398
+ if (info.kind === KIND.ITEM) {
399
+ const item = trim(info.source);
400
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(item) && !names.includes(item)) names.push(item);
401
+ } else if (info.kind === KIND.SCRIPT || info.kind === KIND.GLOBAL_SCRIPT) scripts.push([e, info]);
402
+ }
403
+ chart.declaring = this.declares(chart, scripts, names);
404
+ if (chart.declaring === null) chart.Scope = realm.kit.shape(names);
405
+ chart.scopeNames = names;
406
+ this.charts[slot] = chart;
407
+ return TA_OK;
408
+ }
409
+
410
+ // Whether `source` parses as a function body of the realm, nothing run.
411
+ parses(source) {
412
+ try {
413
+ new this.realm.Function(source); // eslint-disable-line no-new
414
+ return true;
415
+ } catch (error) {
416
+ if (error instanceof this.realm.global.SyntaxError) return false;
417
+ throw error;
418
+ }
419
+ }
420
+
421
+ // A declaring chart's session function and what it declares, or null for
422
+ // a chart that declares nothing (the shared path). Throws a Refused for
423
+ // a chart it cannot run as the addon does.
424
+ declares(chart, scripts, names) {
425
+ const global = []; // [e, source] of the chart-level scripts that parse
426
+ const lexical = new Set(), declared = new Set(), execVars = new Set();
427
+ let refused = null;
428
+ const refuse = (message) => {
429
+ if (refused === null) refused = message;
430
+ };
431
+ for (const [e, info] of scripts) {
432
+ const source = info.source;
433
+ const top = info.kind === KIND.GLOBAL_SCRIPT;
434
+ const strict = strictDirective(source);
435
+ const run = top ? `\n${source}` : `${strict ? '\'use strict\';' : ''}{\n${source}\n}`;
436
+ if (!this.parses(run)) continue; // a syntax error: that evaluation's error.execution
437
+ const candidates = new Set(source.match(CANDIDATES) ?? []);
438
+ for (const name of candidates) {
439
+ if (!this.parses(`let ${name};`) && name !== 'eval' && name !== 'arguments') continue; // not a binding name
440
+ if (this.parses(`${run}\n;let ${name};`)) continue; // not declared at the function's level
441
+ if (name === 'eval' || name === 'arguments' || name.startsWith(PREFIX)) {
442
+ refuse(`the chart's scripts declare ${name}, which @tinyactors/wasm's native datamodel cannot give a session ` +
443
+ '(it runs each session\'s evaluations through a direct eval): rename it');
444
+ continue;
445
+ }
446
+ if (top) {
447
+ declared.add(name);
448
+ if (!this.parses(`${run}\n;var ${name};`)) lexical.add(name);
449
+ } else if (strict) {
450
+ refuse(`a script of executable content that starts with 'use strict' declares var ${name}, which ` +
451
+ '@tinyactors/wasm\'s native datamodel cannot keep between its runs: declare it in a <data> or a chart-level script');
452
+ } else execVars.add(name);
453
+ }
454
+ if (top) {
455
+ if (strict && candidates.size > 0) {
456
+ refuse('a chart-level script starts with \'use strict\', which @tinyactors/wasm\'s native datamodel cannot keep ' +
457
+ 'for it alone (its chart-level scripts are one function\'s body): leave the directive out');
458
+ }
459
+ global.push([e, source]);
460
+ }
461
+ }
462
+ if (refused === null && declared.size === 0 && execVars.size === 0) return null;
463
+ if (refused !== null) throw new Refused(TA_ERROR_INVALID, refused);
464
+ const valid = (name) => IDENTIFIER.test(name) || /^[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*$/u.test(name);
465
+ const vars = [...new Set([...names.filter(valid), ...execVars])].filter((name) => !lexical.has(name));
466
+ for (const name of vars) {
467
+ if (name === 'eval' || name === 'arguments' || name.startsWith(PREFIX)) {
468
+ throw new Refused(TA_ERROR_INVALID, `the chart declares ${name} (a <data> or a <foreach>), which @tinyactors/wasm's ` +
469
+ 'native datamodel cannot give a session: rename it');
470
+ }
471
+ }
472
+ const all = [...new Set([...vars, ...declared])];
473
+ let factory;
474
+ try {
475
+ factory = this.realm.Function('__tinyactors_system', factorySource({ vars, names: all, scripts: global.map(([, s]) => s) }));
476
+ } catch (error) {
477
+ throw new Refused(TA_ERROR_INVALID, `the chart's scripts cannot be one session function: ${error}`);
478
+ }
479
+ const stops = new Map(global.map(([e], k) => [e, k + 1]));
480
+ const record = {
481
+ factory, stops, lexical: lexical.size > 0, declared: new Set([...all, ...names]), stored: all,
482
+ remade: new Set(), odd: names.filter((name) => !valid(name)),
483
+ };
484
+ // the names a fresh session holds a function in: its function declarations, made again at a wake
485
+ const probe = this.startDeclaring(record, this.ensureRealm().kit.system('', '', []));
486
+ for (const name of all) {
487
+ let value;
488
+ try {
489
+ value = probe.handle.get(name);
490
+ } catch {
491
+ continue; // in its TDZ: a lexical binding
492
+ }
493
+ if (typeof value === 'function') record.remade.add(name);
494
+ }
495
+ return record;
496
+ }
497
+
498
+ // ---- sessions ----
499
+
500
+ // The session at `slot` (its scope, or its declaring record), with the
501
+ // evaluating chart set for In() and, with `charge`, a fuel unit charged.
502
+ session(slot, charge) {
503
+ const session = this.sessions[slot];
504
+ if (session === undefined) throw new Refused(TA_ERROR_STALE, 'no such session');
505
+ this.evaluating = this.meta[4 * slot];
506
+ this.current = slot;
507
+ if (charge) this.fn.ta_web_dm_charge(this.pointer, 1);
508
+ return session;
509
+ }
510
+
511
+ chartOf(slot) { return this.charts[this.meta[4 * slot]]; }
512
+
513
+ grow(slot) {
514
+ if (4 * slot + 4 <= this.meta.length) return;
515
+ let length = this.meta.length;
516
+ while (length < 4 * slot + 4) length *= 2;
517
+ const meta = new Uint32Array(length);
518
+ meta.set(this.meta);
519
+ this.meta = meta;
520
+ }
521
+
522
+ // The strings of _event the datamodel keeps: the three types, then the
523
+ // I/O processors' types (every session of a host has the same ones).
524
+ keepStrings(types) {
525
+ if (this.strings !== null) return;
526
+ this.strings = [...TYPES, ...types];
527
+ }
528
+
529
+ // The start's system variables: [sessionid, name, processors].
530
+ systemOf(words) {
531
+ const pointer = this.pointer;
532
+ const sessionid = this.text(words[3], words[4]), name = this.text(words[5], words[6]);
533
+ const processors = [];
534
+ for (let i = 0; i < words[7]; i++) {
535
+ this.fn.ta_web_dm_processor(pointer, i);
536
+ const w = this.words(4);
537
+ processors.push([this.text(w[0], w[1]), this.text(w[2], w[3])]);
538
+ }
539
+ return [sessionid, name, processors];
540
+ }
541
+
542
+ // A declaring session: its scope (the system variables and _event), its
543
+ // generator at its first stop, and the handle the generator fills (get,
544
+ // set, the loop after a chart-level script threw).
545
+ startDeclaring(record, link) {
546
+ const kit = this.realm.kit;
547
+ const scope = new (record.Shape ??= kit.shape([]))(link);
548
+ const handle = { next: record.next ??= Object.freeze({}), none: undefined, value: undefined, get: null, set: null, loop: null };
549
+ const generator = record.factory(scope)(handle);
550
+ generator.next();
551
+ return new Declaring(scope, handle, generator);
552
+ }
553
+
554
+ // Runs `code` as a direct eval in the declaring session's scope: its value.
555
+ run(session, code) {
556
+ const answer = session.dead ? session.handle.loop.next(code).value : session.generator.next(code).value;
557
+ if (!answer[0]) throw answer[1];
558
+ return answer[1];
559
+ }
560
+
561
+ make(slot, chart, link, init) {
562
+ if (chart.declaring === null) {
563
+ link.init = init;
564
+ return new chart.Scope(link);
565
+ }
566
+ if (init !== undefined) init = this.realm.kit.copy(init);
567
+ link.init = init;
568
+ return this.startDeclaring(chart.declaring, link);
569
+ }
570
+
571
+ create(slot) {
572
+ const words = this.words(8);
573
+ const init = (BigInt(words[1]) | (BigInt(words[2]) << 32n));
574
+ const chart = this.charts[words[0]];
575
+ const value = init !== 0n ? this.values[Number(init & 0xFFFFFFFFn) - 1] : undefined;
576
+ if (init !== 0n) this.fn.ta_web_payload_drop(this.pointer, words[1], words[2]); // the init's reference is ours
577
+ if (chart === undefined) throw new Refused(TA_ERROR_INVALID, 'no such chart');
578
+ const system = this.systemOf(words);
579
+ this.keepStrings(system[2].map(([type]) => type));
580
+ const link = this.realm.kit.system(...system);
581
+ const session = this.make(slot, chart, link, value);
582
+ this.grow(slot);
583
+ this.meta.set([words[0], NIL, NIL, NIL], 4 * slot);
584
+ this.sessions[slot] = session;
585
+ return TA_OK;
586
+ }
587
+
588
+ // The scope a session's _event and link are on.
589
+ scopeOf(session) { return session instanceof Declaring ? session.scope : session; }
590
+
591
+ linkOf(session) { return this.scopeOf(session)[this.realm.kit.LINK]; }
592
+
593
+ initData(slot) {
594
+ const declaration = this.module.word(0);
595
+ const session = this.session(slot, true);
596
+ const chart = this.chartOf(slot);
597
+ const data = chart.data[declaration];
598
+ if (data === undefined) throw new Error('no such <data>');
599
+ const init = this.linkOf(session).init;
600
+ let value;
601
+ if (init !== null && typeof init === 'object' && Object.hasOwn(init, data.id)) value = init[data.id];
602
+ else if (data.expression !== NIL) value = this.evaluate(session, data.expression);
603
+ this.setVariable(session, data.id, value);
604
+ return TA_OK;
605
+ }
606
+
607
+ setVariable(session, name, value) {
608
+ if (!(session instanceof Declaring)) {
609
+ session[name] = value;
610
+ return;
611
+ }
612
+ if (!session.handle.set(name, value)) (session.odd ??= {})[name] = value;
613
+ }
614
+
615
+ getVariable(session, name) {
616
+ if (!(session instanceof Declaring)) return session[name];
617
+ if (session.odd !== undefined && Object.hasOwn(session.odd, name)) return session.odd[name];
618
+ return session.handle.get(name);
619
+ }
620
+
621
+ // ---- _event ----
622
+
623
+ // The string of `text` kept at `index` of a chart's list: the one there
624
+ // when its text is the same, else a new one, kept when the place was empty.
625
+ kept(list, index, text) {
626
+ if (index === NIL) return text;
627
+ const kept = list[index];
628
+ if (kept === text) return kept;
629
+ if (kept === undefined) list[index] = text;
630
+ return text;
631
+ }
632
+
633
+ bindEvent(slot) {
634
+ const w = this.words(18);
635
+ const session = this.session(slot, true);
636
+ const chart = this.chartOf(slot);
637
+ const optional = (at) => (w[at + 1] === 0 ? undefined : this.text(w[at], w[at + 1]));
638
+ const strings = this.strings ?? TYPES;
639
+ const data = (BigInt(w[14]) | (BigInt(w[15]) << 32n));
640
+ const fields = [
641
+ this.kept(chart.names, w[1], this.text(w[4], w[5])),
642
+ strings[w[0] % 3],
643
+ optional(6),
644
+ w[9] ? this.kept(chart.origins, w[2], this.text(w[8], w[9])) : undefined,
645
+ w[11] === 0 ? undefined : w[3] !== NIL ? this.kept(strings, 3 + w[3], this.text(w[10], w[11])) : this.text(w[10], w[11]),
646
+ w[13] ? this.kept(chart.invokeids, w[2], this.text(w[12], w[13])) : undefined,
647
+ data !== 0n ? this.values[Number(data & 0xFFFFFFFFn) - 1] : undefined,
648
+ optional(16),
649
+ ];
650
+ const event = this.realm.kit.event(fields);
651
+ const scope = this.scopeOf(session);
652
+ Object.defineProperty(scope, '_event', { value: event, enumerable: true, configurable: true, writable: false });
653
+ scope[this.realm.kit.LINK].init = undefined; // an event has come: the params were read by init_data
654
+ this.meta[4 * slot + 1] = w[1];
655
+ this.meta[4 * slot + 2] = w[2];
656
+ this.meta[4 * slot + 3] = w[3];
657
+ return TA_OK;
658
+ }
659
+
660
+ // ---- evaluations ----
661
+
662
+ evaluate(session, e) {
663
+ const chart = this.chartOf(this.current);
664
+ const info = this.expressionOf(chart, e);
665
+ if (info === null) throw new Error('no such expression');
666
+ if (info.kind === KIND.CONTENT) return this.content(info.source);
667
+ const script = info.kind === KIND.SCRIPT || info.kind === KIND.GLOBAL_SCRIPT;
668
+ if (chart.declaring === null) {
669
+ const shape = script ? SHARED_SCRIPT : SHARED_VALUE;
670
+ const fn = this.compiled(chart.getters, e, () => shape[0] + (script ? info.source : trimmed(info.source)) + shape[1]);
671
+ return fn(session);
672
+ }
673
+ if (info.kind === KIND.GLOBAL_SCRIPT) return this.chartScript(session, chart, e, info);
674
+ if (info.kind === KIND.SCRIPT) {
675
+ const source = info.source;
676
+ return this.run(session, strictDirective(source) ? `'use strict';{\n${source}\n}` : `{\n${source}\n}`);
677
+ }
678
+ const getters = session.getters ??= [];
679
+ let fn = getters[e];
680
+ if (fn === undefined) {
681
+ fn = this.run(session, OWN_VALUE[0] + trimmed(info.source) + OWN_VALUE[1]);
682
+ getters[e] = fn;
683
+ }
684
+ return fn();
685
+ }
686
+
687
+ // The compiled function of `e` in `cache`, compiled in the realm at its
688
+ // first use; null kept when it did not compile, so it is not compiled again.
689
+ compiled(cache, e, source) {
690
+ const kept = cache[e];
691
+ if (kept === null) throw new this.realm.global.Error('the expression did not compile');
692
+ if (kept !== undefined) return kept;
693
+ let made;
694
+ try {
695
+ made = this.realm.evaluate(source(), `<expr:${e}>`);
696
+ } catch (error) {
697
+ cache[e] = null;
698
+ throw error;
699
+ }
700
+ cache[e] = made;
701
+ return made;
702
+ }
703
+
704
+ // A declaring session's chart-level script `e`: the generator goes on to
705
+ // the stop after it. One that does not parse is its own error.execution;
706
+ // one that throws ends the session function, so the scripts after it do
707
+ // not run (the addon runs them in its context per session): its error
708
+ // says so, and the session goes on through its loop.
709
+ chartScript(session, chart, e, info) {
710
+ const stop = chart.declaring.stops.get(e);
711
+ if (stop === undefined) {
712
+ new this.realm.Function(`\n${info.source}`); // eslint-disable-line no-new
713
+ return undefined;
714
+ }
715
+ if (session.dead || session.stop >= stop) return undefined; // run already (a restored session: never)
716
+ while (session.stop < stop) {
717
+ session.stop++;
718
+ try {
719
+ session.generator.next(session.handle.next);
720
+ } catch (error) {
721
+ session.dead = true;
722
+ const later = chart.declaring.stops.size > stop;
723
+ if (later && error !== null && typeof error === 'object') {
724
+ try {
725
+ error.message = `${error.message} (the chart-level scripts after this one did not run: in ` +
726
+ '@tinyactors/wasm a chart\'s chart-level scripts are one function\'s body)';
727
+ } catch {
728
+ // a frozen error keeps its message
729
+ }
730
+ }
731
+ throw error;
732
+ }
733
+ }
734
+ return undefined;
735
+ }
736
+
737
+ assign(session, location, value) {
738
+ const chart = this.chartOf(this.current);
739
+ const info = this.expressionOf(chart, location);
740
+ if (info === null) throw new Error('no such location');
741
+ let name = chart.leading[location];
742
+ if (name === undefined) chart.leading[location] = name = leadingName(info.source);
743
+ const own = chart.declaring === null ? name !== '' && Object.hasOwn(session, name) : chart.declaring.declared.has(name);
744
+ if (!own) throw new this.realm.global.Error('an assignment to a location the session does not declare');
745
+ if (chart.declaring === null) {
746
+ const fn = this.compiled(chart.setters, location, () => SHARED_SETTER[0] + trimmed(info.source) + SHARED_SETTER[1]);
747
+ fn(session, value);
748
+ return;
749
+ }
750
+ const setters = session.setters ??= [];
751
+ let fn = setters[location];
752
+ if (fn === undefined) {
753
+ fn = this.run(session, OWN_SETTER[0] + trimmed(info.source) + OWN_SETTER[1]);
754
+ setters[location] = fn;
755
+ }
756
+ fn(value);
757
+ }
758
+
759
+ log(slot) {
760
+ const e = this.module.word(0);
761
+ let value = this.evaluate(this.session(slot, true), e);
762
+ if (value !== null && typeof value === 'object') {
763
+ try {
764
+ const json = JSON.stringify(value);
765
+ if (typeof json === 'string') value = json;
766
+ } catch {
767
+ // a cycle: its text instead
768
+ }
769
+ }
770
+ this.putText(`${value}`);
771
+ return TA_OK;
772
+ }
773
+
774
+ // ---- SCXML B.2: <content> and <data> text ----
775
+
776
+ content(text) {
777
+ const kit = this.realm.kit;
778
+ try {
779
+ return kit.parse(text); // JSON
780
+ } catch {
781
+ // not JSON
782
+ }
783
+ if (/^[ \t\n\r]*</.test(text)) {
784
+ const document = this.dom(text);
785
+ if (document !== undefined) return document;
786
+ }
787
+ return text.replace(/[ \t\n\r]+/g, ' ').replace(/^ | $/g, '');
788
+ }
789
+
790
+ // The XML document of `text`, made with the kit's XML nodes from the
791
+ // tree txml read in C; undefined when the text is not well-formed XML.
792
+ dom(text) {
793
+ const module = this.module, pointer = this.pointer, scratch = this.scratch;
794
+ return module.scoped(scratch, () => {
795
+ const [at, length] = module.copyIn(scratch, encoder.encode(text));
796
+ module.setWord(0, at);
797
+ module.setWord(1, length);
798
+ const tree = this.fn.ta_web_xml_parse(pointer) >>> 2;
799
+ try {
800
+ const status = module.word(0) | 0;
801
+ if (status === TA_ERROR_NO_MEMORY) throw new Refused(TA_ERROR_NO_MEMORY, 'no memory for the XML content');
802
+ if (status !== TA_OK || tree === 0) return undefined;
803
+ const words = module.words();
804
+ let i = tree;
805
+ const read = () => words[i++];
806
+ const string = () => {
807
+ const p = read(), n = read();
808
+ return module.string(p, n);
809
+ };
810
+ const qualified = (prefix, local) => (prefix ? `${prefix}:${local}` : local);
811
+ const node = () => {
812
+ const kind = read();
813
+ const prefix = string(), name = string(), value = string();
814
+ const attributes = read(), children = read();
815
+ const entry = [kind, undefined, undefined, undefined, []];
816
+ if (kind === 1) {
817
+ entry[1] = qualified(prefix, name);
818
+ const list = {};
819
+ for (let a = 0; a < attributes; a++) {
820
+ const ap = string(), an = string(), av = string();
821
+ Object.defineProperty(list, qualified(ap, an), { value: av, writable: true, enumerable: true, configurable: true });
822
+ }
823
+ entry[3] = list;
824
+ } else {
825
+ entry[1] = kind === 3 ? '#text' : kind === 4 ? '#cdata-section' : kind === 8 ? '#comment' : name;
826
+ entry[2] = value;
827
+ }
828
+ for (let c = 0; c < children; c++) entry[4].push(node());
829
+ return entry;
830
+ };
831
+ const count = read();
832
+ const children = [];
833
+ for (let c = 0; c < count; c++) children.push(node());
834
+ return this.realm.kit.dom(children, text);
835
+ } finally {
836
+ this.fn.ta_web_xml_end(pointer);
837
+ }
838
+ });
839
+ }
840
+
841
+ // ---- <foreach> ----
842
+
843
+ foreachBegin(slot) {
844
+ const [array, loop] = this.words(2);
845
+ const value = this.evaluate(this.session(slot, true), array);
846
+ if (!Array.isArray(value)) throw new this.realm.global.TypeError('<foreach>\'s array is not an array');
847
+ const items = value.slice(); // the loop walks the items it had
848
+ this.loops[loop] = items;
849
+ this.module.setWord(0, items.length);
850
+ return TA_OK;
851
+ }
852
+
853
+ foreachItem(slot) {
854
+ const [loop, i, item, index] = this.words(4);
855
+ const session = this.session(slot, true);
856
+ const items = this.loops[loop];
857
+ if (items === undefined) throw new Refused(TA_ERROR_STALE, 'no such loop');
858
+ this.assign(session, item, items[i]);
859
+ if (index !== NIL) this.assign(session, index, i);
860
+ return TA_OK;
861
+ }
862
+
863
+ // ---- payloads ----
864
+
865
+ capture(slot) {
866
+ const [session, kind, namelistCount, paramCount, content, namelist, params] = this.words(7);
867
+ void kind;
868
+ const s = this.session(session, true);
869
+ const chart = this.chartOf(session);
870
+ const kit = this.realm.kit;
871
+ let captured;
872
+ if (content !== NIL) captured = kit.copy(this.evaluate(s, content));
873
+ else {
874
+ const names = [], values = [];
875
+ const words = () => this.module.words();
876
+ for (let i = 0; i < namelistCount; i++) {
877
+ const location = words()[(namelist >>> 2) + i];
878
+ const info = this.expressionOf(chart, location);
879
+ if (info === null) throw new Error('no such location');
880
+ names.push(trim(info.source));
881
+ values.push(this.evaluate(s, location));
882
+ }
883
+ for (let i = 0; i < paramCount; i++) {
884
+ const sid = words()[(params >>> 2) + 2 * i], e = words()[(params >>> 2) + 2 * i + 1];
885
+ const at = this.fn.ta_web_chart_string(this.pointer, chart.slot, sid) >>> 0;
886
+ names.push(this.module.string(at, this.module.word(0)));
887
+ values.push(this.evaluate(s, e));
888
+ }
889
+ captured = kit.record(names, values);
890
+ }
891
+ this.values[slot] = captured;
892
+ this.module.setWord(0, 1);
893
+ return TA_OK;
894
+ }
895
+
896
+ // A payload's value (to_wire's or the value table's CBOR) in the output.
897
+ payloadOut(slot, wire) {
898
+ try {
899
+ this.putValue(this.values[slot], wire);
900
+ } catch (error) {
901
+ if (error instanceof Refused) throw error;
902
+ if (error instanceof TinyactorsError) {
903
+ const status = error.status === 'TA_ERROR_NO_MEMORY' ? TA_ERROR_NO_MEMORY : wire ? TA_ERROR_INVALID : TA_ERROR_UNSUPPORTED;
904
+ this.fail(error);
905
+ return status;
906
+ }
907
+ throw error;
908
+ }
909
+ return TA_OK;
910
+ }
911
+
912
+ // A payload from CBOR (from_wire, payload_deserialize): read, then copied
913
+ // into the host's realm.
914
+ fromWire(slot) {
915
+ const [at, length] = this.words(2);
916
+ let value;
917
+ try {
918
+ value = this.kit().copy(this.readValue(at, length));
919
+ } catch (error) {
920
+ this.fail(error);
921
+ return TA_ERROR_INVALID;
922
+ }
923
+ this.values[slot] = value;
924
+ this.module.setWord(0, 1);
925
+ return TA_OK;
926
+ }
927
+
928
+ // A <data> variable for inspection (actor.context): the value itself as a
929
+ // payload, which core writes out with to_wire at once and releases.
930
+ variable(slot) {
931
+ const [session, at, length] = this.words(3);
932
+ const name = this.text(at, length);
933
+ const s = this.session(session, false);
934
+ const chart = this.chartOf(session);
935
+ if (!chart.data.some((d) => d.id === name)) throw new Refused(TA_ERROR_INVALID, 'no such variable');
936
+ const value = this.getVariable(s, name);
937
+ this.module.setWord(0, value === undefined ? 0 : 1);
938
+ if (value !== undefined) this.values[slot] = value;
939
+ return TA_OK;
940
+ }
941
+
942
+ // The value of payload `handle` (a bigint) in the application's realm.
943
+ exported(handle) {
944
+ const value = this.values[Number(handle & 0xFFFFFFFFn) - 1];
945
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return value;
946
+ return application().exported(value);
947
+ }
948
+
949
+ // A payload of the host's realm for a value the application gives: one
950
+ // reference, its handle. A value that cannot cross throws a
951
+ // TinyactorsError of the kit's status.
952
+ payload(value) {
953
+ const kit = this.kit();
954
+ let copy;
955
+ try {
956
+ copy = kit.copy(value);
957
+ } catch (error) {
958
+ const refusal = kit.refusal(error);
959
+ if (refusal === undefined) throw error;
960
+ throw new TinyactorsError(String(error?.message ?? error), { status: refusal === 'invalid' ? 'TA_ERROR_INVALID' : 'TA_ERROR_UNSUPPORTED' });
961
+ }
962
+ const slot = this.fn.ta_web_payload_new(this.pointer);
963
+ if (slot === 0) throw new TinyactorsError('no memory for the payload', { status: 'TA_ERROR_NO_MEMORY' });
964
+ this.values[slot - 1] = copy;
965
+ return this.module.word64(0);
966
+ }
967
+
968
+ // ---- hibernation ----
969
+
970
+ // A session's variables as hibernation writes them: [names, values].
971
+ stored(session, chart) {
972
+ if (chart.declaring === null) {
973
+ const names = [], values = [];
974
+ for (const name of Object.keys(session)) {
975
+ if (name === '_event') continue;
976
+ names.push(name);
977
+ values.push(session[name]);
978
+ }
979
+ return [names, values];
980
+ }
981
+ const record = chart.declaring;
982
+ const names = [], values = [];
983
+ for (const name of record.stored) {
984
+ let value;
985
+ try {
986
+ value = session.handle.get(name);
987
+ } catch {
988
+ continue; // in its TDZ
989
+ }
990
+ if (typeof value === 'function' && record.remade.has(name)) continue;
991
+ names.push(name);
992
+ values.push(value);
993
+ }
994
+ if (session.odd !== undefined) for (const name of Object.keys(session.odd)) {
995
+ names.push(name);
996
+ values.push(session.odd[name]);
997
+ }
998
+ return [names, values];
999
+ }
1000
+
1001
+ // Why a declaring session cannot be written out, or undefined: a chart
1002
+ // that declares with let, const or class, or names an undeclared
1003
+ // assignment put on the host's shared realm.
1004
+ unstorable(chart, snapshot) {
1005
+ if (chart.declaring === null) return undefined;
1006
+ if (chart.declaring.lexical) {
1007
+ return snapshot
1008
+ ? 'a session of a chart whose scripts declare with let, const or class at their top level: a new context cannot be given those bindings again'
1009
+ : 'the chart\'s scripts declare with let, const or class at their top level: a new context cannot be given those bindings again, so its sessions stay resident';
1010
+ }
1011
+ const leaked = this.realm.kit.globals();
1012
+ if (leaked.length > 0) {
1013
+ return `an undeclared assignment in a chart's script put ${leaked.map((n) => `'${n}'`).join(', ')} on the host's realm, ` +
1014
+ 'not on a session (in @tinyactors/wasm the host\'s charts share one realm), so it cannot be stored: declare it ' +
1015
+ '(a <data>, or var in a chart-level script)';
1016
+ }
1017
+ return undefined;
1018
+ }
1019
+
1020
+ // _event as a blob holds it: its eight fields, then core's ids; null
1021
+ // when no event came yet.
1022
+ eventOut(session, slot) {
1023
+ const event = this.scopeOf(session)._event;
1024
+ if (event === null || typeof event !== 'object') return null;
1025
+ const fields = EVENT_FIELDS.map((field) => event[field]);
1026
+ fields.push(this.meta[4 * slot + 1], this.meta[4 * slot + 2], this.meta[4 * slot + 3]);
1027
+ return fields;
1028
+ }
1029
+
1030
+ // The value-table refusal of a session's state as the reason the host
1031
+ // gives: which variable, and why.
1032
+ reason(what, name, error) {
1033
+ const message = error instanceof Error || (error !== null && typeof error === 'object' && 'message' in error)
1034
+ ? String(error.message) : 'it is not a value of the value table';
1035
+ return name !== undefined ? `${what}${name}' cannot be stored: ${message}` : `${what} cannot be stored: ${message}`;
1036
+ }
1037
+
1038
+ // Writes one value's CBOR: [pointer, length] in the scratch; a Refused
1039
+ // naming it when the value table refuses it.
1040
+ written(value, what, name) {
1041
+ try {
1042
+ return cbor.write(this.module, this.scratch, value, { realms: true });
1043
+ } catch (error) {
1044
+ if (error instanceof TinyactorsError && error.status === 'TA_ERROR_NO_MEMORY') throw new Refused(TA_ERROR_NO_MEMORY, error.message);
1045
+ const refused = new Refused(TA_ERROR_UNSUPPORTED, this.reason(what, name, error));
1046
+ refused.reason = refused.message;
1047
+ throw refused;
1048
+ }
1049
+ }
1050
+
1051
+ serialize(slot) {
1052
+ this.state.reason = '';
1053
+ const session = this.session(slot, false);
1054
+ const chart = this.chartOf(slot);
1055
+ const why = this.unstorable(chart, false);
1056
+ if (why !== undefined) {
1057
+ const refused = new Refused(TA_ERROR_UNSUPPORTED, why);
1058
+ refused.reason = why;
1059
+ throw refused;
1060
+ }
1061
+ const [names, values] = this.stored(session, chart);
1062
+ const vars = {};
1063
+ for (let i = 0; i < names.length; i++) {
1064
+ Object.defineProperty(vars, names[i], { value: values[i], enumerable: true, writable: true, configurable: true });
1065
+ }
1066
+ let event;
1067
+ try {
1068
+ event = this.eventOut(session, slot);
1069
+ } catch (error) {
1070
+ const refused = new Refused(TA_ERROR_UNSUPPORTED, this.reason('_event', undefined, error));
1071
+ refused.reason = refused.message;
1072
+ throw refused;
1073
+ }
1074
+ const module = this.module, scratch = this.scratch;
1075
+ module.scoped(scratch, () => {
1076
+ let written;
1077
+ try {
1078
+ written = cbor.write(module, scratch, { vars, event }, { realms: true });
1079
+ } catch (error) {
1080
+ if (error instanceof TinyactorsError && error.status === 'TA_ERROR_NO_MEMORY') throw new Refused(TA_ERROR_NO_MEMORY, error.message);
1081
+ // which value: the variable it names, else _event
1082
+ for (let i = 0; i < names.length; i++) module.scoped(scratch, () => this.written(values[i], 'variable \'', names[i]));
1083
+ module.scoped(scratch, () => this.written(event, '_event', undefined));
1084
+ throw error;
1085
+ }
1086
+ this.putBytes(written[0], written[1]);
1087
+ });
1088
+ return TA_OK;
1089
+ }
1090
+
1091
+ // A session from a blob serialize wrote, for its chart now: its
1092
+ // variables (all of them kept in its link's init until the first event
1093
+ // or migrate takes them) and its _event.
1094
+ deserialize(slot) {
1095
+ const words = this.words(8);
1096
+ const chart = this.charts[words[0]];
1097
+ if (chart === undefined) throw new Refused(TA_ERROR_INVALID, 'no such chart');
1098
+ const state = this.readValue(words[1], words[2]);
1099
+ if (state === null || typeof state !== 'object' || state.vars === null || typeof state.vars !== 'object') {
1100
+ throw new Refused(TA_ERROR_INVALID, 'not a blob of the native datamodel');
1101
+ }
1102
+ const system = this.systemOf(words);
1103
+ this.keepStrings(system[2].map(([type]) => type));
1104
+ const session = this.revive(slot, { chart, link: this.realm.kit.system(...system), vars: state.vars, init: state.vars });
1105
+ this.eventIn(session, slot, chart, state.event);
1106
+ return TA_OK;
1107
+ }
1108
+
1109
+ // A session made again (a wake, a restore): its variables set, the names
1110
+ // its chart does not declare kept for migrate.
1111
+ revive(slot, { chart, link, vars, init, added, relink = false }) {
1112
+ const session = this.make(slot, chart, link, init);
1113
+ this.grow(slot);
1114
+ this.meta.set([chart.slot, NIL, NIL, NIL], 4 * slot);
1115
+ if (chart.declaring === null) this.realm.kit.restore(session, vars);
1116
+ else {
1117
+ const kit = this.realm.kit;
1118
+ const extra = [];
1119
+ for (const name of Object.keys(vars)) {
1120
+ const value = kit.copy(vars[name]);
1121
+ if (chart.declaring.declared.has(name) && session.handle.set(name, value)) continue;
1122
+ if (chart.declaring.odd.includes(name)) {
1123
+ (session.odd ??= {})[name] = value;
1124
+ continue;
1125
+ }
1126
+ if (!IDENTIFIER.test(name) || name.startsWith(PREFIX)) continue;
1127
+ session.handle.value = value;
1128
+ this.run(session, `var ${name} = __tinyactors_session.value;`);
1129
+ session.handle.value = undefined;
1130
+ extra.push(name);
1131
+ }
1132
+ if (extra.length) link.added = extra;
1133
+ session.stop = chart.declaring.stops.size; // its chart-level scripts ran before it was written out
1134
+ }
1135
+ if (relink) link.added = Array.isArray(added) ? added.slice() : undefined;
1136
+ this.sessions[slot] = session;
1137
+ return session;
1138
+ }
1139
+
1140
+ // _event from the fields a blob holds, its strings shared with the
1141
+ // chart's (by core's ids, when the text is the same).
1142
+ eventIn(session, slot, chart, fields) {
1143
+ if (fields === null || fields === undefined) return;
1144
+ if (!Array.isArray(fields) || fields.length !== 11) throw new Refused(TA_ERROR_INVALID, 'not a blob of the native datamodel');
1145
+ const id = (v) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= NIL ? v : NIL);
1146
+ const [nameID, invoke, origintype] = [id(fields[8]), id(fields[9]), id(fields[10])];
1147
+ const made = fields.slice(0, 8);
1148
+ const keep = (list, index, text) => (typeof text === 'string' ? this.kept(list, index, text) : text);
1149
+ made[0] = keep(chart.names, nameID, made[0]);
1150
+ const types = this.strings ?? TYPES;
1151
+ for (let i = 0; i < 3; i++) if (types[i] === made[1]) made[1] = types[i];
1152
+ made[3] = keep(chart.origins, invoke, made[3]);
1153
+ made[4] = origintype < NIL - 3 ? keep(types, 3 + origintype, made[4]) : made[4];
1154
+ made[5] = keep(chart.invokeids, invoke, made[5]);
1155
+ if (made[6] !== undefined) made[6] = this.realm.kit.copy(made[6]);
1156
+ const event = this.realm.kit.event(made);
1157
+ Object.defineProperty(this.scopeOf(session), '_event', { value: event, enumerable: true, configurable: true, writable: false });
1158
+ this.meta[4 * slot + 1] = nameID;
1159
+ this.meta[4 * slot + 2] = invoke;
1160
+ this.meta[4 * slot + 3] = origintype;
1161
+ }
1162
+
1163
+ // After deserialize, for a blob of an older version of the chart: the
1164
+ // old bindings (exactly the old chart's variables) as one payload; the
1165
+ // names the blob added that the new chart does not declare go.
1166
+ migrate(slot) {
1167
+ const sessionSlot = this.module.word(0);
1168
+ const session = this.session(sessionSlot, true);
1169
+ const link = this.linkOf(session);
1170
+ const old = link.init;
1171
+ link.init = undefined;
1172
+ if (session instanceof Declaring && link.added !== undefined) {
1173
+ for (const name of link.added) this.run(session, `delete ${name};`);
1174
+ link.added = undefined;
1175
+ } else if (!(session instanceof Declaring)) this.realm.kit.upgrade(session);
1176
+ if (old !== null && typeof old === 'object') {
1177
+ this.values[slot] = this.realm.kit.copy(old);
1178
+ this.module.setWord(0, 1);
1179
+ } else this.module.setWord(0, 0);
1180
+ return TA_OK;
1181
+ }
1182
+
1183
+ // ---- snapshots ----
1184
+
1185
+ // The native datamodel's state for a host snapshot: the tables'
1186
+ // namespaces and every row, each value as CBOR bytes of its own (the
1187
+ // addon's format). Throws a TinyactorsError when a session's state
1188
+ // cannot be stored.
1189
+ snapshot() {
1190
+ const module = this.module, pointer = this.pointer, scratch = this.scratch;
1191
+ const layout = (which) => {
1192
+ const status = this.fn.ta_web_dm_layout(pointer, which);
1193
+ if (status !== TA_OK) throw new TinyactorsError('no memory for the snapshot', { status: 'TA_ERROR_NO_MEMORY' });
1194
+ return module.copyOut(module.word(0), module.word(1));
1195
+ };
1196
+ const rows = (which) => {
1197
+ for (let room = 1024; ; room *= 4) {
1198
+ const out = module.scoped(scratch, () => {
1199
+ const at = module.room(scratch, 12 * room);
1200
+ module.setWord(0, at);
1201
+ module.setWord(1, room);
1202
+ const n = this.fn.ta_web_dm_rows(pointer, which);
1203
+ if (n === room) return null; // perhaps more: again with more room
1204
+ const words = module.words(), base = at >>> 2, found = [];
1205
+ for (let i = 0; i < n; i++) found.push([BigInt(words[base + 3 * i]) | (BigInt(words[base + 3 * i + 1]) << 32n), words[base + 3 * i + 2]]);
1206
+ return found;
1207
+ });
1208
+ if (out !== null) return out;
1209
+ }
1210
+ };
1211
+ const bytes = (value, what, name) => module.scoped(scratch, () => {
1212
+ const [at, length] = this.writtenSnapshot(value, what, name);
1213
+ return module.copyOut(at, length);
1214
+ });
1215
+ const state = { sessions: layout(0), payloads: layout(1), loops: layout(2) };
1216
+ state.rows = rows(0).map(([handle]) => this.snapshotSession(handle, bytes));
1217
+ state.values = rows(1).map(([handle, count]) => [handle, count, bytes(this.values[Number(handle & 0xFFFFFFFFn) - 1], 'a payload')]);
1218
+ state.items = rows(2).map(([handle]) => [handle, bytes(this.loops[Number(handle & 0xFFFFFFFFn) - 1], 'a <foreach>\'s items')]);
1219
+ return state;
1220
+ }
1221
+
1222
+ writtenSnapshot(value, what, name) {
1223
+ try {
1224
+ return cbor.write(this.module, this.scratch, value, { realms: true });
1225
+ } catch (error) {
1226
+ if (error instanceof TinyactorsError && error.status === 'TA_ERROR_NO_MEMORY') throw error;
1227
+ throw new TinyactorsError(this.reason(what, name, error), { status: 'TA_ERROR_UNSUPPORTED' });
1228
+ }
1229
+ }
1230
+
1231
+ // One session row: [handle, segment, chart index, {name: bytes}, _event
1232
+ // as bytes, the link's [sessionid, name, processors] as bytes, its init
1233
+ // as bytes or null, the names a wake added as bytes].
1234
+ snapshotSession(handle, bytes) {
1235
+ const slot = Number(handle & 0xFFFFFFFFn) - 1;
1236
+ const session = this.sessions[slot];
1237
+ const chart = this.chartOf(slot);
1238
+ if (session === undefined || chart === undefined) throw new TinyactorsError('a session without its chart', { status: 'TA_ERROR_INVALID' });
1239
+ const why = this.unstorable(chart, true);
1240
+ if (why !== undefined) throw new TinyactorsError(why, { status: 'TA_ERROR_UNSUPPORTED' });
1241
+ const [names, values] = this.stored(session, chart);
1242
+ const vars = {};
1243
+ for (let i = 0; i < names.length; i++) {
1244
+ Object.defineProperty(vars, names[i], { value: bytes(values[i], 'variable \'', names[i]), enumerable: true, writable: true, configurable: true });
1245
+ }
1246
+ let event;
1247
+ try {
1248
+ event = this.eventOut(session, slot);
1249
+ } catch (error) {
1250
+ throw new TinyactorsError(this.reason('_event', undefined, error), { status: 'TA_ERROR_UNSUPPORTED' });
1251
+ }
1252
+ const linked = this.realm.kit.linked(this.scopeOf(session));
1253
+ return [
1254
+ handle, chart.segment, chart.index, vars, bytes(event, '_event'),
1255
+ bytes([linked[0], linked[1], linked[2]], 'the system variables'),
1256
+ linked[3] === undefined ? null : bytes(linked[3], 'the params'),
1257
+ bytes(linked[4], 'the session'),
1258
+ ];
1259
+ }
1260
+
1261
+ // The state a snapshot holds back into a fresh datamodel: the tables'
1262
+ // namespaces, then every row at its handle (a row twice, or one the
1263
+ // tables do not hold, refused).
1264
+ restore(state) {
1265
+ const module = this.module, pointer = this.pointer, scratch = this.scratch;
1266
+ const invalid = (message) => new TinyactorsError(message, { status: 'TA_ERROR_INVALID' });
1267
+ const keys = ['sessions', 'payloads', 'loops', 'rows', 'values', 'items'];
1268
+ if (state === null || typeof state !== 'object' || Array.isArray(state) || Object.keys(state).join() !== keys.join()) {
1269
+ throw invalid('not a snapshot of the native datamodel');
1270
+ }
1271
+ const bytesOf = (value) => {
1272
+ if (!(value instanceof Uint8Array)) throw invalid('not a snapshot of the native datamodel');
1273
+ return value;
1274
+ };
1275
+ const valueOf = (value) => module.scoped(scratch, () => {
1276
+ const [at, length] = module.copyIn(scratch, bytesOf(value));
1277
+ return cbor.read(module, scratch, at, length);
1278
+ });
1279
+ for (const [which, key] of [[0, 'sessions'], [1, 'payloads'], [2, 'loops']]) {
1280
+ module.scoped(scratch, () => {
1281
+ const [at, length] = module.copyIn(scratch, bytesOf(state[key]));
1282
+ module.setWord(0, at);
1283
+ module.setWord(1, length);
1284
+ const status = this.fn.ta_web_dm_restore(pointer, which);
1285
+ if (status === TA_ERROR_STATE) throw new TinyactorsError('the native datamodel is not a fresh one', { status: 'TA_ERROR_STATE' });
1286
+ if (status !== TA_OK) throw new TinyactorsError('a table of the snapshot does not restore', { status: module.statusName(status) });
1287
+ });
1288
+ }
1289
+ const handleOf = (value) => {
1290
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return BigInt(value);
1291
+ if (typeof value === 'bigint' && value > 0n) return value;
1292
+ throw invalid('not a snapshot of the native datamodel');
1293
+ };
1294
+ const fill = (which, handle, value, what) => {
1295
+ module.setWord64(0, handle);
1296
+ module.setWord(2, value);
1297
+ if (this.fn.ta_web_dm_fill(pointer, which) !== TA_OK) throw invalid(what);
1298
+ };
1299
+ const rows = state.rows, values = state.values, items = state.items;
1300
+ if (!Array.isArray(rows) || !Array.isArray(values) || !Array.isArray(items)) throw invalid('not a snapshot of the native datamodel');
1301
+ this.ensureRealm();
1302
+ const kit = this.realm.kit;
1303
+ for (const row of rows) {
1304
+ if (!Array.isArray(row) || row.length !== 8) throw invalid('not a session of a snapshot');
1305
+ const handle = handleOf(row[0]);
1306
+ const chart = this.charts.find((c) => c !== undefined && c.segment === row[1] && c.index === row[2]);
1307
+ if (chart === undefined) throw invalid('a session whose chart the restored host does not have');
1308
+ fill(0, handle, chart.slot, 'a session the snapshot\'s tables do not hold, or twice');
1309
+ const slot = Number(handle & 0xFFFFFFFFn) - 1;
1310
+ const system = valueOf(row[5]);
1311
+ if (!Array.isArray(system) || system.length !== 3 || !Array.isArray(system[2])) throw invalid('not a session of a snapshot');
1312
+ this.keepStrings(system[2].map((pair) => pair[0]));
1313
+ const init = row[6] === null ? undefined : kit.copy(valueOf(row[6]));
1314
+ if (row[3] === null || typeof row[3] !== 'object') throw invalid('not a session of a snapshot');
1315
+ const vars = {};
1316
+ for (const name of Object.keys(row[3])) {
1317
+ Object.defineProperty(vars, name, { value: valueOf(row[3][name]), enumerable: true, writable: true, configurable: true });
1318
+ }
1319
+ const session = this.revive(slot, { chart, link: kit.system(system[0], system[1], system[2]), vars, init, added: valueOf(row[7]), relink: true });
1320
+ this.eventIn(session, slot, chart, valueOf(row[4]));
1321
+ }
1322
+ for (const row of values) {
1323
+ if (!Array.isArray(row) || row.length !== 3) throw invalid('a payload the snapshot\'s tables do not hold, or twice');
1324
+ const handle = handleOf(row[0]);
1325
+ const count = row[1];
1326
+ if (typeof count !== 'number' || !Number.isInteger(count) || count < 1 || count > NIL) throw invalid('a payload the snapshot\'s tables do not hold, or twice');
1327
+ fill(1, handle, count, 'a payload the snapshot\'s tables do not hold, or twice');
1328
+ this.values[Number(handle & 0xFFFFFFFFn) - 1] = kit.copy(valueOf(row[2]));
1329
+ }
1330
+ for (const row of items) {
1331
+ if (!Array.isArray(row) || row.length !== 2) throw invalid('a <foreach> the snapshot\'s tables do not hold, or twice');
1332
+ const handle = handleOf(row[0]);
1333
+ fill(2, handle, 0, 'a <foreach> the snapshot\'s tables do not hold, or twice');
1334
+ const slot = Number(handle & 0xFFFFFFFFn) - 1;
1335
+ if (this.loops[slot] !== undefined) throw invalid('a <foreach> the snapshot\'s tables do not hold, or twice');
1336
+ const value = kit.copy(valueOf(row[1]));
1337
+ if (!Array.isArray(value)) throw invalid('a <foreach>\'s items are not an array');
1338
+ this.loops[slot] = value;
1339
+ }
1340
+ }
1341
+ }