@northtalk/ts 0.0.0-stage → 0.1.0

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