@northtalk/ts 0.6.0 → 0.8.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 (57) hide show
  1. package/{binary-value-C4ZiXVjv.d.ts → binary-value-B93hEK7l.d.ts} +1 -1
  2. package/{checker-CUhn2XaM.js → checker-Q4w7rLXk.js} +600 -85
  3. package/{core-egHbNmve.d.ts → core-BBPI6EhG.d.ts} +1 -1
  4. package/{debug--Of4MSLw.d.ts → debug-s6QIovKS.d.ts} +142 -10
  5. package/debug.d.ts +1 -1
  6. package/debug.js +1 -1
  7. package/{driver-BIm1mL77.d.ts → driver-D5yrK3Nu.d.ts} +1 -1
  8. package/driver.d.ts +1 -1
  9. package/driver.js +1 -1
  10. package/encoding-B7MCQ4ii.js +338 -0
  11. package/{engine-DbDcopGM.d.ts → engine-Dy-BCoiw.d.ts} +2 -2
  12. package/{engine-CXf5FCwi.js → engine-OL1BveVZ.js} +6 -6
  13. package/{errors-D11zizZg.js → errors-VuwK669R.js} +157 -23
  14. package/{group-BpzTo0k4.js → group-Ccuqwq12.js} +477 -110
  15. package/{http-fetch-DFwVIOQg.js → http-fetch--O27xjSW.js} +2 -2
  16. package/http.d.ts +1 -1
  17. package/http.js +4 -4
  18. package/index.d.ts +6 -6
  19. package/index.js +15 -14
  20. package/{inline-grants-XbX9HL_w.js → inline-grants-DmOdgSoK.js} +4 -5
  21. package/{lean-aCvN6y52.js → lean-BjhQvHyr.js} +13 -8
  22. package/{lean-DiS9rUcn.d.ts → lean-D6DQfbqH.d.ts} +42 -7
  23. package/lean.d.ts +6 -6
  24. package/lean.js +15 -14
  25. package/{manifest-CCfpn0kC.js → manifest-BeViDIoy.js} +4 -3
  26. package/{manifest-mpivREn-.d.ts → manifest-l07K7nW-.d.ts} +4 -2
  27. package/message-layer.d.ts +2 -2
  28. package/message-layer.js +2 -2
  29. package/notify.d.ts +1 -1
  30. package/notify.js +1 -1
  31. package/{objects-DmUc0lha.js → objects-TarIKBL8.js} +1 -1
  32. package/{objects-DYq_YvaQ.d.ts → objects-q0lnCK-4.d.ts} +8 -3
  33. package/{operations-DnCcztkZ.js → operations-BAELnqwf.js} +133 -58
  34. package/package.json +5 -1
  35. package/peer-capability-B8eKbljR.js +151 -0
  36. package/peer.d.ts +180 -0
  37. package/peer.js +559 -0
  38. package/{readers-8WCimMop.d.ts → readers-AeB1bJ--.d.ts} +1 -1
  39. package/{readers-CsvlahLi.js → readers-BG8g59qS.js} +1 -1
  40. package/{request-pump-binary-oqjWFqZA.js → request-pump-binary-87klb6sX.js} +9 -4
  41. package/{router-BZ-aYeXA.js → router-DXmPA-qi.js} +4 -4
  42. package/{router-BQsO8aPV.d.ts → router-DXoJ_2Z4.d.ts} +2 -2
  43. package/session.d.ts +2 -2
  44. package/session.js +64 -16
  45. package/setup.d.ts +3 -2
  46. package/setup.js +14 -16
  47. package/sqlite.d.ts +2 -2
  48. package/sqlite.js +5 -5
  49. package/{store-DHlo6fP5.js → store-DzpyWjt2.js} +2 -2
  50. package/store-capability-CxQJ_Huz.js +187 -0
  51. package/store.d.ts +2 -2
  52. package/store.js +2 -2
  53. package/{user-capability-BcRQyyEw.js → user-capability-ClYd8Vln.js} +3 -4
  54. package/wasm.d.ts +13 -6
  55. package/wasm.js +47 -19
  56. package/encoding-RUuES_e4.js +0 -99
  57. package/store-capability-BrUUAwVS.js +0 -389
package/wasm.js CHANGED
@@ -1,17 +1,18 @@
1
1
 
2
- import { Bt as formatInstant, G as record, Gt as parseInstant, H as quantity, K as requireArgs, L as nothing, N as map, Q as text, R as num, S as functionValue, T as instant, Ut as nowMicros, V as patternValue, W as range, c as Decimal, d as bytes, i as ScriptError, k as list, l as Value, m as civilDate, n as LoadError, o as invalidValue, q as requireValue, r as MailboxFull, s as sendFailed, t as HostError, u as bool, v as dec, z as objectValue } from "./errors-D11zizZg.js";
3
- import { a as rebindObject, n as makeObject, t as defineObjectKind } from "./objects-DmUc0lha.js";
4
- import { _t as defineCapability, ht as LimitReached, pt as limitDefaults, xt as shape } from "./operations-DnCcztkZ.js";
5
- import { c as CallMeter, i as operationData, n as exportManifest, o as shapeData, s as invoke } from "./manifest-CCfpn0kC.js";
2
+ import { D as instant, G as patternValue, H as num, J as range, K as quantity, L as map, N as list, Qt as parseInstant, U as objectValue, V as nothing, X as requireArgs, Xt as nowMicros, Y as record, Z as requireValue, b as dec, c as Decimal, d as bytes, g as civilDate, i as ScriptError, it as text, l as Value, n as LoadError, o as invalidValue, qt as formatInstant, r as MailboxFull, s as sendFailed, t as HostError, u as bool, w as functionValue } from "./errors-VuwK669R.js";
3
+ import { a as rebindObject, n as makeObject, t as defineObjectKind } from "./objects-TarIKBL8.js";
4
+ import { Dt as shape, Et as operationDeclarations, bt as defineCapability, gt as LimitReached, mt as limitDefaults, vt as conforms, wt as explain } from "./operations-BAELnqwf.js";
5
+ import { c as CallMeter, i as operationData, n as exportManifest, o as shapeData, s as invoke } from "./manifest-BeViDIoy.js";
6
6
  import { n as trackOperation } from "./operation-promises-ClA1BTaS.js";
7
7
  import { n as toBase64, t as fromBase64 } from "./base64-CDO-a06R.js";
8
- 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-CsvlahLi.js";
9
- import { i as standardChecks, n as quoteJSON, t as encodeValue } from "./encoding-RUuES_e4.js";
10
- import { a as sqliteCapability, c as talk, i as httpCapability, n as createGroup, o as fromValue, r as handlersOf, s as toValue, t as inlineGrants } from "./inline-grants-XbX9HL_w.js";
11
- import { o as decodeJson, s as encodeJson } from "./http-fetch-DFwVIOQg.js";
12
- import { n as localeCapability, t as userCapability } from "./user-capability-BcRQyyEw.js";
13
- import { a as clockCapability, i as calendarCapability, l as timerCapability, o as consoleCapability, r as storeCapability, t as add } from "./store-capability-BrUUAwVS.js";
14
- 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-oqjWFqZA.js";
8
+ 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-BG8g59qS.js";
9
+ import { a as clockCapability, d as timerCapability, i as calendarCapability, l as isMusicalClock, n as quoteJSON, o as consoleCapability, p as standardChecks, r as MUSICAL_CLOCK, t as encodeValue, u as musicalClockCapability } from "./encoding-B7MCQ4ii.js";
10
+ import { a as peerKind, i as peerCapability } from "./peer-capability-B8eKbljR.js";
11
+ import { a as sqliteCapability, c as talk, i as httpCapability, n as createGroup, o as fromValue, r as handlersOf, s as toValue, t as inlineGrants } from "./inline-grants-DmOdgSoK.js";
12
+ import { o as decodeJson, s as encodeJson } from "./http-fetch--O27xjSW.js";
13
+ import { n as localeCapability, t as userCapability } from "./user-capability-ClYd8Vln.js";
14
+ import { r as storeCapability, t as add } from "./store-capability-CxQJ_Huz.js";
15
+ 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-87klb6sX.js";
15
16
  //#region src/wasm/wire.ts
16
17
  const raw = Symbol("raw JSON");
17
18
  const sep = Symbol("separator");
@@ -375,6 +376,7 @@ const scriptError = (error) => {
375
376
  const textMessage = message.kind === "text";
376
377
  return new ScriptError(error.get("code").asText() ?? "", textMessage ? message.asText() : "", map(error.entries().filter(([k]) => k !== "code" && !(k === "message" && textMessage))));
377
378
  };
379
+ const errorMaps = /* @__PURE__ */ new WeakMap();
378
380
  /** A handle for calls addressed to one Script. */
379
381
  var WasmScript = class {
380
382
  group;
@@ -475,8 +477,14 @@ var WasmGroup = class {
475
477
  /** Answers given while their call was starting, sent once the exchange ends. */
476
478
  #deferred = [];
477
479
  #codec;
480
+ /** The Group's musical clock, granted to every Script as `musical-clock`. */
481
+ #musicalClock;
478
482
  /** @internal Made by WasmCore. */
479
483
  constructor(core, o, restoring) {
484
+ if (o.musicalClock !== void 0) {
485
+ if (!isMusicalClock(o.musicalClock)) throw new HostError("invalid value", "A musical clock comes from musicalClockCapability");
486
+ this.#musicalClock = o.musicalClock.grant("all", void 0);
487
+ }
480
488
  this.#core = core;
481
489
  this.name = o.name;
482
490
  this.#trace = o.trace;
@@ -810,7 +818,7 @@ var WasmGroup = class {
810
818
  return {
811
819
  grants: listOf(field(need, "grants")).map((pair) => {
812
820
  const [script, name] = textsOf(pair);
813
- const grant = o.grants(script, name);
821
+ const grant = name === "musical-clock" ? this.#musicalClock : o.grants(script, name);
814
822
  if (!grant) return null;
815
823
  let scripts = this.#bindings.get(script);
816
824
  if (!scripts) {
@@ -836,7 +844,11 @@ var WasmGroup = class {
836
844
  switch (r.kind) {
837
845
  case "run end": {
838
846
  if (has(j, "result")) r.result = value("result");
839
- if (has(j, "error")) r.error = scriptError(value("error"));
847
+ if (has(j, "error")) {
848
+ const error = value("error");
849
+ errorMaps.set(r, error);
850
+ r.error = scriptError(error);
851
+ }
840
852
  const effect = r.effect;
841
853
  if (effect) {
842
854
  const detail = this.#effectDetails.get(`${effect.segment}/${effect.phase}`);
@@ -901,7 +913,7 @@ var WasmGroup = class {
901
913
  if (r.climbed || !r.delivery) break;
902
914
  if (unhandled.has(r.delivery)) this.#settle(r.delivery, void 0, sendFailed("unhandled"));
903
915
  else if (r.outcome === "completed") this.#settle(r.delivery, r.result ?? nothing);
904
- else this.#settle(r.delivery, void 0, sendFailed(r.outcome));
916
+ else this.#settle(r.delivery, void 0, sendFailed(r.outcome, r.outcome === "errored" ? errorMaps.get(r) : null));
905
917
  break;
906
918
  case "run discarded":
907
919
  if (r.reason !== "rewind") {
@@ -1036,12 +1048,18 @@ var WasmGroup = class {
1036
1048
  }
1037
1049
  load(o) {
1038
1050
  this.#session.syncKinds();
1039
- const grants = o.grants ?? {};
1051
+ const given = o.grants ?? {};
1052
+ if (Object.hasOwn(given, "musical-clock")) throw new HostError("invalid value", `${MUSICAL_CLOCK} is the Group's own Grant name`);
1053
+ const grants = this.#musicalClock ? {
1054
+ ...given,
1055
+ [MUSICAL_CLOCK]: this.#musicalClock
1056
+ } : given;
1040
1057
  const ok = this.worker("load", {
1041
1058
  name: o.name,
1042
1059
  source: o.source,
1043
1060
  grants: this.#grantHandles(grants),
1044
1061
  grantsAsUsed: o.grantsAsUsed,
1062
+ forbidSuspension: o.forbidSuspension || void 0,
1045
1063
  owner: o.owner ? this.#objectRef(o.owner) : void 0,
1046
1064
  objects: o.objects ? Object.fromEntries(Object.entries(o.objects).map(([n, h]) => [n, this.#objectRef(h)])) : void 0,
1047
1065
  limits: {
@@ -1059,11 +1077,12 @@ var WasmGroup = class {
1059
1077
  this.#core.install(this.#session, l);
1060
1078
  this.worker("add-library", { identity: bytesFrame(l.identity) });
1061
1079
  }
1062
- replaceLibrary(l, carry) {
1080
+ replaceLibrary(l, carry, o) {
1063
1081
  this.#core.install(this.#session, l);
1064
1082
  return this.lifecycle("replace-library", {
1065
1083
  identity: bytesFrame(l.identity),
1066
- carry
1084
+ carry,
1085
+ keepMailbox: o?.keepMailbox
1067
1086
  });
1068
1087
  }
1069
1088
  /** @internal Reload and Library replacement end Runs and settle their futures. */
@@ -1280,6 +1299,7 @@ var WasmGroup = class {
1280
1299
  return {
1281
1300
  name: textOf(field(s, "name")),
1282
1301
  ...disabled.length ? { disabledGrants: disabled } : {},
1302
+ ...field(s, "forbidSuspension") === true ? { forbidSuspension: true } : {},
1283
1303
  vars: listOf(field(s, "vars")).map((pair) => {
1284
1304
  const [name, v] = listOf(pair);
1285
1305
  return [textOf(name), decode(this.#codec, v)];
@@ -1537,7 +1557,8 @@ var Session = class {
1537
1557
  })),
1538
1558
  segmentLifecycle: segmentBound(def) || void 0,
1539
1559
  release: def.release ? true : void 0,
1540
- standard: isStandard(def) ? def.name : void 0
1560
+ standard: isStandard(def) && !isMusicalClock(def) ? def.name : void 0,
1561
+ musicalClock: isMusicalClock(def) || void 0
1541
1562
  });
1542
1563
  this.#definitions.set(def, handle);
1543
1564
  return handle;
@@ -1691,6 +1712,13 @@ var WasmCore = class {
1691
1712
  sqliteCapability = sqliteCapability;
1692
1713
  userCapability = userCapability;
1693
1714
  httpCapability = httpCapability;
1715
+ musicalClockCapability = musicalClockCapability;
1716
+ peerCapability = peerCapability;
1717
+ peerKind = this.#known(peerKind);
1718
+ #known(kind) {
1719
+ this.#kinds.push(kind);
1720
+ return kind;
1721
+ }
1694
1722
  defineObjectKind(k) {
1695
1723
  const kind = defineObjectKind(k);
1696
1724
  const at = this.#kinds.findIndex((known) => known.name === kind.name);
@@ -1767,4 +1795,4 @@ const createCore = async (o = {}) => new WasmCore(await compile(o.wasm ?? new UR
1767
1795
  /** Chapter 9's default Limits, which the reactor shares. */
1768
1796
  const defaultLimits = Object.freeze({ ...limitDefaults });
1769
1797
  //#endregion
1770
- export { Decimal, HostError, InstanceLostError, LimitReached, LoadError, MailboxFull, ScriptError, Value, WasmCore, WasmGroup, WasmScript, add, bool, bytes, civilDate, createCore, createGroup, dec, decodeJson, decodeValue, defaultLimits, encodeJson, encodeValue, exportManifest, formatInstant, fromValue, handlersOf, inlineGrants, instant, list, map, nothing, nowMicros, num, parseInstant, quantity, range, readDisplay, record, shape, talk, text, toValue };
1798
+ export { Decimal, HostError, InstanceLostError, LimitReached, LoadError, MailboxFull, ScriptError, Value, WasmCore, WasmGroup, WasmScript, add, bool, bytes, civilDate, conforms, createCore, createGroup, dec, decodeJson, decodeValue, defaultLimits, encodeJson, encodeValue, explain, exportManifest, formatInstant, fromValue, handlersOf, inlineGrants, instant, list, map, nothing, nowMicros, num, operationDeclarations, parseInstant, quantity, range, readDisplay, record, shape, talk, text, toValue };
@@ -1,99 +0,0 @@
1
-
2
- import { o as invalidValue, q as requireValue } from "./errors-D11zizZg.js";
3
- import { n as toBase64 } from "./base64-CDO-a06R.js";
4
- //#region src/standard-capability-checks.ts
5
- const checks = /* @__PURE__ */ new WeakMap();
6
- const registerStandardChecks = (op, rules) => {
7
- checks.set(op, rules);
8
- };
9
- const standardChecks = (op) => checks.get(op);
10
- //#endregion
11
- //#region src/encoding.ts
12
- /** The spec's JSON string form: every U+0000..U+001F uses lowercase \u00xx. */
13
- const quoteJSON = (s) => "\"" + s.replaceAll(/[\u0000-\u001f"\\]/g, (ch) => ch === "\"" ? String.raw`\"` : ch === "\\" ? "\\\\" : String.raw`\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`) + "\"";
14
- const encodeValue = (value, adapter) => {
15
- requireValue(value);
16
- const pending = [value];
17
- const output = [];
18
- while (pending.length) {
19
- const next = pending.pop();
20
- if (typeof next === "string") {
21
- output.push(next);
22
- continue;
23
- }
24
- switch (next.kind) {
25
- case "nothing":
26
- output.push("null");
27
- break;
28
- case "boolean":
29
- output.push(next.asBool() ? "true" : "false");
30
- break;
31
- case "text":
32
- output.push(quoteJSON(next.asText()));
33
- break;
34
- case "number": {
35
- const canonical = next.asDecimal().toString();
36
- output.push(!canonical.includes(".") && BigInt(canonical) > -(2n ** 53n) && BigInt(canonical) < 2n ** 53n ? canonical : `{"$dec":${quoteJSON(canonical)}}`);
37
- break;
38
- }
39
- case "instant":
40
- output.push(`{"$instant":${quoteJSON(next.toString())}}`);
41
- break;
42
- case "civil date":
43
- output.push(`{"$date":${quoteJSON(next.toString())}}`);
44
- break;
45
- case "object": {
46
- const o = next.asObjectRef();
47
- output.push(`{"$object":[${quoteJSON(o.kind)},${quoteJSON(o.id)}]}`);
48
- break;
49
- }
50
- case "bytes":
51
- output.push(`{"$bytes":${quoteJSON(toBase64(next.bytesView()))}}`);
52
- break;
53
- case "quantity": {
54
- const q = next.asQuantity();
55
- output.push(`{"$quantity":[${quoteJSON(q.number.toString())},${quoteJSON(q.unit)}]}`);
56
- break;
57
- }
58
- case "range": {
59
- const { from, to } = next.asRange();
60
- output.push("{\"$range\":[");
61
- pending.push("]}", to, ",", from);
62
- break;
63
- }
64
- case "list":
65
- output.push("[");
66
- pending.push("]");
67
- for (let i = next.length; i >= 1; i--) {
68
- if (i < next.length) pending.push(",");
69
- pending.push(next.index(i));
70
- }
71
- break;
72
- case "map": {
73
- const entries = next.entries();
74
- const tagged = entries.some(([k]) => k.startsWith("$"));
75
- output.push(tagged ? "{\"$map\":[" : "{");
76
- pending.push(tagged ? "]}" : "}");
77
- for (let i = entries.length - 1; i >= 0; i--) {
78
- const [k, v] = entries[i];
79
- if (i < entries.length - 1) pending.push(",");
80
- if (tagged) pending.push("]", v, `[${quoteJSON(k)},`);
81
- else pending.push(v, `${quoteJSON(k)}:`);
82
- }
83
- break;
84
- }
85
- case "function":
86
- case "pattern":
87
- if (adapter) {
88
- output.push(adapter(next));
89
- break;
90
- }
91
- invalidValue(`The Value Encoding of a ${next.kind} isn't implemented yet`);
92
- break;
93
- default: invalidValue(`The Value Encoding of a ${next.kind} isn't implemented yet`);
94
- }
95
- }
96
- return output.join("");
97
- };
98
- //#endregion
99
- export { standardChecks as i, quoteJSON as n, registerStandardChecks as r, encodeValue as t };
@@ -1,389 +0,0 @@
1
-
2
- import { L as nothing, N as map, Q as text, T as instant, i as ScriptError, t as HostError, u as bool } from "./errors-D11zizZg.js";
3
- import { St as validComputedMessageName, dt as errorMessages, i as arithmetic, n as ScriptError$1, vt as defineValueCapability, xt as shape } from "./operations-DnCcztkZ.js";
4
- import { r as registerStandardChecks } from "./encoding-RUuES_e4.js";
5
- //#region src/standard-capabilities.ts
6
- const costOf = (costs, name) => {
7
- const cost = costs && Object.hasOwn(costs, name) ? costs[name] : void 0;
8
- if (!cost || !Number.isSafeInteger(cost.fuel) || cost.fuel < 0 || cost.alloc !== void 0 && (!Number.isSafeInteger(cost.alloc) || cost.alloc < 0)) throw new HostError("invalid value", `Invalid or missing cost for ${name}`);
9
- return Object.freeze({
10
- fuel: cost.fuel,
11
- ...cost.alloc === void 0 ? {} : { alloc: cost.alloc }
12
- });
13
- };
14
- const fixed = (capability) => {
15
- for (const op of capability.operations.values()) {
16
- Object.freeze(op.args);
17
- Object.freeze(op.errors);
18
- Object.freeze(op);
19
- }
20
- return capability;
21
- };
22
- const instantShape = Object.freeze({
23
- k: "kind",
24
- kind: "instant"
25
- });
26
- const textShape$1 = Object.freeze({
27
- k: "kind",
28
- kind: "text"
29
- });
30
- const valueShape = Object.freeze({ k: "value" });
31
- const dataListShape = Object.freeze({
32
- k: "list",
33
- of: Object.freeze({ k: "any" })
34
- });
35
- /** The Pump's Clock reading; there is no Host clock implementation. */
36
- const clockCapability = (costs) => fixed(defineValueCapability("clock", { now: {
37
- mode: "immediate",
38
- args: [],
39
- result: instantShape,
40
- errors: [],
41
- cost: costOf(costs, "now"),
42
- do: (call) => instant(call.now)
43
- } }));
44
- /** The Host owns durable timers, scoped by Script and name. */
45
- const timerCapability = (impl, costs) => {
46
- if (!impl || typeof impl.schedule !== "function" || typeof impl.cancel !== "function") throw new HostError("invalid value", "Timer needs Schedule and Cancel");
47
- return fixed(defineValueCapability("timer", {
48
- schedule: {
49
- mode: "fire-and-forget",
50
- args: [
51
- textShape$1,
52
- instantShape,
53
- textShape$1,
54
- dataListShape
55
- ],
56
- errors: [],
57
- cost: costOf(costs, "schedule"),
58
- fire: (call, name, at, message, args) => impl.schedule(call, name.asText(), at, message.asText(), args)
59
- },
60
- cancel: {
61
- mode: "fire-and-forget",
62
- args: [textShape$1],
63
- errors: [],
64
- cost: costOf(costs, "cancel"),
65
- fire: (call, name) => impl.cancel(call, name.asText())
66
- }
67
- }));
68
- };
69
- /** The Host shows Values in text form and answers read with a line of text. */
70
- const consoleCapability = (impl, costs) => {
71
- if (!impl || typeof impl.write !== "function" || typeof impl.read !== "function") throw new HostError("invalid value", "Console needs Write and Read");
72
- return fixed(defineValueCapability("console", {
73
- write: {
74
- mode: "fire-and-forget",
75
- args: [valueShape],
76
- errors: [],
77
- cost: costOf(costs, "write"),
78
- fire: (call, value) => impl.write(call, value)
79
- },
80
- read: {
81
- mode: "suspending",
82
- args: [],
83
- result: textShape$1,
84
- errors: [],
85
- maxPendingMs: 2147483647,
86
- cost: costOf(costs, "read"),
87
- start: (call) => impl.read(call)
88
- }
89
- }));
90
- };
91
- const civilShape = Object.freeze({
92
- k: "kind",
93
- kind: "civil date"
94
- });
95
- const optionalTextShape = Object.freeze({
96
- k: "optional",
97
- of: textShape$1
98
- });
99
- const secondsShape = Object.freeze({
100
- k: "quantity",
101
- unit: "s"
102
- });
103
- const disambiguations = /* @__PURE__ */ new Set([
104
- "compatible",
105
- "earlier",
106
- "later",
107
- "reject"
108
- ]);
109
- const zoneText = (value) => value?.asText();
110
- const calendarError = (code, data) => data.get("zone").kind === "text" && (code === "unknown zone" || code === "ambiguous time" && data.get("civil").kind === "civil date");
111
- const checkToInstant = (args) => {
112
- const civil = args[0];
113
- const disambiguation = zoneText(args[1]);
114
- const bad = !("hour" in civil.asCivilDate()) ? civil : args.length === 3 && disambiguation !== void 0 && !disambiguations.has(disambiguation) ? args[1] : void 0;
115
- if (bad) throw new ScriptError$1("out of domain", [["function", text("toInstant")], ["value", bad]], true);
116
- };
117
- /** The Host owns zone data; the Grant binding supplies its default zone. */
118
- const calendarCapability = (impl, costs) => {
119
- for (const name of [
120
- "today",
121
- "now",
122
- "toCivil",
123
- "toInstant",
124
- "offset",
125
- "zone"
126
- ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Calendar needs ${name}`);
127
- const unknownZone = [{
128
- code: "unknown zone",
129
- fields: { zone: textShape$1 }
130
- }];
131
- const operations = {
132
- today: {
133
- mode: "immediate",
134
- args: [optionalTextShape],
135
- result: civilShape,
136
- errors: unknownZone,
137
- cost: costOf(costs, "today"),
138
- do: (call, zone) => impl.today(call, zoneText(zone))
139
- },
140
- now: {
141
- mode: "immediate",
142
- args: [optionalTextShape],
143
- result: civilShape,
144
- errors: unknownZone,
145
- cost: costOf(costs, "now"),
146
- do: (call, zone) => impl.now(call, zoneText(zone))
147
- },
148
- toCivil: {
149
- mode: "immediate",
150
- args: [instantShape, optionalTextShape],
151
- result: civilShape,
152
- errors: unknownZone,
153
- cost: costOf(costs, "toCivil"),
154
- do: (call, value, zone) => impl.toCivil(call, value, zoneText(zone))
155
- },
156
- toInstant: {
157
- mode: "immediate",
158
- args: [
159
- civilShape,
160
- optionalTextShape,
161
- optionalTextShape
162
- ],
163
- result: instantShape,
164
- errors: [...unknownZone, {
165
- code: "ambiguous time",
166
- fields: {
167
- civil: civilShape,
168
- zone: textShape$1
169
- }
170
- }],
171
- cost: costOf(costs, "toInstant"),
172
- do: (call, ...args) => {
173
- const second = zoneText(args[1]);
174
- const isZone = args.length === 2 && second !== void 0 && !disambiguations.has(second);
175
- return impl.toInstant(call, args[0], isZone ? "compatible" : second ?? "compatible", isZone ? second : zoneText(args[2]));
176
- }
177
- },
178
- offset: {
179
- mode: "immediate",
180
- args: [instantShape, optionalTextShape],
181
- result: secondsShape,
182
- errors: unknownZone,
183
- cost: costOf(costs, "offset"),
184
- do: (call, value, zone) => impl.offset(call, value, zoneText(zone))
185
- },
186
- zone: {
187
- mode: "immediate",
188
- args: [optionalTextShape],
189
- result: textShape$1,
190
- errors: unknownZone,
191
- cost: costOf(costs, "zone"),
192
- do: (call, zone) => impl.zone(call, zoneText(zone))
193
- }
194
- };
195
- for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
196
- error: calendarError,
197
- ...name === "toInstant" ? { arguments: checkToInstant } : {},
198
- ...[
199
- "today",
200
- "now",
201
- "toCivil"
202
- ].includes(name) ? { result: (value) => !("hour" in value.asCivilDate()) === (name === "today") } : {}
203
- });
204
- return fixed(defineValueCapability("calendar", operations));
205
- };
206
- //#endregion
207
- //#region src/store-capability.ts
208
- /** A Core-raised error as the Host sees it, with its catalogue message. */
209
- const hostScriptError = (code, fields) => {
210
- const message = (errorMessages[code] ?? code).replaceAll(/{(\w+)}/g, (_, name) => {
211
- const field = fields.find(([k]) => k === name);
212
- return field ? field[1].toString() : `{${name}}`;
213
- });
214
- return new ScriptError(code, message, map(fields.map(([k, v]) => [k, v])));
215
- };
216
- /** The `+` rules outside any Run, uncharged (chapter 9, Adding). */
217
- const add = (a, b) => {
218
- try {
219
- return arithmetic("add", a, b);
220
- } catch (error) {
221
- throw error instanceof ScriptError$1 ? hostScriptError(error.code, error.fields) : error;
222
- }
223
- };
224
- const textShape = shape.text;
225
- const keyShape = textShape;
226
- const amountShape = shape.oneOf(shape.number, {
227
- k: "kind",
228
- kind: "quantity"
229
- });
230
- const OPERATIONS = [
231
- "get",
232
- "set",
233
- "delete",
234
- "keys",
235
- "increment",
236
- "swap",
237
- "watch",
238
- "unwatch"
239
- ];
240
- const isText = (data, field) => data.get(field).kind === "text";
241
- const errorFields = {
242
- "can't store": (data) => isText(data, "kind"),
243
- "store full": (data) => [
244
- "size",
245
- "keys",
246
- "value"
247
- ].includes(data.get("limit").asText() ?? ""),
248
- "store busy": (data) => isText(data, "key"),
249
- "watch limit": (data) => [
250
- "watches",
251
- "size",
252
- "pending"
253
- ].includes(data.get("limit").asText() ?? ""),
254
- "wrong kind": (data) => isText(data, "expected") && isText(data, "got") && data.entries().some(([k]) => k === "value"),
255
- "incompatible units": (data) => isText(data, "left") && isText(data, "right"),
256
- overflow: (data) => isText(data, "operator")
257
- };
258
- const checkKey = (args) => {
259
- if (args[0].asText() === "") throw new ScriptError$1("invalid key", [], true);
260
- };
261
- const effectiveMessage = (args) => args[2]?.asText() ?? "storeChanged";
262
- const checkUnwatch = (args) => {
263
- if (args[0].asText() === "") throw new ScriptError$1("invalid watch", [["field", text("name")]], true);
264
- };
265
- const checkWatch = (args) => {
266
- checkUnwatch(args);
267
- const message = effectiveMessage(args);
268
- if (message.includes(":") || !validComputedMessageName(message, 1)) throw new ScriptError$1("invalid watch", [["field", text("message")]], true);
269
- };
270
- const argumentChecks = {
271
- watch: checkWatch,
272
- unwatch: checkUnwatch
273
- };
274
- const errors = (...codes) => codes.map((code) => ({ code }));
275
- const writes = [
276
- "can't store",
277
- "store full",
278
- "store busy"
279
- ];
280
- const key = (args) => args[0].asText();
281
- /** The Store is the Host's; the Grant binding names it, and `impl` coordinates every binding. */
282
- const storeCapability = (impl, costs) => {
283
- for (const name of [
284
- ...OPERATIONS,
285
- "begin",
286
- "commit",
287
- "rollback",
288
- "release"
289
- ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Store needs ${name}`);
290
- const operations = {
291
- watch: {
292
- mode: "immediate",
293
- args: [
294
- textShape,
295
- textShape,
296
- shape.optional(textShape)
297
- ],
298
- result: shape.nothing,
299
- errors: errors("watch limit"),
300
- cost: costOf(costs, "watch"),
301
- do: (call, ...args) => {
302
- impl.watch(call, key(args), args[1].asText(), effectiveMessage(args));
303
- return nothing;
304
- }
305
- },
306
- unwatch: {
307
- mode: "immediate",
308
- args: [textShape],
309
- result: shape.nothing,
310
- errors: [],
311
- cost: costOf(costs, "unwatch"),
312
- do: (call, ...args) => {
313
- impl.unwatch(call, key(args));
314
- return nothing;
315
- }
316
- },
317
- get: {
318
- mode: "immediate",
319
- args: [keyShape, shape.optional(shape.any)],
320
- result: shape.any,
321
- errors: [],
322
- cost: costOf(costs, "get"),
323
- do: (call, ...args) => impl.get(call, key(args), args[1])
324
- },
325
- set: {
326
- mode: "immediate",
327
- args: [keyShape, shape.any],
328
- result: shape.nothing,
329
- errors: errors(...writes),
330
- cost: costOf(costs, "set"),
331
- segmentBound: true,
332
- do: (call, ...args) => {
333
- impl.set(call, key(args), args[1]);
334
- return nothing;
335
- }
336
- },
337
- delete: {
338
- mode: "immediate",
339
- args: [keyShape],
340
- result: shape.nothing,
341
- errors: errors("store busy"),
342
- cost: costOf(costs, "delete"),
343
- segmentBound: true,
344
- do: (call, ...args) => {
345
- impl.delete(call, key(args));
346
- return nothing;
347
- }
348
- },
349
- keys: {
350
- mode: "immediate",
351
- args: [shape.optional(textShape)],
352
- result: shape.listOf(textShape),
353
- errors: [],
354
- cost: costOf(costs, "keys"),
355
- do: (call, prefix) => impl.keys(call, prefix?.asText())
356
- },
357
- increment: {
358
- mode: "immediate",
359
- args: [keyShape, shape.optional(amountShape)],
360
- result: amountShape,
361
- errors: errors("wrong kind", "incompatible units", "overflow", "store full", "store busy"),
362
- cost: costOf(costs, "increment"),
363
- segmentBound: true,
364
- do: (call, ...args) => impl.increment(call, key(args), args[1])
365
- },
366
- swap: {
367
- mode: "immediate",
368
- args: [
369
- keyShape,
370
- shape.any,
371
- shape.any
372
- ],
373
- result: shape.bool,
374
- errors: errors(...writes),
375
- cost: costOf(costs, "swap"),
376
- segmentBound: true,
377
- do: (call, ...args) => bool(impl.swap(call, key(args), args[1], args[2]))
378
- }
379
- };
380
- const coordinator = impl;
381
- const capability = defineValueCapability("store", operations, { coordinator: () => coordinator }, (context) => impl.release(context));
382
- for (const [name, op] of capability.operations) registerStandardChecks(op, {
383
- error: (code, data) => Boolean(op.errors?.some((e) => e.code === code) && errorFields[code]?.(data)),
384
- ...name === "keys" ? {} : { arguments: argumentChecks[name] ?? checkKey }
385
- });
386
- return fixed(capability);
387
- };
388
- //#endregion
389
- export { clockCapability as a, fixed as c, calendarCapability as i, timerCapability as l, hostScriptError as n, consoleCapability as o, storeCapability as r, costOf as s, add as t };