@tinyactors/scxmljs 0.1.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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +174 -0
  3. package/THIRD_PARTY_NOTICES +63 -0
  4. package/dist/bridge.d.ts +44 -0
  5. package/dist/bridge.js +254 -0
  6. package/dist/bridge.js.map +1 -0
  7. package/dist/clock.d.ts +113 -0
  8. package/dist/clock.js +310 -0
  9. package/dist/clock.js.map +1 -0
  10. package/dist/common.d.ts +15 -0
  11. package/dist/common.js +14 -0
  12. package/dist/common.js.map +1 -0
  13. package/dist/datamodel-base.d.ts +122 -0
  14. package/dist/datamodel-base.js +268 -0
  15. package/dist/datamodel-base.js.map +1 -0
  16. package/dist/datamodel-quickjs.d.ts +21 -0
  17. package/dist/datamodel-quickjs.js +286 -0
  18. package/dist/datamodel-quickjs.js.map +1 -0
  19. package/dist/datamodel-trusted.d.ts +1 -0
  20. package/dist/datamodel-trusted.js +149 -0
  21. package/dist/datamodel-trusted.js.map +1 -0
  22. package/dist/diagnostics.d.ts +39 -0
  23. package/dist/diagnostics.js +154 -0
  24. package/dist/diagnostics.js.map +1 -0
  25. package/dist/element-events.d.ts +85 -0
  26. package/dist/element-events.js +129 -0
  27. package/dist/element-events.js.map +1 -0
  28. package/dist/events.d.ts +31 -0
  29. package/dist/events.js +33 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/explorer/element.d.ts +150 -0
  32. package/dist/explorer/element.js +1791 -0
  33. package/dist/explorer/element.js.map +1 -0
  34. package/dist/explorer/layout.d.ts +43 -0
  35. package/dist/explorer/layout.js +50 -0
  36. package/dist/explorer/layout.js.map +1 -0
  37. package/dist/explorer/strings.d.ts +275 -0
  38. package/dist/explorer/strings.js +135 -0
  39. package/dist/explorer/strings.js.map +1 -0
  40. package/dist/explorer/styles.d.ts +10 -0
  41. package/dist/explorer/styles.js +265 -0
  42. package/dist/explorer/styles.js.map +1 -0
  43. package/dist/explorer/viewmodel.d.ts +284 -0
  44. package/dist/explorer/viewmodel.js +481 -0
  45. package/dist/explorer/viewmodel.js.map +1 -0
  46. package/dist/explorer.d.ts +21 -0
  47. package/dist/explorer.js +22 -0
  48. package/dist/explorer.js.map +1 -0
  49. package/dist/index.d.ts +34 -0
  50. package/dist/index.js +39 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/model.d.ts +157 -0
  53. package/dist/model.js +485 -0
  54. package/dist/model.js.map +1 -0
  55. package/dist/session-events.d.ts +136 -0
  56. package/dist/session-events.js +114 -0
  57. package/dist/session-events.js.map +1 -0
  58. package/dist/session.d.ts +412 -0
  59. package/dist/session.js +1399 -0
  60. package/dist/session.js.map +1 -0
  61. package/dist/themes/tinyactors.css +44 -0
  62. package/dist/trusted.d.ts +15 -0
  63. package/dist/trusted.js +30 -0
  64. package/dist/trusted.js.map +1 -0
  65. package/dist/ui/announcer.d.ts +22 -0
  66. package/dist/ui/announcer.js +31 -0
  67. package/dist/ui/announcer.js.map +1 -0
  68. package/dist/ui/svg.d.ts +8 -0
  69. package/dist/ui/svg.js +29 -0
  70. package/dist/ui/svg.js.map +1 -0
  71. package/dist/ui/theme.d.ts +34 -0
  72. package/dist/ui/theme.js +151 -0
  73. package/dist/ui/theme.js.map +1 -0
  74. package/dist/view/element.d.ts +172 -0
  75. package/dist/view/element.js +1045 -0
  76. package/dist/view/element.js.map +1 -0
  77. package/dist/view/layout.d.ts +154 -0
  78. package/dist/view/layout.js +1122 -0
  79. package/dist/view/layout.js.map +1 -0
  80. package/dist/view/strings.d.ts +72 -0
  81. package/dist/view/strings.js +48 -0
  82. package/dist/view/strings.js.map +1 -0
  83. package/dist/view/styles.d.ts +1 -0
  84. package/dist/view/styles.js +115 -0
  85. package/dist/view/styles.js.map +1 -0
  86. package/dist/view.d.ts +20 -0
  87. package/dist/view.js +21 -0
  88. package/dist/view.js.map +1 -0
  89. package/package.json +87 -0
@@ -0,0 +1,268 @@
1
+ /** An error thrown by user code or by an illegal data model operation. */
2
+ export class DataModelError extends Error {
3
+ /** Always `"SCXML_DATAMODEL"`, for matching without `instanceof`. */
4
+ code = "SCXML_DATAMODEL";
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "DataModelError";
8
+ }
9
+ }
10
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
11
+ const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await".split(" "));
12
+ export function isLegalVariableName(name) {
13
+ return IDENT.test(name) && !RESERVED.has(name);
14
+ }
15
+ /** Expressions are wrapped in parentheses; tolerate a trailing `;` as authors often write one. */
16
+ export function exprSource(expr) {
17
+ return expr.trim().replace(/;+$/, "");
18
+ }
19
+ /**
20
+ * Read-only system variables (spec §5.10): assigning one throws, which becomes
21
+ * error.execution. The source is CONSTANT and evaluates to an installer that
22
+ * receives the values as data: per-session source text (with the session id
23
+ * inlined) made the host engines' compilation caches grow with every session
24
+ * created in trusted mode — about 2 KB per session, measured in phase 5.
25
+ */
26
+ export const SYSTEM_VARIABLES_SOURCE = `(function () {
27
+ function deepFreeze(o) { if (o && typeof o === "object") { Object.freeze(o); for (var k in o) deepFreeze(o[k]); } return o; }
28
+ function define(name, value) {
29
+ Object.defineProperty(globalThis, name, { enumerable: true, configurable: false,
30
+ get: function () { return value; },
31
+ set: function () { throw new Error(name + " is a read-only system variable"); } });
32
+ }
33
+ return function (values) {
34
+ define("_sessionid", deepFreeze(values.sessionid));
35
+ define("_name", deepFreeze(values.name));
36
+ define("_ioprocessors", deepFreeze(values.ioprocessors));
37
+ };
38
+ })()`;
39
+ /** The values SYSTEM_VARIABLES_SOURCE's installer is called with. */
40
+ export function systemVariableValues(opts) {
41
+ return { sessionid: opts.sessionId, name: opts.name, ioprocessors: opts.ioprocessors };
42
+ }
43
+ /** Defines the read-only `_event` and evaluates to the function that rebinds it. */
44
+ export const EVENT_SETTER_SOURCE = `(function () { var ev;
45
+ Object.defineProperty(globalThis, "_event", { enumerable: true, configurable: false,
46
+ get: function () { return ev; },
47
+ set: function () { throw new Error("_event is a read-only system variable"); } });
48
+ return function (v) { ev = v; }; })()`;
49
+ /** The `_event` object with every field present (spec §5.10.1). */
50
+ export function eventObject(ev) {
51
+ return {
52
+ name: ev.name,
53
+ type: ev.type,
54
+ sendid: ev.sendid,
55
+ origin: ev.origin,
56
+ origintype: ev.origintype,
57
+ invokeid: ev.invokeid,
58
+ data: ev.data,
59
+ };
60
+ }
61
+ /**
62
+ * The engine-independent part of the ECMAScript data model. Subclasses supply
63
+ * four primitives; everything else is shared, so both engines have identical
64
+ * semantics (and both are checked by the conformance suite).
65
+ * @internal
66
+ */
67
+ export class ScriptDataModel {
68
+ /**
69
+ * Temporary globals are named by nesting depth and reused, not numbered
70
+ * per use: under Bun's node:vm, ~600 uses of fresh names that are deleted
71
+ * in a separate script make a later strict-mode read of the assignment's
72
+ * target return undefined (a JavaScriptCore caching issue, reproduced
73
+ * outside this library). Reusing a handful of names avoids it everywhere.
74
+ */
75
+ tmpDepth = 0;
76
+ evaluate(expr) {
77
+ return this.read(`(${exprSource(expr)}\n)`);
78
+ }
79
+ condition(expr) {
80
+ return this.read(`!!(${exprSource(expr)}\n)`) === true;
81
+ }
82
+ script(code) {
83
+ this.run(code);
84
+ }
85
+ declareExpr(id, expr) {
86
+ this.setGlobalFromExpr(id, `(${exprSource(expr)}\n)`);
87
+ }
88
+ declareValue(id, value) {
89
+ this.setGlobal(id, value);
90
+ }
91
+ /**
92
+ * The assignment runs in strict mode, so assigning to an undeclared
93
+ * variable, through `undefined`, or to a system variable throws.
94
+ */
95
+ assignExpr(location, expr) {
96
+ const tmp = this.acquireTmp();
97
+ try {
98
+ this.run(`globalThis.${tmp} = (${exprSource(expr)}\n);`);
99
+ this.assignFromTmp(location, tmp);
100
+ }
101
+ finally {
102
+ this.releaseTmp();
103
+ }
104
+ }
105
+ assignValue(location, value) {
106
+ const tmp = this.acquireTmp();
107
+ try {
108
+ this.setGlobal(tmp, value);
109
+ this.assignFromTmp(location, tmp);
110
+ }
111
+ finally {
112
+ this.releaseTmp();
113
+ }
114
+ }
115
+ isValidLocation(location) {
116
+ try {
117
+ // evaluate only: a missing variable or a broken path throws
118
+ this.run(`(function () { "use strict"; void (${location}\n); })()`);
119
+ return true;
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ }
125
+ foreach(arrayExpr, item, index, body) {
126
+ if (!isLegalVariableName(item))
127
+ throw new DataModelError(`foreach: "${item}" is not a legal variable name`);
128
+ if (index != null && !isLegalVariableName(index))
129
+ throw new DataModelError(`foreach: "${index}" is not a legal variable name`);
130
+ const tmp = this.acquireTmp();
131
+ try {
132
+ this.run(`(function (a) { if (!Array.isArray(a)) throw new TypeError("foreach: array is not an array"); globalThis.${tmp} = a.slice(); })((${exprSource(arrayExpr)}\n));`);
133
+ const length = this.read(`globalThis.${tmp}.length`);
134
+ for (const name of [item, index])
135
+ if (name)
136
+ this.run(`if (!(${JSON.stringify(name)} in globalThis)) globalThis.${name} = undefined;`);
137
+ for (let i = 0; i < length; i++) {
138
+ this.run(`${item} = globalThis.${tmp}[${i}];${index ? ` ${index} = ${i};` : ""}`);
139
+ body();
140
+ }
141
+ }
142
+ finally {
143
+ this.run(`delete globalThis.${tmp};`);
144
+ this.releaseTmp();
145
+ }
146
+ }
147
+ snapshot(ids) {
148
+ const out = {};
149
+ for (const id of ids) {
150
+ try {
151
+ out[id] = this.read(`globalThis[${JSON.stringify(id)}]`);
152
+ }
153
+ catch {
154
+ out[id] = undefined;
155
+ }
156
+ }
157
+ return out;
158
+ }
159
+ assignFromTmp(location, tmp) {
160
+ try {
161
+ // "location" must name something that already exists (spec §5.4): strict mode enforces it
162
+ this.run(`(function () { "use strict"; void (${location}\n); ${location} = globalThis.${tmp}; })();`);
163
+ }
164
+ finally {
165
+ this.run(`delete globalThis.${tmp};`);
166
+ }
167
+ }
168
+ /** A temporary global for the current nesting depth (released in reverse order). */
169
+ acquireTmp() {
170
+ return `__scxml_tmp${this.tmpDepth++}`;
171
+ }
172
+ releaseTmp() {
173
+ this.tmpDepth--;
174
+ }
175
+ }
176
+ /**
177
+ * How every value leaves a data model (logs, send payloads, done data,
178
+ * snapshots, `evaluate()`), identical in both engines:
179
+ *
180
+ * - top-level primitives pass through unchanged (including `undefined`,
181
+ * `NaN`, `-0` and bigints); a top-level function or symbol becomes `undefined`;
182
+ * - inside objects and arrays the JSON rules apply: keys holding `undefined`,
183
+ * functions or symbols are dropped, such array entries become `null`,
184
+ * non-finite numbers become `null`, bigints become strings;
185
+ * - anything with `toJSON()` (Dates, the sandbox's XML values) is replaced by its result;
186
+ * - Maps, Sets and class instances become plain objects of their own enumerable keys;
187
+ * - a reference back into its own ancestors (a cycle) is dropped;
188
+ * - `keep(v)` objects pass through untouched (the trusted engine keeps DOM nodes).
189
+ *
190
+ * `PLAIN_DATA_SOURCE` is the same algorithm as engine-side source; a test
191
+ * checks the two agree.
192
+ */
193
+ export function plainData(value, keep) {
194
+ const ancestors = [];
195
+ const convert = (v, nested) => {
196
+ if (typeof v === "function" || typeof v === "symbol")
197
+ return undefined;
198
+ if (typeof v === "number")
199
+ return nested && !Number.isFinite(v) ? null : v;
200
+ if (typeof v === "bigint")
201
+ return nested ? String(v) : v;
202
+ if (v === null || typeof v !== "object")
203
+ return v;
204
+ if (keep?.(v))
205
+ return v;
206
+ const toJSON = v.toJSON;
207
+ if (typeof toJSON === "function")
208
+ return convert(toJSON.call(v), nested);
209
+ if (ancestors.includes(v))
210
+ return undefined;
211
+ ancestors.push(v);
212
+ try {
213
+ if (Array.isArray(v)) {
214
+ const out = [];
215
+ for (let i = 0; i < v.length; i++) {
216
+ const c = convert(v[i], true);
217
+ out.push(c === undefined ? null : c);
218
+ }
219
+ return out;
220
+ }
221
+ const out = {};
222
+ for (const k of Object.keys(v)) {
223
+ const c = convert(v[k], true);
224
+ if (c !== undefined)
225
+ out[k] = c;
226
+ }
227
+ return out;
228
+ }
229
+ finally {
230
+ ancestors.pop();
231
+ }
232
+ };
233
+ return convert(value, false);
234
+ }
235
+ /** `plainData` as engine-side source: evaluates to a function of one value. */
236
+ export const PLAIN_DATA_SOURCE = `(function () {
237
+ return function (value) {
238
+ var ancestors = [];
239
+ function convert(v, nested) {
240
+ if (typeof v === "function" || typeof v === "symbol") return undefined;
241
+ if (typeof v === "number") return nested && !isFinite(v) ? null : v;
242
+ if (typeof v === "bigint") return nested ? String(v) : v;
243
+ if (v === null || typeof v !== "object") return v;
244
+ if (typeof v.toJSON === "function") return convert(v.toJSON(), nested);
245
+ if (ancestors.indexOf(v) >= 0) return undefined;
246
+ ancestors.push(v);
247
+ try {
248
+ var out, c, i, k, keys;
249
+ if (Array.isArray(v)) {
250
+ out = [];
251
+ for (i = 0; i < v.length; i++) { c = convert(v[i], true); out.push(c === undefined ? null : c); }
252
+ return out;
253
+ }
254
+ out = {};
255
+ keys = Object.keys(v);
256
+ for (i = 0; i < keys.length; i++) { k = keys[i]; c = convert(v[k], true); if (c !== undefined) out[k] = c; }
257
+ return out;
258
+ } finally {
259
+ ancestors.pop();
260
+ }
261
+ }
262
+ return convert(value, false);
263
+ };
264
+ })()`;
265
+ export function isDomNode(v) {
266
+ return typeof v === "object" && v !== null && typeof v.nodeType === "number" && "nodeName" in v;
267
+ }
268
+ //# sourceMappingURL=datamodel-base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datamodel-base.js","sourceRoot":"","sources":["../src/datamodel-base.ts"],"names":[],"mappings":"AAsEA,0EAA0E;AAC1E,MAAM,OAAO,cAAe,SAAQ,KAAK;IACvC,qEAAqE;IAC5D,IAAI,GAAG,iBAA0B,CAAC;IAC3C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AAED,MAAM,KAAK,GAAG,oBAAoB,CAAC;AACnC,MAAM,QAAQ,GAAG,IAAI,GAAG,CACtB,uSA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,CAAC;gBAC/B,MAAM,CAAC,GAAG,OAAO,CAAE,CAA6B,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;gBAC3D,IAAI,CAAC,KAAK,SAAS;oBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;gBAAS,CAAC;YACT,SAAS,CAAC,GAAG,EAAE,CAAC;QAClB,CAAC;IACH,CAAC,CAAC;IACF,OAAO,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4B5B,CAAC;AAEN,MAAM,UAAU,SAAS,CAAC,CAAU;IAClC,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,OAAQ,CAAU,CAAC,QAAQ,KAAK,QAAQ,IAAI,UAAU,IAAK,CAAY,CAAC;AACxH,CAAC","sourcesContent":["/**\n * The ECMAScript data model (spec Appendix B.2), independent of the engine\n * that runs it.\n *\n * All the spec-relevant behaviour lives here, written as JavaScript source\n * that runs *inside* the engine: read-only system variables, strict-mode\n * `<assign>` (so undeclared locations fail), `<foreach>` over a shallow\n * copy, and location checks. An engine only has to run code in a per-session\n * global scope and move values in and out. Two engines exist:\n *\n * - sandboxed (datamodel-quickjs.ts): QuickJS in WebAssembly — isolated,\n * interruptible; the default entry point.\n * - trusted (datamodel-trusted.ts): the host's own JS engine in a separate\n * realm (an iframe, or node:vm) — no download, but no isolation.\n */\nimport type { SCXMLEvent } from \"./events.ts\";\n\n/** What a session hands a data model when it creates one (see `DataModelFactory`). */\nexport interface DataModelOptions {\n /** The value of the read-only `_sessionid` system variable. */\n sessionId: string;\n /** The value of `_name` (the `<scxml name>` attribute). */\n name: string;\n /** The value of `_ioprocessors`: each processor's type URI (and aliases) with its location. */\n ioprocessors: Record<\n string,\n {\n /** The address to send to this session through that processor. */\n location: string;\n }\n >;\n /** Implements the `In(stateId)` predicate against the session's configuration. */\n In: (stateId: string) => boolean;\n /** Maximum run time of a single evaluation before it is interrupted (ms). Sandboxed engine only. */\n timeoutMs?: number;\n /** Maximum memory of one session's engine, in bytes. Sandboxed engine only (default 64 MiB). */\n memoryLimitBytes?: number;\n}\n\n/** What a session needs from its data model. Values in and out are plain host data. */\nexport interface DataModel {\n /** Evaluate an expression; the value is returned as plain data. */\n evaluate(expr: string): unknown;\n /** Evaluate a conditional expression (spec §5.9.1); errors propagate. */\n condition(expr: string): boolean;\n /** Run `<script>` content as a global script. */\n script(code: string): void;\n /** Declare (or re-initialise) a variable from an expression, keeping the value inside the engine. */\n declareExpr(id: string, expr: string): void;\n /** Declare (or re-initialise) a variable from a host value. */\n declareValue(id: string, value: unknown): void;\n /** `<assign location expr>`: evaluated and assigned inside the engine. */\n assignExpr(location: string, expr: string): void;\n /** Assign a host value (e.g. inline content) to a location. */\n assignValue(location: string, value: unknown): void;\n /** Is `location` a valid location right now? */\n isValidLocation(location: string): boolean;\n /** `<foreach>` (spec §4.6). */\n foreach(arrayExpr: string, item: string, index: string | null, body: () => void): void;\n /** Bind `_event`. */\n setEvent(ev: SCXMLEvent): void;\n /** Current values of the given variables, as plain data. */\n snapshot(ids: Iterable<string>): Record<string, unknown>;\n /** Release the engine (QuickJS context or realm). The data model isn't used afterwards. */\n dispose(): void;\n}\n\n/** Creates one data model per session. Pass one as `SessionOptions.datamodel` to plug in another engine. */\nexport type DataModelFactory = (opts: DataModelOptions) => DataModel;\n\n/** An error thrown by user code or by an illegal data model operation. */\nexport class DataModelError extends Error {\n /** Always `\"SCXML_DATAMODEL\"`, for matching without `instanceof`. */\n readonly code = \"SCXML_DATAMODEL\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"DataModelError\";\n }\n}\n\nconst IDENT = /^[A-Za-z_$][\\w$]*$/;\nconst RESERVED = new Set(\n \"break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await\".split(\n \" \",\n ),\n);\n\nexport function isLegalVariableName(name: string) {\n return IDENT.test(name) && !RESERVED.has(name);\n}\n\n/** Expressions are wrapped in parentheses; tolerate a trailing `;` as authors often write one. */\nexport function exprSource(expr: string) {\n return expr.trim().replace(/;+$/, \"\");\n}\n\n/**\n * Read-only system variables (spec §5.10): assigning one throws, which becomes\n * error.execution. The source is CONSTANT and evaluates to an installer that\n * receives the values as data: per-session source text (with the session id\n * inlined) made the host engines' compilation caches grow with every session\n * created in trusted mode — about 2 KB per session, measured in phase 5.\n */\nexport const SYSTEM_VARIABLES_SOURCE = `(function () {\n function deepFreeze(o) { if (o && typeof o === \"object\") { Object.freeze(o); for (var k in o) deepFreeze(o[k]); } return o; }\n function define(name, value) {\n Object.defineProperty(globalThis, name, { enumerable: true, configurable: false,\n get: function () { return value; },\n set: function () { throw new Error(name + \" is a read-only system variable\"); } });\n }\n return function (values) {\n define(\"_sessionid\", deepFreeze(values.sessionid));\n define(\"_name\", deepFreeze(values.name));\n define(\"_ioprocessors\", deepFreeze(values.ioprocessors));\n };\n})()`;\n\n/** The values SYSTEM_VARIABLES_SOURCE's installer is called with. */\nexport function systemVariableValues(opts: DataModelOptions) {\n return { sessionid: opts.sessionId, name: opts.name, ioprocessors: opts.ioprocessors };\n}\n\n/** Defines the read-only `_event` and evaluates to the function that rebinds it. */\nexport const EVENT_SETTER_SOURCE = `(function () { var ev;\n Object.defineProperty(globalThis, \"_event\", { enumerable: true, configurable: false,\n get: function () { return ev; },\n set: function () { throw new Error(\"_event is a read-only system variable\"); } });\n return function (v) { ev = v; }; })()`;\n\n/** The `_event` object with every field present (spec §5.10.1). */\nexport function eventObject(ev: SCXMLEvent) {\n return {\n name: ev.name,\n type: ev.type,\n sendid: ev.sendid,\n origin: ev.origin,\n origintype: ev.origintype,\n invokeid: ev.invokeid,\n data: ev.data,\n };\n}\n\n/**\n * The engine-independent part of the ECMAScript data model. Subclasses supply\n * four primitives; everything else is shared, so both engines have identical\n * semantics (and both are checked by the conformance suite).\n * @internal\n */\nexport abstract class ScriptDataModel implements DataModel {\n /**\n * Temporary globals are named by nesting depth and reused, not numbered\n * per use: under Bun's node:vm, ~600 uses of fresh names that are deleted\n * in a separate script make a later strict-mode read of the assignment's\n * target return undefined (a JavaScriptCore caching issue, reproduced\n * outside this library). Reusing a handful of names avoids it everywhere.\n */\n private tmpDepth = 0;\n\n /** Run code as a global script; throw DataModelError on failure. */\n protected abstract run(code: string): void;\n /** Evaluate expression code; return its value as plain host data. */\n protected abstract read(code: string): unknown;\n /** Set a global variable to a host value. */\n protected abstract setGlobal(name: string, value: unknown): void;\n /** Set a global variable to the value of expression code, kept inside the engine. */\n protected abstract setGlobalFromExpr(name: string, code: string): void;\n abstract setEvent(ev: SCXMLEvent): void;\n abstract dispose(): void;\n\n evaluate(expr: string): unknown {\n return this.read(`(${exprSource(expr)}\\n)`);\n }\n\n condition(expr: string): boolean {\n return this.read(`!!(${exprSource(expr)}\\n)`) === true;\n }\n\n script(code: string) {\n this.run(code);\n }\n\n declareExpr(id: string, expr: string) {\n this.setGlobalFromExpr(id, `(${exprSource(expr)}\\n)`);\n }\n\n declareValue(id: string, value: unknown) {\n this.setGlobal(id, value);\n }\n\n /**\n * The assignment runs in strict mode, so assigning to an undeclared\n * variable, through `undefined`, or to a system variable throws.\n */\n assignExpr(location: string, expr: string) {\n const tmp = this.acquireTmp();\n try {\n this.run(`globalThis.${tmp} = (${exprSource(expr)}\\n);`);\n this.assignFromTmp(location, tmp);\n } finally {\n this.releaseTmp();\n }\n }\n\n assignValue(location: string, value: unknown) {\n const tmp = this.acquireTmp();\n try {\n this.setGlobal(tmp, value);\n this.assignFromTmp(location, tmp);\n } finally {\n this.releaseTmp();\n }\n }\n\n isValidLocation(location: string): boolean {\n try {\n // evaluate only: a missing variable or a broken path throws\n this.run(`(function () { \"use strict\"; void (${location}\\n); })()`);\n return true;\n } catch {\n return false;\n }\n }\n\n foreach(arrayExpr: string, item: string, index: string | null, body: () => void) {\n if (!isLegalVariableName(item)) throw new DataModelError(`foreach: \"${item}\" is not a legal variable name`);\n if (index != null && !isLegalVariableName(index)) throw new DataModelError(`foreach: \"${index}\" is not a legal variable name`);\n const tmp = this.acquireTmp();\n try {\n this.run(\n `(function (a) { if (!Array.isArray(a)) throw new TypeError(\"foreach: array is not an array\"); globalThis.${tmp} = a.slice(); })((${exprSource(arrayExpr)}\\n));`,\n );\n const length = this.read(`globalThis.${tmp}.length`) as number;\n for (const name of [item, index]) if (name) this.run(`if (!(${JSON.stringify(name)} in globalThis)) globalThis.${name} = undefined;`);\n for (let i = 0; i < length; i++) {\n this.run(`${item} = globalThis.${tmp}[${i}];${index ? ` ${index} = ${i};` : \"\"}`);\n body();\n }\n } finally {\n this.run(`delete globalThis.${tmp};`);\n this.releaseTmp();\n }\n }\n\n snapshot(ids: Iterable<string>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const id of ids) {\n try {\n out[id] = this.read(`globalThis[${JSON.stringify(id)}]`);\n } catch {\n out[id] = undefined;\n }\n }\n return out;\n }\n\n private assignFromTmp(location: string, tmp: string) {\n try {\n // \"location\" must name something that already exists (spec §5.4): strict mode enforces it\n this.run(`(function () { \"use strict\"; void (${location}\\n); ${location} = globalThis.${tmp}; })();`);\n } finally {\n this.run(`delete globalThis.${tmp};`);\n }\n }\n\n /** A temporary global for the current nesting depth (released in reverse order). */\n private acquireTmp() {\n return `__scxml_tmp${this.tmpDepth++}`;\n }\n\n private releaseTmp() {\n this.tmpDepth--;\n }\n}\n\n/**\n * How every value leaves a data model (logs, send payloads, done data,\n * snapshots, `evaluate()`), identical in both engines:\n *\n * - top-level primitives pass through unchanged (including `undefined`,\n * `NaN`, `-0` and bigints); a top-level function or symbol becomes `undefined`;\n * - inside objects and arrays the JSON rules apply: keys holding `undefined`,\n * functions or symbols are dropped, such array entries become `null`,\n * non-finite numbers become `null`, bigints become strings;\n * - anything with `toJSON()` (Dates, the sandbox's XML values) is replaced by its result;\n * - Maps, Sets and class instances become plain objects of their own enumerable keys;\n * - a reference back into its own ancestors (a cycle) is dropped;\n * - `keep(v)` objects pass through untouched (the trusted engine keeps DOM nodes).\n *\n * `PLAIN_DATA_SOURCE` is the same algorithm as engine-side source; a test\n * checks the two agree.\n */\nexport function plainData(value: unknown, keep?: (v: object) => boolean): unknown {\n const ancestors: object[] = [];\n const convert = (v: unknown, nested: boolean): unknown => {\n if (typeof v === \"function\" || typeof v === \"symbol\") return undefined;\n if (typeof v === \"number\") return nested && !Number.isFinite(v) ? null : v;\n if (typeof v === \"bigint\") return nested ? String(v) : v;\n if (v === null || typeof v !== \"object\") return v;\n if (keep?.(v)) return v;\n const toJSON = (v as { toJSON?: unknown }).toJSON;\n if (typeof toJSON === \"function\") return convert(toJSON.call(v), nested);\n if (ancestors.includes(v)) return undefined;\n ancestors.push(v);\n try {\n if (Array.isArray(v)) {\n const out: unknown[] = [];\n for (let i = 0; i < v.length; i++) {\n const c = convert(v[i], true);\n out.push(c === undefined ? null : c);\n }\n return out;\n }\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(v)) {\n const c = convert((v as Record<string, unknown>)[k], true);\n if (c !== undefined) out[k] = c;\n }\n return out;\n } finally {\n ancestors.pop();\n }\n };\n return convert(value, false);\n}\n\n/** `plainData` as engine-side source: evaluates to a function of one value. */\nexport const PLAIN_DATA_SOURCE = `(function () {\n return function (value) {\n var ancestors = [];\n function convert(v, nested) {\n if (typeof v === \"function\" || typeof v === \"symbol\") return undefined;\n if (typeof v === \"number\") return nested && !isFinite(v) ? null : v;\n if (typeof v === \"bigint\") return nested ? String(v) : v;\n if (v === null || typeof v !== \"object\") return v;\n if (typeof v.toJSON === \"function\") return convert(v.toJSON(), nested);\n if (ancestors.indexOf(v) >= 0) return undefined;\n ancestors.push(v);\n try {\n var out, c, i, k, keys;\n if (Array.isArray(v)) {\n out = [];\n for (i = 0; i < v.length; i++) { c = convert(v[i], true); out.push(c === undefined ? null : c); }\n return out;\n }\n out = {};\n keys = Object.keys(v);\n for (i = 0; i < keys.length; i++) { k = keys[i]; c = convert(v[k], true); if (c !== undefined) out[k] = c; }\n return out;\n } finally {\n ancestors.pop();\n }\n }\n return convert(value, false);\n };\n})()`;\n\nexport function isDomNode(v: unknown): v is Node {\n return typeof v === \"object\" && v !== null && typeof (v as Node).nodeType === \"number\" && \"nodeName\" in (v as object);\n}\n"]}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The sandboxed engine for the ECMAScript data model: one QuickJS context
3
+ * (WebAssembly) per session. Semantics live in datamodel-base.ts.
4
+ *
5
+ * Why a separate engine: the spec's scoping rules need a real global scope per
6
+ * session. `<script>` runs as a global script (so `var` and function
7
+ * declarations persist), `<data>` ids become global variables, system
8
+ * variables are read-only (assigning one raises `error.execution`), and
9
+ * sessions cannot see each other or the host page.
10
+ *
11
+ * Values cross the boundary as plain data (JSON-like, plus `undefined`):
12
+ * event payloads go in, send payloads / logs / snapshots come out. Anything
13
+ * that stays inside (assign, foreach, data expressions) is never marshalled,
14
+ * so functions and object identity survive.
15
+ */
16
+ /**
17
+ * Loads the QuickJS WebAssembly module (once; later calls return the same
18
+ * promise). `createSession` does this for you; await it yourself before
19
+ * constructing `Session`s directly.
20
+ */
21
+ export declare function loadQuickJS(): Promise<void>;
@@ -0,0 +1,286 @@
1
+ /**
2
+ * The sandboxed engine for the ECMAScript data model: one QuickJS context
3
+ * (WebAssembly) per session. Semantics live in datamodel-base.ts.
4
+ *
5
+ * Why a separate engine: the spec's scoping rules need a real global scope per
6
+ * session. `<script>` runs as a global script (so `var` and function
7
+ * declarations persist), `<data>` ids become global variables, system
8
+ * variables are read-only (assigning one raises `error.execution`), and
9
+ * sessions cannot see each other or the host page.
10
+ *
11
+ * Values cross the boundary as plain data (JSON-like, plus `undefined`):
12
+ * event payloads go in, send payloads / logs / snapshots come out. Anything
13
+ * that stays inside (assign, foreach, data expressions) is never marshalled,
14
+ * so functions and object identity survive.
15
+ */
16
+ // the WebAssembly is inlined, so bundlers and browsers need no extra asset
17
+ import variant from "@jitl/quickjs-singlefile-browser-release-sync";
18
+ import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
19
+ import { DataModelError, EVENT_SETTER_SOURCE, eventObject, isDomNode, PLAIN_DATA_SOURCE, ScriptDataModel, SYSTEM_VARIABLES_SOURCE, systemVariableValues, } from "./datamodel-base.js";
20
+ let modulePromise;
21
+ let moduleSync;
22
+ /**
23
+ * Loads the QuickJS WebAssembly module (once; later calls return the same
24
+ * promise). `createSession` does this for you; await it yourself before
25
+ * constructing `Session`s directly.
26
+ */
27
+ export function loadQuickJS() {
28
+ modulePromise ??= newQuickJSWASMModuleFromVariant(variant).then((m) => (moduleSync = m));
29
+ return modulePromise.then(() => { });
30
+ }
31
+ /** @internal */
32
+ export function quickJSModule() {
33
+ if (!moduleSync)
34
+ throw new Error("QuickJS is not loaded yet: await loadQuickJS() (createSession does this for you)");
35
+ return moduleSync;
36
+ }
37
+ /**
38
+ * The sandboxed ECMAScript data model: one QuickJS context per session.
39
+ * @internal
40
+ */
41
+ export class QuickJSDataModel extends ScriptDataModel {
42
+ vm;
43
+ setEventFn;
44
+ plainFn;
45
+ deadline = 0;
46
+ timeoutMs;
47
+ disposed = false;
48
+ constructor(opts) {
49
+ super();
50
+ this.timeoutMs = opts.timeoutMs ?? 2000;
51
+ this.vm = quickJSModule().newContext();
52
+ const rt = this.vm.runtime;
53
+ rt.setMemoryLimit(opts.memoryLimitBytes ?? 64 * 1024 * 1024);
54
+ rt.setMaxStackSize(1024 * 1024);
55
+ rt.setInterruptHandler(() => Date.now() > this.deadline);
56
+ const inFn = this.vm.newFunction("In", (h) => (opts.In(this.vm.getString(h)) ? this.vm.true : this.vm.false));
57
+ this.vm.setProp(this.vm.global, "In", inFn);
58
+ inFn.dispose();
59
+ const install = this.evalHandle(SYSTEM_VARIABLES_SOURCE);
60
+ const values = this.toVm(systemVariableValues(opts));
61
+ const r = this.vm.callFunction(install, this.vm.undefined, values);
62
+ values.dispose();
63
+ install.dispose();
64
+ if (r.error) {
65
+ const err = this.describe(r.error);
66
+ r.error.dispose();
67
+ throw new DataModelError(err);
68
+ }
69
+ r.value.dispose();
70
+ this.run(MINI_DOM);
71
+ this.setEventFn = this.evalHandle(EVENT_SETTER_SOURCE);
72
+ this.plainFn = this.evalHandle(PLAIN_DATA_SOURCE);
73
+ }
74
+ dispose() {
75
+ if (this.disposed)
76
+ return;
77
+ this.disposed = true;
78
+ this.setEventFn.dispose();
79
+ this.plainFn.dispose();
80
+ this.vm.dispose();
81
+ }
82
+ setEvent(ev) {
83
+ const h = this.toVm(eventObject(ev));
84
+ const r = this.vm.callFunction(this.setEventFn, this.vm.undefined, h);
85
+ h.dispose();
86
+ if (r.error)
87
+ r.error.dispose();
88
+ else
89
+ r.value.dispose();
90
+ }
91
+ // ─────────────────────────── engine primitives ───────────────────────────
92
+ run(code) {
93
+ this.evalHandle(code).dispose();
94
+ }
95
+ read(code) {
96
+ const h = this.evalHandle(code);
97
+ try {
98
+ // converted to plain data inside the engine first (see plainData), then copied out
99
+ this.deadline = Date.now() + this.timeoutMs;
100
+ const r = this.vm.callFunction(this.plainFn, this.vm.undefined, h);
101
+ if (r.error) {
102
+ r.error.dispose();
103
+ return undefined;
104
+ }
105
+ try {
106
+ return this.dump(r.value);
107
+ }
108
+ finally {
109
+ r.value.dispose();
110
+ }
111
+ }
112
+ finally {
113
+ h.dispose();
114
+ }
115
+ }
116
+ setGlobal(name, value) {
117
+ const h = this.toVm(value);
118
+ this.vm.setProp(this.vm.global, name, h);
119
+ h.dispose();
120
+ }
121
+ setGlobalFromExpr(name, code) {
122
+ const h = this.evalHandle(code);
123
+ this.vm.setProp(this.vm.global, name, h);
124
+ h.dispose();
125
+ }
126
+ evalHandle(code) {
127
+ this.deadline = Date.now() + this.timeoutMs;
128
+ const r = this.vm.evalCode(code, "scxml.js");
129
+ if (r.error) {
130
+ const err = this.describe(r.error);
131
+ r.error.dispose();
132
+ throw new DataModelError(err);
133
+ }
134
+ return r.value;
135
+ }
136
+ describe(h) {
137
+ try {
138
+ const e = this.vm.dump(h);
139
+ if (e && typeof e === "object" && "message" in e) {
140
+ const err = e;
141
+ return `${err.name ?? "Error"}: ${err.message}`;
142
+ }
143
+ return String(e);
144
+ }
145
+ catch {
146
+ return "error";
147
+ }
148
+ }
149
+ dump(h) {
150
+ try {
151
+ return this.vm.dump(h);
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ }
157
+ // ─────────────────────────── marshalling ─────────────────────────────
158
+ /** Host value → engine value. A reference back into its own ancestors (a cycle) becomes `undefined`, as in the trusted engine. */
159
+ toVm(value, depth = 0, ancestors = []) {
160
+ const vm = this.vm;
161
+ if (depth > 64)
162
+ return vm.undefined;
163
+ switch (typeof value) {
164
+ case "undefined":
165
+ return vm.undefined;
166
+ case "boolean":
167
+ return value ? vm.true : vm.false;
168
+ case "number":
169
+ return vm.newNumber(value);
170
+ case "bigint":
171
+ return vm.newBigInt(value);
172
+ case "string":
173
+ return vm.newString(value);
174
+ case "object": {
175
+ if (value === null)
176
+ return vm.null;
177
+ if (ancestors.includes(value))
178
+ return vm.undefined;
179
+ if (value instanceof Date)
180
+ return vm.newNumber(value.getTime());
181
+ if (isDomNode(value))
182
+ return this.evalHandle(`__scxml_xml(${JSON.stringify(domTree(value))})`);
183
+ ancestors.push(value);
184
+ try {
185
+ if (Array.isArray(value)) {
186
+ const arr = vm.newArray();
187
+ value.forEach((v, i) => {
188
+ const h = this.toVm(v, depth + 1, ancestors);
189
+ vm.setProp(arr, i, h);
190
+ h.dispose();
191
+ });
192
+ return arr;
193
+ }
194
+ const obj = vm.newObject();
195
+ for (const [k, v] of Object.entries(value)) {
196
+ const h = this.toVm(v, depth + 1, ancestors);
197
+ vm.setProp(obj, k, h);
198
+ h.dispose();
199
+ }
200
+ return obj;
201
+ }
202
+ finally {
203
+ ancestors.pop();
204
+ }
205
+ }
206
+ default:
207
+ return vm.undefined; // functions and symbols do not cross the boundary
208
+ }
209
+ }
210
+ }
211
+ /**
212
+ * Factory for the sandboxed data model. QuickJS must be loaded (`await loadQuickJS()`).
213
+ * @internal
214
+ */
215
+ export const sandboxedDataModel = (opts) => new QuickJSDataModel(opts);
216
+ /** Host DOM → plain tree, rebuilt as a DOM inside the sandbox by MINI_DOM. */
217
+ function domTree(node) {
218
+ if (node.nodeType === 9)
219
+ return domTree(node.documentElement);
220
+ if (node.nodeType !== 1)
221
+ return { t: "x", v: node.nodeValue ?? "" };
222
+ const el = node;
223
+ return {
224
+ t: "e",
225
+ n: el.localName,
226
+ p: el.prefix,
227
+ ns: el.namespaceURI,
228
+ a: Array.from(el.attributes).map((a) => [a.name, a.value]),
229
+ c: Array.from(el.childNodes)
230
+ .filter((c) => c.nodeType === 1 || c.nodeType === 3 || c.nodeType === 4)
231
+ .map(domTree),
232
+ };
233
+ }
234
+ /**
235
+ * A small XML DOM for the sandbox (spec B.2: XML data values are DOM objects).
236
+ * Values are Documents; they serialise back to XML text when they leave the
237
+ * sandbox (toJSON) or are converted to strings.
238
+ */
239
+ const MINI_DOM = `
240
+ var __scxml_xml = (function () {
241
+ function esc(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }
242
+ function Text(v, parent) { this.nodeType = 3; this.nodeName = "#text"; this.nodeValue = this.data = v; this.parentNode = parent; this.childNodes = []; }
243
+ Object.defineProperty(Text.prototype, "textContent", { get: function () { return this.nodeValue; } });
244
+ Text.prototype.serialize = function () { return esc(this.nodeValue).replace(/"/g, '"'); };
245
+ function Element(t, parent) {
246
+ var self = this;
247
+ this.nodeType = 1; this.localName = t.n; this.prefix = t.p || null; this.namespaceURI = t.ns || null;
248
+ this.nodeName = this.tagName = t.p ? t.p + ":" + t.n : t.n; this.parentNode = parent || null;
249
+ this.attributes = t.a.map(function (a) { return { name: a[0], nodeName: a[0], value: a[1], nodeValue: a[1] }; });
250
+ this.childNodes = t.c.map(function (c) { return c.t === "e" ? new Element(c, self) : new Text(c.v, self); });
251
+ }
252
+ var E = Element.prototype;
253
+ Object.defineProperty(E, "children", { get: function () { return this.childNodes.filter(function (c) { return c.nodeType === 1; }); } });
254
+ Object.defineProperty(E, "firstChild", { get: function () { return this.childNodes[0] || null; } });
255
+ Object.defineProperty(E, "lastChild", { get: function () { return this.childNodes[this.childNodes.length - 1] || null; } });
256
+ Object.defineProperty(E, "firstElementChild", { get: function () { return this.children[0] || null; } });
257
+ Object.defineProperty(E, "textContent", { get: function () { return this.childNodes.map(function (c) { return c.textContent; }).join(""); } });
258
+ E.getAttribute = function (n) { for (var i = 0; i < this.attributes.length; i++) if (this.attributes[i].name === n) return this.attributes[i].value; return null; };
259
+ E.hasAttribute = function (n) { return this.getAttribute(n) !== null; };
260
+ E.setAttribute = function (n, v) { v = String(v); for (var i = 0; i < this.attributes.length; i++) if (this.attributes[i].name === n) { this.attributes[i].value = this.attributes[i].nodeValue = v; return; } this.attributes.push({ name: n, nodeName: n, value: v, nodeValue: v }); };
261
+ E.getElementsByTagName = function (name) {
262
+ var out = [];
263
+ (function walk(e) { e.children.forEach(function (c) { if (name === "*" || c.nodeName === name || c.localName === name) out.push(c); walk(c); }); })(this);
264
+ return out;
265
+ };
266
+ E.serialize = function (parentNs) {
267
+ var self = this;
268
+ var a = this.attributes.map(function (x) { return " " + x.name + '="' + esc(x.value) + '"'; }).join("");
269
+ // declare the default namespace where it changes (it may have been inherited in the source)
270
+ if (!this.prefix && (this.namespaceURI || null) !== (parentNs === undefined ? null : parentNs) && !this.hasAttribute("xmlns"))
271
+ a = ' xmlns="' + esc(this.namespaceURI || "") + '"' + a;
272
+ var body = this.childNodes.map(function (c) { return c.serialize(self.namespaceURI || null); }).join("");
273
+ return "<" + this.nodeName + a + (body ? ">" + body + "</" + this.nodeName + ">" : "/>");
274
+ };
275
+ E.toString = E.toJSON = function () { return this.serialize(); };
276
+ function Doc(root) { this.nodeType = 9; this.nodeName = "#document"; this.documentElement = root; this.childNodes = [root]; root.parentNode = this; }
277
+ Doc.prototype.getElementsByTagName = function (name) {
278
+ var r = this.documentElement;
279
+ return (name === "*" || r.nodeName === name || r.localName === name ? [r] : []).concat(r.getElementsByTagName(name));
280
+ };
281
+ Doc.prototype.toString = Doc.prototype.toJSON = function () { return this.documentElement.serialize(); };
282
+ Object.defineProperty(Doc.prototype, "textContent", { get: function () { return this.documentElement.textContent; } });
283
+ return function (tree) { return tree.t === "e" ? new Doc(new Element(tree)) : tree.v; };
284
+ })();
285
+ `;
286
+ //# sourceMappingURL=datamodel-quickjs.js.map