@northtalk/ts 0.1.0 → 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.
Files changed (54) hide show
  1. package/README.md +9 -5
  2. package/{encoding-DWlbPq-e.js → base64-DORMd3Hv.js} +197 -1368
  3. package/binary-value-CEmh60GC.d.ts +15 -0
  4. package/capabilities-CH0FkRMq.js +1301 -0
  5. package/checker-Dc1jl2WH.js +6657 -0
  6. package/core-DptnvQT9.d.ts +14 -0
  7. package/{debug-D8Z_u244.d.ts → debug-CQBxKnJB.d.ts} +1147 -780
  8. package/debug.d.ts +2 -1
  9. package/debug.js +2 -1
  10. package/driver.d.ts +16 -2
  11. package/driver.js +98 -20
  12. package/encoding-nlrpj-Pb.js +99 -0
  13. package/{engine-CgCMdGGd.js → engine-BGaJ9dAk.js} +7 -5
  14. package/{engine-BPFnHT9N.d.ts → engine-vbYInVYF.d.ts} +3 -3
  15. package/{errors-DHwz1Vho.js → errors-LYJZ_c8h.js} +91 -17
  16. package/{group-B4eyJKTA.js → group-B742gg4T.js} +1490 -7278
  17. package/{sqlite-capability-CrCej3Po.js → http-capability-CSTkw1Yt.js} +255 -5
  18. package/http.d.ts +59 -0
  19. package/http.js +465 -0
  20. package/index.d.ts +23 -17
  21. package/index.js +19 -12
  22. package/manifest-BscyH_rW.d.ts +70 -0
  23. package/{manifest-DKe2Je6Z.js → manifest-DjsxDSuB.js} +11 -90
  24. package/message-layer.d.ts +12 -0
  25. package/message-layer.js +4 -0
  26. package/notify.d.ts +2 -1
  27. package/notify.js +2 -1
  28. package/{objects-MeXIDDFo.d.ts → objects-DJ3QtCCs.d.ts} +23 -8
  29. package/objects-Db7IB5vQ.js +91 -0
  30. package/operation-promises-EgZXG5N_.js +23 -0
  31. package/package.json +9 -1
  32. package/readers-BFPuosPk.d.ts +25 -0
  33. package/{readers-DyjxJEkL.js → readers-CjJHKHvH.js} +6 -3
  34. package/request-pump-binary-DdY3X-yl.js +2246 -0
  35. package/{router-DHPJNvbt.js → router--71qvxtY.js} +8 -6
  36. package/{router-DpDpAJjz.d.ts → router-Zhrw5l__.d.ts} +6 -5
  37. package/session.d.ts +2 -1
  38. package/session.js +58 -24
  39. package/setup.d.ts +2 -1
  40. package/setup.js +8 -4
  41. package/{sha256-0jiTgVJu.js → sha256-B_kyYw3Z.js} +1 -0
  42. package/sqlite.d.ts +3 -4
  43. package/sqlite.js +6 -5
  44. package/{store-capability-CDoVafZL.js → store-capability-OZp4hXmj.js} +10 -7
  45. package/{store-DrYjcoru.js → store-hJrRULMx.js} +3 -2
  46. package/store.d.ts +3 -2
  47. package/store.js +3 -2
  48. package/{user-capability-Cv0oJhhv.js → user-capability-BK4Asg7D.js} +8 -5
  49. package/wasm.d.ts +42 -22
  50. package/wasm.js +330 -46
  51. package/core-eU5KaYkz.d.ts +0 -23
  52. package/readers-Oh4tO2dK.d.ts +0 -57
  53. package/sqlite-capability-C7-SYdD7.d.ts +0 -87
  54. package/user-capability-CLkDsrCX.d.ts +0 -40
package/wasm.js CHANGED
@@ -1,19 +1,33 @@
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";
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";
8
14
  //#region src/wasm/wire.ts
9
15
  const raw = Symbol("raw JSON");
10
16
  const sep = Symbol("separator");
11
17
  /** Text already in JSON, such as a Value Encoding, placed in a frame as is. */
12
18
  var Raw = class {
13
- json;
19
+ source;
20
+ value;
14
21
  [raw] = true;
15
- constructor(json) {
16
- this.json = json;
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;
17
31
  }
18
32
  };
19
33
  var Sep = class {
@@ -53,27 +67,55 @@ const frameJSON = (frame) => {
53
67
  }
54
68
  return out.join("");
55
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
+ };
56
100
  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
101
  /** A member of a JSON object, or undefined. */
60
102
  const field = (j, key) => {
61
- if (!isObject(j)) return;
103
+ if (!isJsonObject(j)) return;
62
104
  for (const [k, v] of j.pairs) if (k === key) return v;
63
105
  };
64
106
  const has = (j, key) => field(j, key) !== void 0;
65
107
  const textOf = (j) => typeof j === "string" ? j : void 0;
66
108
  /** 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;
109
+ const intOf = (j) => isJsonNumber(j) ? Number(j.source) : typeof j === "string" && /^-?\d+$/.test(j) ? Number(j) : void 0;
68
110
  const boolOf = (j) => typeof j === "boolean" ? j : void 0;
69
111
  const listOf = (j) => Array.isArray(j) ? j : [];
70
112
  const textsOf = (j) => listOf(j).map((t) => textOf(t) ?? "");
71
- const entriesOf = (j) => isObject(j) ? j.pairs : [];
113
+ const entriesOf = (j) => isJsonObject(j) ? j.pairs : [];
72
114
  /** Protocol data that holds no Values, as plain JavaScript. */
73
115
  const plain = (j) => {
74
116
  if (j === void 0 || j === null || typeof j !== "object") return j;
75
117
  if (Array.isArray(j)) return j.map(plain);
76
- if (isNumber(j)) return Number(j.source);
118
+ if (isJsonNumber(j)) return Number(j.source);
77
119
  return Object.fromEntries(j.pairs.map(([k, v]) => [k, plain(v)]));
78
120
  };
79
121
  //#endregion
@@ -111,13 +153,23 @@ const checkOwned = (codec, v) => {
111
153
  }
112
154
  };
113
155
  const encode = (codec, v) => {
156
+ requireValue(v);
114
157
  checkOwned(codec, v);
115
- return new Raw(encodeValue(v, (other) => {
158
+ return new Raw(() => encodeValue(v, (other) => {
116
159
  if (other.kind === "pattern") return `{"$pattern":${quoteJSON(other.patternSource())}}`;
117
160
  const f = other.asFunction();
118
161
  const code = f.code;
119
162
  return `{"$function":[${quoteJSON(f.home)},${quoteJSON(other.toString())},${quoteJSON(code.token)}]}`;
120
- }));
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
+ ];
121
173
  };
122
174
  const encodeAll = (codec, vs) => vs.map((v) => encode(codec, v));
123
175
  const guestFunction = (codec, data) => {
@@ -147,13 +199,53 @@ const guestPattern = (data) => {
147
199
  data: null
148
200
  });
149
201
  };
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));
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));
151
243
  //#endregion
152
244
  //#region src/wasm/reactor.ts
153
245
  const EBADF = 8;
154
246
  const ENOSYS = 52;
155
- const encoder = new TextEncoder();
156
- const decoder = new TextDecoder("utf-8", { fatal: true });
247
+ const encoder$1 = new TextEncoder();
248
+ const decoder$1 = new TextDecoder("utf-8", { fatal: true });
157
249
  /**
158
250
  * The WASI imports `talk.wasm` takes. The Core reads no clock, file or
159
251
  * environment of its own: its Clock comes with each Pump. The safe build's
@@ -234,10 +326,14 @@ var Reactor = class {
234
326
  this.#exports = exports;
235
327
  this.#guard(() => exports._initialize());
236
328
  }
237
- /** One frame of JSON in, its reply out. */
329
+ /** One JSON frame, retained for Hosts speaking only JSON. */
238
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) {
239
336
  const e = this.#exports;
240
- const bytes = encoder.encode(json);
241
337
  const pointer = this.#guard(() => e.talk_buffer(bytes.length));
242
338
  if (pointer === 0) throw new FrameRefusedError(bytes.length);
243
339
  return this.#guard(() => {
@@ -245,7 +341,7 @@ var Reactor = class {
245
341
  const packed = BigInt.asUintN(64, e.talk_send(bytes.length));
246
342
  const at = Number(packed >> 32n);
247
343
  const length = Number(packed & 4294967295n);
248
- return decoder.decode(new Uint8Array(e.memory.buffer, at, length));
344
+ return new Uint8Array(e.memory.buffer, at, length).slice().buffer;
249
345
  });
250
346
  }
251
347
  /** The instance's linear memory, in bytes. */
@@ -278,7 +374,6 @@ const scriptError = (error) => {
278
374
  const textMessage = message.kind === "text";
279
375
  return new ScriptError(error.get("code").asText() ?? "", textMessage ? message.asText() : "", map(error.entries().filter(([k]) => k !== "code" && !(k === "message" && textMessage))));
280
376
  };
281
- const sendFailed = (reason) => new ScriptError("send failed", `No answer came: the receiver's Run ended ${reason}`, map([["reason", text(reason)]]));
282
377
  /** A handle for calls addressed to one Script. */
283
378
  var WasmScript = class {
284
379
  group;
@@ -300,6 +395,16 @@ var WasmScript = class {
300
395
  request(m, o) {
301
396
  return this.group.ask({ to: { script: this.name } }, m, o);
302
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
+ }
303
408
  decide(m, o) {
304
409
  return this.group.decision({ to: { script: this.name } }, m, o);
305
410
  }
@@ -363,6 +468,7 @@ var WasmGroup = class {
363
468
  #restored = /* @__PURE__ */ new Map();
364
469
  #restoring = null;
365
470
  #exchanging = 0;
471
+ #combining = false;
366
472
  /** Answers given while their call was starting, sent once the exchange ends. */
367
473
  #deferred = [];
368
474
  #codec;
@@ -378,6 +484,7 @@ var WasmGroup = class {
378
484
  identity: this,
379
485
  object: (kind, id) => objects.get(key(kind, id))?.handle
380
486
  };
487
+ this.#session.bind(binaryValues(this.#codec));
381
488
  if (!restoring) this.#session.exchange("new-group", {
382
489
  group: this.name,
383
490
  name: this.name,
@@ -386,13 +493,16 @@ var WasmGroup = class {
386
493
  });
387
494
  }
388
495
  /** @internal One exchange for this Group, its needs answered here. */
389
- send(m, fields = {}) {
496
+ send(m, fields = {}, receive) {
390
497
  this.#exchanging++;
391
498
  try {
392
499
  return this.#session.exchange(m, {
393
500
  group: this.name,
394
501
  ...fields
395
- }, (need, packet) => this.#need(need, packet), (packet, sent) => this.#observe(packet, sent));
502
+ }, (need, packet) => this.#need(need, packet), (packet, sent) => {
503
+ receive?.(packet);
504
+ this.#observe(packet, sent);
505
+ });
396
506
  } finally {
397
507
  this.#exchanging--;
398
508
  if (!this.#exchanging && this.#deferred.length) {
@@ -407,13 +517,14 @@ var WasmGroup = class {
407
517
  * `reentrant call`, with its refusal record, as the in-process Core does.
408
518
  */
409
519
  worker(m, fields = {}) {
520
+ if (this.#combining) throw new HostError("reentrant call");
410
521
  this.#session.syncKinds();
411
522
  return this.send(m, fields);
412
523
  }
413
524
  #observe(packet, m) {
414
525
  this.#abandon(textsOf(field(packet, "abandoned")));
415
526
  const ok = field(packet, "ok");
416
- if (m === "pump" || m === "reload" || m === "replace-library") this.#abandon(textsOf(field(ok, "abandoned")));
527
+ if (m === "pump" || m === "request-pump" || m === "call-pump" || m === "reload" || m === "replace-library") this.#abandon(textsOf(field(ok, "abandoned")));
417
528
  if (!this.#trace) return;
418
529
  const lines = [...textsOf(field(packet, "trace"))];
419
530
  if (m !== "grants") lines.push(...textsOf(field(ok, "trace")));
@@ -431,7 +542,7 @@ var WasmGroup = class {
431
542
  }
432
543
  #ready() {
433
544
  if (!this.#onReady) return;
434
- if (this.#exchanging) queueMicrotask(this.#onReady);
545
+ if (this.#exchanging || this.#combining) queueMicrotask(this.#onReady);
435
546
  else this.#onReady();
436
547
  }
437
548
  #need(need, _packet) {
@@ -460,6 +571,7 @@ var WasmGroup = class {
460
571
  #callOf(need, grant, pending, charge) {
461
572
  const id = textOf(field(need, "call"));
462
573
  const scope = textOf(field(need, "scope"));
574
+ const delivery = textOf(field(need, "delivery"));
463
575
  return Object.freeze({
464
576
  group: this,
465
577
  id,
@@ -469,6 +581,7 @@ var WasmGroup = class {
469
581
  segmentId: textOf(field(need, "segment")),
470
582
  ...scope ? { scopeName: scope } : {},
471
583
  automatic: boolOf(field(need, "automatic")) ?? false,
584
+ ...delivery ? { delivery } : {},
472
585
  binding: grant.binding,
473
586
  now: parseInstant(textOf(field(need, "now"))),
474
587
  signal: pending.abort.signal,
@@ -583,7 +696,7 @@ var WasmGroup = class {
583
696
  op.start(call, ...args);
584
697
  return;
585
698
  }
586
- op.run(call, ...args).then((v) => call.answer(v)).catch((error) => call.fail(error));
699
+ trackOperation(this, op.run(call, ...args).then((v) => call.answer(v)).catch((error) => call.fail(error)));
587
700
  return;
588
701
  }
589
702
  }
@@ -819,7 +932,8 @@ var WasmGroup = class {
819
932
  if (failure) waiting.reject(failure);
820
933
  else waiting.resolve(value);
821
934
  }
822
- #message(m) {
935
+ /** @internal Message data shared with the Script combined operation. */
936
+ messageFrame(m) {
823
937
  return {
824
938
  name: m.name,
825
939
  args: encodeAll(this.#codec, m.args ?? []),
@@ -840,7 +954,7 @@ var WasmGroup = class {
840
954
  queue(m, fields, message) {
841
955
  const ok = this.send(m, {
842
956
  ...fields,
843
- ...message ? { message: this.#message(message) } : {}
957
+ ...message ? { message: this.messageFrame(message) } : {}
844
958
  });
845
959
  this.#ready();
846
960
  return textOf(field(ok, "delivery")) ?? textOf(field(ok, "broadcast"));
@@ -971,6 +1085,127 @@ var WasmGroup = class {
971
1085
  request(to, m, o) {
972
1086
  return this.ask({ to: this.#target(to) }, m, o);
973
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
+ }
974
1209
  broadcast(m) {
975
1210
  return this.queue("broadcast", {}, m);
976
1211
  }
@@ -994,6 +1229,9 @@ var WasmGroup = class {
994
1229
  fuelSlice: o?.fuelSlice,
995
1230
  fuelCap: o?.fuelCap
996
1231
  });
1232
+ return this.#pumpResult(ok);
1233
+ }
1234
+ #pumpResult(ok) {
997
1235
  this.#restored.clear();
998
1236
  const deadline = textOf(field(ok, "nextDeadline"));
999
1237
  return {
@@ -1140,7 +1378,20 @@ const features = [
1140
1378
  "restore-bindings-v1"
1141
1379
  ];
1142
1380
  /** Features this Host uses when the guest offers them (#1143). */
1143
- const optionalFeatures = ["object-elements-v1"];
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 });
1144
1395
  const failure = (err) => {
1145
1396
  const kind = textOf(field(err, "kind"));
1146
1397
  if (kind === "host error") return new HostError(textOf(field(err, "code")), textOf(field(err, "detail")) || textOf(field(err, "code")));
@@ -1166,15 +1417,26 @@ var Session = class {
1166
1417
  #libraries = /* @__PURE__ */ new Set();
1167
1418
  /** Whether the guest accepts Object Collection declarations. */
1168
1419
  elements;
1169
- constructor(module, diagnostics, registry) {
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) {
1170
1430
  this.registry = registry;
1171
1431
  this.reactor = new Reactor(module, diagnostics);
1172
1432
  const hello = this.exchange("hello", {
1173
1433
  protocol: 1,
1174
- features: [...features, ...optionalFeatures]
1434
+ features: [...features, ...optionalFeatures.filter((f) => binaryCallbacks || f !== callbacksFeature)]
1175
1435
  });
1176
1436
  const offered = new Set(textsOf(field(hello, "features")));
1177
1437
  this.elements = offered.has("object-elements-v1");
1438
+ this.requestPump = offered.has(requestPumpFeature);
1439
+ this.callbacks = binaryCallbacks && offered.has(callbacksFeature);
1178
1440
  const missing = features.filter((f) => !offered.has(f));
1179
1441
  if (missing.length) throw new InstanceLostError(`talk.wasm lacks ${missing.join(", ")}`);
1180
1442
  this.versions = {
@@ -1192,28 +1454,46 @@ var Session = class {
1192
1454
  */
1193
1455
  exchange(m, fields, answer, observe) {
1194
1456
  const ref = ++this.#ref;
1195
- let frame = {
1457
+ const binaryExchange = this.requestPump && binaryMethods.has(m);
1458
+ const first = {
1196
1459
  m,
1197
1460
  ref,
1198
1461
  ...fields
1199
1462
  };
1463
+ let input = binaryExchange ? new Uint8Array(encodeBinaryFrame(frameTree(first), this.#values)) : encoder.encode(frameJSON(first));
1200
1464
  for (;;) {
1201
- const packet = readReply(this.reactor.frame(frameJSON(frame)));
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");
1202
1470
  if (intOf(field(packet, "ref")) !== ref) throw new InstanceLostError(`The reply to ${m} has another ref`);
1203
1471
  observe?.(packet, m);
1204
1472
  const err = field(packet, "err");
1205
1473
  if (err !== void 0) throw failure(err);
1206
- const need = field(packet, "need");
1474
+ if (binaryExchange && !binaryReply && need === void 0) throw new InstanceLostError("The binary exchange ended with a JSON success");
1207
1475
  if (need === void 0) return field(packet, "ok") ?? null;
1208
1476
  if (!answer) throw new InstanceLostError(`${m} asked for an unexpected need`);
1209
- frame = {
1210
- ...answer(need, packet),
1211
- m: `${textOf(field(need, "m"))}-result`,
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`,
1212
1483
  ref,
1213
1484
  group: fields.group
1214
- };
1485
+ }));
1215
1486
  }
1216
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
+ }
1217
1497
  /** The guest's handle for a Capability, declared on first use. */
1218
1498
  define(def) {
1219
1499
  let handle = this.#definitions.get(def);
@@ -1334,6 +1614,7 @@ const compile = async (source) => {
1334
1614
  };
1335
1615
  const hex = (b) => [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
1336
1616
  var WasmCore = class {
1617
+ binaryCallbacks;
1337
1618
  /** The reactor's `hello`: its Core, language, Cost Model, Unicode and save format. */
1338
1619
  versions;
1339
1620
  #module;
@@ -1345,7 +1626,8 @@ var WasmCore = class {
1345
1626
  #libraries;
1346
1627
  #groupCore;
1347
1628
  /** @internal Use createCore. */
1348
- constructor(module, diagnostics) {
1629
+ constructor(module, diagnostics, binaryCallbacks = true) {
1630
+ this.binaryCallbacks = binaryCallbacks;
1349
1631
  this.#module = module;
1350
1632
  this.#diagnostics = diagnostics;
1351
1633
  this.#libraries = this.#session();
@@ -1369,7 +1651,7 @@ var WasmCore = class {
1369
1651
  return handle;
1370
1652
  },
1371
1653
  kinds: this.#kinds
1372
- });
1654
+ }, this.binaryCallbacks);
1373
1655
  }
1374
1656
  defineCapability = defineCapability;
1375
1657
  clockCapability = clockCapability;
@@ -1380,6 +1662,7 @@ var WasmCore = class {
1380
1662
  storeCapability = storeCapability;
1381
1663
  sqliteCapability = sqliteCapability;
1382
1664
  userCapability = userCapability;
1665
+ httpCapability = httpCapability;
1383
1666
  defineObjectKind(k) {
1384
1667
  const kind = defineObjectKind(k);
1385
1668
  const at = this.#kinds.findIndex((known) => known.name === kind.name);
@@ -1413,6 +1696,7 @@ var WasmCore = class {
1413
1696
  declarations: Object.fromEntries(Object.entries(declarations ?? {}).map(([grant, ops]) => [grant, Object.fromEntries(Object.entries(ops).map(([op, d]) => [op, {
1414
1697
  mode: d.mode,
1415
1698
  args: d.args.map((a) => shapeData(a)),
1699
+ ...d.labels?.length ? { labels: [...d.labels] } : {},
1416
1700
  command: d.command
1417
1701
  }]))]))
1418
1702
  };
@@ -1444,10 +1728,10 @@ var WasmCore = class {
1444
1728
  * Compiles `talk.wasm` once and returns a Core over it. The one asynchronous
1445
1729
  * call: `await createCore()` also works with the TS Core's synchronous one.
1446
1730
  */
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}`)));
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);
1448
1732
  //#endregion
1449
1733
  //#region src/wasm/index.ts
1450
1734
  /** Chapter 9's default Limits, which the reactor shares. */
1451
1735
  const defaultLimits = Object.freeze({ ...limitDefaults });
1452
1736
  //#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 };
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 };
@@ -1,23 +0,0 @@
1
- import { A as restore, I as compileLibrary, Ot as defineObjectKind, Qt as defineCapability, k as newGroup } from "./debug-D8Z_u244.js";
2
- import { c as localeCapability, g as timerCapability, h as consoleCapability, m as clockCapability, o as sqliteCapability, p as calendarCapability } from "./sqlite-capability-C7-SYdD7.js";
3
- import { a as storeCapability, n as userCapability } from "./user-capability-CLkDsrCX.js";
4
- //#region src/core.d.ts
5
- type Core = {
6
- calendarCapability: typeof calendarCapability;
7
- clockCapability: typeof clockCapability;
8
- compileLibrary: typeof compileLibrary;
9
- consoleCapability: typeof consoleCapability;
10
- defineCapability: typeof defineCapability;
11
- defineObjectKind: typeof defineObjectKind;
12
- localeCapability: typeof localeCapability;
13
- newGroup: typeof newGroup;
14
- restore: typeof restore;
15
- sqliteCapability: typeof sqliteCapability;
16
- storeCapability: typeof storeCapability;
17
- timerCapability: typeof timerCapability;
18
- userCapability: typeof userCapability;
19
- };
20
- /** Return the process-wide Core, also used by the free-function helpers. */
21
- declare const createCore: () => Core;
22
- //#endregion
23
- export { createCore as n, Core as t };