@northtalk/ts 0.0.0-stage → 0.2.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 +59 -2
- package/UNICODE-LICENSE.txt +39 -0
- package/base64-DORMd3Hv.js +6621 -0
- package/binary-value-CEmh60GC.d.ts +15 -0
- package/capabilities-CH0FkRMq.js +1301 -0
- package/checker-Dc1jl2WH.js +6657 -0
- package/core-DptnvQT9.d.ts +14 -0
- package/debug-CQBxKnJB.d.ts +3065 -0
- package/debug.d.ts +3 -0
- package/debug.js +2 -0
- package/driver.d.ts +41 -0
- package/driver.js +152 -0
- package/encoding-nlrpj-Pb.js +99 -0
- package/engine-BGaJ9dAk.js +326 -0
- package/engine-vbYInVYF.d.ts +86 -0
- package/errors-LYJZ_c8h.js +3735 -0
- package/group-B742gg4T.js +10170 -0
- package/http-capability-CSTkw1Yt.js +728 -0
- package/http.d.ts +59 -0
- package/http.js +465 -0
- package/index.d.ts +651 -0
- package/index.js +44 -0
- package/manifest-BscyH_rW.d.ts +70 -0
- package/manifest-DjsxDSuB.js +129 -0
- package/message-layer.d.ts +12 -0
- package/message-layer.js +4 -0
- package/notify.d.ts +3 -0
- package/notify.js +2 -0
- package/objects-DJ3QtCCs.d.ts +640 -0
- package/objects-Db7IB5vQ.js +91 -0
- package/operation-promises-EgZXG5N_.js +23 -0
- package/package.json +70 -4
- package/readers-BFPuosPk.d.ts +25 -0
- package/readers-CjJHKHvH.js +482 -0
- package/request-pump-binary-DdY3X-yl.js +2246 -0
- package/router--71qvxtY.js +343 -0
- package/router-Zhrw5l__.d.ts +55 -0
- package/session.d.ts +9 -0
- package/session.js +3510 -0
- package/setup.d.ts +3 -0
- package/setup.js +193 -0
- package/sha256-B_kyYw3Z.js +124 -0
- package/sqlite.d.ts +74 -0
- package/sqlite.js +529 -0
- package/store-capability-OZp4hXmj.js +390 -0
- package/store-hJrRULMx.js +60 -0
- package/store.d.ts +21 -0
- package/store.js +4 -0
- package/user-capability-BK4Asg7D.js +276 -0
- package/wasm.d.ts +243 -0
- package/wasm.js +1737 -0
package/wasm.js
ADDED
|
@@ -0,0 +1,1737 @@
|
|
|
1
|
+
|
|
2
|
+
import { B as range, F as num, H as requireValue, I as objectValue, K as text, L as patternValue, M as map, O as list, P as nothing, Qt as parseInstant, R as quantity, V as record, Xt as nowMicros, _ as dec, c as Decimal, d as bytes, i as ScriptError, l as Value, m as civilDate, n as LoadError, o as invalidValue, qt as formatInstant, r as MailboxFull, s as sendFailed, t as HostError, u as bool, w as instant, x as functionValue } from "./errors-LYJZ_c8h.js";
|
|
3
|
+
import { a as rebindObject, n as makeObject, t as defineObjectKind } from "./objects-Db7IB5vQ.js";
|
|
4
|
+
import { i as defineCapability, t as LimitReached, u as shape } from "./capabilities-CH0FkRMq.js";
|
|
5
|
+
import { dt as limitDefaults, n as toBase64, t as fromBase64 } from "./base64-DORMd3Hv.js";
|
|
6
|
+
import { t as trackOperation } from "./operation-promises-EgZXG5N_.js";
|
|
7
|
+
import { a as fromJson, c as readDisplay, l as readOrderedJSON, n as JsonObject, o as isJsonNumber, r as decodeValue, s as isJsonObject, t as JsonNumber } from "./readers-CjJHKHvH.js";
|
|
8
|
+
import { i as standardChecks, n as quoteJSON, t as encodeValue } from "./encoding-nlrpj-Pb.js";
|
|
9
|
+
import { a as shapeData, i as operationData, n as exportManifest, o as invoke } from "./manifest-DjsxDSuB.js";
|
|
10
|
+
import { a as fromValue, i as encodeJson, n as sqliteCapability, o as toValue, r as decodeJson, s as talk, t as httpCapability } from "./http-capability-CSTkw1Yt.js";
|
|
11
|
+
import { n as localeCapability, t as userCapability } from "./user-capability-BK4Asg7D.js";
|
|
12
|
+
import { a as clockCapability, i as calendarCapability, l as timerCapability, o as consoleCapability, r as storeCapability, t as add } from "./store-capability-OZp4hXmj.js";
|
|
13
|
+
import { a as encodeResult, c as isRequestPumpBinary, d as valueNode, i as encodeBinaryFrame, l as placeholderValues, n as decodeBinaryFrame, o as heldValue, r as decodeNeed, s as isBinaryNeed, t as callbacksFeature, u as requestPumpFeature } from "./request-pump-binary-DdY3X-yl.js";
|
|
14
|
+
//#region src/wasm/wire.ts
|
|
15
|
+
const raw = Symbol("raw JSON");
|
|
16
|
+
const sep = Symbol("separator");
|
|
17
|
+
/** Text already in JSON, such as a Value Encoding, placed in a frame as is. */
|
|
18
|
+
var Raw = class {
|
|
19
|
+
source;
|
|
20
|
+
value;
|
|
21
|
+
[raw] = true;
|
|
22
|
+
/** `value`, when given, is the Value `json` encodes. */
|
|
23
|
+
constructor(source, value) {
|
|
24
|
+
this.source = source;
|
|
25
|
+
this.value = value;
|
|
26
|
+
}
|
|
27
|
+
/** Binary frames use `value` directly; only JSON frames need its encoding. */
|
|
28
|
+
get json() {
|
|
29
|
+
if (typeof this.source === "function") this.source = this.source();
|
|
30
|
+
return this.source;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var Sep = class {
|
|
34
|
+
text;
|
|
35
|
+
[sep] = true;
|
|
36
|
+
constructor(text) {
|
|
37
|
+
this.text = text;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** A frame's JSON; undefined fields are left out. */
|
|
41
|
+
const frameJSON = (frame) => {
|
|
42
|
+
const out = [];
|
|
43
|
+
const pending = [frame];
|
|
44
|
+
while (pending.length) {
|
|
45
|
+
const next = pending.pop();
|
|
46
|
+
if (next === null) out.push("null");
|
|
47
|
+
else if (typeof next === "string") out.push(quoteJSON(next));
|
|
48
|
+
else if (typeof next === "number" || typeof next === "boolean") out.push(JSON.stringify(next));
|
|
49
|
+
else if (raw in next) out.push(next.json);
|
|
50
|
+
else if (Array.isArray(next)) {
|
|
51
|
+
out.push("[");
|
|
52
|
+
pending.push(new Sep("]"));
|
|
53
|
+
for (let i = next.length - 1; i >= 0; i--) {
|
|
54
|
+
pending.push(next[i]);
|
|
55
|
+
if (i > 0) pending.push(new Sep(","));
|
|
56
|
+
}
|
|
57
|
+
} else if (sep in next) out.push(next.text);
|
|
58
|
+
else {
|
|
59
|
+
const entries = Object.entries(next).filter(([, v]) => v !== void 0);
|
|
60
|
+
out.push("{");
|
|
61
|
+
pending.push(new Sep("}"));
|
|
62
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
63
|
+
const [key, value] = entries[i];
|
|
64
|
+
pending.push(value, new Sep(`${i > 0 ? "," : ""}${quoteJSON(key)}:`));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return out.join("");
|
|
69
|
+
};
|
|
70
|
+
/** A frame as the reader's nodes, for the binary transport; Values stay Values. */
|
|
71
|
+
const frameTree = (frame) => {
|
|
72
|
+
let root;
|
|
73
|
+
const pending = [[frame, (j) => root = j]];
|
|
74
|
+
while (pending.length) {
|
|
75
|
+
const [next, assign] = pending.pop();
|
|
76
|
+
if (next === null || typeof next === "string" || typeof next === "boolean") assign(next);
|
|
77
|
+
else if (typeof next === "number") assign(new JsonNumber(JSON.stringify(next)));
|
|
78
|
+
else if (raw in next) assign(next.value ? valueNode(next.value) : readReply(next.json));
|
|
79
|
+
else if (Array.isArray(next)) {
|
|
80
|
+
const xs = [];
|
|
81
|
+
assign(xs);
|
|
82
|
+
next.forEach((x, i) => pending.push([x, (j) => xs[i] = j]));
|
|
83
|
+
} else {
|
|
84
|
+
const pairs = [];
|
|
85
|
+
assign(new JsonObject(pairs));
|
|
86
|
+
Object.entries(next).filter(([, v]) => v !== void 0).forEach(([k, v], i) => pending.push([v, (j) => pairs[i] = [k, j]]));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return root;
|
|
90
|
+
};
|
|
91
|
+
/** A callback answer's members for a binary result: its Values as Values. */
|
|
92
|
+
const answerFields = (answer) => {
|
|
93
|
+
const out = {};
|
|
94
|
+
for (const k in answer) {
|
|
95
|
+
const v = answer[k];
|
|
96
|
+
out[k] = v !== null && typeof v === "object" && raw in v ? v.value ?? readReply(v.json) : v !== null && typeof v === "object" && !Array.isArray(v) ? answerFields(v) : v;
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
};
|
|
100
|
+
const readReply = (s) => readOrderedJSON(s);
|
|
101
|
+
/** A member of a JSON object, or undefined. */
|
|
102
|
+
const field = (j, key) => {
|
|
103
|
+
if (!isJsonObject(j)) return;
|
|
104
|
+
for (const [k, v] of j.pairs) if (k === key) return v;
|
|
105
|
+
};
|
|
106
|
+
const has = (j, key) => field(j, key) !== void 0;
|
|
107
|
+
const textOf = (j) => typeof j === "string" ? j : void 0;
|
|
108
|
+
/** Integers cross as JSON numbers below 2⁵³ and as decimal text above. */
|
|
109
|
+
const intOf = (j) => isJsonNumber(j) ? Number(j.source) : typeof j === "string" && /^-?\d+$/.test(j) ? Number(j) : void 0;
|
|
110
|
+
const boolOf = (j) => typeof j === "boolean" ? j : void 0;
|
|
111
|
+
const listOf = (j) => Array.isArray(j) ? j : [];
|
|
112
|
+
const textsOf = (j) => listOf(j).map((t) => textOf(t) ?? "");
|
|
113
|
+
const entriesOf = (j) => isJsonObject(j) ? j.pairs : [];
|
|
114
|
+
/** Protocol data that holds no Values, as plain JavaScript. */
|
|
115
|
+
const plain = (j) => {
|
|
116
|
+
if (j === void 0 || j === null || typeof j !== "object") return j;
|
|
117
|
+
if (Array.isArray(j)) return j.map(plain);
|
|
118
|
+
if (isJsonNumber(j)) return Number(j.source);
|
|
119
|
+
return Object.fromEntries(j.pairs.map(([k, v]) => [k, plain(v)]));
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/wasm/codec.ts
|
|
123
|
+
const wrongGroup = (what) => {
|
|
124
|
+
throw new HostError("wrong group", `${what} belongs to another Group`);
|
|
125
|
+
};
|
|
126
|
+
/** Refuses another Group's Host Objects and Function Values, anywhere inside. */
|
|
127
|
+
const checkOwned = (codec, v) => {
|
|
128
|
+
const pending = [v];
|
|
129
|
+
while (pending.length) {
|
|
130
|
+
const next = pending.pop();
|
|
131
|
+
switch (next.kind) {
|
|
132
|
+
case "object": {
|
|
133
|
+
const ref = next.asObjectRef();
|
|
134
|
+
const own = codec.object(ref.kind, ref.id);
|
|
135
|
+
if (!own || own.value.asObjectRef().handle !== ref.handle) wrongGroup(`Host Object ${ref.kind} ${ref.id}`);
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
case "function":
|
|
139
|
+
if (next.asFunction().code?.group !== codec.identity) wrongGroup("the Function Value");
|
|
140
|
+
break;
|
|
141
|
+
case "list":
|
|
142
|
+
for (let i = 1; i <= next.length; i++) pending.push(next.index(i));
|
|
143
|
+
break;
|
|
144
|
+
case "map":
|
|
145
|
+
for (const [, item] of next.entries()) pending.push(item);
|
|
146
|
+
break;
|
|
147
|
+
case "range": {
|
|
148
|
+
const { from, to } = next.asRange();
|
|
149
|
+
pending.push(from, to);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const encode = (codec, v) => {
|
|
156
|
+
requireValue(v);
|
|
157
|
+
checkOwned(codec, v);
|
|
158
|
+
return new Raw(() => encodeValue(v, (other) => {
|
|
159
|
+
if (other.kind === "pattern") return `{"$pattern":${quoteJSON(other.patternSource())}}`;
|
|
160
|
+
const f = other.asFunction();
|
|
161
|
+
const code = f.code;
|
|
162
|
+
return `{"$function":[${quoteJSON(f.home)},${quoteJSON(other.toString())},${quoteJSON(code.token)}]}`;
|
|
163
|
+
}), v);
|
|
164
|
+
};
|
|
165
|
+
/** A guest Function's binary payload: the parts its `$function` carries. */
|
|
166
|
+
const guestPayload = (f) => {
|
|
167
|
+
const code = f.asFunction().code;
|
|
168
|
+
return [
|
|
169
|
+
text(f.asFunction().home),
|
|
170
|
+
text(f.toString()),
|
|
171
|
+
text(code.token)
|
|
172
|
+
];
|
|
173
|
+
};
|
|
174
|
+
const encodeAll = (codec, vs) => vs.map((v) => encode(codec, v));
|
|
175
|
+
const guestFunction = (codec, data) => {
|
|
176
|
+
if (!Array.isArray(data) || data.length !== 3 || !data.every((part) => typeof part === "string")) throw new HostError("invalid value", "Malformed $function");
|
|
177
|
+
const [home, display, token] = data;
|
|
178
|
+
const inner = display.replace(/^<function /, "").replace(/>$/, "");
|
|
179
|
+
const colon = inner.indexOf(":");
|
|
180
|
+
return functionValue({
|
|
181
|
+
home,
|
|
182
|
+
displayHome: colon >= 0 ? inner.slice(0, colon) : inner,
|
|
183
|
+
place: colon >= 0 ? inner.slice(colon + 1) : "",
|
|
184
|
+
identity: token,
|
|
185
|
+
captures: [],
|
|
186
|
+
maySuspend: false,
|
|
187
|
+
code: Object.freeze({
|
|
188
|
+
group: codec.identity,
|
|
189
|
+
token
|
|
190
|
+
}),
|
|
191
|
+
group: codec.identity
|
|
192
|
+
});
|
|
193
|
+
};
|
|
194
|
+
const guestPattern = (data) => {
|
|
195
|
+
if (typeof data !== "string") throw new HostError("invalid value", "Malformed $pattern");
|
|
196
|
+
return patternValue({
|
|
197
|
+
source: data,
|
|
198
|
+
program: 0,
|
|
199
|
+
data: null
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
const unknownObject = Object.freeze({});
|
|
203
|
+
/** How this Group's Values cross in binary callback frames. */
|
|
204
|
+
const binaryValues = (codec) => ({
|
|
205
|
+
encodeFunction: guestPayload,
|
|
206
|
+
object: (kind, id) => codec.object(kind, id)?.value ?? objectValue({
|
|
207
|
+
kind,
|
|
208
|
+
id,
|
|
209
|
+
handle: unknownObject
|
|
210
|
+
}),
|
|
211
|
+
decodeFunction: (payload) => guestFunction(codec, payload.map((v) => v.asText()))
|
|
212
|
+
});
|
|
213
|
+
const known = (v) => {
|
|
214
|
+
const pending = [v];
|
|
215
|
+
while (pending.length) {
|
|
216
|
+
const next = pending.pop();
|
|
217
|
+
switch (next.kind) {
|
|
218
|
+
case "object": {
|
|
219
|
+
const ref = next.asObjectRef();
|
|
220
|
+
if (ref.handle === unknownObject) invalidValue(`No Host Object ${ref.kind} ${ref.id}`);
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
case "list":
|
|
224
|
+
for (let i = 1; i <= next.length; i++) pending.push(next.index(i));
|
|
225
|
+
break;
|
|
226
|
+
case "map":
|
|
227
|
+
for (const [, item] of next.entries()) pending.push(item);
|
|
228
|
+
break;
|
|
229
|
+
case "range": {
|
|
230
|
+
const { from, to } = next.asRange();
|
|
231
|
+
pending.push(from, to);
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return v;
|
|
237
|
+
};
|
|
238
|
+
const decode = (codec, j) => {
|
|
239
|
+
const held = heldValue(j);
|
|
240
|
+
return held ? known(held) : decodeJson$1(codec, j);
|
|
241
|
+
};
|
|
242
|
+
const decodeJson$1 = (codec, j) => fromJson(j ?? null, (kind, id) => codec.object(kind, id), void 0, (tag, data) => tag === "$function" ? guestFunction(codec, data) : guestPattern(data));
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/wasm/reactor.ts
|
|
245
|
+
const EBADF = 8;
|
|
246
|
+
const ENOSYS = 52;
|
|
247
|
+
const encoder$1 = new TextEncoder();
|
|
248
|
+
const decoder$1 = new TextDecoder("utf-8", { fatal: true });
|
|
249
|
+
/**
|
|
250
|
+
* The WASI imports `talk.wasm` takes. The Core reads no clock, file or
|
|
251
|
+
* environment of its own: its Clock comes with each Pump. The safe build's
|
|
252
|
+
* panic handler links the rest of WASI, so each import the module names gets
|
|
253
|
+
* a function, and those it never needs refuse with ENOSYS. `fd_read` is for
|
|
254
|
+
* the inline transport, which this Host doesn't negotiate, so every read
|
|
255
|
+
* finds the end of its input.
|
|
256
|
+
*/
|
|
257
|
+
const wasi = (module, memory, diagnostics) => {
|
|
258
|
+
let pending = "";
|
|
259
|
+
const stream = new TextDecoder();
|
|
260
|
+
const view = () => new DataView(memory().buffer);
|
|
261
|
+
const implemented = {
|
|
262
|
+
fd_write(fd, iovs, count, written) {
|
|
263
|
+
if (fd !== 1 && fd !== 2) return EBADF;
|
|
264
|
+
const v = view();
|
|
265
|
+
let total = 0;
|
|
266
|
+
for (let i = 0; i < count; i++) {
|
|
267
|
+
const base = v.getUint32(iovs + i * 8, true);
|
|
268
|
+
const length = v.getUint32(iovs + i * 8 + 4, true);
|
|
269
|
+
pending += stream.decode(new Uint8Array(memory().buffer, base, length), { stream: true });
|
|
270
|
+
total += length;
|
|
271
|
+
}
|
|
272
|
+
let line;
|
|
273
|
+
while ((line = pending.indexOf("\n")) >= 0) {
|
|
274
|
+
diagnostics(pending.slice(0, line));
|
|
275
|
+
pending = pending.slice(line + 1);
|
|
276
|
+
}
|
|
277
|
+
v.setUint32(written, total, true);
|
|
278
|
+
return 0;
|
|
279
|
+
},
|
|
280
|
+
fd_read(fd, _iovs, _count, read) {
|
|
281
|
+
if (fd !== 0) return EBADF;
|
|
282
|
+
view().setUint32(read, 0, true);
|
|
283
|
+
return 0;
|
|
284
|
+
},
|
|
285
|
+
random_get(at, length) {
|
|
286
|
+
for (let i = 0; i < length; i += 65536) crypto.getRandomValues(new Uint8Array(memory().buffer, at + i, Math.min(65536, length - i)));
|
|
287
|
+
return 0;
|
|
288
|
+
},
|
|
289
|
+
clock_time_get(_id, _precision, at) {
|
|
290
|
+
const ns = BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6));
|
|
291
|
+
view().setBigUint64(at, ns, true);
|
|
292
|
+
return 0;
|
|
293
|
+
},
|
|
294
|
+
clock_res_get(_id, at) {
|
|
295
|
+
view().setBigUint64(at, 1000n, true);
|
|
296
|
+
return 0;
|
|
297
|
+
},
|
|
298
|
+
environ_sizes_get(count, size) {
|
|
299
|
+
view().setUint32(count, 0, true);
|
|
300
|
+
view().setUint32(size, 0, true);
|
|
301
|
+
return 0;
|
|
302
|
+
},
|
|
303
|
+
environ_get: () => 0
|
|
304
|
+
};
|
|
305
|
+
return Object.fromEntries(WebAssembly.Module.imports(module).filter((i) => i.module === "wasi_snapshot_preview1" && i.kind === "function").map((i) => [i.name, implemented[i.name] ?? (() => ENOSYS)]));
|
|
306
|
+
};
|
|
307
|
+
/** Thrown when the instance traps or replies with something unreadable: it is lost. */
|
|
308
|
+
var InstanceLostError = class extends Error {
|
|
309
|
+
name = "InstanceLostError";
|
|
310
|
+
};
|
|
311
|
+
/** A frame the reactor won't take, past its 64 MiB limit or its memory. */
|
|
312
|
+
var FrameRefusedError = class extends Error {
|
|
313
|
+
bytes;
|
|
314
|
+
name = "FrameRefusedError";
|
|
315
|
+
constructor(bytes) {
|
|
316
|
+
super(`talk.wasm refused a frame of ${bytes} bytes`);
|
|
317
|
+
this.bytes = bytes;
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
var Reactor = class {
|
|
321
|
+
#exports;
|
|
322
|
+
#lost = null;
|
|
323
|
+
/** Synchronous: the module is compiled once, by createCore. */
|
|
324
|
+
constructor(module, diagnostics) {
|
|
325
|
+
const exports = new WebAssembly.Instance(module, { wasi_snapshot_preview1: wasi(module, () => exports.memory, diagnostics) }).exports;
|
|
326
|
+
this.#exports = exports;
|
|
327
|
+
this.#guard(() => exports._initialize());
|
|
328
|
+
}
|
|
329
|
+
/** One JSON frame, retained for Hosts speaking only JSON. */
|
|
330
|
+
frame(json) {
|
|
331
|
+
const reply = this.frameBytes(encoder$1.encode(json));
|
|
332
|
+
return this.#guard(() => decoder$1.decode(new Uint8Array(reply)));
|
|
333
|
+
}
|
|
334
|
+
/** One mixed-transport frame; copy the reply before another export can run. */
|
|
335
|
+
frameBytes(bytes) {
|
|
336
|
+
const e = this.#exports;
|
|
337
|
+
const pointer = this.#guard(() => e.talk_buffer(bytes.length));
|
|
338
|
+
if (pointer === 0) throw new FrameRefusedError(bytes.length);
|
|
339
|
+
return this.#guard(() => {
|
|
340
|
+
new Uint8Array(e.memory.buffer, pointer, bytes.length).set(bytes);
|
|
341
|
+
const packed = BigInt.asUintN(64, e.talk_send(bytes.length));
|
|
342
|
+
const at = Number(packed >> 32n);
|
|
343
|
+
const length = Number(packed & 4294967295n);
|
|
344
|
+
return new Uint8Array(e.memory.buffer, at, length).slice().buffer;
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
/** The instance's linear memory, in bytes. */
|
|
348
|
+
memoryBytes() {
|
|
349
|
+
return this.#exports.memory.buffer.byteLength;
|
|
350
|
+
}
|
|
351
|
+
#guard(f) {
|
|
352
|
+
if (this.#lost) throw this.#lost;
|
|
353
|
+
try {
|
|
354
|
+
return f();
|
|
355
|
+
} catch (error) {
|
|
356
|
+
this.#lost = error instanceof InstanceLostError ? error : new InstanceLostError(error instanceof Error ? error.message : String(error), { cause: error });
|
|
357
|
+
throw this.#lost;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region src/wasm/group.ts
|
|
363
|
+
const key = (kind, id) => `${kind}\u0000${id}`;
|
|
364
|
+
const isLimitReached = (error) => error instanceof Error && error.name === "LimitReached";
|
|
365
|
+
const propertyFailure = (details, detail) => {
|
|
366
|
+
details.push(detail);
|
|
367
|
+
return { hostError: detail };
|
|
368
|
+
};
|
|
369
|
+
const bytesFrame = (b) => ({ $bytes: toBase64(b) });
|
|
370
|
+
const bytesOfFrame = (j) => fromBase64(textOf(field(j, "$bytes")) ?? "") ?? /* @__PURE__ */ new Uint8Array();
|
|
371
|
+
const detailOf = (e) => e instanceof Error ? `${e.name}: ${e.message}` : `the Host threw ${typeof e === "symbol" ? e.toString() : String(e)}`;
|
|
372
|
+
const scriptError = (error) => {
|
|
373
|
+
const message = error.get("message");
|
|
374
|
+
const textMessage = message.kind === "text";
|
|
375
|
+
return new ScriptError(error.get("code").asText() ?? "", textMessage ? message.asText() : "", map(error.entries().filter(([k]) => k !== "code" && !(k === "message" && textMessage))));
|
|
376
|
+
};
|
|
377
|
+
/** A handle for calls addressed to one Script. */
|
|
378
|
+
var WasmScript = class {
|
|
379
|
+
group;
|
|
380
|
+
name;
|
|
381
|
+
constructor(group, name) {
|
|
382
|
+
this.group = group;
|
|
383
|
+
this.name = name;
|
|
384
|
+
}
|
|
385
|
+
grants() {
|
|
386
|
+
const ok = this.group.worker("grants", { script: this.name });
|
|
387
|
+
return Object.fromEntries(entriesOf(ok).map(([name, ops]) => [name, textsOf(ops)]));
|
|
388
|
+
}
|
|
389
|
+
counters() {
|
|
390
|
+
return plain(this.group.worker("counters", { script: this.name }));
|
|
391
|
+
}
|
|
392
|
+
deliver(m) {
|
|
393
|
+
return this.group.queue("deliver", { to: { script: this.name } }, m);
|
|
394
|
+
}
|
|
395
|
+
request(m, o) {
|
|
396
|
+
return this.group.ask({ to: { script: this.name } }, m, o);
|
|
397
|
+
}
|
|
398
|
+
requestPump(m, now, o) {
|
|
399
|
+
return this.group.combined("request-pump", () => ({
|
|
400
|
+
to: { script: this.name },
|
|
401
|
+
message: this.group.messageFrame(m)
|
|
402
|
+
}), now, o);
|
|
403
|
+
}
|
|
404
|
+
/** Queued. A Request for the answer only; use `request` for its id or a signal. */
|
|
405
|
+
invoke(name, ...args) {
|
|
406
|
+
return invoke(this, name, args);
|
|
407
|
+
}
|
|
408
|
+
decide(m, o) {
|
|
409
|
+
return this.group.decision({ to: { script: this.name } }, m, o);
|
|
410
|
+
}
|
|
411
|
+
reload(source, carry, o) {
|
|
412
|
+
return this.group.lifecycle("reload", {
|
|
413
|
+
script: this.name,
|
|
414
|
+
source,
|
|
415
|
+
carry,
|
|
416
|
+
keepMailbox: o?.keepMailbox
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
extend(source) {
|
|
420
|
+
this.group.worker("extend", {
|
|
421
|
+
script: this.name,
|
|
422
|
+
source
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
stop(reason) {
|
|
426
|
+
this.group.control("stop", {
|
|
427
|
+
script: this.name,
|
|
428
|
+
reason
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
cancelRun(runId) {
|
|
432
|
+
this.group.control("cancel-run", {
|
|
433
|
+
script: this.name,
|
|
434
|
+
run: runId
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
rewindRun(runId) {
|
|
438
|
+
this.group.control("rewind-run", {
|
|
439
|
+
script: this.name,
|
|
440
|
+
run: runId
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
revoke(grantName) {
|
|
444
|
+
this.group.control("revoke", {
|
|
445
|
+
script: this.name,
|
|
446
|
+
grant: grantName
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
var WasmGroup = class {
|
|
451
|
+
name;
|
|
452
|
+
#core;
|
|
453
|
+
#session;
|
|
454
|
+
#trace;
|
|
455
|
+
#onReady;
|
|
456
|
+
#scripts = /* @__PURE__ */ new Map();
|
|
457
|
+
/** Each Script's Grants, by the name it uses. */
|
|
458
|
+
#bindings = /* @__PURE__ */ new Map();
|
|
459
|
+
#objects = /* @__PURE__ */ new Map();
|
|
460
|
+
#requests = /* @__PURE__ */ new Map();
|
|
461
|
+
#decisions = /* @__PURE__ */ new Map();
|
|
462
|
+
#runs = /* @__PURE__ */ new Map();
|
|
463
|
+
#calls = /* @__PURE__ */ new Map();
|
|
464
|
+
#failureDetails = /* @__PURE__ */ new Map();
|
|
465
|
+
#propertyDetails = [];
|
|
466
|
+
#effectDetails = /* @__PURE__ */ new Map();
|
|
467
|
+
/** Calls a restore left pending, until the first Pump. */
|
|
468
|
+
#restored = /* @__PURE__ */ new Map();
|
|
469
|
+
#restoring = null;
|
|
470
|
+
#exchanging = 0;
|
|
471
|
+
#combining = false;
|
|
472
|
+
/** Answers given while their call was starting, sent once the exchange ends. */
|
|
473
|
+
#deferred = [];
|
|
474
|
+
#codec;
|
|
475
|
+
/** @internal Made by WasmCore. */
|
|
476
|
+
constructor(core, o, restoring) {
|
|
477
|
+
this.#core = core;
|
|
478
|
+
this.name = o.name;
|
|
479
|
+
this.#trace = o.trace;
|
|
480
|
+
this.#onReady = o.onReady;
|
|
481
|
+
this.#session = core.session();
|
|
482
|
+
const objects = this.#objects;
|
|
483
|
+
this.#codec = {
|
|
484
|
+
identity: this,
|
|
485
|
+
object: (kind, id) => objects.get(key(kind, id))?.handle
|
|
486
|
+
};
|
|
487
|
+
this.#session.bind(binaryValues(this.#codec));
|
|
488
|
+
if (!restoring) this.#session.exchange("new-group", {
|
|
489
|
+
group: this.name,
|
|
490
|
+
name: this.name,
|
|
491
|
+
trace: !!o.trace,
|
|
492
|
+
seed: o.seed === void 0 ? void 0 : o.seed < 2n ** 53n && o.seed >= 0n ? Number(o.seed) : o.seed.toString()
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
/** @internal One exchange for this Group, its needs answered here. */
|
|
496
|
+
send(m, fields = {}, receive) {
|
|
497
|
+
this.#exchanging++;
|
|
498
|
+
try {
|
|
499
|
+
return this.#session.exchange(m, {
|
|
500
|
+
group: this.name,
|
|
501
|
+
...fields
|
|
502
|
+
}, (need, packet) => this.#need(need, packet), (packet, sent) => {
|
|
503
|
+
receive?.(packet);
|
|
504
|
+
this.#observe(packet, sent);
|
|
505
|
+
});
|
|
506
|
+
} finally {
|
|
507
|
+
this.#exchanging--;
|
|
508
|
+
if (!this.#exchanging && this.#deferred.length) {
|
|
509
|
+
const deferred = this.#deferred;
|
|
510
|
+
this.#deferred = [];
|
|
511
|
+
for (const settle of deferred) settle();
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* A worker call. Made from a callback, the guest refuses it as
|
|
517
|
+
* `reentrant call`, with its refusal record, as the in-process Core does.
|
|
518
|
+
*/
|
|
519
|
+
worker(m, fields = {}) {
|
|
520
|
+
if (this.#combining) throw new HostError("reentrant call");
|
|
521
|
+
this.#session.syncKinds();
|
|
522
|
+
return this.send(m, fields);
|
|
523
|
+
}
|
|
524
|
+
#observe(packet, m) {
|
|
525
|
+
this.#abandon(textsOf(field(packet, "abandoned")));
|
|
526
|
+
const ok = field(packet, "ok");
|
|
527
|
+
if (m === "pump" || m === "request-pump" || m === "call-pump" || m === "reload" || m === "replace-library") this.#abandon(textsOf(field(ok, "abandoned")));
|
|
528
|
+
if (!this.#trace) return;
|
|
529
|
+
const lines = [...textsOf(field(packet, "trace"))];
|
|
530
|
+
if (m !== "grants") lines.push(...textsOf(field(ok, "trace")));
|
|
531
|
+
for (const line of lines) this.#trace(line);
|
|
532
|
+
}
|
|
533
|
+
#abandon(ids) {
|
|
534
|
+
for (const id of ids) {
|
|
535
|
+
const pending = this.#calls.get(id);
|
|
536
|
+
if (pending) {
|
|
537
|
+
this.#calls.delete(id);
|
|
538
|
+
pending.live = false;
|
|
539
|
+
pending.abort.abort();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
#ready() {
|
|
544
|
+
if (!this.#onReady) return;
|
|
545
|
+
if (this.#exchanging || this.#combining) queueMicrotask(this.#onReady);
|
|
546
|
+
else this.#onReady();
|
|
547
|
+
}
|
|
548
|
+
#need(need, _packet) {
|
|
549
|
+
switch (textOf(field(need, "m"))) {
|
|
550
|
+
case "op": return this.#operation(need);
|
|
551
|
+
case "prop": return this.#property(need);
|
|
552
|
+
case "effect": return this.#effect(need);
|
|
553
|
+
case "release":
|
|
554
|
+
this.#release(need);
|
|
555
|
+
return {};
|
|
556
|
+
case "resolve": return this.#resolve(need);
|
|
557
|
+
case "trace": return {};
|
|
558
|
+
default: throw new InstanceLostError(`Unsupported need ${textOf(field(need, "m")) ?? ""}`);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
#grantOf(script, name) {
|
|
562
|
+
return this.#bindings.get(script)?.get(name);
|
|
563
|
+
}
|
|
564
|
+
#failure(e) {
|
|
565
|
+
return {
|
|
566
|
+
code: e.code,
|
|
567
|
+
message: e.message || void 0,
|
|
568
|
+
data: Value.isValue(e.data) && e.data.kind === "map" ? encode(this.#codec, e.data) : void 0
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
#callOf(need, grant, pending, charge) {
|
|
572
|
+
const id = textOf(field(need, "call"));
|
|
573
|
+
const scope = textOf(field(need, "scope"));
|
|
574
|
+
const delivery = textOf(field(need, "delivery"));
|
|
575
|
+
return Object.freeze({
|
|
576
|
+
group: this,
|
|
577
|
+
id,
|
|
578
|
+
scriptName: textOf(field(need, "script")),
|
|
579
|
+
runId: textOf(field(need, "run")),
|
|
580
|
+
grantName: textOf(field(need, "grant")),
|
|
581
|
+
segmentId: textOf(field(need, "segment")),
|
|
582
|
+
...scope ? { scopeName: scope } : {},
|
|
583
|
+
automatic: boolOf(field(need, "automatic")) ?? false,
|
|
584
|
+
...delivery ? { delivery } : {},
|
|
585
|
+
binding: grant.binding,
|
|
586
|
+
now: parseInstant(textOf(field(need, "now"))),
|
|
587
|
+
signal: pending.abort.signal,
|
|
588
|
+
charge,
|
|
589
|
+
answer: (v, late) => this.#settleCall(id, pending, "answer", {
|
|
590
|
+
value: encode(this.#codec, v),
|
|
591
|
+
fuel: late?.fuel
|
|
592
|
+
}),
|
|
593
|
+
fail: (e) => this.#settleCall(id, pending, "fail", { error: e instanceof ScriptError ? this.#failure(e) : void 0 })
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
#settleCall(id, pending, m, fields) {
|
|
597
|
+
if (pending.starting) {
|
|
598
|
+
if (!pending.queued) {
|
|
599
|
+
pending.queued = true;
|
|
600
|
+
this.#deferred.push(() => this.#settleCall(id, pending, m, fields));
|
|
601
|
+
}
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
pending.live = false;
|
|
605
|
+
this.#calls.delete(id);
|
|
606
|
+
try {
|
|
607
|
+
this.send(m, {
|
|
608
|
+
call: id,
|
|
609
|
+
...fields
|
|
610
|
+
});
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (!(error instanceof HostError)) throw error;
|
|
613
|
+
}
|
|
614
|
+
this.#ready();
|
|
615
|
+
}
|
|
616
|
+
#operation(need) {
|
|
617
|
+
const id = textOf(field(need, "call"));
|
|
618
|
+
const grant = this.#grantOf(textOf(field(need, "script")), textOf(field(need, "grant")));
|
|
619
|
+
const name = textOf(field(need, "operation"));
|
|
620
|
+
const op = grant?.capability.operations.get(name);
|
|
621
|
+
if (!grant || !op || !grant.ops.has(name)) {
|
|
622
|
+
const detail = `No Operation ${name} for ${textOf(field(need, "grant"))}`;
|
|
623
|
+
this.#failureDetails.set(id, detail);
|
|
624
|
+
return {
|
|
625
|
+
hostError: detail,
|
|
626
|
+
charged: 0
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
let args;
|
|
630
|
+
try {
|
|
631
|
+
args = listOf(field(need, "args")).map((a) => decode(this.#codec, a));
|
|
632
|
+
} catch (error) {
|
|
633
|
+
this.#failureDetails.set(id, detailOf(error));
|
|
634
|
+
return {
|
|
635
|
+
hostError: detailOf(error),
|
|
636
|
+
charged: 0
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
const automatic = boolOf(field(need, "automatic")) ?? false;
|
|
640
|
+
const left = intOf(field(need, "fuelLeft"));
|
|
641
|
+
let starting = true, charged = 0, reached = false;
|
|
642
|
+
const charge = (fuel) => {
|
|
643
|
+
if (!starting || automatic) throw new HostError("invalid value", "Charge only while starting");
|
|
644
|
+
if (!Number.isSafeInteger(fuel) || fuel < 0) throw new HostError("invalid value", "Fuel must be a whole number");
|
|
645
|
+
if (reached || left !== void 0 && charged + fuel > left) {
|
|
646
|
+
reached = true;
|
|
647
|
+
throw new LimitReached("the Run can’t cover this charge");
|
|
648
|
+
}
|
|
649
|
+
charged += fuel;
|
|
650
|
+
};
|
|
651
|
+
const pending = {
|
|
652
|
+
abort: new AbortController(),
|
|
653
|
+
live: true,
|
|
654
|
+
starting: true
|
|
655
|
+
};
|
|
656
|
+
const call = this.#callOf(need, grant, pending, charge);
|
|
657
|
+
const out = {};
|
|
658
|
+
try {
|
|
659
|
+
out.charged = 0;
|
|
660
|
+
const result = this.#invoke(op, call, args, pending);
|
|
661
|
+
if (reached) out.limit = true;
|
|
662
|
+
else if (op.mode === "suspending") out.started = true;
|
|
663
|
+
else if (op.mode === "fire-and-forget") out.done = true;
|
|
664
|
+
else try {
|
|
665
|
+
out.result = encode(this.#codec, result);
|
|
666
|
+
} catch (error) {
|
|
667
|
+
out.hostError = detailOf(error);
|
|
668
|
+
}
|
|
669
|
+
} catch (error) {
|
|
670
|
+
if (reached || isLimitReached(error)) out.limit = true;
|
|
671
|
+
else if (error instanceof ScriptError) try {
|
|
672
|
+
out.fail = this.#failure(error);
|
|
673
|
+
} catch (encodeError) {
|
|
674
|
+
out.hostError = detailOf(encodeError);
|
|
675
|
+
}
|
|
676
|
+
else out.hostError = detailOf(error);
|
|
677
|
+
} finally {
|
|
678
|
+
starting = false;
|
|
679
|
+
pending.starting = false;
|
|
680
|
+
}
|
|
681
|
+
out.charged = charged;
|
|
682
|
+
if (typeof out.hostError === "string") this.#failureDetails.set(id, out.hostError);
|
|
683
|
+
if (op.mode === "suspending" && out.started) {
|
|
684
|
+
if (pending.live) this.#calls.set(id, pending);
|
|
685
|
+
} else pending.live = false;
|
|
686
|
+
return out;
|
|
687
|
+
}
|
|
688
|
+
#invoke(op, call, args, pending) {
|
|
689
|
+
switch (op.mode) {
|
|
690
|
+
case "immediate": return op.do(call, ...args);
|
|
691
|
+
case "fire-and-forget":
|
|
692
|
+
op.fire(call, ...args);
|
|
693
|
+
return;
|
|
694
|
+
case "suspending":
|
|
695
|
+
if (op.start) {
|
|
696
|
+
op.start(call, ...args);
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
trackOperation(this, op.run(call, ...args).then((v) => call.answer(v)).catch((error) => call.fail(error)));
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
#property(need) {
|
|
704
|
+
const ref = field(field(need, "object"), "$object");
|
|
705
|
+
const [kind, id] = textsOf(ref);
|
|
706
|
+
const object = this.#objects.get(key(kind, id))?.handle;
|
|
707
|
+
const name = textOf(field(need, "prop"));
|
|
708
|
+
const details = this.#propertyDetails;
|
|
709
|
+
if (has(need, "op")) return this.#collection(need, object, kind, id);
|
|
710
|
+
const prop = object?.kind.props.get(name);
|
|
711
|
+
if (!object || !prop) return propertyFailure(details, `No property ${name} on ${kind} ${id}`);
|
|
712
|
+
try {
|
|
713
|
+
if (has(need, "value")) {
|
|
714
|
+
if (!prop.set) return propertyFailure(details, `${name} is read-only`);
|
|
715
|
+
prop.set(object, decode(this.#codec, field(need, "value")));
|
|
716
|
+
return { ok: true };
|
|
717
|
+
}
|
|
718
|
+
return { value: encode(this.#codec, prop.get(object)) };
|
|
719
|
+
} catch (error) {
|
|
720
|
+
if (error instanceof ScriptError) return { fail: this.#failure(error) };
|
|
721
|
+
return propertyFailure(details, detailOf(error));
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
#collection(need, object, kind, id) {
|
|
725
|
+
const details = this.#propertyDetails;
|
|
726
|
+
const elements = object?.kind.elements;
|
|
727
|
+
if (!object || !elements) return propertyFailure(details, `No collection on ${kind} ${id}`);
|
|
728
|
+
const op = textOf(field(need, "op"));
|
|
729
|
+
try {
|
|
730
|
+
const selector = has(need, "selector") ? decode(this.#codec, field(need, "selector")) : null;
|
|
731
|
+
const result = op === "count" ? elements.count(object) : op === "at" && selector?.kind === "number" ? elements.at(object, Number(selector.asDecimal().toString())) : op === "find" && selector?.kind === "text" ? elements.find(object, selector.asText()) : void 0;
|
|
732
|
+
if (result === void 0) return propertyFailure(details, `Malformed collection need ${op}`);
|
|
733
|
+
return { value: encode(this.#codec, result) };
|
|
734
|
+
} catch (error) {
|
|
735
|
+
if (error instanceof ScriptError) return { fail: this.#failure(error) };
|
|
736
|
+
return propertyFailure(details, detailOf(error));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
#effect(need) {
|
|
740
|
+
const script = textOf(field(need, "script"));
|
|
741
|
+
const name = textOf(field(need, "grant"));
|
|
742
|
+
const phase = textOf(field(need, "phase"));
|
|
743
|
+
const grant = this.#grantOf(script, name);
|
|
744
|
+
const named = textOf(field(need, "coordinator"));
|
|
745
|
+
const hooks = (named ? this.#session.coordinator(named) : void 0) ?? grant?.coordinator ?? grant?.capability.lifecycle;
|
|
746
|
+
const segment = textOf(field(need, "segment"));
|
|
747
|
+
let result;
|
|
748
|
+
if (!grant || !hooks) result = {
|
|
749
|
+
status: "unknown",
|
|
750
|
+
detail: `No lifecycle hooks for ${name}`
|
|
751
|
+
};
|
|
752
|
+
else try {
|
|
753
|
+
result = hooks[phase]({
|
|
754
|
+
group: this,
|
|
755
|
+
scriptName: script,
|
|
756
|
+
runId: textOf(field(need, "run")),
|
|
757
|
+
grantName: name,
|
|
758
|
+
segmentId: segment,
|
|
759
|
+
binding: grant.binding,
|
|
760
|
+
now: parseInstant(textOf(field(need, "now"))),
|
|
761
|
+
grants: textsOf(field(need, "grants")).map((g) => ({
|
|
762
|
+
grantName: g,
|
|
763
|
+
binding: this.#grantOf(script, g)?.binding
|
|
764
|
+
}))
|
|
765
|
+
});
|
|
766
|
+
if (![
|
|
767
|
+
"ok",
|
|
768
|
+
"failed",
|
|
769
|
+
"unknown"
|
|
770
|
+
].includes(result?.status)) result = {
|
|
771
|
+
status: "unknown",
|
|
772
|
+
detail: "not an EffectResult"
|
|
773
|
+
};
|
|
774
|
+
} catch (error) {
|
|
775
|
+
result = {
|
|
776
|
+
status: "unknown",
|
|
777
|
+
detail: detailOf(error)
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
if (result.status !== "ok" && result.detail !== void 0) this.#effectDetails.set(`${segment}/${phase}`, result.detail);
|
|
781
|
+
return { status: result.status };
|
|
782
|
+
}
|
|
783
|
+
#release(need) {
|
|
784
|
+
const script = textOf(field(need, "script"));
|
|
785
|
+
const name = textOf(field(need, "grant"));
|
|
786
|
+
const grant = this.#grantOf(script, name);
|
|
787
|
+
try {
|
|
788
|
+
grant?.capability.release?.({
|
|
789
|
+
group: this,
|
|
790
|
+
scriptName: script,
|
|
791
|
+
grantName: name,
|
|
792
|
+
binding: grant.binding,
|
|
793
|
+
now: parseInstant(textOf(field(need, "now"))),
|
|
794
|
+
reason: textOf(field(need, "reason"))
|
|
795
|
+
});
|
|
796
|
+
} catch {}
|
|
797
|
+
}
|
|
798
|
+
#resolve(need) {
|
|
799
|
+
const o = this.#restoring;
|
|
800
|
+
return {
|
|
801
|
+
grants: listOf(field(need, "grants")).map((pair) => {
|
|
802
|
+
const [script, name] = textsOf(pair);
|
|
803
|
+
const grant = o.grants(script, name);
|
|
804
|
+
if (!grant) return null;
|
|
805
|
+
let scripts = this.#bindings.get(script);
|
|
806
|
+
if (!scripts) {
|
|
807
|
+
scripts = /* @__PURE__ */ new Map();
|
|
808
|
+
this.#bindings.set(script, scripts);
|
|
809
|
+
}
|
|
810
|
+
scripts.set(name, grant);
|
|
811
|
+
return this.#session.grant(grant);
|
|
812
|
+
}),
|
|
813
|
+
objects: listOf(field(need, "objects")).map((pair) => {
|
|
814
|
+
const [kind, id] = textsOf(pair);
|
|
815
|
+
const resolved = o.resolve(kind, id);
|
|
816
|
+
const k = this.#core.kind(kind);
|
|
817
|
+
if (!resolved || !k) return false;
|
|
818
|
+
this.#objects.set(key(kind, id), makeObject(k, id, resolved.native));
|
|
819
|
+
return true;
|
|
820
|
+
})
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
#report(j) {
|
|
824
|
+
const r = plain(j);
|
|
825
|
+
const value = (name) => decode(this.#codec, field(j, name));
|
|
826
|
+
switch (r.kind) {
|
|
827
|
+
case "run end": {
|
|
828
|
+
if (has(j, "result")) r.result = value("result");
|
|
829
|
+
if (has(j, "error")) r.error = scriptError(value("error"));
|
|
830
|
+
const effect = r.effect;
|
|
831
|
+
if (effect) {
|
|
832
|
+
const detail = this.#effectDetails.get(`${effect.segment}/${effect.phase}`);
|
|
833
|
+
if (detail !== void 0) effect.detail = detail;
|
|
834
|
+
}
|
|
835
|
+
break;
|
|
836
|
+
}
|
|
837
|
+
case "effect failure": {
|
|
838
|
+
const detail = this.#effectDetails.get(`${String(r.segment)}/${String(r.phase)}`);
|
|
839
|
+
if (detail !== void 0) r.detail = detail;
|
|
840
|
+
break;
|
|
841
|
+
}
|
|
842
|
+
case "unhandled": {
|
|
843
|
+
const message = field(j, "message");
|
|
844
|
+
r.message = {
|
|
845
|
+
name: textOf(field(message, "name")),
|
|
846
|
+
args: listOf(field(message, "args")).map((a) => decode(this.#codec, a))
|
|
847
|
+
};
|
|
848
|
+
if (has(j, "target")) r.target = value("target").asObject();
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
case "run started":
|
|
852
|
+
r.args = listOf(field(j, "args")).map((a) => decode(this.#codec, a));
|
|
853
|
+
if (has(j, "fn")) r.fn = value("fn");
|
|
854
|
+
break;
|
|
855
|
+
case "decided":
|
|
856
|
+
r.vetoes = listOf(field(j, "vetoes")).map((v) => ({
|
|
857
|
+
script: textOf(field(v, "script")),
|
|
858
|
+
run: textOf(field(v, "run")),
|
|
859
|
+
reason: decode(this.#codec, field(v, "reason"))
|
|
860
|
+
}));
|
|
861
|
+
r.undecided = r.undecided.map((u) => u.run ? u : (({ run: _, ...rest }) => rest)(u));
|
|
862
|
+
break;
|
|
863
|
+
case "call failed": {
|
|
864
|
+
const operation = r.operation;
|
|
865
|
+
operation.capability = this.#session.capabilityName(operation.capability) ?? operation.capability;
|
|
866
|
+
const call = String(r.call);
|
|
867
|
+
r.detail = (call ? this.#failureDetails.get(call) : this.#propertyDetails.shift()) ?? (r.detail || "Host result rejected by the Core");
|
|
868
|
+
break;
|
|
869
|
+
}
|
|
870
|
+
case "host error": r.code = r.code;
|
|
871
|
+
}
|
|
872
|
+
return r;
|
|
873
|
+
}
|
|
874
|
+
/** The reports of a final reply, with the futures they settle. */
|
|
875
|
+
#reports(ok) {
|
|
876
|
+
const rows = listOf(field(ok, "reports")).map((j) => this.#report(j));
|
|
877
|
+
for (const id of textsOf(field(ok, "gone"))) this.#settle(id, void 0, sendFailed("function gone"));
|
|
878
|
+
const unhandled = new Set(rows.flatMap((r) => r.kind === "unhandled" ? [r.delivery] : []));
|
|
879
|
+
for (const r of rows) {
|
|
880
|
+
switch (r.kind) {
|
|
881
|
+
case "run started":
|
|
882
|
+
if (r.delivery) this.#runs.set(r.run, r.delivery);
|
|
883
|
+
break;
|
|
884
|
+
case "run end":
|
|
885
|
+
if (r.run) this.#runs.delete(r.run);
|
|
886
|
+
if (r.climbed || !r.delivery) break;
|
|
887
|
+
if (unhandled.has(r.delivery)) this.#settle(r.delivery, void 0, sendFailed("unhandled"));
|
|
888
|
+
else if (r.outcome === "completed") this.#settle(r.delivery, r.result ?? nothing);
|
|
889
|
+
else this.#settle(r.delivery, void 0, sendFailed(r.outcome));
|
|
890
|
+
break;
|
|
891
|
+
case "run discarded":
|
|
892
|
+
if (r.reason !== "rewind") {
|
|
893
|
+
const delivery = this.#runs.get(r.run);
|
|
894
|
+
if (delivery) this.#settle(delivery, void 0, sendFailed("stopped"));
|
|
895
|
+
}
|
|
896
|
+
this.#runs.delete(r.run);
|
|
897
|
+
break;
|
|
898
|
+
case "unhandled":
|
|
899
|
+
this.#settle(r.delivery, void 0, sendFailed("unhandled"));
|
|
900
|
+
break;
|
|
901
|
+
case "stop":
|
|
902
|
+
for (const id of r.droppedMessages) this.#settle(id, void 0, sendFailed("stopped"));
|
|
903
|
+
for (const run of r.discardedRuns) {
|
|
904
|
+
const delivery = this.#runs.get(run);
|
|
905
|
+
if (delivery) this.#settle(delivery, void 0, sendFailed("stopped"));
|
|
906
|
+
this.#runs.delete(run);
|
|
907
|
+
}
|
|
908
|
+
break;
|
|
909
|
+
case "decided": {
|
|
910
|
+
const id = r.broadcast ?? r.delivery;
|
|
911
|
+
const d = this.#decisions.get(id);
|
|
912
|
+
if (d) {
|
|
913
|
+
this.#decisions.delete(id);
|
|
914
|
+
d.sealed = true;
|
|
915
|
+
const { kind: _, ...decided } = r;
|
|
916
|
+
d.resolve(decided);
|
|
917
|
+
}
|
|
918
|
+
break;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
delete r.climbed;
|
|
922
|
+
}
|
|
923
|
+
this.#failureDetails.clear();
|
|
924
|
+
this.#effectDetails.clear();
|
|
925
|
+
this.#propertyDetails = [];
|
|
926
|
+
return rows;
|
|
927
|
+
}
|
|
928
|
+
#settle(delivery, value, failure) {
|
|
929
|
+
const waiting = this.#requests.get(delivery);
|
|
930
|
+
if (!waiting) return;
|
|
931
|
+
this.#requests.delete(delivery);
|
|
932
|
+
if (failure) waiting.reject(failure);
|
|
933
|
+
else waiting.resolve(value);
|
|
934
|
+
}
|
|
935
|
+
/** @internal Message data shared with the Script combined operation. */
|
|
936
|
+
messageFrame(m) {
|
|
937
|
+
return {
|
|
938
|
+
name: m.name,
|
|
939
|
+
args: encodeAll(this.#codec, m.args ?? []),
|
|
940
|
+
limits: m.limits ? { ...m.limits } : void 0
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
#target(to) {
|
|
944
|
+
return { object: this.#held(to) };
|
|
945
|
+
}
|
|
946
|
+
#held(o) {
|
|
947
|
+
if (this.#objects.get(key(o.kind.name, o.id))?.handle !== o) throw new HostError("wrong group", `${o.value} isn't this Group's`);
|
|
948
|
+
return { $object: [o.kind.name, o.id] };
|
|
949
|
+
}
|
|
950
|
+
#objectRef(o) {
|
|
951
|
+
return this.#objects.get(key(o.kind.name, o.id))?.handle === o ? { $object: [o.kind.name, o.id] } : { $object: ["", ""] };
|
|
952
|
+
}
|
|
953
|
+
/** @internal */
|
|
954
|
+
queue(m, fields, message) {
|
|
955
|
+
const ok = this.send(m, {
|
|
956
|
+
...fields,
|
|
957
|
+
...message ? { message: this.messageFrame(message) } : {}
|
|
958
|
+
});
|
|
959
|
+
this.#ready();
|
|
960
|
+
return textOf(field(ok, "delivery")) ?? textOf(field(ok, "broadcast"));
|
|
961
|
+
}
|
|
962
|
+
#cancellable(id, signal, live) {
|
|
963
|
+
if (!signal) return;
|
|
964
|
+
const cancel = () => {
|
|
965
|
+
if (live()) this.control("cancel-delivery", { delivery: id });
|
|
966
|
+
};
|
|
967
|
+
if (signal.aborted) cancel();
|
|
968
|
+
else signal.addEventListener("abort", cancel, { once: true });
|
|
969
|
+
}
|
|
970
|
+
#waiting(id, signal) {
|
|
971
|
+
let waiting;
|
|
972
|
+
const result = new Promise((resolve, reject) => {
|
|
973
|
+
waiting = {
|
|
974
|
+
resolve,
|
|
975
|
+
reject
|
|
976
|
+
};
|
|
977
|
+
});
|
|
978
|
+
result.catch(() => {});
|
|
979
|
+
this.#requests.set(id, waiting);
|
|
980
|
+
this.#cancellable(id, signal, () => this.#requests.has(id));
|
|
981
|
+
return {
|
|
982
|
+
id,
|
|
983
|
+
result
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
/** @internal */
|
|
987
|
+
ask(to, m, o) {
|
|
988
|
+
return this.#waiting(this.queue("request", to, m), o?.signal);
|
|
989
|
+
}
|
|
990
|
+
/** @internal */
|
|
991
|
+
decision(fields, m, o) {
|
|
992
|
+
const id = this.queue("decide", fields, m);
|
|
993
|
+
let deciding;
|
|
994
|
+
const decided = new Promise((resolve) => {
|
|
995
|
+
deciding = {
|
|
996
|
+
resolve,
|
|
997
|
+
sealed: false
|
|
998
|
+
};
|
|
999
|
+
});
|
|
1000
|
+
this.#decisions.set(id, deciding);
|
|
1001
|
+
this.#cancellable(id, o?.signal, () => !deciding.sealed);
|
|
1002
|
+
return {
|
|
1003
|
+
id,
|
|
1004
|
+
decided
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/** @internal Queued controls, which make the Group runnable. */
|
|
1008
|
+
control(m, fields) {
|
|
1009
|
+
this.send(m, fields);
|
|
1010
|
+
this.#ready();
|
|
1011
|
+
}
|
|
1012
|
+
script(name) {
|
|
1013
|
+
return this.#scripts.get(name);
|
|
1014
|
+
}
|
|
1015
|
+
scriptNames() {
|
|
1016
|
+
return [...this.#scripts.keys()];
|
|
1017
|
+
}
|
|
1018
|
+
#grantHandles(grants) {
|
|
1019
|
+
return Object.fromEntries(Object.entries(grants).map(([name, g]) => [name, this.#session.grant(g)]));
|
|
1020
|
+
}
|
|
1021
|
+
load(o) {
|
|
1022
|
+
this.#session.syncKinds();
|
|
1023
|
+
const grants = o.grants ?? {};
|
|
1024
|
+
const ok = this.worker("load", {
|
|
1025
|
+
name: o.name,
|
|
1026
|
+
source: o.source,
|
|
1027
|
+
grants: this.#grantHandles(grants),
|
|
1028
|
+
grantsAsUsed: o.grantsAsUsed,
|
|
1029
|
+
owner: o.owner ? this.#objectRef(o.owner) : void 0,
|
|
1030
|
+
objects: o.objects ? Object.fromEntries(Object.entries(o.objects).map(([n, h]) => [n, this.#objectRef(h)])) : void 0,
|
|
1031
|
+
limits: {
|
|
1032
|
+
...limitDefaults,
|
|
1033
|
+
...o.limits
|
|
1034
|
+
}
|
|
1035
|
+
});
|
|
1036
|
+
const name = textOf(field(ok, "script")) ?? o.name;
|
|
1037
|
+
this.#bindings.set(name, new Map(Object.entries(grants)));
|
|
1038
|
+
const script = new WasmScript(this, name);
|
|
1039
|
+
this.#scripts.set(name, script);
|
|
1040
|
+
return script;
|
|
1041
|
+
}
|
|
1042
|
+
addLibrary(l) {
|
|
1043
|
+
this.#core.install(this.#session, l);
|
|
1044
|
+
this.worker("add-library", { identity: bytesFrame(l.identity) });
|
|
1045
|
+
}
|
|
1046
|
+
replaceLibrary(l, carry) {
|
|
1047
|
+
this.#core.install(this.#session, l);
|
|
1048
|
+
return this.lifecycle("replace-library", {
|
|
1049
|
+
identity: bytesFrame(l.identity),
|
|
1050
|
+
carry
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
/** @internal Reload and Library replacement end Runs and settle their futures. */
|
|
1054
|
+
lifecycle(m, fields) {
|
|
1055
|
+
const reports = this.#reports(this.worker(m, fields) ?? null);
|
|
1056
|
+
this.#ready();
|
|
1057
|
+
return reports;
|
|
1058
|
+
}
|
|
1059
|
+
object(kind, id, native) {
|
|
1060
|
+
if (this.#objects.has(key(kind.name, id))) throw new HostError("duplicate object id", `${kind.name} ${id}`);
|
|
1061
|
+
this.#session.syncKinds();
|
|
1062
|
+
this.send("object", {
|
|
1063
|
+
kind: kind.name,
|
|
1064
|
+
id
|
|
1065
|
+
});
|
|
1066
|
+
const state = makeObject(kind, id, native);
|
|
1067
|
+
this.#objects.set(key(kind.name, id), state);
|
|
1068
|
+
return state.handle;
|
|
1069
|
+
}
|
|
1070
|
+
objectById(kind, id) {
|
|
1071
|
+
return this.#objects.get(key(kind, id))?.handle;
|
|
1072
|
+
}
|
|
1073
|
+
setParent(o, parent) {
|
|
1074
|
+
this.control("set-parent", {
|
|
1075
|
+
object: this.#held(o),
|
|
1076
|
+
parent: parent ? this.#held(parent) : null
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
dispose(o) {
|
|
1080
|
+
this.control("dispose", { object: this.#held(o) });
|
|
1081
|
+
}
|
|
1082
|
+
deliver(to, m) {
|
|
1083
|
+
return this.queue("deliver", { to: this.#target(to) }, m);
|
|
1084
|
+
}
|
|
1085
|
+
request(to, m, o) {
|
|
1086
|
+
return this.ask({ to: this.#target(to) }, m, o);
|
|
1087
|
+
}
|
|
1088
|
+
requestPump(to, m, now, o) {
|
|
1089
|
+
return this.combined("request-pump", () => ({
|
|
1090
|
+
to: this.#target(to),
|
|
1091
|
+
message: this.messageFrame(m)
|
|
1092
|
+
}), now, o);
|
|
1093
|
+
}
|
|
1094
|
+
callPump(fn, args, now, o) {
|
|
1095
|
+
return this.combined("call-pump", () => ({
|
|
1096
|
+
fn: encode(this.#codec, fn),
|
|
1097
|
+
args: encodeAll(this.#codec, args),
|
|
1098
|
+
limits: o?.limits ? { ...o.limits } : void 0
|
|
1099
|
+
}), now, o);
|
|
1100
|
+
}
|
|
1101
|
+
/** @internal Shared by Script and Object targets. No fallback on old guests. */
|
|
1102
|
+
combined(m, fields, now, o) {
|
|
1103
|
+
if (this.#combining) return {
|
|
1104
|
+
admitted: false,
|
|
1105
|
+
error: new HostError("reentrant call")
|
|
1106
|
+
};
|
|
1107
|
+
if (!this.#session.requestPump) return {
|
|
1108
|
+
admitted: false,
|
|
1109
|
+
error: new HostError("invalid value", "talk.wasm lacks request-pump-fields-v1")
|
|
1110
|
+
};
|
|
1111
|
+
this.#combining = true;
|
|
1112
|
+
let requested;
|
|
1113
|
+
let waiting;
|
|
1114
|
+
const result = new Promise((resolve, reject) => {
|
|
1115
|
+
waiting = {
|
|
1116
|
+
resolve,
|
|
1117
|
+
reject
|
|
1118
|
+
};
|
|
1119
|
+
});
|
|
1120
|
+
result.catch(() => {});
|
|
1121
|
+
let sent = false;
|
|
1122
|
+
let refused = false;
|
|
1123
|
+
let cancelled = o?.signal?.aborted ?? false;
|
|
1124
|
+
let token;
|
|
1125
|
+
const cancel = () => {
|
|
1126
|
+
if (!sent) {
|
|
1127
|
+
cancelled = true;
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (refused) return;
|
|
1131
|
+
if (requested) {
|
|
1132
|
+
if (this.#requests.has(requested.id)) this.control("cancel-delivery", { delivery: requested.id });
|
|
1133
|
+
} else this.control("cancel-correlated", { token });
|
|
1134
|
+
};
|
|
1135
|
+
o?.signal?.addEventListener("abort", cancel, { once: true });
|
|
1136
|
+
try {
|
|
1137
|
+
this.#session.syncKinds();
|
|
1138
|
+
if (o?.signal?.aborted) {
|
|
1139
|
+
const ok = this.send(m === "request-pump" ? "request" : "call", fields());
|
|
1140
|
+
const id = textOf(field(ok, "delivery"));
|
|
1141
|
+
requested = this.#waiting(id, o.signal);
|
|
1142
|
+
const pumped = this.send("pump", {
|
|
1143
|
+
now: formatInstant(now),
|
|
1144
|
+
fuelSlice: o.fuelSlice,
|
|
1145
|
+
fuelCap: o.fuelCap
|
|
1146
|
+
});
|
|
1147
|
+
return {
|
|
1148
|
+
admitted: true,
|
|
1149
|
+
requested,
|
|
1150
|
+
pump: {
|
|
1151
|
+
ok: true,
|
|
1152
|
+
result: this.#pumpResult(pumped)
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
token = this.#session.nextToken();
|
|
1157
|
+
const ok = this.send(m, {
|
|
1158
|
+
...fields(),
|
|
1159
|
+
token,
|
|
1160
|
+
now: formatInstant(now),
|
|
1161
|
+
fuelSlice: o?.fuelSlice,
|
|
1162
|
+
fuelCap: o?.fuelCap
|
|
1163
|
+
}, (packet) => {
|
|
1164
|
+
sent = true;
|
|
1165
|
+
const id = textOf(field(packet, "delivery"));
|
|
1166
|
+
if (id) {
|
|
1167
|
+
const replyToken = field(packet, "token");
|
|
1168
|
+
if (!replyToken || typeof replyToken !== "object" || Array.isArray(replyToken) || replyToken.kind !== "number" || replyToken.source !== token.json) throw new HostError("invalid value", "The reply names another correlation token");
|
|
1169
|
+
requested = {
|
|
1170
|
+
id,
|
|
1171
|
+
result
|
|
1172
|
+
};
|
|
1173
|
+
this.#requests.set(id, waiting);
|
|
1174
|
+
} else if (field(packet, "need") === void 0) refused = true;
|
|
1175
|
+
if (cancelled && !refused) {
|
|
1176
|
+
cancelled = false;
|
|
1177
|
+
cancel();
|
|
1178
|
+
}
|
|
1179
|
+
});
|
|
1180
|
+
if (!requested) throw new HostError("invalid value", "The combined reply omitted its delivery");
|
|
1181
|
+
return {
|
|
1182
|
+
admitted: true,
|
|
1183
|
+
requested,
|
|
1184
|
+
pump: {
|
|
1185
|
+
ok: true,
|
|
1186
|
+
result: this.#pumpResult(ok)
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
if (!requested) return {
|
|
1191
|
+
admitted: false,
|
|
1192
|
+
error
|
|
1193
|
+
};
|
|
1194
|
+
this.#ready();
|
|
1195
|
+
return {
|
|
1196
|
+
admitted: true,
|
|
1197
|
+
requested,
|
|
1198
|
+
pump: {
|
|
1199
|
+
ok: false,
|
|
1200
|
+
error
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
} finally {
|
|
1204
|
+
this.#combining = false;
|
|
1205
|
+
if (!requested) o?.signal?.removeEventListener("abort", cancel);
|
|
1206
|
+
else requested.result.then(() => o?.signal?.removeEventListener("abort", cancel), () => o?.signal?.removeEventListener("abort", cancel));
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
broadcast(m) {
|
|
1210
|
+
return this.queue("broadcast", {}, m);
|
|
1211
|
+
}
|
|
1212
|
+
decide(to, m, o) {
|
|
1213
|
+
return this.decision({ to: this.#target(to) }, m, o);
|
|
1214
|
+
}
|
|
1215
|
+
decideBroadcast(m, o) {
|
|
1216
|
+
return this.decision({ broadcast: true }, m, o);
|
|
1217
|
+
}
|
|
1218
|
+
call(fn, args, o) {
|
|
1219
|
+
const id = this.queue("call", {
|
|
1220
|
+
fn: encode(this.#codec, fn),
|
|
1221
|
+
args: encodeAll(this.#codec, args),
|
|
1222
|
+
limits: o?.limits ? { ...o.limits } : void 0
|
|
1223
|
+
});
|
|
1224
|
+
return this.#waiting(id, o?.signal);
|
|
1225
|
+
}
|
|
1226
|
+
pump(now, o) {
|
|
1227
|
+
const ok = this.worker("pump", {
|
|
1228
|
+
now: formatInstant(now),
|
|
1229
|
+
fuelSlice: o?.fuelSlice,
|
|
1230
|
+
fuelCap: o?.fuelCap
|
|
1231
|
+
});
|
|
1232
|
+
return this.#pumpResult(ok);
|
|
1233
|
+
}
|
|
1234
|
+
#pumpResult(ok) {
|
|
1235
|
+
this.#restored.clear();
|
|
1236
|
+
const deadline = textOf(field(ok, "nextDeadline"));
|
|
1237
|
+
return {
|
|
1238
|
+
state: textOf(field(ok, "state")),
|
|
1239
|
+
...deadline ? { nextDeadline: parseInstant(deadline) } : {},
|
|
1240
|
+
fuelUsed: intOf(field(ok, "fuelUsed")) ?? 0,
|
|
1241
|
+
reports: this.#reports(ok)
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
save() {
|
|
1245
|
+
return bytesOfFrame(field(this.worker("save"), "save"));
|
|
1246
|
+
}
|
|
1247
|
+
fingerprint() {
|
|
1248
|
+
return bytesOfFrame(field(this.worker("fingerprint"), "fingerprint"));
|
|
1249
|
+
}
|
|
1250
|
+
inspect() {
|
|
1251
|
+
const ok = this.worker("inspect");
|
|
1252
|
+
return { scripts: listOf(field(ok, "scripts")).map((s) => {
|
|
1253
|
+
const disabled = textsOf(field(s, "disabledGrants"));
|
|
1254
|
+
return {
|
|
1255
|
+
name: textOf(field(s, "name")),
|
|
1256
|
+
...disabled.length ? { disabledGrants: disabled } : {},
|
|
1257
|
+
vars: listOf(field(s, "vars")).map((pair) => {
|
|
1258
|
+
const [name, v] = listOf(pair);
|
|
1259
|
+
return [textOf(name), decode(this.#codec, v)];
|
|
1260
|
+
}),
|
|
1261
|
+
runs: listOf(field(s, "runs")).map((r) => {
|
|
1262
|
+
const run = plain(r);
|
|
1263
|
+
if (typeof run.until === "string") run.until = parseInstant(run.until);
|
|
1264
|
+
return run;
|
|
1265
|
+
}),
|
|
1266
|
+
mailbox: listOf(field(s, "mailbox")).map((item) => {
|
|
1267
|
+
const message = field(item, "message");
|
|
1268
|
+
const limits = plain(field(message, "limits"));
|
|
1269
|
+
return {
|
|
1270
|
+
...has(item, "delivery") ? { delivery: textOf(field(item, "delivery")) } : {},
|
|
1271
|
+
...has(item, "from") ? { from: textOf(field(item, "from")) } : {},
|
|
1272
|
+
message: {
|
|
1273
|
+
name: textOf(field(message, "name")),
|
|
1274
|
+
args: listOf(field(message, "args")).map((a) => decode(this.#codec, a)),
|
|
1275
|
+
...limits ? { limits } : {}
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
})
|
|
1279
|
+
};
|
|
1280
|
+
}) };
|
|
1281
|
+
}
|
|
1282
|
+
settle(callId, s) {
|
|
1283
|
+
const pending = this.#restored.get(callId);
|
|
1284
|
+
const adopt = "adopt" in s;
|
|
1285
|
+
if (adopt && pending) {
|
|
1286
|
+
const op = this.#grantOf(textOf(field(pending, "script")), textOf(field(pending, "grant")))?.capability.operations.get(textOf(field(pending, "operation")));
|
|
1287
|
+
if (op?.mode === "suspending" && op.run) throw new HostError("not adoptable", `${callId} runs a Promise`);
|
|
1288
|
+
}
|
|
1289
|
+
this.send("settle", {
|
|
1290
|
+
call: callId,
|
|
1291
|
+
settlement: "answer" in s ? { answer: encode(this.#codec, s.answer) } : "fail" in s ? { fail: this.#failure(s.fail) } : "reissue" in s ? { reissue: true } : { adopt: true }
|
|
1292
|
+
});
|
|
1293
|
+
this.#restored.delete(callId);
|
|
1294
|
+
this.#ready();
|
|
1295
|
+
if (!adopt || !pending) return;
|
|
1296
|
+
const grant = this.#grantOf(textOf(field(pending, "script")), textOf(field(pending, "grant")));
|
|
1297
|
+
const live = {
|
|
1298
|
+
abort: new AbortController(),
|
|
1299
|
+
live: true
|
|
1300
|
+
};
|
|
1301
|
+
this.#calls.set(callId, live);
|
|
1302
|
+
return this.#callOf(pending, grant, live, () => {
|
|
1303
|
+
throw new HostError("invalid value", "Charge only while starting");
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/** @internal */
|
|
1307
|
+
restore(save, o) {
|
|
1308
|
+
for (const l of o.libraries) this.#core.install(this.#session, l);
|
|
1309
|
+
this.#session.syncKinds();
|
|
1310
|
+
this.#restoring = o;
|
|
1311
|
+
let ok;
|
|
1312
|
+
try {
|
|
1313
|
+
ok = this.send("restore", {
|
|
1314
|
+
name: o.name,
|
|
1315
|
+
save: bytesFrame(save),
|
|
1316
|
+
libraries: o.libraries.map((l) => bytesFrame(l.identity)),
|
|
1317
|
+
mismatch: o.onMismatch,
|
|
1318
|
+
trace: !!o.trace
|
|
1319
|
+
});
|
|
1320
|
+
} finally {
|
|
1321
|
+
this.#restoring = null;
|
|
1322
|
+
}
|
|
1323
|
+
for (const name of textsOf(field(ok, "scripts"))) {
|
|
1324
|
+
this.#scripts.set(name, new WasmScript(this, name));
|
|
1325
|
+
if (!this.#bindings.has(name)) this.#bindings.set(name, /* @__PURE__ */ new Map());
|
|
1326
|
+
}
|
|
1327
|
+
for (const pair of listOf(field(ok, "objects"))) {
|
|
1328
|
+
const [kind, id] = textsOf(pair);
|
|
1329
|
+
const k = this.#core.kind(kind);
|
|
1330
|
+
if (k && !this.#objects.has(key(kind, id))) this.#objects.set(key(kind, id), makeObject(k, id, void 0));
|
|
1331
|
+
}
|
|
1332
|
+
const pending = listOf(field(ok, "pending")).map((p) => {
|
|
1333
|
+
const id = textOf(field(p, "call"));
|
|
1334
|
+
this.#restored.set(id, p);
|
|
1335
|
+
const script = textOf(field(p, "script"));
|
|
1336
|
+
const grant = textOf(field(p, "grant"));
|
|
1337
|
+
return {
|
|
1338
|
+
id,
|
|
1339
|
+
script,
|
|
1340
|
+
grant,
|
|
1341
|
+
operation: {
|
|
1342
|
+
capability: this.#grantOf(script, grant)?.capability.name ?? textOf(field(p, "capability")) ?? "",
|
|
1343
|
+
operation: textOf(field(p, "operation"))
|
|
1344
|
+
},
|
|
1345
|
+
args: listOf(field(p, "args")).map((a) => decode(this.#codec, a))
|
|
1346
|
+
};
|
|
1347
|
+
});
|
|
1348
|
+
return {
|
|
1349
|
+
reports: this.#reports(ok),
|
|
1350
|
+
variablesOnly: boolOf(field(ok, "variablesOnly")) ?? false,
|
|
1351
|
+
pending,
|
|
1352
|
+
discardedRuns: textsOf(field(ok, "discardedRuns")),
|
|
1353
|
+
disposed: listOf(field(ok, "disposed")).map((d) => textsOf(d)),
|
|
1354
|
+
droppedMessages: textsOf(field(ok, "droppedMessages")),
|
|
1355
|
+
abandonedCalls: textsOf(field(ok, "abandonedCalls"))
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
/** This Group's guest linear memory, in bytes. */
|
|
1359
|
+
memoryBytes() {
|
|
1360
|
+
return this.#session.reactor.memoryBytes();
|
|
1361
|
+
}
|
|
1362
|
+
/** @internal Rebinds a restored handle's native, as the TS Core does. */
|
|
1363
|
+
rebind(o, native) {
|
|
1364
|
+
const state = this.#objects.get(key(o.kind.name, o.id));
|
|
1365
|
+
if (state) rebindObject(state, native);
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
1368
|
+
//#endregion
|
|
1369
|
+
//#region src/wasm/session.ts
|
|
1370
|
+
/** The features this Host relies on; a guest without one is refused. */
|
|
1371
|
+
const features = [
|
|
1372
|
+
"paused-inputs-v1",
|
|
1373
|
+
"abandoned-before-needs-v1",
|
|
1374
|
+
"crossing-trace-v1",
|
|
1375
|
+
"climb-v1",
|
|
1376
|
+
"function-gone-v1",
|
|
1377
|
+
"standard-refinements-v1",
|
|
1378
|
+
"restore-bindings-v1"
|
|
1379
|
+
];
|
|
1380
|
+
/** Features this Host uses when the guest offers them (#1143). */
|
|
1381
|
+
const optionalFeatures = [
|
|
1382
|
+
"object-elements-v1",
|
|
1383
|
+
requestPumpFeature,
|
|
1384
|
+
callbacksFeature
|
|
1385
|
+
];
|
|
1386
|
+
const binaryMethods = /* @__PURE__ */ new Set([
|
|
1387
|
+
"request",
|
|
1388
|
+
"call",
|
|
1389
|
+
"pump",
|
|
1390
|
+
"request-pump",
|
|
1391
|
+
"call-pump"
|
|
1392
|
+
]);
|
|
1393
|
+
const encoder = new TextEncoder();
|
|
1394
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1395
|
+
const failure = (err) => {
|
|
1396
|
+
const kind = textOf(field(err, "kind"));
|
|
1397
|
+
if (kind === "host error") return new HostError(textOf(field(err, "code")), textOf(field(err, "detail")) || textOf(field(err, "code")));
|
|
1398
|
+
if (kind === "load error") return new LoadError(plain(field(err, "diagnostics")));
|
|
1399
|
+
if (kind === "mailbox full") return new MailboxFull("mailbox full");
|
|
1400
|
+
return /* @__PURE__ */ new Error(`Message Layer ${kind ?? "error"}: ${textOf(field(err, "detail")) ?? ""}`);
|
|
1401
|
+
};
|
|
1402
|
+
const costFrame = (c) => ({
|
|
1403
|
+
fuel: c.fuel,
|
|
1404
|
+
alloc: c.alloc ?? 0
|
|
1405
|
+
});
|
|
1406
|
+
const isStandard = (def) => [...def.operations.values()].some((op) => standardChecks(op));
|
|
1407
|
+
const segmentBound = (def) => [...def.operations.values()].some((op) => op.mode === "immediate" && op.segmentBound);
|
|
1408
|
+
var Session = class {
|
|
1409
|
+
registry;
|
|
1410
|
+
reactor;
|
|
1411
|
+
versions;
|
|
1412
|
+
#ref = 0;
|
|
1413
|
+
#definitions = /* @__PURE__ */ new Map();
|
|
1414
|
+
#grants = /* @__PURE__ */ new Map();
|
|
1415
|
+
#coordinators = /* @__PURE__ */ new Map();
|
|
1416
|
+
#kinds = /* @__PURE__ */ new Set();
|
|
1417
|
+
#libraries = /* @__PURE__ */ new Set();
|
|
1418
|
+
/** Whether the guest accepts Object Collection declarations. */
|
|
1419
|
+
elements;
|
|
1420
|
+
requestPump;
|
|
1421
|
+
callbacks;
|
|
1422
|
+
#token = 0n;
|
|
1423
|
+
/** How Values in binary frames resolve, once a Group binds its own. */
|
|
1424
|
+
#values = placeholderValues({ encodeFunction: guestPayload });
|
|
1425
|
+
nextToken() {
|
|
1426
|
+
if (this.#token === 2n ** 64n - 1n) throw new HostError("invalid value", "Correlation tokens exhausted");
|
|
1427
|
+
return new Raw((++this.#token).toString());
|
|
1428
|
+
}
|
|
1429
|
+
constructor(module, diagnostics, registry, binaryCallbacks = true) {
|
|
1430
|
+
this.registry = registry;
|
|
1431
|
+
this.reactor = new Reactor(module, diagnostics);
|
|
1432
|
+
const hello = this.exchange("hello", {
|
|
1433
|
+
protocol: 1,
|
|
1434
|
+
features: [...features, ...optionalFeatures.filter((f) => binaryCallbacks || f !== callbacksFeature)]
|
|
1435
|
+
});
|
|
1436
|
+
const offered = new Set(textsOf(field(hello, "features")));
|
|
1437
|
+
this.elements = offered.has("object-elements-v1");
|
|
1438
|
+
this.requestPump = offered.has(requestPumpFeature);
|
|
1439
|
+
this.callbacks = binaryCallbacks && offered.has(callbacksFeature);
|
|
1440
|
+
const missing = features.filter((f) => !offered.has(f));
|
|
1441
|
+
if (missing.length) throw new InstanceLostError(`talk.wasm lacks ${missing.join(", ")}`);
|
|
1442
|
+
this.versions = {
|
|
1443
|
+
language: textOf(field(hello, "language")),
|
|
1444
|
+
costModel: textOf(field(hello, "costModel")),
|
|
1445
|
+
unicode: textOf(field(hello, "unicode")),
|
|
1446
|
+
core: textOf(field(hello, "core")),
|
|
1447
|
+
saveFormat: textOf(field(hello, "saveFormat"))
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* One complete exchange: the message, then every need answered under its
|
|
1452
|
+
* ref, until the final reply. Returns its `ok`, or throws its `err`.
|
|
1453
|
+
* A callback may start other exchanges meanwhile, under their own refs.
|
|
1454
|
+
*/
|
|
1455
|
+
exchange(m, fields, answer, observe) {
|
|
1456
|
+
const ref = ++this.#ref;
|
|
1457
|
+
const binaryExchange = this.requestPump && binaryMethods.has(m);
|
|
1458
|
+
const first = {
|
|
1459
|
+
m,
|
|
1460
|
+
ref,
|
|
1461
|
+
...fields
|
|
1462
|
+
};
|
|
1463
|
+
let input = binaryExchange ? new Uint8Array(encodeBinaryFrame(frameTree(first), this.#values)) : encoder.encode(frameJSON(first));
|
|
1464
|
+
for (;;) {
|
|
1465
|
+
const output = this.reactor.frameBytes(input);
|
|
1466
|
+
const bytes = new Uint8Array(output);
|
|
1467
|
+
const binaryReply = isRequestPumpBinary(bytes);
|
|
1468
|
+
const packet = binaryReply ? this.#readBinary(output, binaryExchange) : readReply(decoder.decode(output));
|
|
1469
|
+
const need = field(packet, "need");
|
|
1470
|
+
if (intOf(field(packet, "ref")) !== ref) throw new InstanceLostError(`The reply to ${m} has another ref`);
|
|
1471
|
+
observe?.(packet, m);
|
|
1472
|
+
const err = field(packet, "err");
|
|
1473
|
+
if (err !== void 0) throw failure(err);
|
|
1474
|
+
if (binaryExchange && !binaryReply && need === void 0) throw new InstanceLostError("The binary exchange ended with a JSON success");
|
|
1475
|
+
if (need === void 0) return field(packet, "ok") ?? null;
|
|
1476
|
+
if (!answer) throw new InstanceLostError(`${m} asked for an unexpected need`);
|
|
1477
|
+
const name = textOf(field(need, "m"));
|
|
1478
|
+
const result = answer(need, packet);
|
|
1479
|
+
const binary = this.callbacks ? encodeResult(name, ref, fields.group, answerFields(result), this.#values) : void 0;
|
|
1480
|
+
input = binary ? new Uint8Array(binary) : encoder.encode(frameJSON({
|
|
1481
|
+
...result,
|
|
1482
|
+
m: `${name}-result`,
|
|
1483
|
+
ref,
|
|
1484
|
+
group: fields.group
|
|
1485
|
+
}));
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
#readBinary(output, binaryExchange) {
|
|
1489
|
+
const need = isBinaryNeed(new Uint8Array(output));
|
|
1490
|
+
if (need ? !this.callbacks : !binaryExchange) throw new InstanceLostError("Unnegotiated binary reply");
|
|
1491
|
+
return need ? decodeNeed(output, this.#values) : decodeBinaryFrame(output);
|
|
1492
|
+
}
|
|
1493
|
+
/** Resolves binary callback Values as the Group that owns this guest does. */
|
|
1494
|
+
bind(values) {
|
|
1495
|
+
this.#values = values;
|
|
1496
|
+
}
|
|
1497
|
+
/** The guest's handle for a Capability, declared on first use. */
|
|
1498
|
+
define(def) {
|
|
1499
|
+
let handle = this.#definitions.get(def);
|
|
1500
|
+
if (handle !== void 0) return handle;
|
|
1501
|
+
handle = this.registry.handleOf(def);
|
|
1502
|
+
this.exchange("define-capability", {
|
|
1503
|
+
name: def.name,
|
|
1504
|
+
handle,
|
|
1505
|
+
ops: [...def.operations].map(([name, op]) => ({
|
|
1506
|
+
...operationData(name, op),
|
|
1507
|
+
description: op.description,
|
|
1508
|
+
examples: op.examples ? [...op.examples] : void 0
|
|
1509
|
+
})),
|
|
1510
|
+
segmentLifecycle: segmentBound(def) || void 0,
|
|
1511
|
+
release: def.release ? true : void 0,
|
|
1512
|
+
standard: isStandard(def) ? def.name : void 0
|
|
1513
|
+
});
|
|
1514
|
+
this.#definitions.set(def, handle);
|
|
1515
|
+
return handle;
|
|
1516
|
+
}
|
|
1517
|
+
/** The guest's handle for a Grant, made on first use. */
|
|
1518
|
+
grant(grant) {
|
|
1519
|
+
let handle = this.#grants.get(grant);
|
|
1520
|
+
if (handle !== void 0) return handle;
|
|
1521
|
+
const def = grant.capability;
|
|
1522
|
+
const capability = this.define(def);
|
|
1523
|
+
let coordinator;
|
|
1524
|
+
if (segmentBound(def) && grant.coordinator) {
|
|
1525
|
+
coordinator = this.#coordinators.get(grant.coordinator);
|
|
1526
|
+
if (coordinator === void 0) {
|
|
1527
|
+
coordinator = `coordinator-${this.#coordinators.size + 1}`;
|
|
1528
|
+
this.#coordinators.set(grant.coordinator, coordinator);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
const standard = isStandard(def);
|
|
1532
|
+
const binding = grant.binding;
|
|
1533
|
+
const ok = this.exchange("grant", {
|
|
1534
|
+
capability,
|
|
1535
|
+
ops: [...grant.ops].sort(),
|
|
1536
|
+
coordinator,
|
|
1537
|
+
locale: standard && def.name === "locale" ? typeof binding === "string" ? binding : "und" : void 0,
|
|
1538
|
+
maxRows: standard && def.name === "sqlite" && typeof binding === "object" ? binding.maxRows : void 0
|
|
1539
|
+
});
|
|
1540
|
+
handle = intOf(field(ok, "grant"));
|
|
1541
|
+
this.#grants.set(grant, handle);
|
|
1542
|
+
return handle;
|
|
1543
|
+
}
|
|
1544
|
+
/** A declared Capability's name, from the handle the guest reports. */
|
|
1545
|
+
capabilityName(handle) {
|
|
1546
|
+
for (const [def, h] of this.#definitions) if (h === handle) return def.name;
|
|
1547
|
+
}
|
|
1548
|
+
/** The coordinator a Grant's effect need names, by the name given it here. */
|
|
1549
|
+
coordinator(name) {
|
|
1550
|
+
for (const [c, n] of this.#coordinators) if (n === name) return c;
|
|
1551
|
+
}
|
|
1552
|
+
/** Declares every Object Kind the Core knows that this guest doesn't yet. */
|
|
1553
|
+
syncKinds() {
|
|
1554
|
+
for (const kind of this.registry.kinds) {
|
|
1555
|
+
if (this.#kinds.has(kind.name)) continue;
|
|
1556
|
+
if (kind.elements && !this.elements) throw new HostError("invalid value", `talk.wasm lacks object-elements-v1 for ${kind.name}'s collection`);
|
|
1557
|
+
this.exchange("define-object-kind", {
|
|
1558
|
+
name: kind.name,
|
|
1559
|
+
...kind.elements ? { elements: {
|
|
1560
|
+
shape: shapeData(kind.elements.shape),
|
|
1561
|
+
countCost: costFrame(kind.elements.countCost),
|
|
1562
|
+
atCost: costFrame(kind.elements.atCost),
|
|
1563
|
+
findCost: costFrame(kind.elements.findCost)
|
|
1564
|
+
} } : {},
|
|
1565
|
+
props: [...kind.props].map(([name, p]) => ({
|
|
1566
|
+
name,
|
|
1567
|
+
shape: p.shape ? shapeData(p.shape) : "value",
|
|
1568
|
+
readOnly: !p.set,
|
|
1569
|
+
getCost: {
|
|
1570
|
+
fuel: p.getCost?.fuel ?? 0,
|
|
1571
|
+
alloc: p.getCost?.alloc ?? 0
|
|
1572
|
+
},
|
|
1573
|
+
setCost: {
|
|
1574
|
+
fuel: p.setCost?.fuel ?? 0,
|
|
1575
|
+
alloc: p.setCost?.alloc ?? 0
|
|
1576
|
+
}
|
|
1577
|
+
})),
|
|
1578
|
+
parentKinds: [...kind.parentKinds]
|
|
1579
|
+
});
|
|
1580
|
+
this.#kinds.add(kind.name);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
/** Whether this guest has compiled a Library, by its identity. */
|
|
1584
|
+
hasLibrary(identity) {
|
|
1585
|
+
return this.#libraries.has(identity);
|
|
1586
|
+
}
|
|
1587
|
+
addedLibrary(identity) {
|
|
1588
|
+
this.#libraries.add(identity);
|
|
1589
|
+
}
|
|
1590
|
+
};
|
|
1591
|
+
//#endregion
|
|
1592
|
+
//#region src/wasm/core.ts
|
|
1593
|
+
const readFileURL = async (url) => {
|
|
1594
|
+
const { readFile } = await import(
|
|
1595
|
+
/* @vite-ignore */
|
|
1596
|
+
"node:fs/promises"
|
|
1597
|
+
);
|
|
1598
|
+
return readFile(url);
|
|
1599
|
+
};
|
|
1600
|
+
const compile = async (source) => {
|
|
1601
|
+
if (source instanceof WebAssembly.Module) return source;
|
|
1602
|
+
if (typeof source === "string" || source instanceof URL) {
|
|
1603
|
+
const base = globalThis.location?.href ?? import.meta.url;
|
|
1604
|
+
const url = new URL(source, base);
|
|
1605
|
+
if (url.protocol === "file:") return WebAssembly.compile(await readFileURL(url));
|
|
1606
|
+
source = fetch(url);
|
|
1607
|
+
}
|
|
1608
|
+
const resolved = await source;
|
|
1609
|
+
if (resolved instanceof Response) {
|
|
1610
|
+
if (!resolved.ok) throw new Error(`talk.wasm: ${resolved.status} ${resolved.statusText}`);
|
|
1611
|
+
return WebAssembly.compile(await resolved.arrayBuffer());
|
|
1612
|
+
}
|
|
1613
|
+
return WebAssembly.compile(resolved);
|
|
1614
|
+
};
|
|
1615
|
+
const hex = (b) => [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
1616
|
+
var WasmCore = class {
|
|
1617
|
+
binaryCallbacks;
|
|
1618
|
+
/** The reactor's `hello`: its Core, language, Cost Model, Unicode and save format. */
|
|
1619
|
+
versions;
|
|
1620
|
+
#module;
|
|
1621
|
+
#diagnostics;
|
|
1622
|
+
#handles = /* @__PURE__ */ new Map();
|
|
1623
|
+
#named = /* @__PURE__ */ new Map();
|
|
1624
|
+
#kinds = [];
|
|
1625
|
+
#declarations = /* @__PURE__ */ new WeakMap();
|
|
1626
|
+
#libraries;
|
|
1627
|
+
#groupCore;
|
|
1628
|
+
/** @internal Use createCore. */
|
|
1629
|
+
constructor(module, diagnostics, binaryCallbacks = true) {
|
|
1630
|
+
this.binaryCallbacks = binaryCallbacks;
|
|
1631
|
+
this.#module = module;
|
|
1632
|
+
this.#diagnostics = diagnostics;
|
|
1633
|
+
this.#libraries = this.#session();
|
|
1634
|
+
this.versions = this.#libraries.versions;
|
|
1635
|
+
this.#groupCore = {
|
|
1636
|
+
session: () => this.#session(),
|
|
1637
|
+
install: (session, library) => this.#install(session, library),
|
|
1638
|
+
kind: (name) => this.#kinds.find((k) => k.name === name)
|
|
1639
|
+
};
|
|
1640
|
+
}
|
|
1641
|
+
#session() {
|
|
1642
|
+
return new Session(this.#module, this.#diagnostics, {
|
|
1643
|
+
handleOf: (def) => {
|
|
1644
|
+
let handle = this.#handles.get(def);
|
|
1645
|
+
if (handle === void 0) {
|
|
1646
|
+
const n = this.#named.get(def.name) ?? 0;
|
|
1647
|
+
this.#named.set(def.name, n + 1);
|
|
1648
|
+
handle = n ? `${def.name}#${n + 1}` : def.name;
|
|
1649
|
+
this.#handles.set(def, handle);
|
|
1650
|
+
}
|
|
1651
|
+
return handle;
|
|
1652
|
+
},
|
|
1653
|
+
kinds: this.#kinds
|
|
1654
|
+
}, this.binaryCallbacks);
|
|
1655
|
+
}
|
|
1656
|
+
defineCapability = defineCapability;
|
|
1657
|
+
clockCapability = clockCapability;
|
|
1658
|
+
calendarCapability = calendarCapability;
|
|
1659
|
+
localeCapability = localeCapability;
|
|
1660
|
+
timerCapability = timerCapability;
|
|
1661
|
+
consoleCapability = consoleCapability;
|
|
1662
|
+
storeCapability = storeCapability;
|
|
1663
|
+
sqliteCapability = sqliteCapability;
|
|
1664
|
+
userCapability = userCapability;
|
|
1665
|
+
httpCapability = httpCapability;
|
|
1666
|
+
defineObjectKind(k) {
|
|
1667
|
+
const kind = defineObjectKind(k);
|
|
1668
|
+
const at = this.#kinds.findIndex((known) => known.name === kind.name);
|
|
1669
|
+
if (at >= 0) this.#kinds[at] = kind;
|
|
1670
|
+
else this.#kinds.push(kind);
|
|
1671
|
+
return kind;
|
|
1672
|
+
}
|
|
1673
|
+
/** Checked in a guest the Core keeps; each Group's guest compiles it again when added. */
|
|
1674
|
+
compileLibrary(src, imports = [], declarations) {
|
|
1675
|
+
for (const l of imports) this.#install(this.#libraries, l);
|
|
1676
|
+
const ok = this.#libraries.exchange("compile-library", this.#libraryFields(src, imports, declarations));
|
|
1677
|
+
const identity = bytesOfFrame(field(ok, "identity"));
|
|
1678
|
+
const library = Object.freeze({
|
|
1679
|
+
name: src.name,
|
|
1680
|
+
version: src.version,
|
|
1681
|
+
source: src.source,
|
|
1682
|
+
identity,
|
|
1683
|
+
imports: Object.freeze([...imports]),
|
|
1684
|
+
needs: Object.freeze(listOf(field(ok, "needs")).map((n) => plain(n)))
|
|
1685
|
+
});
|
|
1686
|
+
this.#declarations.set(library, declarations);
|
|
1687
|
+
this.#libraries.addedLibrary(hex(identity));
|
|
1688
|
+
return library;
|
|
1689
|
+
}
|
|
1690
|
+
#libraryFields(src, imports, declarations) {
|
|
1691
|
+
return {
|
|
1692
|
+
name: src.name,
|
|
1693
|
+
version: src.version,
|
|
1694
|
+
source: src.source,
|
|
1695
|
+
imports: imports.map((l) => bytesFrame(l.identity)),
|
|
1696
|
+
declarations: Object.fromEntries(Object.entries(declarations ?? {}).map(([grant, ops]) => [grant, Object.fromEntries(Object.entries(ops).map(([op, d]) => [op, {
|
|
1697
|
+
mode: d.mode,
|
|
1698
|
+
args: d.args.map((a) => shapeData(a)),
|
|
1699
|
+
...d.labels?.length ? { labels: [...d.labels] } : {},
|
|
1700
|
+
command: d.command
|
|
1701
|
+
}]))]))
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
#install(session, library) {
|
|
1705
|
+
const id = hex(library.identity);
|
|
1706
|
+
if (session.hasLibrary(id)) return;
|
|
1707
|
+
if (!this.#declarations.has(library)) throw new HostError("invalid value", `${library.name} wasn't compiled by this Core`);
|
|
1708
|
+
for (const l of library.imports) this.#install(session, l);
|
|
1709
|
+
const ok = session.exchange("compile-library", this.#libraryFields(library, library.imports, this.#declarations.get(library)));
|
|
1710
|
+
if (hex(bytesOfFrame(field(ok, "identity"))) !== id) throw new HostError("library mismatch", `${library.name} compiled differently`);
|
|
1711
|
+
session.addedLibrary(id);
|
|
1712
|
+
}
|
|
1713
|
+
newGroup(o) {
|
|
1714
|
+
return new WasmGroup(this.#groupCore, o);
|
|
1715
|
+
}
|
|
1716
|
+
restore(save, o) {
|
|
1717
|
+
const group = new WasmGroup(this.#groupCore, o, {
|
|
1718
|
+
save,
|
|
1719
|
+
options: o
|
|
1720
|
+
});
|
|
1721
|
+
return {
|
|
1722
|
+
group,
|
|
1723
|
+
result: group.restore(save, o)
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
/**
|
|
1728
|
+
* Compiles `talk.wasm` once and returns a Core over it. The one asynchronous
|
|
1729
|
+
* call: `await createCore()` also works with the TS Core's synchronous one.
|
|
1730
|
+
*/
|
|
1731
|
+
const createCore = async (o = {}) => new WasmCore(await compile(o.wasm ?? new URL("./talk.wasm", import.meta.url)), o.diagnostics ?? ((line) => console.warn(`talk.wasm: ${line}`)), o.binaryCallbacks);
|
|
1732
|
+
//#endregion
|
|
1733
|
+
//#region src/wasm/index.ts
|
|
1734
|
+
/** Chapter 9's default Limits, which the reactor shares. */
|
|
1735
|
+
const defaultLimits = Object.freeze({ ...limitDefaults });
|
|
1736
|
+
//#endregion
|
|
1737
|
+
export { Decimal, HostError, InstanceLostError, LimitReached, LoadError, MailboxFull, ScriptError, Value, WasmCore, WasmGroup, WasmScript, add, bool, bytes, civilDate, createCore, dec, decodeJson, decodeValue, defaultLimits, encodeJson, encodeValue, exportManifest, formatInstant, fromValue, instant, list, map, nothing, nowMicros, num, parseInstant, quantity, range, readDisplay, record, shape, talk, text, toValue };
|