@tinyactors/node 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,670 +0,0 @@
1
- /**
2
- * The SCXML ECMAScript datamodel (SCXML Appendix B.2) for the JS bindings,
3
- * value-level: the backends (bindings/node/src/addon.c, bindings/web) forward
4
- * the core's datamodel calls here with plain JS values; payload handles stay
5
- * theirs (one table shared with the xstate datamodel, so machines and SCXML
6
- * documents exchange events directly).
7
- *
8
- * The same semantics as the C datamodel (src/datamodel_ecmascript, quickjs-ng) in its
9
- * shared realm: each session's variables live in a scope object (null
10
- * prototype: only its own names shadow the globals), expressions are compiled
11
- * once per chart as strict functions evaluated `with` that scope, so
12
- * assigning an undeclared name is a ReferenceError (error.execution) and
13
- * _event, _sessionid, _name, _ioprocessors and In are read-only.
14
- *
15
- * What a <script> declares at its top level (var, let, const, class,
16
- * function) is asked of the engine when the chart is attached (analyze). A
17
- * chart with such scripts is "isolated", as in the C datamodel: its scripts
18
- * run against a proxy of the scope that keeps implicit globals out of the
19
- * host's global object, and a declaring script's bindings become the
20
- * session's (accessors on the scope, shared with the script's functions; a
21
- * const stays const). Such sessions are stored like the C datamodel's
22
- * (docs/durability.md): variables and let/const bindings with their values,
23
- * top-level function declarations re-created on restore; anything else that
24
- * cannot be stored is refused naming the variable and, for a function, its
25
- * line in the document. Where one JS realm cannot be a C one: functions are
26
- * called with the scope as `this` (it is a `with` object), and closures other
27
- * than declarations keep seeing the script run that created them.
28
- * Charts compile with `new Function` (a CSP must allow 'unsafe-eval').
29
- */
30
-
31
- const KIND = { COND: 1, VALUE: 2, LOCATION: 3, SCRIPT: 4, STRING: 5, CONTENT: 6 };
32
- const EVENT_TYPES = ['platform', 'internal', 'external'];
33
- const SYSVARS = new Set(['_sessionid', '_name', '_ioprocessors']);
34
- const READONLY = new Set(['_event', '_sessionid', '_name', '_ioprocessors', 'In']);
35
-
36
- /* ---- a minimal XML DOM for XML <content>/<data> (SCXML B.2: XML content becomes a DOM) ---- */
37
- class XNode {
38
- constructor(type, name) {
39
- this.nodeType = type;
40
- this.nodeName = name;
41
- this.childNodes = [];
42
- this.parentNode = null;
43
- }
44
- appendChild(c) {
45
- c.parentNode = this;
46
- this.childNodes.push(c);
47
- return c;
48
- }
49
- get firstChild() {
50
- return this.childNodes[0] || null;
51
- }
52
- get textContent() {
53
- if (this.nodeType === 3 || this.nodeType === 4) return this.nodeValue;
54
- return this.childNodes.map((c) => c.textContent).join('');
55
- }
56
- getElementsByTagName(n) {
57
- const r = [];
58
- (function walk(e) {
59
- for (const c of e.childNodes)
60
- if (c.nodeType === 1) {
61
- if (n === '*' || c.nodeName === n || c.localName === n) r.push(c);
62
- walk(c);
63
- }
64
- })(this);
65
- return r;
66
- }
67
- getAttribute(n) {
68
- return this.attributes && Object.prototype.hasOwnProperty.call(this.attributes, n) ? this.attributes[n] : null;
69
- }
70
- hasAttribute(n) {
71
- return this.getAttribute(n) !== null;
72
- }
73
- }
74
- const ent = (s) =>
75
- s.replace(/&(lt|gt|amp|quot|apos|#x[0-9a-fA-F]+|#[0-9]+);/g, (m, e) =>
76
- e === 'lt' ? '<' : e === 'gt' ? '>' : e === 'amp' ? '&' : e === 'quot' ? '"' : e === 'apos' ? "'" : e[1] === 'x' ? String.fromCharCode(parseInt(e.slice(2), 16)) : String.fromCharCode(parseInt(e.slice(1), 10)),
77
- );
78
- function xmlDocument(src) {
79
- const doc = new XNode(9, '#document');
80
- let cur = doc;
81
- const re = /<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([^\s>]+)\s*>|<([^\s/>]+)([^>]*?)(\/?)>|([^<]+)/g;
82
- let m;
83
- while ((m = re.exec(src))) {
84
- if (m[1] !== undefined) {
85
- const t = new XNode(4, '#cdata-section');
86
- t.nodeValue = m[1];
87
- cur.appendChild(t);
88
- } else if (m[2]) {
89
- if (cur.parentNode) cur = cur.parentNode;
90
- } else if (m[3]) {
91
- const e = new XNode(1, m[3]);
92
- e.tagName = m[3];
93
- const k = m[3].indexOf(':');
94
- e.localName = k < 0 ? m[3] : m[3].slice(k + 1);
95
- e.attributes = {};
96
- const ar = /([^\s=]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
97
- let a;
98
- while ((a = ar.exec(m[4]))) e.attributes[a[1]] = ent(a[3] !== undefined ? a[3] : a[4]);
99
- cur.appendChild(e);
100
- if (!m[5]) cur = e;
101
- } else if (m[6] !== undefined && !/^\s*$/.test(m[6])) {
102
- const x = new XNode(3, '#text');
103
- x.nodeValue = ent(m[6]);
104
- cur.appendChild(x);
105
- }
106
- }
107
- doc.documentElement = doc.childNodes.find((c) => c.nodeType === 1);
108
- Object.defineProperty(doc, 'toString', { value: () => src });
109
- return doc;
110
- }
111
-
112
- /* SCXML B.2: JSON if it parses, a DOM if it is XML, else a space-normalized string */
113
- function contentValue(src) {
114
- try {
115
- return JSON.parse(src);
116
- } catch {
117
- /* not JSON */
118
- }
119
- if (/^\s*</.test(src)) {
120
- try {
121
- return xmlDocument(src);
122
- } catch {
123
- /* not XML either */
124
- }
125
- }
126
- return src.replace(/\s+/g, ' ').trim();
127
- }
128
-
129
- /* ---- what a <script> declares, asked of the engine (as chart_analyze in the C datamodel) ----
130
- * The source only proposes candidate identifiers. The script is compiled as a
131
- * function body that returns a reader per candidate before the script runs:
132
- * hoisting has happened, nothing executed. A reader that reaches the trap
133
- * scope around the function found no declaration; one that throws found a
134
- * let/const/class binding in its temporal dead zone; one that returns a
135
- * function found a function declaration (hoisted with its value); anything
136
- * else is a var (anywhere outside nested functions, also in blocks). */
137
- const ID_CHAR = String.raw`[\p{ID_Continue}$\u200c\u200d]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}`;
138
- const CANDIDATE = new RegExp(String.raw`(?:[\p{ID_Start}$_]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\})(?:${ID_CHAR})*`, 'gu');
139
- const IDENT = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200c\u200d]*$/u;
140
- const RESERVED = new Set(
141
- ('break case catch class const continue debugger default delete do else enum export extends false finally for function if import in ' +
142
- 'instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package ' +
143
- 'private protected public await arguments eval').split(' '),
144
- );
145
- const unescapeID = (s) => s.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([0-9a-fA-F]{4})/g, (_, a, b) => String.fromCodePoint(parseInt(a || b, 16)));
146
- const fnText = (f) => {
147
- try {
148
- return Function.prototype.toString.call(f);
149
- } catch {
150
- return '';
151
- }
152
- };
153
-
154
- /* { strict, vars, lex, fns: [{ name, src }] } of a script's top-level declarations, or null */
155
- function analyze(src) {
156
- try {
157
- new Function(src);
158
- } catch {
159
- return null; /* it does not compile: it fails when it runs */
160
- }
161
- let strict = false;
162
- try {
163
- new Function(`${src}\n;with({});`); /* `with` is a syntax error in strict code only */
164
- } catch {
165
- strict = true;
166
- }
167
- const names = [...new Set((src.match(CANDIDATE) || []).map(unescapeID))].filter((n) => IDENT.test(n) && !RESERVED.has(n) && !n.startsWith('__ta_'));
168
- if (!names.length) return null;
169
- const missed = new Set();
170
- const trap = new Proxy(Object.create(null), { has: (_, k) => (missed.add(k), true), get: () => undefined });
171
- let readers;
172
- try {
173
- readers = new Function('__ta_t', `with(__ta_t){return function(){${strict ? "'use strict';" : ''}return [${names.map((n) => `()=>${n}`).join(',')}];\n${src}\n}}`)(trap)();
174
- } catch {
175
- return null;
176
- }
177
- const d = { strict, vars: [], lex: [], fns: [] };
178
- names.forEach((n, i) => {
179
- missed.clear();
180
- let v;
181
- try {
182
- v = readers[i]();
183
- } catch {
184
- d.lex.push(n); /* in its temporal dead zone */
185
- return;
186
- }
187
- if (missed.has(n)) return;
188
- if (typeof v === 'function') d.fns.push({ name: n, src: fnText(v), strict });
189
- else d.vars.push(n);
190
- });
191
- /* a function declared in a block (sloppy code, Annex B) is a var too, but as a
192
- * parameter it would not be hoisted: a real var is the one a `let` clashes with */
193
- d.params = d.vars.filter((n) => {
194
- try {
195
- new Function(`${src}
196
- ;let ${n};`);
197
- return false;
198
- } catch {
199
- return true;
200
- }
201
- });
202
- return d.vars.length || d.lex.length || d.fns.length ? d : null;
203
- }
204
-
205
- /* ---- what cannot be stored, named (as explain_var in the C datamodel) ---- */
206
- /* what the hibernation codec (tagged JSON) keeps; class instances come back as plain objects */
207
- const STORABLE = /^\[object (Object|Array|Date|RegExp|Map|Set|Uint8Array)\]$/;
208
-
209
- /* [path, kind (0 function, 1 class, 2 object of another kind, 3 symbol), detail] or null */
210
- function unstorable(v, name) {
211
- const seen = new Set();
212
- let hit = null;
213
- (function walk(v, p, depth) {
214
- if (hit || depth > 1000) return;
215
- if (typeof v === 'function') {
216
- hit = [p, /^class\b/.test(fnText(v)) ? 1 : 0, v];
217
- return;
218
- }
219
- if (typeof v === 'symbol') {
220
- hit = [p, 3, null];
221
- return;
222
- }
223
- if (v === null || typeof v !== 'object' || seen.has(v)) return;
224
- seen.add(v);
225
- const t = Object.prototype.toString.call(v);
226
- if (!STORABLE.test(t)) {
227
- hit = [p, 2, t.slice(8, -1)];
228
- return;
229
- }
230
- if (v instanceof Map) {
231
- let i = 0;
232
- for (const [k, x] of v) {
233
- walk(k, `${p} (key ${i})`, depth + 1);
234
- walk(x, `${p} (value ${i++})`, depth + 1);
235
- }
236
- return;
237
- }
238
- if (v instanceof Set) {
239
- let i = 0;
240
- for (const x of v) walk(x, `${p} (item ${i++})`, depth + 1);
241
- return;
242
- }
243
- if (v instanceof Date || v instanceof RegExp || v instanceof Uint8Array) return;
244
- const arr = Array.isArray(v);
245
- for (const k of Object.keys(v)) walk(v[k], arr ? `${p}[${k}]` : /^[A-Za-z_$][\w$]*$/.test(k) ? `${p}.${k}` : `${p}[${JSON.stringify(k)}]`, depth + 1);
246
- })(v, name, 0);
247
- return hit;
248
- }
249
-
250
- /* the document line of a function written in the chart (0: unknown); engines do not
251
- * report it, so its source text is looked up in the chart's expressions */
252
- function fnLine(chart, f) {
253
- const text = fnText(f);
254
- if (!text) return 0;
255
- for (const x of chart.exprs) {
256
- const i = x && x.line ? x.source.indexOf(text) : -1;
257
- if (i >= 0) return x.line + (x.source.slice(0, i).match(/\n/g) || []).length;
258
- }
259
- return 0;
260
- }
261
-
262
- function whyNot(chart, name, v) {
263
- const hit = unstorable(v, name);
264
- if (!hit) return null;
265
- const [path, kind, x] = hit;
266
- const self = path === name;
267
- const line = kind < 2 ? fnLine(chart, x) : 0;
268
- const at = line ? ` (line ${line})` : '';
269
- const head = `variable '${name}' cannot be stored: `;
270
- if (kind === 1) return `${head}${self ? 'it' : path} is a class${at}; classes are not stored — keep the data in plain objects and the code in top-level function declarations`;
271
- if (kind === 0 && self) return `${head}it holds a function${at}; only top-level function declarations are stored (re-created on restore): write \`function ${name}(...) {...}\``;
272
- if (kind === 0) return `${head}${path} is a function${at}; functions in data are not stored`;
273
- if (kind === 3) return `${head}${path} is a symbol`;
274
- return `${head}${path} is ${/^[AEIOU]/.test(x) ? 'an' : 'a'} ${x} object`;
275
- }
276
-
277
- /* what was added to a declared function since its declaration (it would be lost), or null */
278
- function fnAdded(f, name) {
279
- for (const k of Reflect.ownKeys(f)) if (!['length', 'name', 'prototype', 'arguments', 'caller'].includes(k)) return `${name}.${String(k)}`;
280
- const p = Object.getOwnPropertyDescriptor(f, 'prototype');
281
- if (p && p.value && typeof p.value === 'object') for (const k of Reflect.ownKeys(p.value)) if (k !== 'constructor') return `${name}.prototype.${String(k)}`;
282
- return null;
283
- }
284
-
285
- const trimExpr = (s) => s.replace(/[;\s]+$/, '');
286
- const rootName = (s) => {
287
- const m = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)/.exec(s);
288
- return m ? m[1] : null;
289
- };
290
- const dataProp = (o, k, v) => Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true });
291
-
292
- export function createEcmascript() {
293
- const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
294
- const remade = new WeakMap(); /* function re-created from a declaration -> its name */
295
-
296
- /* chart: { exprs: [{ source, kind, line }], data: [{ id, expr }], decls[e] (scripts that
297
- * declare globals), isolated, key, get[], set[], run[], make } */
298
- function attach(info) {
299
- const chart = { name: info.name, exprs: info.exprs, data: info.data, get: [], set: [], run: [], decls: [], fdecl: new Map(), make: new Map() };
300
- let hash = 0x811c9dc5;
301
- info.exprs.forEach((x, e) => {
302
- if (!x || x.kind !== KIND.SCRIPT) return;
303
- for (let i = 0; i < x.source.length; i++) hash = Math.imul(hash ^ x.source.charCodeAt(i), 16777619);
304
- const d = analyze(x.source);
305
- if (!d) return;
306
- chart.decls[e] = d;
307
- for (const f of d.fns) chart.fdecl.set(f.name, Object.assign(f, { e }));
308
- });
309
- chart.isolated = chart.decls.some(Boolean);
310
- /* which declarations a stored session refers to: blobs for another version re-run its own */
311
- chart.key = `${info.name}#${(hash >>> 0).toString(36)}`;
312
- return chart;
313
- }
314
-
315
- function getter(chart, e) {
316
- let f = chart.get[e];
317
- if (f) return f;
318
- const x = chart.exprs[e];
319
- if (!x) throw new RangeError('bad expression id');
320
- if (x.kind === KIND.SCRIPT) f = new Function('__ta_s', `with(__ta_s){(function(){'use strict';\n${x.source}\n})();}`);
321
- else f = new Function('__ta_s', `with(__ta_s){return (function(){'use strict';return (\n${trimExpr(x.source)}\n);})();}`);
322
- return (chart.get[e] = f);
323
- }
324
-
325
- /* A script that declares globals runs as a function body (strict if the script is)
326
- * whose var names are parameters, so re-declaring keeps a value as a global var does.
327
- * Before the script, __ta_x (hoisted) and the hoisted functions are handed out: even
328
- * when it throws, its bindings become the session's — accessors on the scope that
329
- * read and write them, so the session and the script's functions share them. */
330
- function runner(chart, e) {
331
- let r = chart.run[e];
332
- if (r) return r;
333
- const d = chart.decls[e];
334
- const params = d.params.filter((n) => !READONLY.has(n));
335
- const names = [...d.vars, ...d.fns.map((f) => f.name), ...d.lex];
336
- const cases = names.map((n, i) => `case ${i}:if(__ta_w){${n}=__ta_v;return}return ${n};`).join('');
337
- const f = new Function(
338
- '__ta_s',
339
- '__ta_o',
340
- '__ta_a',
341
- `with(__ta_s){return (function(${params.join(',')}){${d.strict ? "'use strict';" : ''}__ta_o.x=__ta_x;__ta_o.h=[${d.fns.map((f) => f.name).join(',')}];\n` +
342
- `${chart.exprs[e].source}\n;function __ta_x(__ta_k,__ta_w,__ta_v){switch(__ta_k){${cases}}}}).apply(void 0,__ta_a);}`,
343
- );
344
- return (chart.run[e] = { f, params, names, d, e });
345
- }
346
-
347
- function declare(inst, r) {
348
- const decl = inst.decl;
349
- for (const n of r.d.lex) if (decl.has(n)) throw new SyntaxError(`Identifier '${n}' has already been declared`);
350
- for (const n of r.names) if (decl.has(n) && decl.get(n).lex) throw new SyntaxError(`Identifier '${n}' has already been declared`);
351
- const out = {};
352
- try {
353
- return r.f(proxyOf(inst), out, r.params.map((n) => inst.scope[n]));
354
- } finally {
355
- if (out.x) bind(inst, r, out);
356
- }
357
- }
358
-
359
- function bind(inst, r, out) {
360
- const x = out.x, nv = r.d.vars.length, nf = r.d.fns.length;
361
- r.names.forEach((n, i) => {
362
- if (READONLY.has(n)) return;
363
- let kind = i < nv ? 'var' : i < nv + nf ? 'fn' : 'let';
364
- if (kind === 'let')
365
- try {
366
- x(i, true, x(i));
367
- } catch (err) {
368
- if (err instanceof TypeError) kind = 'const'; /* (a ReferenceError: never initialized) */
369
- }
370
- inst.decl.set(n, { kind, lex: kind === 'let' || kind === 'const', e: r.e });
371
- Object.defineProperty(inst.scope, n, { get: () => x(i), set: (v) => x(i, true, v), enumerable: true, configurable: true });
372
- });
373
- r.d.fns.forEach((f, j) => inst.orig.set(f.name, out.h[j]));
374
- }
375
-
376
- /* a function declaration again, closing over the session (restore) */
377
- function remake(inst, fd) {
378
- const key = `${fd.e}:${fd.name}`;
379
- let mk = inst.chart.make.get(key);
380
- if (!mk) inst.chart.make.set(key, (mk = new Function('__ta_s', `with(__ta_s){return (function(){${fd.strict ? "'use strict';" : ''}return (\n${fd.src}\n);})();}`)));
381
- const fn = mk(proxyOf(inst));
382
- remade.set(fn, fd.name);
383
- return fn;
384
- }
385
-
386
- function setter(chart, e) {
387
- let f = chart.set[e];
388
- if (f) return f;
389
- const x = chart.exprs[e];
390
- if (!x) throw new RangeError('bad expression id');
391
- f = new Function('__ta_s', '__ta_v', `with(__ta_s){(\n${x.source}\n) = __ta_v;}`);
392
- return (chart.set[e] = f);
393
- }
394
-
395
- /* the scope an isolated chart's scripts run against: unknown names (not host
396
- * globals) resolve to the session, so `x = 1` declares x there */
397
- function proxyOf(inst) {
398
- if (!inst.proxy)
399
- inst.proxy = new Proxy(inst.scope, {
400
- /* (not the wrapper's own __ta_ names) */
401
- has: (t, k) => typeof k === 'string' && (k in t || (!(k in globalThis) && !k.startsWith('__ta_'))),
402
- });
403
- return inst.proxy;
404
- }
405
-
406
- function value(inst, e) {
407
- const x = inst.chart.exprs[e];
408
- if (x && x.kind === KIND.CONTENT) return contentValue(x.source);
409
- if (x && x.kind === KIND.SCRIPT && inst.chart.decls[e]) return declare(inst, runner(inst.chart, e));
410
- const f = getter(inst.chart, e);
411
- return f(inst.chart.isolated && x.kind === KIND.SCRIPT ? proxyOf(inst) : inst.scope);
412
- }
413
-
414
- /* a location must start with one of the session's own variables */
415
- function locationOk(inst, e) {
416
- const name = rootName(inst.chart.exprs[e].source);
417
- return !!name && !READONLY.has(name) && own(inst.scope, name);
418
- }
419
-
420
- function assignTo(inst, loc, v) {
421
- if (!locationOk(inst, loc)) throw new ReferenceError('not a declared location');
422
- const src = inst.chart.exprs[loc].source.trim();
423
- const d = Object.getOwnPropertyDescriptor(inst.scope, src);
424
- if (d && 'value' in d && !d.writable) throw new TypeError(`Assignment to constant variable '${src}'`);
425
- setter(inst.chart, loc)(inst.scope, v);
426
- }
427
-
428
- const ro = (o, k, v) => Object.defineProperty(o, k, { value: v, enumerable: true, configurable: true, writable: false });
429
-
430
- function create(chart, sys, init, In) {
431
- const scope = Object.create(null);
432
- ro(scope, 'In', In);
433
- ro(scope, '_sessionid', String(sys.sessionid));
434
- ro(scope, '_name', String(sys.name || ''));
435
- const io = {};
436
- for (const p of sys.ioprocessors || []) {
437
- const e = { location: p.location };
438
- io[p.type] = e;
439
- if (p.type.endsWith('#SCXMLEventProcessor')) io.scxml = e;
440
- if (p.type.endsWith('#BasicHTTPEventProcessor')) io.basichttp = e;
441
- }
442
- ro(scope, '_ioprocessors', io);
443
- /* declared from the start (late binding: undefined); a migration may drop them */
444
- for (const d of chart.data) dataProp(scope, d.id, undefined);
445
- /* decl: names scripts declared -> { kind: var|fn|let|const, lex, e }; orig: the
446
- * functions the last run of a script declared */
447
- return { chart, scope, init, proxy: null, sys, decl: new Map(), orig: new Map() };
448
- }
449
-
450
- /* each call: true on success, false = error.execution */
451
- const run = (fn) => {
452
- try {
453
- return fn();
454
- } catch {
455
- return false;
456
- }
457
- };
458
-
459
- return {
460
- KIND,
461
- attach,
462
- create,
463
- initData(inst, decl) {
464
- const d = inst.chart.data[decl];
465
- if (!d) return false;
466
- if (inst.init && typeof inst.init === 'object' && d.id in inst.init) {
467
- inst.scope[d.id] = inst.init[d.id]; /* <invoke> namelist/param: overrides the expr */
468
- return true;
469
- }
470
- if (d.expr < 0) return true;
471
- try {
472
- inst.scope[d.id] = value(inst, d.expr);
473
- return true;
474
- } catch {
475
- inst.scope[d.id] = undefined;
476
- return false;
477
- }
478
- },
479
- bindEvent(inst, ev) {
480
- const o = {
481
- name: ev.name,
482
- type: EVENT_TYPES[ev.type % 3],
483
- sendid: ev.sendid || undefined,
484
- origin: ev.origin || undefined,
485
- origintype: ev.origintype || undefined,
486
- invokeid: ev.invokeid || undefined,
487
- data: ev.data,
488
- };
489
- if (ev.raw) o.raw = ev.raw;
490
- ro(inst.scope, '_event', o);
491
- },
492
- cond(inst, e) {
493
- try {
494
- return value(inst, e) ? 1 : 0;
495
- } catch {
496
- return -1;
497
- }
498
- },
499
- /* *expr attributes; null = error.execution */
500
- string(inst, e) {
501
- try {
502
- return String(value(inst, e));
503
- } catch {
504
- return null;
505
- }
506
- },
507
- log(inst, e) {
508
- let v;
509
- try {
510
- v = value(inst, e);
511
- } catch {
512
- return null;
513
- }
514
- if (v && typeof v === 'object') {
515
- try {
516
- return JSON.stringify(v);
517
- } catch {
518
- /* cycles: as a string */
519
- }
520
- }
521
- try {
522
- return String(v);
523
- } catch {
524
- return null;
525
- }
526
- },
527
- assign: (inst, loc, val) => run(() => (assignTo(inst, loc, value(inst, val)), true)),
528
- assignString: (inst, loc, s) => run(() => (assignTo(inst, loc, s), true)),
529
- script: (inst, e) => run(() => (value(inst, e), true)),
530
- /* the items (a shallow copy), or null = error.execution */
531
- foreachBegin(inst, arr) {
532
- try {
533
- const a = value(inst, arr);
534
- return Array.isArray(a) ? a.slice() : null;
535
- } catch {
536
- return null;
537
- }
538
- },
539
- foreachItem(inst, items, i, item, index) {
540
- return run(() => {
541
- for (const loc of index >= 0 ? [item, index] : [item]) {
542
- const s = inst.chart.exprs[loc].source.trim(); /* <foreach> may introduce item/index */
543
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s) && !own(inst.scope, s) && !READONLY.has(s)) dataProp(inst.scope, s, undefined);
544
- }
545
- assignTo(inst, item, items[i]);
546
- if (index >= 0) assignTo(inst, index, i);
547
- return true;
548
- });
549
- },
550
- /* <send>/<invoke>/<donedata> data: { ok, v } */
551
- capture(inst, content, namelist, params) {
552
- try {
553
- if (content >= 0) return { ok: true, v: value(inst, content) };
554
- const v = {};
555
- for (const e of namelist) v[inst.chart.exprs[e].source.trim()] = value(inst, e);
556
- for (const [name, e] of params) v[name] = value(inst, e);
557
- return { ok: true, v };
558
- } catch {
559
- return { ok: false };
560
- }
561
- },
562
- /* The session as plain values (docs/durability.md): its variables and _event
563
- * (system variables come back on restore); under keys no data id can be: the
564
- * <invoke> params late binding still applies ('#init'), let/const/class bindings
565
- * ('#lex': [name, 0 let | 1 const | 2 uninitialized, value]), top-level function
566
- * declarations, re-created on restore ('#fns': [name, script]), and which
567
- * declarations those are ('#chart'). What cannot be stored throws, naming the
568
- * variable (and a function's line). */
569
- serialize(inst) {
570
- const o = {};
571
- const lex = [], fns = [];
572
- for (const k of Object.keys(inst.scope)) {
573
- if (SYSVARS.has(k) || k === 'In') continue;
574
- const dk = inst.decl.get(k);
575
- let v;
576
- try {
577
- v = inst.scope[k];
578
- } catch {
579
- lex.push([k, 2]); /* still uninitialized */
580
- continue;
581
- }
582
- if (typeof v === 'function' && dk && dk.kind === 'fn' && (remade.get(v) === k || inst.orig.get(k) === v)) {
583
- const added = fnAdded(v, k);
584
- if (added) throw new Error(`function '${k}' cannot be stored: ${added} was added after its declaration (only unchanged top-level function declarations are re-created)`);
585
- fns.push([k, dk.e]);
586
- continue;
587
- }
588
- const why = whyNot(inst.chart, k, v);
589
- if (why) throw new Error(why);
590
- if (dk && dk.lex) lex.push([k, dk.kind === 'const' ? 1 : 0, v]);
591
- else o[k] = v;
592
- }
593
- if (inst.init !== undefined) o['#init'] = inst.init;
594
- if (lex.length) o['#lex'] = lex;
595
- if (fns.length) o['#fns'] = fns;
596
- if (inst.chart.isolated) o['#chart'] = inst.chart.key;
597
- return o;
598
- },
599
- /* a blob of another version of the chart (a migration): lexical bindings come back
600
- * as plain variables (the migration drops what the new chart does not declare) and
601
- * functions from the new chart's declarations of their names */
602
- deserialize(chart, sys, o, In) {
603
- o = o || {};
604
- const inst = create(chart, sys, o['#init'], In);
605
- const scope = inst.scope;
606
- const same = !o['#chart'] || o['#chart'] === chart.key;
607
- /* <data> of this version the stored session did not have: not previous bindings */
608
- inst.added = chart.data.map((d) => d.id).filter((k) => !own(o, k));
609
- for (const [k, v] of Object.entries(o)) {
610
- if (k[0] === '#') continue;
611
- if (k === '_event') ro(scope, k, v);
612
- else dataProp(scope, k, v);
613
- }
614
- for (const [k, kind, v] of o['#lex'] || []) {
615
- if (!same) {
616
- if (kind !== 2) dataProp(scope, k, v);
617
- continue;
618
- }
619
- inst.decl.set(k, { kind: kind === 1 ? 'const' : 'let', lex: true });
620
- if (kind === 2) {
621
- const tdz = () => {
622
- throw new ReferenceError(`Cannot access '${k}' before initialization`);
623
- };
624
- Object.defineProperty(scope, k, { get: tdz, set: tdz, enumerable: true, configurable: true });
625
- } else Object.defineProperty(scope, k, { value: v, writable: kind === 0, enumerable: true, configurable: true });
626
- }
627
- for (const [k, e] of o['#fns'] || []) {
628
- const fd = (same && chart.decls[e] && chart.decls[e].fns.find((f) => f.name === k)) || chart.fdecl.get(k);
629
- if (!fd) continue; /* not declared by this version */
630
- inst.decl.set(k, { kind: 'fn', lex: false, e: fd.e });
631
- dataProp(scope, k, remake(inst, fd));
632
- }
633
- return inst;
634
- },
635
- /* live migration: the previous bindings (functions are code the new chart
636
- * re-creates, not bindings); variables the new chart declares nowhere go */
637
- migrate(inst) {
638
- const prev = {};
639
- const declared = new Set(inst.chart.data.map((d) => d.id));
640
- for (const d of inst.chart.decls) if (d) for (const n of [...d.vars, ...d.lex, ...d.fns.map((f) => f.name)]) declared.add(n);
641
- for (const k of Object.keys(inst.scope)) {
642
- if (SYSVARS.has(k) || k === '_event' || k === 'In') continue;
643
- try {
644
- const v = inst.scope[k];
645
- if (!(typeof v === 'function' && remade.has(v)) && !(inst.added && inst.added.includes(k))) prev[k] = v;
646
- } catch {
647
- /* uninitialized */
648
- }
649
- if (!declared.has(k)) {
650
- delete inst.scope[k];
651
- inst.decl.delete(k);
652
- }
653
- }
654
- return prev;
655
- },
656
- /* the variables, for snapshots (getSnapshot().context) */
657
- vars(inst) {
658
- const o = {};
659
- for (const k of Object.keys(inst.scope)) {
660
- if (SYSVARS.has(k) || k === '_event' || k === 'In') continue;
661
- try {
662
- o[k] = inst.scope[k];
663
- } catch {
664
- /* uninitialized */
665
- }
666
- }
667
- return o;
668
- },
669
- };
670
- }