@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.
- package/LICENSE +21 -0
- package/README.md +75 -2
- package/index.d.ts +1221 -0
- package/index.mjs +11 -0
- package/init.d.ts +16 -0
- package/init.mjs +7 -0
- package/lib/address.mjs +112 -0
- package/lib/cbor.mjs +262 -0
- package/lib/checks.mjs +54 -0
- package/lib/compile.mjs +379 -0
- package/lib/convenience.mjs +162 -0
- package/lib/datamodel.mjs +1341 -0
- package/lib/direct.mjs +12 -0
- package/lib/errors.mjs +66 -0
- package/lib/host.mjs +2049 -0
- package/lib/http.mjs +85 -0
- package/lib/module.mjs +324 -0
- package/lib/quickjs.mjs +78 -0
- package/lib/realm-script.mjs +2 -0
- package/lib/realms.mjs +122 -0
- package/lib/state.mjs +32 -0
- package/lib/values.mjs +31 -0
- package/package.json +51 -4
- package/tinyactors.wasm +0 -0
package/lib/http.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// encodeHTTPPost and parseHTTPRequest, as the addon defines them
|
|
2
|
+
// (src/http.c): SCXML's BasicHTTP codec of core (tinyactors/basic_http.h,
|
|
3
|
+
// wasm/src/codecs.c), for a transport the application runs. Both are
|
|
4
|
+
// module calls with no host: their scratch is the environment's arena, a
|
|
5
|
+
// mark per call, and what they give back is copied once (a Uint8Array,
|
|
6
|
+
// strings).
|
|
7
|
+
import { bytesOf, optionalText, textOf } from './checks.mjs';
|
|
8
|
+
import { refusal } from './errors.mjs';
|
|
9
|
+
import { instance } from './state.mjs';
|
|
10
|
+
|
|
11
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
12
|
+
|
|
13
|
+
// encodeHTTPPost({url, event, fields, body}) -> Uint8Array
|
|
14
|
+
export function encodeHTTPPost(post) {
|
|
15
|
+
if (post === null || typeof post !== 'object') throw new TypeError('encodeHTTPPost takes {url, event, fields, body}');
|
|
16
|
+
const { url, event, fields, body } = post;
|
|
17
|
+
const module = instance();
|
|
18
|
+
const scratch = module.scratch;
|
|
19
|
+
return module.scoped(scratch, () => {
|
|
20
|
+
const u = module.text(scratch, textOf(url, 'a post\'s url is a string'));
|
|
21
|
+
const e = module.text(scratch, optionalText(event, 'a post\'s event is a string'));
|
|
22
|
+
let pairs = 0, count = 0;
|
|
23
|
+
if (fields !== undefined && fields !== null) {
|
|
24
|
+
if (!Array.isArray(fields)) throw new TypeError('a post\'s fields are an array of {name, value}');
|
|
25
|
+
count = fields.length;
|
|
26
|
+
pairs = module.room(scratch, 16 * (count || 1));
|
|
27
|
+
for (let i = 0; i < count; i++) {
|
|
28
|
+
const field = fields[i];
|
|
29
|
+
if (field === null || typeof field !== 'object') throw new TypeError('a post\'s fields are an array of {name, value}');
|
|
30
|
+
const [n, nl] = module.text(scratch, textOf(field.name, 'a field\'s name is a string'));
|
|
31
|
+
const [v, vl] = module.text(scratch, textOf(field.value, 'a field\'s value is a string'));
|
|
32
|
+
module.words().set([n, nl, v, vl], (pairs >>> 2) + 4 * i);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const b = module.text(scratch, optionalText(body, 'a post\'s body is a string'));
|
|
36
|
+
module.words().set([u[0], u[1], e[0], e[1], pairs, count, b[0], b[1]], module.record);
|
|
37
|
+
const status = module.call('ta_web_http_encode', module.env);
|
|
38
|
+
if (status !== 0) {
|
|
39
|
+
throw refusal(module.statusName(status), status === -3 ? 'a post\'s url is http://host[:port]/path' : 'no memory for the request');
|
|
40
|
+
}
|
|
41
|
+
return module.copyOut(module.word(0), module.word(1));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// A string of a view core wrote, refused when it is not UTF-8 (a decoded
|
|
46
|
+
// field may hold any byte): never replaced.
|
|
47
|
+
function strict(module, pointer, length) {
|
|
48
|
+
try {
|
|
49
|
+
return utf8.decode(module.bytes().subarray(pointer, pointer + length));
|
|
50
|
+
} catch {
|
|
51
|
+
throw refusal('TA_ERROR_INVALID', 'the request holds text that is not UTF-8');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// parseHTTPRequest(message) -> {method, target, body, event, fields}
|
|
56
|
+
export function parseHTTPRequest(message) {
|
|
57
|
+
const bytes = bytesOf(message, 'parseHTTPRequest takes the message\'s bytes: a Uint8Array or an ArrayBuffer');
|
|
58
|
+
const module = instance();
|
|
59
|
+
const scratch = module.scratch;
|
|
60
|
+
return module.scoped(scratch, () => {
|
|
61
|
+
const [at, length] = module.copyIn(scratch, bytes);
|
|
62
|
+
module.setWord(0, at);
|
|
63
|
+
module.setWord(1, length);
|
|
64
|
+
const status = module.call('ta_web_http_parse', module.env);
|
|
65
|
+
if (status !== 0) throw refusal(module.statusName(status), 'the message is not an HTTP request');
|
|
66
|
+
const words = module.words().slice(module.record, module.record + 10);
|
|
67
|
+
const result = {
|
|
68
|
+
method: strict(module, words[0], words[1]),
|
|
69
|
+
target: strict(module, words[2], words[3]),
|
|
70
|
+
body: strict(module, words[4], words[5]),
|
|
71
|
+
event: strict(module, words[6], words[7]),
|
|
72
|
+
};
|
|
73
|
+
const fields = [];
|
|
74
|
+
const base = words[9] >>> 2;
|
|
75
|
+
for (let i = 0; i < words[8]; i++) {
|
|
76
|
+
const w = module.words();
|
|
77
|
+
fields.push(Object.freeze({
|
|
78
|
+
name: strict(module, w[base + 4 * i], w[base + 4 * i + 1]),
|
|
79
|
+
value: strict(module, w[base + 4 * i + 2], w[base + 4 * i + 3]),
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
result.fields = Object.freeze(fields);
|
|
83
|
+
return Object.freeze(result);
|
|
84
|
+
});
|
|
85
|
+
}
|
package/lib/module.mjs
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// The module instance (docs/browser.md): loads tinyactors.wasm, gives it
|
|
2
|
+
// its imports, and calls its exports. Everything above it (the classes)
|
|
3
|
+
// goes through `WebModule.call` or its guarded exports `WebModule.fn`,
|
|
4
|
+
// never through the exports themselves, so the two rules of "Exceptions, an unclosed host, the
|
|
5
|
+
// floor, the address space" hold in one place:
|
|
6
|
+
//
|
|
7
|
+
// - every import catches what JavaScript throws and answers a status
|
|
8
|
+
// (the error is kept by the import's owner for its turn to report), so
|
|
9
|
+
// no exception unwinds through wasm frames, which would skip C's
|
|
10
|
+
// cleanup and leave shadow stack behind;
|
|
11
|
+
// - anything that still escapes an export (a trap: a WebAssembly
|
|
12
|
+
// RuntimeError, the stack exhausted, unreachable) poisons the
|
|
13
|
+
// instance: every later call refuses with TA_ERROR_STATE naming the
|
|
14
|
+
// first cause, and the application loads the module again.
|
|
15
|
+
//
|
|
16
|
+
// Views of linear memory are this module's own, re-derived when growth
|
|
17
|
+
// detached them (byteLength 0); nothing the application holds is one.
|
|
18
|
+
import { TinyactorsError } from './errors.mjs';
|
|
19
|
+
|
|
20
|
+
// The module the package ships, beside its entries.
|
|
21
|
+
const BUNDLED = new URL('../tinyactors.wasm', import.meta.url);
|
|
22
|
+
|
|
23
|
+
const TA_OK = 0;
|
|
24
|
+
const TA_ERROR_EXECUTION = -1;
|
|
25
|
+
const TA_ERROR_INVALID = -3;
|
|
26
|
+
const TA_ERROR_NO_MEMORY = -4;
|
|
27
|
+
const TA_ERROR_STATE = -6;
|
|
28
|
+
const TA_ERROR_ABORTED = -9;
|
|
29
|
+
|
|
30
|
+
const encoder = new TextEncoder();
|
|
31
|
+
// A double and its two words (little-endian, as wasm's memory is).
|
|
32
|
+
const DOUBLE = new Float64Array(1);
|
|
33
|
+
const BITS = new Uint32Array(DOUBLE.buffer);
|
|
34
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
35
|
+
|
|
36
|
+
// node:fs by a name a bundler does not follow (esbuild cannot resolve a
|
|
37
|
+
// built-in of Node.js for a page): a page never takes the `file:` branch.
|
|
38
|
+
const NODE_FS = 'node:fs/promises';
|
|
39
|
+
|
|
40
|
+
// A WebAssembly.Module from `source`: undefined for the bundled one, a URL
|
|
41
|
+
// or a string (relative to this file), a Response or its promise, bytes,
|
|
42
|
+
// or a module. A `file:` URL is read with node:fs (node, bun).
|
|
43
|
+
async function compileModule(source) {
|
|
44
|
+
if (source instanceof WebAssembly.Module) return source;
|
|
45
|
+
if (source === undefined || source instanceof URL || typeof source === 'string') {
|
|
46
|
+
const url = source === undefined ? BUNDLED : new URL(source, import.meta.url);
|
|
47
|
+
if (url.protocol === 'file:') {
|
|
48
|
+
const { readFile } = await import(/* @vite-ignore */ /* webpackIgnore: true */ NODE_FS);
|
|
49
|
+
return WebAssembly.compile(await readFile(url));
|
|
50
|
+
}
|
|
51
|
+
source = fetch(url);
|
|
52
|
+
}
|
|
53
|
+
if (source instanceof Promise) source = await source;
|
|
54
|
+
if (typeof Response !== 'undefined' && source instanceof Response) {
|
|
55
|
+
if (!source.ok) throw new TinyactorsError(`tinyactors.wasm: ${source.status} ${source.statusText} for ${source.url}`, { status: 'TA_ERROR_INVALID' });
|
|
56
|
+
if (WebAssembly.compileStreaming) {
|
|
57
|
+
try {
|
|
58
|
+
return await WebAssembly.compileStreaming(source.clone());
|
|
59
|
+
} catch {
|
|
60
|
+
// A server that does not give application/wasm: compile the bytes.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return WebAssembly.compile(await source.arrayBuffer());
|
|
64
|
+
}
|
|
65
|
+
return WebAssembly.compile(source);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Loads the module (the bundled one, or `source`) and makes an instance:
|
|
69
|
+
// each load is an instance of its own, whose hosts share its memory.
|
|
70
|
+
export async function load(source) {
|
|
71
|
+
return new WebModule(await compileModule(source));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class WebModule {
|
|
75
|
+
#exports;
|
|
76
|
+
#memory;
|
|
77
|
+
#bytes = new Uint8Array(0);
|
|
78
|
+
#words = new Uint32Array(0);
|
|
79
|
+
#owners = new Map(); // id -> WeakRef of what an import calls (a host's handler, a compilation's)
|
|
80
|
+
#next = 1;
|
|
81
|
+
#poison = null; // the first cause, once poisoned
|
|
82
|
+
#env = 0;
|
|
83
|
+
#record = 0; // the record's index in #words
|
|
84
|
+
|
|
85
|
+
constructor(module) {
|
|
86
|
+
const guard = (id, answer, failed) => {
|
|
87
|
+
// what an import does: its owner's work, never an exception into wasm
|
|
88
|
+
try {
|
|
89
|
+
return answer(this.#owner(id));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.#raised(id, error);
|
|
92
|
+
return failed;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const imports = {
|
|
96
|
+
ta_web: {
|
|
97
|
+
effect: (host, index, extra) => guard(host, (owner) => owner.effect(index, extra) ?? TA_OK, TA_ERROR_EXECUTION),
|
|
98
|
+
output: (host, kind, length) => guard(host, (owner) => owner.output(kind, length) ?? TA_OK, TA_ERROR_NO_MEMORY),
|
|
99
|
+
clock: (host, which) => guard(host, (owner) => owner.clock(which), 0),
|
|
100
|
+
resolve: (compilation) => guard(compilation, (owner) => owner.resolve() ?? TA_OK, TA_ERROR_ABORTED),
|
|
101
|
+
datamodel: (host, entry, slot) => guard(host, (owner) => owner.datamodel(entry, slot) ?? TA_OK, TA_ERROR_EXECUTION),
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
const instance = new WebAssembly.Instance(module, imports);
|
|
105
|
+
this.#exports = instance.exports;
|
|
106
|
+
this.#memory = instance.exports.memory;
|
|
107
|
+
// Each export guarded as call() guards it, with its three arguments
|
|
108
|
+
// fixed (no export takes more): the calls the hot paths make.
|
|
109
|
+
const fn = {};
|
|
110
|
+
for (const [name, f] of Object.entries(instance.exports)) {
|
|
111
|
+
if (typeof f !== 'function') continue;
|
|
112
|
+
fn[name] = (a, b, c) => {
|
|
113
|
+
if (this.#poison !== null) throw this.#poisoned();
|
|
114
|
+
let result;
|
|
115
|
+
try {
|
|
116
|
+
result = f(a, b, c);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (this.#poison === null) this.#poison = error;
|
|
119
|
+
throw this.#poisoned();
|
|
120
|
+
}
|
|
121
|
+
if (this.#poison !== null) throw this.#poisoned();
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
this.fn = Object.freeze(fn);
|
|
126
|
+
this.call('_initialize');
|
|
127
|
+
this.#env = this.call('ta_web_env_new');
|
|
128
|
+
if (this.#env === 0) throw new TinyactorsError('no memory for the module\'s environment', { status: 'TA_ERROR_NO_MEMORY' });
|
|
129
|
+
this.#record = this.call('ta_web_env_record', this.#env) >>> 2;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ---- calls ------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
// Calls export `name`: refused once poisoned; whatever escapes it poisons
|
|
135
|
+
// the instance (and so does a nested call's escape, seen when this one
|
|
136
|
+
// returns).
|
|
137
|
+
call(name, ...args) {
|
|
138
|
+
if (this.#poison !== null) throw this.#poisoned();
|
|
139
|
+
let result;
|
|
140
|
+
try {
|
|
141
|
+
result = this.#exports[name](...args);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (this.#poison === null) this.#poison = error;
|
|
144
|
+
throw this.#poisoned();
|
|
145
|
+
}
|
|
146
|
+
if (this.#poison !== null) throw this.#poisoned();
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
get poisoned() { return this.#poison !== null; }
|
|
151
|
+
|
|
152
|
+
#poisoned() {
|
|
153
|
+
const cause = this.#poison;
|
|
154
|
+
const what = cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
|
|
155
|
+
return new TinyactorsError(`the tinyactors module stopped (load it again): ${what}`, { status: 'TA_ERROR_STATE', cause });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---- owners of imports ----------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
// A number for `owner` (a host's handler, a compilation's resolver),
|
|
161
|
+
// which C gives back to name it in an import; held weakly, so the table
|
|
162
|
+
// keeps nothing alive.
|
|
163
|
+
register(owner) {
|
|
164
|
+
const id = this.#next++;
|
|
165
|
+
this.#owners.set(id, new WeakRef(owner));
|
|
166
|
+
return id;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
unregister(id) { this.#owners.delete(id); }
|
|
170
|
+
|
|
171
|
+
#owner(id) {
|
|
172
|
+
const owner = this.#owners.get(id)?.deref();
|
|
173
|
+
if (owner === undefined) throw new TinyactorsError(`no owner ${id} for an import`, { status: 'TA_ERROR_STALE' });
|
|
174
|
+
return owner;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// What an import's owner threw: kept by it (raised), for its turn or call
|
|
178
|
+
// to report; an owner that is gone loses it.
|
|
179
|
+
#raised(id, error) {
|
|
180
|
+
try {
|
|
181
|
+
this.#owners.get(id)?.deref()?.raised?.(error);
|
|
182
|
+
} catch {
|
|
183
|
+
// keeping the error threw (out of memory): nothing more can be done
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---- memory --------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
get env() { return this.#env; }
|
|
190
|
+
|
|
191
|
+
// The record's index in words(), for a caller that writes many words.
|
|
192
|
+
get record() { return this.#record; }
|
|
193
|
+
|
|
194
|
+
// The views of linear memory, re-derived when growth detached them.
|
|
195
|
+
bytes() {
|
|
196
|
+
if (this.#bytes.byteLength === 0) this.#views();
|
|
197
|
+
return this.#bytes;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
words() {
|
|
201
|
+
if (this.#words.byteLength === 0) this.#views();
|
|
202
|
+
return this.#words;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
#views() {
|
|
206
|
+
const buffer = this.#memory.buffer;
|
|
207
|
+
this.#bytes = new Uint8Array(buffer);
|
|
208
|
+
this.#words = new Uint32Array(buffer);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// The record's words (web.h): written right before an export, read right
|
|
212
|
+
// after; an import reads them at its entry and writes them at its exit.
|
|
213
|
+
word(at) { return this.words()[this.#record + at]; }
|
|
214
|
+
setWord(at, value) { this.words()[this.#record + at] = value; }
|
|
215
|
+
word64(at) { return BigInt(this.word(at)) | (BigInt(this.word(at + 1)) << 32n); }
|
|
216
|
+
setWord64(at, value) {
|
|
217
|
+
const v = BigInt.asUintN(64, BigInt(value));
|
|
218
|
+
this.setWord(at, Number(v & 0xffffffffn));
|
|
219
|
+
this.setWord(at + 1, Number(v >> 32n));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The double whose bits are the record's words `at` and `at + 1`.
|
|
223
|
+
wordFloat(at) {
|
|
224
|
+
BITS[0] = this.word(at);
|
|
225
|
+
BITS[1] = this.word(at + 1);
|
|
226
|
+
return DOUBLE[0];
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
setWordFloat(at, value) {
|
|
230
|
+
DOUBLE[0] = value;
|
|
231
|
+
this.setWord(at, BITS[0]);
|
|
232
|
+
this.setWord(at + 1, BITS[1]);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---- calls with an arena: a mark at entry, a release on every path ----------------
|
|
236
|
+
|
|
237
|
+
// Runs `fn` as one call of `scratch` (an arena of the environment's or a
|
|
238
|
+
// host's): what it allocates there ends when it returns or throws.
|
|
239
|
+
scoped(scratch, fn) {
|
|
240
|
+
const level = this.call('ta_web_scratch_enter', scratch);
|
|
241
|
+
if (level === 0) throw new TinyactorsError('calls nested 64 deep', { status: 'TA_ERROR_STATE' });
|
|
242
|
+
try {
|
|
243
|
+
return fn();
|
|
244
|
+
} finally {
|
|
245
|
+
this.call('ta_web_scratch_leave', scratch, level);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
get scratch() { return this.call('ta_web_env_scratch', this.#env); }
|
|
250
|
+
|
|
251
|
+
// `length` bytes of room in `scratch`, above its current call's mark.
|
|
252
|
+
room(scratch, length) {
|
|
253
|
+
const at = this.call('ta_web_scratch_room', scratch, length) >>> 0; // a u32: past 2 GiB, an i32 reads negative
|
|
254
|
+
if (at === 0) throw new TinyactorsError('no memory for the call', { status: 'TA_ERROR_NO_MEMORY' });
|
|
255
|
+
return at;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Text in: the string's UTF-8 in `scratch`, as [pointer, length]; a lone
|
|
259
|
+
// surrogate is refused, never replaced (docs/values.md).
|
|
260
|
+
text(scratch, string) {
|
|
261
|
+
const n = string.length;
|
|
262
|
+
if (n === 0) return [0, 0];
|
|
263
|
+
let ascii = true;
|
|
264
|
+
for (let i = 0; i < n; i++) {
|
|
265
|
+
if (string.charCodeAt(i) > 0x7f) {
|
|
266
|
+
ascii = false;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (ascii) {
|
|
271
|
+
const at = this.room(scratch, n);
|
|
272
|
+
const bytes = this.bytes();
|
|
273
|
+
for (let i = 0; i < n; i++) bytes[at + i] = string.charCodeAt(i);
|
|
274
|
+
return [at, n];
|
|
275
|
+
}
|
|
276
|
+
if (!string.isWellFormed()) throw new TinyactorsError('text with a lone surrogate', { status: 'TA_ERROR_INVALID' });
|
|
277
|
+
const at = this.room(scratch, 3 * n);
|
|
278
|
+
const { written } = encoder.encodeInto(string, this.bytes().subarray(at, at + 3 * n));
|
|
279
|
+
return [at, written];
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Bytes in: a copy of `bytes` (a Uint8Array) in `scratch`.
|
|
283
|
+
copyIn(scratch, bytes) {
|
|
284
|
+
if (bytes.byteLength === 0) return [0, 0];
|
|
285
|
+
const at = this.room(scratch, bytes.byteLength);
|
|
286
|
+
this.bytes().set(bytes, at);
|
|
287
|
+
return [at, bytes.byteLength];
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Text out: the UTF-8 at `pointer`, decoded.
|
|
291
|
+
string(pointer, length) {
|
|
292
|
+
if (length === 0) return '';
|
|
293
|
+
const bytes = this.bytes();
|
|
294
|
+
if (length <= 32) {
|
|
295
|
+
let ascii = true;
|
|
296
|
+
for (let i = 0; i < length; i++) {
|
|
297
|
+
if (bytes[pointer + i] > 0x7f) {
|
|
298
|
+
ascii = false;
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (ascii) return String.fromCharCode.apply(null, bytes.subarray(pointer, pointer + length));
|
|
303
|
+
}
|
|
304
|
+
return decoder.decode(bytes.subarray(pointer, pointer + length));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Bytes out: a copy the application owns.
|
|
308
|
+
copyOut(pointer, length) { return this.bytes().slice(pointer, pointer + length); }
|
|
309
|
+
|
|
310
|
+
// core's name of a status (ta_status_name).
|
|
311
|
+
statusName(status) {
|
|
312
|
+
const at = this.call('ta_web_status_name', status) >>> 0;
|
|
313
|
+
const bytes = this.bytes();
|
|
314
|
+
let end = at;
|
|
315
|
+
while (bytes[end] !== 0) end++;
|
|
316
|
+
return this.string(at, end - at);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
refusal(status, message) {
|
|
320
|
+
return new TinyactorsError(`${message} (${this.statusName(status)})`, { status: this.statusName(status) });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export const STATUS = Object.freeze({ TA_OK, TA_ERROR_EXECUTION, TA_ERROR_INVALID, TA_ERROR_NO_MEMORY, TA_ERROR_STATE, TA_ERROR_ABORTED });
|
package/lib/quickjs.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// A host's quickjs datamodel (datamodel: "quickjs"): core's ECMAScript
|
|
2
|
+
// datamodel on quickjs-ng, inside the same module (wasm/src/quickjs.c), as
|
|
3
|
+
// the addon holds it (src/host.c, src/effects.c). Its values cross as CBOR
|
|
4
|
+
// only: a value the application gives is written into the host's arena
|
|
5
|
+
// and made a payload by quickjs (an Address as tag 32 on its text); a
|
|
6
|
+
// payload the application reads is quickjs's CBOR, a view of its memory
|
|
7
|
+
// until its next call, read at once (tag 32 as its text).
|
|
8
|
+
import * as cbor from './cbor.mjs';
|
|
9
|
+
import { TinyactorsError } from './errors.mjs';
|
|
10
|
+
|
|
11
|
+
const TA_OK = 0, TA_ERROR_UNSUPPORTED = -7;
|
|
12
|
+
|
|
13
|
+
export class QuickJSDatamodel {
|
|
14
|
+
constructor(state) {
|
|
15
|
+
this.state = state;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
get module() { return this.state.module; }
|
|
19
|
+
|
|
20
|
+
// A payload of `value`, one reference (core's once an input takes it).
|
|
21
|
+
payload(value) {
|
|
22
|
+
const state = this.state, module = this.module;
|
|
23
|
+
const [at, length] = cbor.write(module, state.scratch, value, { addresses: true });
|
|
24
|
+
module.setWord(0, at);
|
|
25
|
+
module.setWord(1, length);
|
|
26
|
+
const status = module.call('ta_web_quickjs_payload', state.pointer);
|
|
27
|
+
if (status !== TA_OK) {
|
|
28
|
+
throw new TinyactorsError('the value could not be made a payload', { status: module.statusName(status) });
|
|
29
|
+
}
|
|
30
|
+
return module.word64(0);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// A payload's value, made from its CBOR in the application's realm.
|
|
34
|
+
exported(payload) {
|
|
35
|
+
const state = this.state, module = this.module;
|
|
36
|
+
const status = module.call('ta_web_quickjs_cbor', state.pointer, Number(payload & 0xFFFFFFFFn), Number(payload >> 32n));
|
|
37
|
+
if (status !== TA_OK) throw new TinyactorsError('the send\'s data could not be read', { status: module.statusName(status) });
|
|
38
|
+
const at = module.word(0), length = module.word(1);
|
|
39
|
+
return module.scoped(state.scratch, () => cbor.read(module, state.scratch, at, length));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// quickjs's state, as bytes (a copy: the room is the datamodel's next
|
|
43
|
+
// output's); a refusal names what could not be stored.
|
|
44
|
+
snapshot() {
|
|
45
|
+
const state = this.state, module = this.module;
|
|
46
|
+
const status = module.call('ta_web_quickjs_state', state.pointer);
|
|
47
|
+
if (status !== TA_OK) {
|
|
48
|
+
const reason = status === TA_ERROR_UNSUPPORTED ? this.reason() : '';
|
|
49
|
+
throw new TinyactorsError(reason || 'the quickjs datamodel\'s state could not be written', { status: module.statusName(status) });
|
|
50
|
+
}
|
|
51
|
+
return module.copyOut(module.word(0), module.word(1));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// quickjs's state back, before anything runs.
|
|
55
|
+
restore(bytes) {
|
|
56
|
+
if (!(bytes instanceof Uint8Array)) throw new TinyactorsError('not a snapshot of a Host', { status: 'TA_ERROR_INVALID' });
|
|
57
|
+
const state = this.state, module = this.module;
|
|
58
|
+
const status = module.scoped(state.scratch, () => {
|
|
59
|
+
const [at, length] = module.copyIn(state.scratch, bytes);
|
|
60
|
+
module.setWord(0, at);
|
|
61
|
+
module.setWord(1, length);
|
|
62
|
+
return module.call('ta_web_quickjs_restore', state.pointer);
|
|
63
|
+
});
|
|
64
|
+
if (status !== TA_OK) throw new TinyactorsError('the quickjs datamodel\'s state does not restore', { status: module.statusName(status) });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Why the last hibernation, export or snapshot was refused ("" when it
|
|
68
|
+
// was not).
|
|
69
|
+
reason() {
|
|
70
|
+
const module = this.module;
|
|
71
|
+
const at = module.call('ta_web_quickjs_reason', this.state.pointer) >>> 0;
|
|
72
|
+
return module.string(at, module.word(0));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
heapBytes() { return this.module.call('ta_web_quickjs_heap_bytes', this.state.pointer); }
|
|
76
|
+
|
|
77
|
+
free() {}
|
|
78
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// GENERATED by mise/wasm.rb from src/datamodel/realm.js: the realm's script as text.
|
|
2
|
+
export default "// The realm's script of the native \"ecmascript\" datamodel (AGENTS.md, \"The\n// native \"ecmascript\" datamodel\"; src/datamodel/realms.c): run once in every\n// node:vm context the datamodel makes, the host's shared one and each\n// declaring session's own, with In() as its argument. It returns the\n// context's kit, the functions that make what must be made with that\n// context's constructors: copies of values crossing between actors, the\n// scopes of a chart (one constructor per chart, over a frozen prototype of\n// null prototype holding the system variables), the system variables of a\n// session, _event, and XML documents. The build embeds it in the addon\n// (mise/napi.rb); it is not shipped as a file and never runs in the\n// application's realm.\n(function tinyactorsRealm(In, Address) {\n 'use strict';\n const LINK = Symbol('tinyactors.session');\n const XML = Symbol.for('tinyactors.xml');\n const SOURCE = Symbol.for('tinyactors.xml.source');\n const { create, defineProperty, freeze, getPrototypeOf, hasOwn, keys } = Object;\n const tag = Object.prototype.toString;\n const source = Function.prototype.toString;\n const isArray = Array.isArray;\n const isView = ArrayBuffer.isView;\n const names = Object.getOwnPropertyNames;\n // The global's own names before any chart's: what a context starts with,\n // and the system variables a declaring session's context gets (declare).\n const baseline = new Set(names(globalThis));\n const systemNames = new Set(['_sessionid', '_name', '_ioprocessors', 'In', '_event']);\n const indirect = eval; // global code of this context, whatever a chart puts on its global\n const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n // The errors copy throws for a value that cannot cross, by status: an\n // input refused with them throws a TinyactorsError of that status.\n const refusals = new WeakMap();\n function refuse(status, error) {\n refusals.set(error, status);\n return error;\n }\n\n function own(object, key, value) {\n defineProperty(object, key, { value, writable: true, enumerable: true, configurable: true });\n }\n\n function plain(prototype) {\n if (prototype === null) return true;\n if (getPrototypeOf(prototype) !== null || !hasOwn(prototype, 'constructor')) return false;\n const made = prototype.constructor;\n return typeof made === 'function' && made.prototype === prototype && made.name === 'Object' &&\n source.call(made).includes('[native code]');\n }\n\n class XMLNode {\n constructor(nodeType, nodeName) {\n this.nodeType = nodeType;\n this.nodeName = nodeName;\n this.childNodes = [];\n defineProperty(this, 'parentNode', { value: null, writable: true, configurable: true });\n }\n get firstChild() { return this.childNodes.length ? this.childNodes[0] : null; }\n get lastChild() { return this.childNodes.length ? this.childNodes[this.childNodes.length - 1] : null; }\n get documentElement() {\n if (this.nodeType !== 9) return undefined;\n for (const child of this.childNodes) if (child.nodeType === 1) return child;\n return null;\n }\n get textContent() {\n if (this.nodeType === 3 || this.nodeType === 4) return this.nodeValue;\n let text = '';\n for (const child of this.childNodes) if (child.nodeType !== 8 && child.nodeType !== 7) text += child.textContent;\n return text;\n }\n appendChild(child) {\n child.parentNode = this;\n this.childNodes.push(child);\n return child;\n }\n getElementsByTagName(name) {\n const found = [];\n const pending = this.childNodes.slice().reverse();\n while (pending.length) {\n const node = pending.pop();\n if (node.nodeType !== 1) continue;\n if (name === '*' || node.nodeName === name || node.localName === name) found.push(node);\n for (let i = node.childNodes.length - 1; i >= 0; i--) pending.push(node.childNodes[i]);\n }\n return found;\n }\n getAttribute(name) {\n return this.attributes !== undefined && hasOwn(this.attributes, name) ? this.attributes[name] : null;\n }\n hasAttribute(name) { return this.getAttribute(name) !== null; }\n // A document's text is the XML it was read from: what an <invoke>'s\n // content expression gives the system as the document to run.\n toString() { return this[SOURCE] !== undefined ? this[SOURCE] : Object.prototype.toString.call(this); }\n // As a neutral value (to_wire, JSON.stringify), a node is its XML text.\n toJSON() { return xmlText(this); }\n }\n defineProperty(XMLNode.prototype, XML, { value: true });\n\n // A node's XML: a document's the text it was read from, any other node's\n // written out.\n const escaped = (text, quote) => String(text).replaceAll('&', '&').replaceAll('<', '<')\n .replaceAll('>', '>').replaceAll(quote ? '\"' : '\\0', quote ? '"' : '\\0');\n function xmlText(node) {\n if (node[SOURCE] !== undefined) return node[SOURCE];\n const inner = () => node.childNodes.map(xmlText).join('');\n switch (node.nodeType) {\n case 1: {\n let text = '<' + node.nodeName;\n for (const key of keys(node.attributes ?? {})) text += ' ' + key + '=\"' + escaped(node.attributes[key], true) + '\"';\n return node.childNodes.length ? text + '>' + inner() + '</' + node.nodeName + '>' : text + '/>';\n }\n case 3: return escaped(node.nodeValue ?? '', false);\n case 4: return '<![CDATA[' + node.nodeValue + ']]>';\n case 7: return '<?' + node.nodeName + ' ' + (node.nodeValue ?? '') + '?>';\n case 8: return '<!--' + (node.nodeValue ?? '') + '-->';\n default: return inner();\n }\n }\n\n // A node of the tree C read with txml: [nodeType, nodeName, text, attributes, children].\n function node(entry) {\n const [type, name, text, attributes, children] = entry;\n const made = new XMLNode(type, name);\n if (type === 1) {\n made.tagName = name;\n const colon = name.indexOf(':');\n made.localName = colon < 0 ? name : name.slice(colon + 1);\n made.attributes = {};\n for (const key of keys(attributes)) own(made.attributes, key, attributes[key]);\n } else if (text !== undefined) made.nodeValue = text;\n for (const child of children) made.appendChild(node(child));\n return made;\n }\n\n function dom(children, text) {\n const document = new XMLNode(9, '#document');\n defineProperty(document, SOURCE, { value: text });\n for (const child of children) document.appendChild(node(child));\n return document;\n }\n\n function copy(value, depth) {\n if (typeof value === 'symbol')\n throw refuse('unsupported', new TypeError('a value crossing between actors is a primitive, a plain object, ' +\n 'an array, a Uint8Array or an XML node, not a symbol'));\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return value;\n if (depth >= 64) throw refuse('invalid', new RangeError('a value nested deeper than 64 (or a cycle) does not cross between actors'));\n if (isArray(value)) {\n const made = [];\n for (let i = 0; i < value.length; i++) made.push(copy(value[i], depth + 1));\n return made;\n }\n if (typeof value === 'object') {\n if (isView(value) && tag.call(value) === '[object Uint8Array]') return new Uint8Array(value);\n // an application's Address (decode gives them): a chart has no reference type, so its text\n if (Address !== undefined && value instanceof Address) return value.text;\n if (value[XML] === true) {\n const made = new XMLNode(value.nodeType, value.nodeName);\n if (value[SOURCE] !== undefined) defineProperty(made, SOURCE, { value: value[SOURCE] });\n for (const key of keys(value)) if (key !== 'childNodes') own(made, key, copy(value[key], depth + 1));\n for (const child of value.childNodes) made.appendChild(copy(child, depth + 1));\n return made;\n }\n if (plain(getPrototypeOf(value))) {\n const made = {};\n for (const key of keys(value)) own(made, key, copy(value[key], depth + 1));\n return made;\n }\n }\n throw refuse('unsupported', new TypeError('a value crossing between actors is a primitive, a plain object, ' +\n 'an array, a Uint8Array or an XML node, not ' + tag.call(value)));\n }\n\n // A payload's value copied out to the application, in the realm this\n // script runs in (the application's own, for this): as copy, but an XML\n // node is its XML text.\n function exported(value, depth) {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return value;\n if (depth >= 64) throw new RangeError('a value nested deeper than 64 (or a cycle)');\n if (isArray(value)) {\n const made = [];\n for (let i = 0; i < value.length; i++) made.push(exported(value[i], depth + 1));\n return made;\n }\n if (typeof value === 'object') {\n if (isView(value) && tag.call(value) === '[object Uint8Array]') return new Uint8Array(value);\n if (value[XML] === true) return xmlText(value);\n const made = {};\n for (const key of keys(value)) own(made, key, exported(value[key], depth + 1));\n return made;\n }\n return value; // a function: kept as it is, as the payload held it\n }\n\n // _ioprocessors, made at its first read and kept in the link: {type:\n // {location}}, with the short names the W3C tests use. The link holds\n // the processors core gave ([type, location] pairs), or undefined when\n // they are the context's template with this session's id (system below).\n let template; // [prefix of the first location, the processors of the session that made it]\n function ioprocessors(link) {\n if (link.io !== undefined && !isArray(link.io)) return link.io;\n let processors = link.io;\n if (processors === undefined) {\n processors = template[1].slice();\n processors[0] = [processors[0][0], template[0] + link.sessionid];\n }\n const io = {};\n for (const [type, location] of processors) {\n const entry = freeze({ location });\n own(io, type, entry);\n if (type.endsWith('#SCXMLEventProcessor')) own(io, 'scxml', entry);\n if (type.endsWith('#BasicHTTPEventProcessor')) own(io, 'basichttp', entry);\n }\n link.io = freeze(io);\n return link.io;\n }\n\n // The system variables of the scopes, read through the session's link.\n const variables = freeze(create(null, {\n _sessionid: { get() { return this[LINK].sessionid; }, enumerable: true },\n _name: { get() { return this[LINK].name; }, enumerable: true },\n _ioprocessors: { get() { return ioprocessors(this[LINK]); }, enumerable: true },\n In: { value: In, enumerable: true },\n }));\n\n // A chart's constructor of scopes: the session's link, then every name the\n // chart declares, then _event, so every scope of the chart has one shape.\n function shape(names) {\n const declared = names.slice();\n function Scope(link) {\n this[LINK] = link;\n for (let i = 0; i < declared.length; i++) own(this, declared[i], undefined);\n defineProperty(this, '_event', { value: undefined, enumerable: true, configurable: true });\n }\n Scope.prototype = variables;\n return Scope;\n }\n\n // A session's link: its system variables and its params until its first\n // event. What sessions of a context have in common is kept once: the name\n // of the session made before (a chart's sessions mostly share one), and\n // the processors as a template whose first location ends with the\n // session's id, so a session whose processors match it, text for text,\n // keeps nothing of them until it reads _ioprocessors.\n let lastName;\n function same(processors, sessionid) {\n if (template === undefined) {\n const first = processors.length ? processors[0][1] : undefined;\n if (typeof first !== 'string' || !first.endsWith(sessionid)) return false;\n template = [first.slice(0, first.length - sessionid.length), processors];\n return true;\n }\n const kept = template[1];\n if (kept.length !== processors.length || processors[0][1] !== template[0] + sessionid) return false;\n for (let i = 0; i < kept.length; i++)\n if (kept[i][0] !== processors[i][0] || (i > 0 && kept[i][1] !== processors[i][1])) return false;\n return true;\n }\n function system(sessionid, name, processors) {\n if (name === lastName) name = lastName;\n else lastName = name;\n return { sessionid, name, io: same(processors, sessionid) ? undefined : processors, init: undefined };\n }\n\n // A context of its own session: the names on its global object.\n function declare(names, link) {\n const global = globalThis;\n global[LINK] = link;\n for (const name of names) if (!hasOwn(global, name)) own(global, name, undefined);\n defineProperty(global, '_sessionid', { get() { return link.sessionid; }, enumerable: true });\n defineProperty(global, '_name', { get() { return link.name; }, enumerable: true });\n defineProperty(global, '_ioprocessors', { get() { return ioprocessors(link); }, enumerable: true });\n defineProperty(global, 'In', { value: In, enumerable: true });\n defineProperty(global, '_event', { value: undefined, enumerable: true, configurable: true });\n return global;\n }\n\n function event(fields) {\n const [name, type, sendid, origin, origintype, invokeid, data, raw] = fields;\n const made = { name, type, sendid, origin, origintype, invokeid, data };\n if (raw !== undefined) made.raw = raw;\n return freeze(made);\n }\n\n // A session's variables, what hibernation writes: [names, values]. A\n // shared chart's scope: its own names but _event. A declaring session's\n // global: the names its chart and scripts put there (var, function, an\n // implicit global); one in `remade` (a function declaration of the\n // chart's scripts) is left out while it holds a function, since the\n // wake makes it again from the scripts.\n // A global's binding is read by its name, not as the global object's\n // property: bun's vm context leaves that property stale after a function\n // writes the var (spike, bun 1.4.1, 2026-10-16: `total += k` in a\n // function, globalThis.total still the old value, `total` the new one).\n function stored(target, remade) {\n const found = [];\n const values = [];\n const global = target === globalThis;\n for (const name of global ? names(target) : keys(target)) {\n if (name === '_event' || (global && (baseline.has(name) || systemNames.has(name)))) continue;\n const value = global && identifier.test(name) ? indirect(name) : target[name];\n if (global && typeof value === 'function' && remade.includes(name)) continue;\n found.push(name);\n values.push(value);\n }\n return [found, values];\n }\n\n // A woken session's variables, `vars` of a hibernation blob (made in\n // another realm), copied into this context: a shared scope keeps the\n // names its chart declares; a declaring session's global takes them all,\n // and its link keeps the names its chart did not declare, which upgrade\n // drops should the blob be of another version.\n function restore(target, vars) {\n const added = [];\n for (const name of keys(vars)) {\n if (hasOwn(target, name)) target[name] = copy(vars[name], 0);\n else if (target === globalThis) {\n own(target, name, copy(vars[name], 0));\n added.push(name);\n }\n }\n if (added.length) target[LINK].added = added;\n }\n\n // A woken session migrated to a new version of its chart: the old\n // bindings, the blob's variables its link kept since the wake, taken\n // from it; on a declaring session's global the names the new chart did\n // not declare go.\n function upgrade(target) {\n const link = target[LINK];\n const old = link.init;\n link.init = undefined;\n if (link.added !== undefined) {\n for (const name of link.added) delete target[name];\n link.added = undefined;\n }\n return old;\n }\n\n // A session's link as a host snapshot holds it: [sessionid, name, its I/O\n // processors as [type, location] pairs, init, added]. The processors are\n // the template's with this session's id, the pairs the link kept, or,\n // once _ioprocessors was read, its entries (an alias, `scxml` or\n // `basichttp`, is the same frozen entry as the type before it).\n function linked(target) {\n const link = target[LINK];\n let processors = link.io;\n if (processors === undefined) {\n processors = template[1].slice();\n processors[0] = [processors[0][0], template[0] + link.sessionid];\n } else if (!isArray(processors)) {\n const seen = new Set();\n const pairs = [];\n for (const type of keys(processors)) {\n const entry = processors[type];\n if (seen.has(entry)) continue;\n seen.add(entry);\n pairs.push([type, entry.location]);\n }\n processors = pairs;\n }\n return [link.sessionid, link.name, processors, link.init, link.added];\n }\n\n // A restored session's link gets the names a snapshot recorded as added\n // (restore computed its own), or none.\n function relink(target, added) {\n target[LINK].added = isArray(added) ? added.slice() : undefined;\n }\n\n // In a scratch context after a chart's scripts were instantiated: the\n // names they declared as functions.\n function functions() {\n const found = [];\n for (const name of names(globalThis)) if (!baseline.has(name) && typeof globalThis[name] === 'function') found.push(name);\n return found;\n }\n\n // The global's names a chart's scripts made (globals), and the names\n // made again from them on a wake (remade): the functions they declare,\n // and the names a strict scratch context's global (`strict`, its\n // globals()) lacks: a sloppy block's function declarations (Annex B),\n // whose var a script in executable content fills each time it runs.\n function globals() {\n return names(globalThis).filter((name) => !baseline.has(name));\n }\n function remade(strict) {\n const kept = new Set(strict);\n const found = functions();\n for (const name of globals()) if (!kept.has(name) && !found.includes(name)) found.push(name);\n return found;\n }\n\n function record(names, values) {\n const made = {};\n for (let i = 0; i < names.length; i++) own(made, names[i], copy(values[i], 1));\n return made;\n }\n\n return freeze({\n LINK,\n global: globalThis,\n objectPrototype: Object.prototype,\n copy: (value) => copy(value, 0),\n exported: (value) => exported(value, 0),\n refusal: (error) => refusals.get(error),\n shape,\n system,\n declare,\n event,\n record,\n stored,\n restore,\n upgrade,\n linked,\n relink,\n functions,\n globals,\n remade,\n dom,\n parse: (text) => JSON.parse(text),\n });\n})\n";
|
package/lib/realms.mjs
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// The realms of the native "ecmascript" datamodel (docs/browser.md, "The
|
|
2
|
+
// native datamodel without node:vm"): where a host's charts evaluate, never
|
|
3
|
+
// the application's realm where the runtime gives another one.
|
|
4
|
+
//
|
|
5
|
+
// node, bun a node:vm context (process.getBuiltinModule), as the addon's;
|
|
6
|
+
// a page a hidden same-origin iframe, one per host, removed when the
|
|
7
|
+
// host is freed (close(), or the FinalizationRegistry);
|
|
8
|
+
// a Worker the worker's own global: a Worker has no document, so an
|
|
9
|
+
// application that wants its charts apart from its own code
|
|
10
|
+
// gives tinyactors a worker of its own (the README says so).
|
|
11
|
+
//
|
|
12
|
+
// Every realm runs the realm's script (src/datamodel/realm.js, the addon's
|
|
13
|
+
// own, embedded as text by mise/wasm.rb into realm-script.mjs) for its
|
|
14
|
+
// kit: what must be made with that realm's constructors (copies of values,
|
|
15
|
+
// scopes, _event, XML nodes) is made by the kit's functions. The
|
|
16
|
+
// application's realm gets a kit of its own, for the values it reads.
|
|
17
|
+
//
|
|
18
|
+
// A realm is made at the host's first chart, not at its creation (an
|
|
19
|
+
// iframe costs about 600 KB and 3.6 ms in Chromium); the policy a page
|
|
20
|
+
// runs under is checked at the host's creation (policyRefusal), in this
|
|
21
|
+
// module's realm, whose policy an iframe inherits.
|
|
22
|
+
import { Address } from './address.mjs';
|
|
23
|
+
import realmScript from './realm-script.mjs';
|
|
24
|
+
|
|
25
|
+
const REALM_NAME = 'tinyactors:realm.js';
|
|
26
|
+
|
|
27
|
+
// The node:vm module where the runtime has one (node, bun), else null.
|
|
28
|
+
function nodeVM() {
|
|
29
|
+
const getBuiltinModule = globalThis.process?.getBuiltinModule;
|
|
30
|
+
if (typeof getBuiltinModule !== 'function') return null;
|
|
31
|
+
try {
|
|
32
|
+
return getBuiltinModule('node:vm') ?? null;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// What kind of realm this runtime gives a host: 'vm', 'iframe' or 'global'.
|
|
39
|
+
export function realmKind() {
|
|
40
|
+
if (nodeVM() !== null) return 'vm';
|
|
41
|
+
if (typeof globalThis.document?.createElement === 'function') return 'iframe';
|
|
42
|
+
return 'global';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Why a host on the native datamodel cannot run here, or null: the native
|
|
46
|
+
// datamodel evaluates the charts' text, so it needs string evaluation
|
|
47
|
+
// (`'unsafe-eval'` in a Content Security Policy's script-src) and, on a
|
|
48
|
+
// page, an iframe of the page's own origin (a CSP or iframe `sandbox`
|
|
49
|
+
// without allow-same-origin gives the page an opaque origin); Trusted
|
|
50
|
+
// Types enforced (`require-trusted-types-for 'script'`) refuse a string to
|
|
51
|
+
// evaluate even with 'unsafe-eval'. In node and bun there is no policy.
|
|
52
|
+
export function policyRefusal() {
|
|
53
|
+
if (nodeVM() !== null) return null;
|
|
54
|
+
try {
|
|
55
|
+
// eslint-disable-next-line no-new-func
|
|
56
|
+
new Function('');
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const text = String(error?.message ?? error);
|
|
59
|
+
if (/trusted/i.test(text)) {
|
|
60
|
+
return 'the page enforces Trusted Types (require-trusted-types-for \'script\'), which refuse the chart text ' +
|
|
61
|
+
'the native datamodel evaluates: use datamodel "quickjs"';
|
|
62
|
+
}
|
|
63
|
+
return 'the page\'s Content Security Policy refuses string evaluation (its script-src has no \'unsafe-eval\'), ' +
|
|
64
|
+
'which the native datamodel needs to evaluate the charts\' text: allow it, or use datamodel "quickjs"';
|
|
65
|
+
}
|
|
66
|
+
// a sandboxed page's opaque origin: its iframes are cross-origin to it
|
|
67
|
+
// (spike, Chromium 141: reading the iframe's eval is a SecurityError)
|
|
68
|
+
if (realmKind() === 'iframe' && globalThis.origin === 'null' && globalThis.location?.protocol !== 'file:') {
|
|
69
|
+
return 'the page runs under a sandbox (CSP or iframe) without allow-same-origin: its opaque origin gives the ' +
|
|
70
|
+
'native datamodel no realm of its own; use datamodel "quickjs"';
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// The kit of this module's realm, the application's: made once.
|
|
76
|
+
let applicationKit = null;
|
|
77
|
+
export function application() {
|
|
78
|
+
if (applicationKit === null) applicationKit = (0, eval)(realmScript)(() => false, Address);
|
|
79
|
+
return applicationKit;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// A new realm for a host, with `In` (the evaluating session's In()) given to
|
|
83
|
+
// its kit: {kind, global, evaluate(source, name), Function, kit, free()}.
|
|
84
|
+
// `evaluate` runs `source` as the realm's global code and answers its
|
|
85
|
+
// value; `Function` is the realm's own constructor.
|
|
86
|
+
export function makeRealm(In) {
|
|
87
|
+
const vm = nodeVM();
|
|
88
|
+
let realm;
|
|
89
|
+
if (vm !== null) {
|
|
90
|
+
const context = vm.createContext();
|
|
91
|
+
realm = {
|
|
92
|
+
kind: 'vm',
|
|
93
|
+
evaluate: (source, name) => vm.runInContext(source, context, { filename: name }),
|
|
94
|
+
free() {},
|
|
95
|
+
};
|
|
96
|
+
realm.global = realm.evaluate('globalThis', REALM_NAME);
|
|
97
|
+
} else if (realmKind() === 'iframe') {
|
|
98
|
+
const frame = globalThis.document.createElement('iframe');
|
|
99
|
+
frame.style.display = 'none';
|
|
100
|
+
frame.setAttribute('aria-hidden', 'true');
|
|
101
|
+
frame.setAttribute('data-tinyactors', 'realm');
|
|
102
|
+
(globalThis.document.body ?? globalThis.document.documentElement).appendChild(frame);
|
|
103
|
+
const window = frame.contentWindow;
|
|
104
|
+
realm = {
|
|
105
|
+
kind: 'iframe',
|
|
106
|
+
global: window,
|
|
107
|
+
// the iframe's eval called as its method: indirect, its global code
|
|
108
|
+
evaluate: (source) => window.eval(source),
|
|
109
|
+
free() { frame.remove(); },
|
|
110
|
+
};
|
|
111
|
+
} else {
|
|
112
|
+
realm = {
|
|
113
|
+
kind: 'global',
|
|
114
|
+
global: globalThis,
|
|
115
|
+
evaluate: (source) => (0, eval)(source),
|
|
116
|
+
free() {},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
realm.Function = realm.evaluate('Function', REALM_NAME);
|
|
120
|
+
realm.kit = realm.evaluate(realmScript, REALM_NAME)(In, Address);
|
|
121
|
+
return realm;
|
|
122
|
+
}
|