@tinyactors/wasm 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +84 -2
- package/index.d.ts +1530 -0
- package/index.mjs +10 -0
- package/init.d.ts +16 -0
- package/init.mjs +6 -0
- package/lib/address.mjs +112 -0
- package/lib/cbor.mjs +262 -0
- package/lib/checks.mjs +56 -0
- package/lib/compile.mjs +390 -0
- package/lib/convenience.mjs +876 -0
- package/lib/datamodel.mjs +1002 -0
- package/lib/direct.mjs +14 -0
- package/lib/errors.mjs +94 -0
- package/lib/host.mjs +2206 -0
- package/lib/http.mjs +104 -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/lib/version.mjs +5 -0
- package/package.json +51 -4
- package/tinyactors.wasm +0 -0
package/lib/http.mjs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
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 * as cbor from './cbor.mjs';
|
|
10
|
+
import { instance } from './state.mjs';
|
|
11
|
+
|
|
12
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
13
|
+
|
|
14
|
+
// encodeHTTPPost({url, event, fields, body}) -> Uint8Array
|
|
15
|
+
export function encodeHTTPPost(post) {
|
|
16
|
+
if (post === null || typeof post !== 'object') throw new TypeError('encodeHTTPPost takes {url, event, fields, body}');
|
|
17
|
+
const { url, event, fields, body } = post;
|
|
18
|
+
const module = instance();
|
|
19
|
+
const scratch = module.scratch;
|
|
20
|
+
return module.scoped(scratch, () => {
|
|
21
|
+
const u = module.text(scratch, textOf(url, 'a post\'s url is a string'));
|
|
22
|
+
const e = module.text(scratch, optionalText(event, 'a post\'s event is a string'));
|
|
23
|
+
let pairs = 0, count = 0;
|
|
24
|
+
if (fields !== undefined && fields !== null) {
|
|
25
|
+
if (!Array.isArray(fields)) throw new TypeError('a post\'s fields are an array of {name, value}');
|
|
26
|
+
count = fields.length;
|
|
27
|
+
pairs = module.room(scratch, 16 * (count || 1));
|
|
28
|
+
for (let i = 0; i < count; i++) {
|
|
29
|
+
const field = fields[i];
|
|
30
|
+
if (field === null || typeof field !== 'object') throw new TypeError('a post\'s fields are an array of {name, value}');
|
|
31
|
+
const [n, nl] = module.text(scratch, textOf(field.name, 'a field\'s name is a string'));
|
|
32
|
+
const [v, vl] = module.text(scratch, textOf(field.value, 'a field\'s value is a string'));
|
|
33
|
+
module.words().set([n, nl, v, vl], (pairs >>> 2) + 4 * i);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const b = module.text(scratch, optionalText(body, 'a post\'s body is a string'));
|
|
37
|
+
module.words().set([u[0], u[1], e[0], e[1], pairs, count, b[0], b[1]], module.record);
|
|
38
|
+
const status = module.call('ta_web_http_encode', module.env);
|
|
39
|
+
if (status !== 0) {
|
|
40
|
+
throw refusal(module.statusName(status), status === -3 ? 'a post\'s url is http://host[:port]/path' : 'no memory for the request');
|
|
41
|
+
}
|
|
42
|
+
return module.copyOut(module.word(0), module.word(1));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A string of a view core wrote, refused when it is not UTF-8 (a decoded
|
|
47
|
+
// field may hold any byte): never replaced.
|
|
48
|
+
function strict(module, pointer, length) {
|
|
49
|
+
try {
|
|
50
|
+
return utf8.decode(module.bytes().subarray(pointer, pointer + length));
|
|
51
|
+
} catch {
|
|
52
|
+
throw refusal('TA_ERROR_INVALID', 'the request holds text that is not UTF-8');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// decodeTraces(bytes) -> spans: an OTLP ExportTraceServiceRequest's spans
|
|
57
|
+
// (the addon's src/traces.c, compiled into the module), read as CBOR.
|
|
58
|
+
export function decodeTraces(traces) {
|
|
59
|
+
const bytes = bytesOf(traces, 'decodeTraces takes a Uint8Array or an ArrayBuffer');
|
|
60
|
+
const module = instance();
|
|
61
|
+
const scratch = module.scratch;
|
|
62
|
+
return module.scoped(scratch, () => {
|
|
63
|
+
const [at, length] = module.copyIn(scratch, bytes);
|
|
64
|
+
module.setWord(0, at);
|
|
65
|
+
module.setWord(1, length);
|
|
66
|
+
const status = module.call('ta_web_traces_decode', module.env);
|
|
67
|
+
if (status !== 0) {
|
|
68
|
+
throw refusal(module.statusName(status), status === -3 ? 'the bytes are not an ExportTraceServiceRequest' : 'no memory for the spans');
|
|
69
|
+
}
|
|
70
|
+
return cbor.read(module, scratch, module.word(0), module.word(1), { addresses: false });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// parseHTTPRequest(message) -> {method, target, body, event, fields}
|
|
75
|
+
export function parseHTTPRequest(message) {
|
|
76
|
+
const bytes = bytesOf(message, 'parseHTTPRequest takes the message\'s bytes: a Uint8Array or an ArrayBuffer');
|
|
77
|
+
const module = instance();
|
|
78
|
+
const scratch = module.scratch;
|
|
79
|
+
return module.scoped(scratch, () => {
|
|
80
|
+
const [at, length] = module.copyIn(scratch, bytes);
|
|
81
|
+
module.setWord(0, at);
|
|
82
|
+
module.setWord(1, length);
|
|
83
|
+
const status = module.call('ta_web_http_parse', module.env);
|
|
84
|
+
if (status !== 0) throw refusal(module.statusName(status), 'the message is not an HTTP request');
|
|
85
|
+
const words = module.words().slice(module.record, module.record + 10);
|
|
86
|
+
const result = {
|
|
87
|
+
method: strict(module, words[0], words[1]),
|
|
88
|
+
target: strict(module, words[2], words[3]),
|
|
89
|
+
body: strict(module, words[4], words[5]),
|
|
90
|
+
event: strict(module, words[6], words[7]),
|
|
91
|
+
};
|
|
92
|
+
const fields = [];
|
|
93
|
+
const base = words[9] >>> 2;
|
|
94
|
+
for (let i = 0; i < words[8]; i++) {
|
|
95
|
+
const w = module.words();
|
|
96
|
+
fields.push(Object.freeze({
|
|
97
|
+
name: strict(module, w[base + 4 * i], w[base + 4 * i + 1]),
|
|
98
|
+
value: strict(module, w[base + 4 * i + 2], w[base + 4 * i + 3]),
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
result.fields = Object.freeze(fields);
|
|
102
|
+
return Object.freeze(result);
|
|
103
|
+
});
|
|
104
|
+
}
|
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 one shared context), with\n// In() as its argument. It returns the context's kit, the functions that\n// make what must be made with that context's constructors: copies of values\n// crossing between actors, the scopes of a chart (one constructor per\n// chart, over a frozen prototype of null prototype holding the system\n// variables and the chart's helpers), the system variables of a session,\n// _event, and XML documents; and what a chart's scripts declare, asked of\n// the engine (the binding parses no JavaScript). It runs in the\n// application's realm too, once, for the copies the application reads and\n// the compile call's advice. The build embeds it in the addon\n// (mise/napi.rb); it is not shipped as a file.\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 Code = Function; // this context's: what it compiles is this context's\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 // ---- what a script declares ----------------------------------------------\n\n // Whether `body` parses as a function body of this context, nothing run.\n function parses(body) {\n try {\n Code(body); // eslint-disable-line no-new-func\n return true;\n } catch (error) {\n if (error instanceof SyntaxError) return false;\n throw error;\n }\n }\n\n // What may be an identifier in a script's text: the candidates the\n // engine is asked about.\n const candidates = /[\\p{ID_Start}$_][\\p{ID_Continue}$\\u200c\\u200d]*/gu;\n const declaring = /\\b(?:var|let|const|class|function)\\b/;\n\n // The names a script declares at its top level, asked of the engine:\n // [functions, vars, lexicals] (let, const and class), each in the order\n // of the text; null when the script does not parse as the strict\n // function body the datamodel runs it as. A candidate is declared when\n // the script followed by `let <name>` does not parse, lexically when the\n // script followed by `var <name>` does not either; a declared var holds\n // a function before any statement runs when it is a function\n // declaration.\n function declarations(source) {\n const body = \"'use strict';\\n\" + source;\n if (!parses(body)) return null;\n const functions = [], vars = [], lexicals = [];\n if (!declaring.test(source)) return [functions, vars, lexicals];\n const seen = new Set(), hoisted = [];\n for (const [name] of source.matchAll(candidates)) {\n if (seen.has(name)) continue;\n seen.add(name);\n if (!parses(\"'use strict';let \" + name + ';') || parses(body + '\\n;let ' + name + ';')) continue;\n if (!parses(body + '\\n;var ' + name + ';')) lexicals.push(name);\n else hoisted.push(name);\n }\n if (hoisted.length) {\n const kinds = Code(\"'use strict';return [\" + hoisted.map((name) => 'typeof ' + name).join(',') + '];\\n' + source)();\n for (let i = 0; i < hoisted.length; i++) (kinds[i] === 'function' ? functions : vars).push(hoisted[i]);\n }\n return [functions, vars, lexicals];\n }\n\n const advised = (name) => 'declare it with <data id=\"' + name + '\"/> instead';\n\n // Why the native datamodel refuses a script: its first top-level let,\n // const or class declaration; undefined when it refuses none.\n function refusal(found) {\n if (found === null || !found[2].length) return undefined;\n return 'a <script> declares ' + found[2][0] + ' with let, const or class at its top level, which the native ' +\n '\"ecmascript\" datamodel refuses (the script is error.execution): ' + advised(found[2][0]);\n }\n\n // What the compile call warns of in a script: a refusal, or its first\n // top-level var, which the native datamodel makes a variable of the\n // session; null for neither.\n function advice(source) {\n const found = declarations(source);\n const refused = refusal(found);\n if (refused !== undefined) return refused;\n if (found === null || !found[1].length) return null;\n return 'a <script> declares var ' + found[1][0] + ' at its top level, which the native \"ecmascript\" datamodel ' +\n 'makes a variable of the session: ' + advised(found[1][0]);\n }\n\n // A script as the datamodel runs it, a function of the session's scope:\n // [functions, vars, refusal, head, tail], the head and tail around its\n // source; null when it does not parse (its evaluation's SyntaxError). Its\n // top-level vars are the session's variables: read from the scope before\n // it runs and written back after, as global code would keep them.\n function script(source) {\n const found = declarations(source);\n if (found === null) return null;\n const [functions, vars] = found;\n let head = \"(function(__s){with(__s){(function(){'use strict';\", tail = '\\n';\n if (vars.length) {\n head += vars.map((name) => name + '=__s.' + name + ';').join('') + 'try{';\n tail += '}finally{' + vars.map((name) => '__s.' + name + '=' + name + ';').join('') + '}';\n }\n return [functions, vars, refusal(found), head + '\\n', tail + '})();}})'];\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 // Its prototype holds the system variables and, when its chart-level\n // scripts declare functions, those: made once per chart from each\n // script's text ([source, function names] in `scripts`), no statement of\n // it run, so they close over this context's globals and nothing of a\n // session's.\n function shape(names, scripts) {\n const declared = [...new Set(names)];\n let prototype = variables;\n if (scripts.length) {\n const helpers = {};\n for (const [source, functions] of scripts) {\n const made = Code(\"'use strict';return {\" + functions.join(',') + '};\\n' + source)();\n for (const name of functions) helpers[name] = { value: made[name], enumerable: true };\n }\n prototype = freeze(create(variables, helpers));\n }\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 = prototype;\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 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], its\n // scope's own names but _event.\n function stored(target) {\n const found = [];\n const values = [];\n for (const name of keys(target)) {\n if (name === '_event') continue;\n found.push(name);\n values.push(target[name]);\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: the scope keeps the names its\n // chart declares.\n function restore(target, vars) {\n for (const name of keys(vars)) if (hasOwn(target, name)) target[name] = copy(vars[name], 0);\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.\n function upgrade(target) {\n const link = target[LINK];\n const old = link.init;\n link.init = undefined;\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]. The processors are the\n // template's with this session's id, the pairs the link kept, or, once\n // _ioprocessors was read, its entries (an alias, `scxml` or `basichttp`,\n // 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];\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 objectPrototype: Object.prototype,\n copy: (value) => copy(value, 0),\n exported: (value) => exported(value, 0),\n refusal: (error) => refusals.get(error),\n shape,\n script,\n advice,\n system,\n event,\n record,\n stored,\n restore,\n upgrade,\n linked,\n dom,\n parse: (text) => JSON.parse(text),\n });\n})\n";
|