@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
@@ -1,5 +1,5 @@
1
1
 
2
- import { $ as textStorage, $t as lower, A as listValues, At as US_PER_DAY, B as ownedMapPairs, Ct as multiply, D as isDecimal, Dt as subtract, E as instantOf, Et as roundRatio, H as quantity, Ht as isoWeek, I as mapWithEntry, It as civilOfDays, J as sliceText, Jt as assertScalarText, Kt as parseInstantText, L as nothing, Lt as civilOfUs, M as literalDigits, Mt as addMonths, N as map, Nt as checkInstant, Ot as withinLimits, Pt as civilDays, Q as text, Qt as isWhiteSpace, R as num, Rt as civilUs, St as mod, T as instant, Tt as powerInteger, U as quantityOf, V as patternValue, W as range, Wt as parseCivil, X as smallNumber, Xt as charactersAt, Y as smallInteger, Yt as characterBoundaries, Zt as generalCategory, _ as concatText, _t as div, at as parseUnit, b as displayText, bt as integerOf, ct as toBase, d as bytes, dt as ArithmeticError, en as normalizeNFC, et as trimWhiteSpace, f as bytesOf, ft as add, g as compareBytes, gt as digitsOf, h as civilOf, ht as digitCount$1, it as ownUnit, j as listWithItem, jt as US_PER_SECOND, k as list, kt as DateRangeError, l as Value, ln as unitKinds, lt as unitEntry, mt as decOf, nn as simpleFold, nt as combine, o as invalidValue, ot as powerOf, p as canonicalNumber, pt as compareDec, qt as weekday, rn as upper, rt as fromBase, sn as grammar, st as sameDimension, t as HostError, tn as scalarCount, tt as UnitError, u as bool, ut as unitText, v as dec, vt as divide, wt as negate, x as extendList, xt as isInteger, y as decimalParts, yt as formatDec, zt as dayOfYear } from "./errors-D11zizZg.js";
2
+ import { $ as smallCoefficient, $t as parseInstantText, At as multiply, B as mapWithEntry, Bt as checkInstant, C as extendList, Ct as digitsOf, D as instant, Dt as integerOf, Et as formatDec, F as listWithItem, Ft as withinLimits, G as patternValue, Gt as civilUs, H as num, I as literalDigits, It as DateRangeError, J as range, K as quantity, Kt as dayOfYear, L as map, Lt as US_PER_DAY, M as knownSize, Mt as powerInteger, N as list, Nt as roundRatio, O as instantOf, Ot as isInteger, P as listValues, Pt as subtract, Q as sliceText, Rt as US_PER_SECOND, S as displayText, St as digitCount$1, Tt as divide, Ut as civilOfDays, V as nothing, Vt as civilDays, W as ownedMapPairs, Wt as civilOfUs, Yt as isoWeek, Zt as parseCivil, _ as civilOf, _n as unitKinds, _t as unitText, an as isWhiteSpace, at as textStorage, b as dec, bt as compareDec, cn as scalarCount, ct as combine, d as bytes, dn as utf8Length, dt as ownUnit, en as weekday, et as smallDecimalNumber, f as bytesOf, ft as parseUnit, gt as unitEntry, h as canonicalNumber, hn as grammar, ht as toBase, in as generalCategory, it as text, j as knownContents, jt as negate, k as isDecimal, kt as mod, l as Value, ln as simpleFold, lt as fromBase, m as cacheSize, mt as sameDimension, nn as characterBoundaries, nt as smallInteger, o as invalidValue, on as lower, ot as trimWhiteSpace, p as cacheContents, pt as powerOf, q as quantityOf, rn as charactersAt, sn as normalizeNFC, st as UnitError, t as HostError, tn as assertScalarText, tt as smallExponent, u as bool, un as upper, ut as musicalKind, v as compareBytes, vt as ArithmeticError, wt as div, x as decimalParts, xt as decOf, y as concatText, yt as add, zt as addMonths } from "./errors-VuwK669R.js";
3
3
  //#region src/tasks.ts
4
4
  const runTask = (root) => {
5
5
  const stack = [root];
@@ -625,6 +625,20 @@ const wrapperKeys = [
625
625
  "map"
626
626
  ];
627
627
  const scalarsOf = (s) => [...s].length;
628
+ const decodedShapes = /* @__PURE__ */ new WeakMap();
629
+ /**
630
+ * `decodeShape`, kept per Shape data value: values are immutable, and a
631
+ * Constant's Shape data is decoded once per load rather than per test.
632
+ * The scanned count is kept too, so the Fuel charged is unchanged.
633
+ */
634
+ const decodeShapeCached = (data) => {
635
+ let decoded = decodedShapes.get(data);
636
+ if (!decoded) {
637
+ decoded = decodeShape(data);
638
+ decodedShapes.set(data, decoded);
639
+ }
640
+ return decoded;
641
+ };
628
642
  /** Reads Shape data into a Shape, or gives the first definition error. */
629
643
  const decodeShape = (data) => {
630
644
  let scanned = 0;
@@ -821,22 +835,21 @@ const shapeDiagnostics = (v, s, first, scanned) => {
821
835
  let halted = false;
822
836
  const deepInfo = /* @__PURE__ */ new Map();
823
837
  const infoOf = (rootValue) => {
824
- const pending = [rootValue];
825
- const order = [];
826
- const seen = /* @__PURE__ */ new Set();
838
+ const pending = [{ v: rootValue }];
827
839
  while (pending.length) {
828
- const next = pending.pop();
829
- if (deepInfo.has(next) || seen.has(next)) continue;
830
- seen.add(next);
831
- order.push(next);
832
- if (next.kind === "list") for (let i = 1; i <= next.length; i++) pending.push(next.index(i));
833
- else if (next.kind === "map") for (const [, value] of next.entries()) pending.push(value);
834
- }
835
- for (let i = order.length - 1; i >= 0; i--) {
836
- const value = order[i];
840
+ const { children, v: value } = pending.pop();
841
+ if (deepInfo.has(value)) continue;
842
+ if (!children) {
843
+ const parts = value.kind === "list" ? Array.from({ length: value.length }, (_, j) => value.index(j + 1)) : value.kind === "map" ? value.entries().map(([, item]) => item) : [];
844
+ pending.push({
845
+ children: parts,
846
+ v: value
847
+ });
848
+ for (let i = parts.length - 1; i >= 0; i--) pending.push({ v: parts[i] });
849
+ continue;
850
+ }
837
851
  let clean = value.kind !== "function";
838
852
  let nodes = 1;
839
- const children = value.kind === "list" ? Array.from({ length: value.length }, (_, j) => value.index(j + 1)) : value.kind === "map" ? value.entries().map(([, item]) => item) : [];
840
853
  for (const child of children) {
841
854
  const info = deepInfo.get(child);
842
855
  clean = clean && info.clean;
@@ -1152,9 +1165,9 @@ const checkMetering = (op) => {
1152
1165
  * Define a Capability whose Host functions take and return Values. The
1153
1166
  * standard Capabilities and replay Stubs use this form.
1154
1167
  */
1155
- const defineValueCapability = (name, ops, lifecycle, release) => {
1168
+ const defineValueCapability = (name, ops, lifecycle, release, reserved) => {
1156
1169
  if (release !== void 0 && typeof release !== "function") invalidValue("A release hook must be a function");
1157
- for (const op of Object.keys(ops)) if (refusedNames.has(op)) throw new HostError("invalid value", `${op} can't name an Operation`);
1170
+ for (const op of Object.keys(ops)) if (refusedNames.has(op) && !(reserved && op === "wait")) throw new HostError("invalid value", `${op} can't name an Operation`);
1158
1171
  const coordinated = !!lifecycle && typeof lifecycle === "object" && "coordinator" in lifecycle ? lifecycle : void 0;
1159
1172
  if (coordinated && typeof coordinated.coordinator !== "function") invalidValue("A coordinator mapping must be a function");
1160
1173
  if (lifecycle !== void 0 && !coordinated && !hasHooks(lifecycle)) invalidValue("A participant requires synchronous begin, commit and rollback hooks");
@@ -1163,7 +1176,7 @@ const defineValueCapability = (name, ops, lifecycle, release) => {
1163
1176
  const scopeEffects = /* @__PURE__ */ new Map();
1164
1177
  for (const [opName, op] of Object.entries(ops)) {
1165
1178
  if (op.command !== void 0 && typeof op.command !== "boolean") invalidValue("command must be Boolean");
1166
- if (op.command && RESERVED.has(opName)) invalidValue(`${opName} is a Reserved Word, so it can't be a command`);
1179
+ if (op.command && RESERVED.has(opName)) invalidValue(`\`${opName}\` is a Reserved Word, so it can't name a command`);
1167
1180
  if (op.labels !== void 0) {
1168
1181
  if (!Array.isArray(op.labels) || [...op.labels].some((label) => typeof label !== "string" || !validArgumentLabel(label))) invalidValue("labels must be a list of Argument Label words");
1169
1182
  if (op.labels.length && op.labels.length !== (op.args?.length ?? 0) - 1) invalidValue("labels must have one entry per argument after the first");
@@ -1316,6 +1329,26 @@ const defineTyped = (name, ops, lifecycle, release) => defineValueCapability(nam
1316
1329
  function defineCapability(...input) {
1317
1330
  return input.length === 0 ? defineTyped : defineTyped(...input);
1318
1331
  }
1332
+ /**
1333
+ * The Operation declarations a Library's Capability calls are checked
1334
+ * against, for `compileLibrary`'s `declarations`. Takes CapabilityDefs, keyed
1335
+ * by their names, or a map from the name each is granted under.
1336
+ */
1337
+ const operationDeclarations = (capabilities) => {
1338
+ const entries = typeof capabilities.get === "function" ? capabilities : [...capabilities].map((c) => [c.name, c]);
1339
+ const declarations = Object.create(null);
1340
+ for (const [name, capability] of entries) declarations[name] = Object.fromEntries([...capability.operations].map(([operation, op]) => [operation, {
1341
+ args: op.args ?? [],
1342
+ mode: op.mode,
1343
+ ...op.labels?.length ? { labels: op.labels } : {},
1344
+ ...op.command ? { command: true } : {}
1345
+ }]));
1346
+ return declarations;
1347
+ };
1348
+ /** True exactly when `v` fits `s`, with a Capability argument's acceptance (ADR 0176). */
1349
+ const conforms = (v, s) => shapeDiagnostics(v, s, true, 0).diags.length === 0;
1350
+ /** The `explain` Built-in's report for `v` against `s` (ADR 0176). */
1351
+ const explain = (v, s) => listValues(shapeDiagnostics(v, s, false, 0).diags.map(diagnosticRecord));
1319
1352
  //#endregion
1320
1353
  //#region src/generated/machine.ts
1321
1354
  const instructions = [
@@ -2603,10 +2636,13 @@ const errorMessages = {
2603
2636
  "not read-only": "A query must not change the database",
2604
2637
  "too many rows": "The statement gave more than {max} rows",
2605
2638
  "unrepresentable": "The value in {column} can't be represented",
2639
+ "no musical time": "This Host keeps no musical time",
2606
2640
  "user busy": "Another prompt is waiting for an answer",
2607
2641
  "invalid serve": "A Serve Registration's {field} isn't valid",
2608
2642
  "address in use": "That address is already in use",
2609
2643
  "bad address": "That address isn't allowed",
2644
+ "name in use": "That name is already exposed",
2645
+ "not exposed": "No Script is exposed under that name",
2610
2646
  "invalid response": "The response's {field} isn't valid",
2611
2647
  "already responded": "That HTTP request has already been answered",
2612
2648
  "exchange closed": "The client has gone",
@@ -5876,9 +5912,8 @@ const sizes = new Map(Object.entries(costModel.sizes));
5876
5912
  const { constant: CONSTANT, size: SIZE, contents: CONTENTS, characters: CHARACTERS, scalars: SCALARS, utf8: UTF8, bytes: BYTES, items: ITEMS, entries: ENTRIES, digits: DIGITS, scanned: SCANNED, steps: STEPS, program: PROGRAM, frames: FRAMES, count: COUNT, declared: DECLARED } = costMeasure;
5877
5913
  const { none: NONE, input: INPUT, result: RESULT, v: V, x1: X1 } = costSubject;
5878
5914
  const noCounts = {};
5879
- const encoder = new TextEncoder();
5880
- const known = /* @__PURE__ */ new WeakMap();
5881
- const knownContents = /* @__PURE__ */ new WeakMap();
5915
+ /** A map entry's contents besides its value: 16 plus its key's UTF-8 bytes. */
5916
+ const keySize = (key) => 16 + utf8Length(key);
5882
5917
  /** The measures of one value that aren't sizes. */
5883
5918
  const measureOf = (measure, v) => {
5884
5919
  if (!v) return 0;
@@ -5942,18 +5977,19 @@ const countOf = (measure, counts) => {
5942
5977
  const contentsOf = (v) => {
5943
5978
  switch (v.kind) {
5944
5979
  case "list": {
5945
- const cached = knownContents.get(v);
5946
- if (cached !== void 0) return cached;
5980
+ const cached = knownContents(v);
5981
+ if (cached >= 0) return cached;
5947
5982
  let total = 0;
5948
5983
  for (let i = 1; i <= v.length; i++) total += sizeOf(v.index(i));
5949
- knownContents.set(v, total);
5984
+ cacheContents(v, total);
5950
5985
  return total;
5951
5986
  }
5952
5987
  case "map": {
5953
- const cached = knownContents.get(v);
5954
- if (cached !== void 0) return cached;
5955
- const total = ownedMapPairs(v).reduce((sum, [key, value]) => sum + 16 + encoder.encode(key).length + sizeOf(value), 0);
5956
- knownContents.set(v, total);
5988
+ const cached = knownContents(v);
5989
+ if (cached >= 0) return cached;
5990
+ let total = 0;
5991
+ for (const [key, value] of ownedMapPairs(v)) total += keySize(key) + sizeOf(value);
5992
+ cacheContents(v, total);
5957
5993
  return total;
5958
5994
  }
5959
5995
  case "range": {
@@ -5967,39 +6003,39 @@ const contentsOf = (v) => {
5967
6003
  /** Seed a List's contents after growth, without walking its retained items. */
5968
6004
  const cacheListExtension = (result, current, part, all) => {
5969
6005
  const contents = contentsOf(current) + (all ? contentsOf(part) : sizeOf(part));
5970
- knownContents.set(result, contents);
5971
- known.set(result, partSize("list", result.length, contents));
6006
+ cacheContents(result, contents);
6007
+ cacheSize(result, partSize("list", result.length, contents));
5972
6008
  };
5973
6009
  /** The part of a map's contents its keys add, one term per key. */
5974
- const keysContents = (keys) => keys.reduce((sum, key) => sum + 16 + encoder.encode(key).length, 0);
6010
+ const keysContents = (keys) => keys.reduce((sum, key) => sum + keySize(key), 0);
5975
6011
  /** Seed a newly built List's or map's size from the values it was built of. */
5976
6012
  const cacheBuild = (result, items, keys) => {
5977
6013
  let contents = keys;
5978
6014
  for (const item of items) contents += sizeOf(item);
5979
- knownContents.set(result, contents);
5980
- known.set(result, partSize(result.kind, result.kind === "map" ? result.mapSize : result.length, contents));
6015
+ cacheContents(result, contents);
6016
+ cacheSize(result, partSize(result.kind, result.kind === "map" ? result.mapSize : result.length, contents));
5981
6017
  };
5982
6018
  /** Seed the logical sizes of point edits from their retained collection. */
5983
6019
  const cacheMapWrite = (result, current, key, part) => {
5984
6020
  if (result === current) return;
5985
- const previous = current.hasKey(key) ? 16 + encoder.encode(key).length + sizeOf(current.get(key)) : 0;
5986
- const added = part === void 0 ? 0 : 16 + encoder.encode(key).length + sizeOf(part);
6021
+ const previous = current.hasKey(key) ? keySize(key) + sizeOf(current.get(key)) : 0;
6022
+ const added = part === void 0 ? 0 : keySize(key) + sizeOf(part);
5987
6023
  const contents = contentsOf(current) - previous + added;
5988
- knownContents.set(result, contents);
5989
- known.set(result, partSize("map", result.mapSize, contents));
6024
+ cacheContents(result, contents);
6025
+ cacheSize(result, partSize("map", result.mapSize, contents));
5990
6026
  };
5991
6027
  const cacheListEdit = (result, current, i, part) => {
5992
6028
  const contents = contentsOf(current) - sizeOf(current.index(i + 1)) + (part === void 0 ? 0 : sizeOf(part));
5993
- knownContents.set(result, contents);
5994
- known.set(result, partSize("list", result.length, contents));
6029
+ cacheContents(result, contents);
6030
+ cacheSize(result, partSize("list", result.length, contents));
5995
6031
  };
5996
6032
  /** A value's logical size (chapter 8, Logical sizes), as if nothing were shared. */
5997
6033
  const sizeOf = (v) => {
5998
- const cached = known.get(v);
5999
- if (cached !== void 0) return cached;
6034
+ const cached = knownSize(v);
6035
+ if (cached >= 0) return cached;
6000
6036
  const leaf = leafSize(v, measureOf);
6001
6037
  if (leaf !== void 0) {
6002
- known.set(v, leaf);
6038
+ cacheSize(v, leaf);
6003
6039
  return leaf;
6004
6040
  }
6005
6041
  const pending = [v];
@@ -6007,22 +6043,22 @@ const sizeOf = (v) => {
6007
6043
  const seen = /* @__PURE__ */ new Set();
6008
6044
  while (pending.length) {
6009
6045
  const next = pending.pop();
6010
- if (known.has(next) || seen.has(next)) continue;
6046
+ if (knownSize(next) >= 0 || seen.has(next)) continue;
6011
6047
  const leaf = leafSize(next, measureOf);
6012
6048
  if (leaf !== void 0) {
6013
- known.set(next, leaf);
6049
+ cacheSize(next, leaf);
6014
6050
  continue;
6015
6051
  }
6016
6052
  seen.add(next);
6017
6053
  order.push(next);
6018
- for (const child of childrenOf(next)) if (!known.has(child) && !seen.has(child)) pending.push(child);
6054
+ for (const child of childrenOf(next)) if (knownSize(child) < 0 && !seen.has(child)) pending.push(child);
6019
6055
  }
6020
6056
  for (let i = order.length - 1; i >= 0; i--) {
6021
6057
  const value = order[i];
6022
6058
  const formula = sizes.get(value.kind);
6023
- known.set(value, evaluate(formula, noCounts, value));
6059
+ cacheSize(value, evaluate(formula, noCounts, value));
6024
6060
  }
6025
- return known.get(v);
6061
+ return knownSize(v);
6026
6062
  };
6027
6063
  const childrenOf = (v) => {
6028
6064
  switch (v.kind) {
@@ -7370,11 +7406,11 @@ const comparison = (op, a, b, fold) => {
7370
7406
  scanned
7371
7407
  };
7372
7408
  }
7373
- const x = smallOf(a);
7374
- const y = smallOf(b);
7409
+ const x = smallCoefficientOf(a);
7410
+ const y = smallCoefficientOf(b);
7375
7411
  let scanned = 0;
7376
7412
  let o;
7377
- if (!Number.isNaN(x) && !Number.isNaN(y)) o = x < y ? -1 : x > y ? 1 : 0;
7413
+ if (!Number.isNaN(x) && !Number.isNaN(y) && exponentOf(a) === exponentOf(b)) o = x < y ? -1 : x > y ? 1 : 0;
7378
7414
  else {
7379
7415
  const comparer = new Comparer(fold);
7380
7416
  scanned = comparer.scanned(a, b);
@@ -7514,6 +7550,18 @@ const waitUs = (v) => {
7514
7550
  ]);
7515
7551
  return durationUs(q);
7516
7552
  };
7553
+ /**
7554
+ * `wait q`'s count when `q` is in a Musical Unit (chapter 5, `wait` in
7555
+ * Musical Units): a whole number, 0 or more, or `out of domain`. Undefined
7556
+ * for any other value, which waits as an exact duration.
7557
+ */
7558
+ const musicalCount = (v) => {
7559
+ const q = v.asQuantityRef();
7560
+ if (!q || !musicalKind(q.unit)) return;
7561
+ const n = numberOf(q);
7562
+ if (!isInteger(n) || n.negative && n.coefficient !== 0n) throw outOfDomain("wait", v);
7563
+ return integerOf(n);
7564
+ };
7517
7565
  const secondsOf = (us) => {
7518
7566
  let d = {
7519
7567
  negative: us < 0n,
@@ -7556,19 +7604,46 @@ const dateArithmetic = (op, a, b) => {
7556
7604
  if (us % US_PER_DAY !== 0n) throw incompatible(DAYS, q.unit);
7557
7605
  return inRangeDate(() => civilOf(civilOfDays(civilDays(c) + us / US_PER_DAY, null)));
7558
7606
  };
7607
+ const MIN_EXPONENT = -6176;
7559
7608
  /**
7560
- * Add, subtract or multiply two small integers (see `smallInteger`), or
7561
- * undefined when either isn't one or the result isn't a safe integer. The
7562
- * exact result needs no rounding, so it equals the Decimal path's.
7609
+ * Add, subtract or multiply two small Decimals: safe-integer coefficients x
7610
+ * and y with exponents ex and ey (see `smallCoefficient`). Undefined when
7611
+ * either isn't one, when adding or subtracting unequal exponents, or when the
7612
+ * result's coefficient isn't a safe integer or its exponent is out of range.
7613
+ * Such a result is exact and at the ideal exponent, so it equals the Decimal
7614
+ * path's.
7563
7615
  */
7564
- const smallArithmetic = (op, x, y) => {
7565
- const r = op === "add" ? x + y : op === "subtract" ? x - y : op === "multiply" ? x * y : NaN;
7566
- return Number.isSafeInteger(r) ? smallNumber(r) : void 0;
7616
+ const smallArithmetic = (op, x, ex, y, ey) => {
7617
+ let r;
7618
+ let e = ex;
7619
+ if (op === "multiply") {
7620
+ r = x * y;
7621
+ e = ex + ey;
7622
+ if (e < MIN_EXPONENT) return;
7623
+ } else if (op === "divide") return smallQuotient(x, ex, y, ey);
7624
+ else if (ex !== ey) return;
7625
+ else r = op === "add" ? x + y : op === "subtract" ? x - y : NaN;
7626
+ return Number.isSafeInteger(r) ? smallDecimalNumber(r, e) : void 0;
7627
+ };
7628
+ const smallQuotient = (x, ex, y, ey) => {
7629
+ if (y === 0 || Number.isNaN(x) || Number.isNaN(y)) return;
7630
+ let n = x;
7631
+ let e = ex - ey;
7632
+ for (; e > 0; e--) n *= 10;
7633
+ while (Number.isSafeInteger(n) && e >= MIN_EXPONENT) {
7634
+ if (n % y === 0) return smallDecimalNumber(n / y, e);
7635
+ n *= 10;
7636
+ e--;
7637
+ }
7567
7638
  };
7568
7639
  /** A number Value's small integer, or NaN. */
7569
7640
  const smallOf = (v) => v.kind === "number" ? smallInteger(v.asDecimal()) : NaN;
7641
+ /** A number Value's small coefficient (see `smallCoefficient`), or NaN. */
7642
+ const smallCoefficientOf = (v) => v.kind === "number" ? smallCoefficient(v.asDecimal()) : NaN;
7643
+ /** A number Value's exponent, or 0 for another kind. */
7644
+ const exponentOf = (v) => v.kind === "number" ? smallExponent(v.asDecimal()) : 0;
7570
7645
  const arithmetic = (op, a, b) => {
7571
- const small = smallArithmetic(op, smallOf(a), smallOf(b));
7646
+ const small = smallArithmetic(op, smallCoefficientOf(a), exponentOf(a), smallCoefficientOf(b), exponentOf(b));
7572
7647
  if (small) return small;
7573
7648
  if (isDate(a) || isDate(b)) try {
7574
7649
  return dateArithmetic(op, a, b);
@@ -8570,7 +8645,7 @@ const builtin = (name, args, measure = {}) => {
8570
8645
  case "conforms":
8571
8646
  case "check":
8572
8647
  case "explain": {
8573
- const decoded = decodeShape(y);
8648
+ const decoded = decodeShapeCached(y);
8574
8649
  measure.scanned = decoded.scanned;
8575
8650
  if (decoded.error) throw new ScriptError("invalid shape", [
8576
8651
  ["reason", text(decoded.error.reason)],
@@ -8689,4 +8764,4 @@ const builtinDefaults = {
8689
8764
  toFloat32: [text("big")]
8690
8765
  };
8691
8766
  //#endregion
8692
- export { disassemble as $, negated as A, subjectText as B, isKind as C, validMessageSelector as Ct, matchCaptures as D, runTask as Dt, makeRange as E, RESERVED as Et, search as F, charge as G, waitUs as H, setKey as I, partSize as J, fixedRates as K, smallArithmetic as L, prepareConversion as M, property as N, matchesOf as O, randomBound as P, arityOf as Q, smallOf as R, isEmpty as S, validComputedMessageName as St, makePatternValue as T, Lexer as Tt, wrongKind as U, textForm as V, cacheBuild as W, resetMeasured as X, rateOf as Y, sizeOf as Z, deleteKey as _, defineCapability as _t, builtin as a, patternSource as at, hasKey as b, mismatch as bt, canConvert as c, textDisplay as ct, chunkSet as d, errorMessages as dt, functionHead as et, chunkThere as f, languageVersion as ft, decodeUtf8 as g, acceptsArgumentCount as gt, convert as h, LimitReached as ht, arithmetic as i, numberText as it, outOfRange as j, member as k, chunkDelete as l, compareText as lt, concat as m, reservedErrorKeys as mt, ScriptError as n, opcodes as nt, builtinDefaults as o, quantityText as ot, comparison as p, limitDefaults as pt, keysContents as q, appendTo as r, capturesOf$1 as rt, byteOf as s, splicesOf as st, NotImplementedError as t, instructionSpec as tt, chunkGet as u, costModel as ut, equals as v, defineValueCapability as vt, keyText as w, validStaticMessageName as wt, integerValue as x, shape as xt, getKey as y, expectedOf as yt, splice as z };
8767
+ export { arityOf as $, musicalCount as A, validMessageSelector as At, splice as B, isKind as C, expectedOf as Ct, matchCaptures as D, shape as Dt, makeRange as E, operationDeclarations as Et, randomBound as F, cacheBuild as G, textForm as H, search as I, keysContents as J, charge as K, setKey as L, outOfRange as M, Lexer as Mt, prepareConversion as N, RESERVED as Nt, matchesOf as O, shapeDiagnostics as Ot, property as P, runTask as Pt, sizeOf as Q, smallArithmetic as R, isEmpty as S, diagnosticRecord as St, makePatternValue as T, mismatch as Tt, waitUs as U, subjectText as V, wrongKind as W, rateOf as X, partSize as Y, resetMeasured as Z, deleteKey as _, acceptsArgumentCount as _t, builtin as a, numberText as at, hasKey as b, defineCapability as bt, canConvert as c, splicesOf as ct, chunkSet as d, costModel as dt, disassemble as et, chunkThere as f, errorMessages as ft, decodeUtf8 as g, LimitReached as gt, convert as h, reservedErrorKeys as ht, arithmetic as i, capturesOf$1 as it, negated as j, validStaticMessageName as jt, member as k, validComputedMessageName as kt, chunkDelete as l, textDisplay as lt, concat as m, limitDefaults as mt, ScriptError as n, instructionSpec as nt, builtinDefaults as o, patternSource as ot, comparison as p, languageVersion as pt, fixedRates as q, appendTo as r, opcodes as rt, byteOf as s, quantityText as st, NotImplementedError as t, functionHead as tt, chunkGet as u, compareText as ut, equals as v, conforms as vt, keyText as w, explain as wt, integerValue as x, defineValueCapability as xt, getKey as y, decodeShape as yt, smallCoefficientOf as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@northtalk/ts",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "NorthTalk, a readable scripting language for embedding: the TS Core, its Session Host and Standard Capabilities.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -65,6 +65,10 @@
65
65
  "types": "./message-layer.d.ts",
66
66
  "default": "./message-layer.js"
67
67
  },
68
+ "./peer": {
69
+ "types": "./peer.d.ts",
70
+ "default": "./peer.js"
71
+ },
68
72
  "./session": {
69
73
  "types": "./session.d.ts",
70
74
  "default": "./session.js"
@@ -0,0 +1,151 @@
1
+
2
+ import { P as listValues, V as nothing, b as dec, it as text, t as HostError } from "./errors-VuwK669R.js";
3
+ import { t as defineObjectKind } from "./objects-TarIKBL8.js";
4
+ import { Dt as shape, kt as validComputedMessageName, n as ScriptError, xt as defineValueCapability } from "./operations-BAELnqwf.js";
5
+ import { c as fixed, f as registerStandardChecks, s as costOf } from "./encoding-B7MCQ4ii.js";
6
+ //#region src/peer-capability.ts
7
+ /** The Core-fixed Object Kind of a Peer: no properties, no collection. */
8
+ const PEER_KIND = "peer";
9
+ const peerKind = defineObjectKind({
10
+ name: PEER_KIND,
11
+ props: {}
12
+ });
13
+ const itemsOf = (list) => Array.from({ length: list.length }, (_, i) => list.index(i + 1));
14
+ const OPERATIONS = [
15
+ "expose",
16
+ "unexpose",
17
+ "reach",
18
+ "post",
19
+ "call",
20
+ "caller"
21
+ ];
22
+ /** The Operations `send` uses: `post` for a plain one, `call` with `and wait`. */
23
+ const PEER_POST = "post";
24
+ const PEER_CALL = "call";
25
+ const peerShape = {
26
+ k: "object",
27
+ kind: PEER_KIND
28
+ };
29
+ const argsShape = shape.listOf(shape.any);
30
+ const outOfDomain = (fn, value) => new ScriptError("out of domain", [["function", text(fn)], ["value", value]], true);
31
+ /** Whether a value is a Peer: a Host Object of the Core's kind `peer`. */
32
+ const isPeer = (v) => v.kind === "object" && v.asObjectRef()?.kind === "peer";
33
+ const strayObject = (v, path) => {
34
+ if (v.kind === "object") return isPeer(v) ? null : path;
35
+ if (v.kind === "list") for (let i = 1; i <= v.length; i++) {
36
+ const found = strayObject(v.index(i), [...path, i]);
37
+ if (found) return found;
38
+ }
39
+ if (v.kind === "map") for (const [key, item] of v.entries()) {
40
+ const found = strayObject(item, [...path, key]);
41
+ if (found) return found;
42
+ }
43
+ return null;
44
+ };
45
+ /**
46
+ * A Remote Send's arguments, checked as the `post` and `call` Operations
47
+ * check them, after their Shapes: a Selector a computed `send` could use,
48
+ * then no Host Object other than a Peer at any depth (chapter 5, Remote
49
+ * Sends). `path` counts from the Operation's arguments.
50
+ */
51
+ const checkRemoteSend = (args) => {
52
+ const message = args[1];
53
+ const sent = args[2];
54
+ if (!validComputedMessageName(message.asText(), sent.length)) throw new ScriptError("bad message name", [["name", message], ["arguments", dec(String(sent.length))]], true);
55
+ const path = strayObject(sent, [3]);
56
+ if (path) throw new ScriptError("not encodable", [["kind", text("object")], ["path", listValues(path.map(keyValue))]], true);
57
+ };
58
+ const keyValue = (k) => typeof k === "number" ? dec(String(k)) : text(k);
59
+ const nonEmpty = (fn, v) => {
60
+ if (v?.kind === "text" && v.asText() === "") throw outOfDomain(fn, v);
61
+ };
62
+ /**
63
+ * Optional for Hosts. The binding is the Host's own description of the
64
+ * names the Grant may `reach` and `expose`; the Core never reads it.
65
+ */
66
+ const peerCapability = (impl, costs) => {
67
+ for (const name of OPERATIONS) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Peer needs ${name}`);
68
+ if (impl.release !== void 0 && typeof impl.release !== "function") throw new HostError("invalid value", "Peer release must be a function");
69
+ const operations = {
70
+ expose: {
71
+ mode: "suspending",
72
+ args: [shape.optional(shape.text)],
73
+ result: peerShape,
74
+ errors: [{ code: "bad address" }, { code: "name in use" }],
75
+ cost: costOf(costs, "expose"),
76
+ start: (call, name) => name?.kind === "text" ? impl.expose(call, name.asText()) : impl.expose(call)
77
+ },
78
+ unexpose: {
79
+ mode: "immediate",
80
+ args: [shape.oneOf(shape.text, peerShape)],
81
+ result: shape.nothing,
82
+ errors: [],
83
+ cost: costOf(costs, "unexpose"),
84
+ do: (call, exposure) => {
85
+ impl.unexpose(call, exposure.kind === "text" ? exposure.asText() : exposure.asObject());
86
+ return nothing;
87
+ }
88
+ },
89
+ reach: {
90
+ mode: "suspending",
91
+ args: [shape.text],
92
+ result: peerShape,
93
+ errors: [{ code: "bad address" }, { code: "not exposed" }],
94
+ cost: costOf(costs, "reach"),
95
+ start: (call, address) => impl.reach(call, address.asText())
96
+ },
97
+ post: {
98
+ mode: "fire-and-forget",
99
+ args: [
100
+ peerShape,
101
+ shape.text,
102
+ argsShape
103
+ ],
104
+ errors: [],
105
+ cost: costOf(costs, "post"),
106
+ fire: (call, peer, message, args) => impl.post(call, peer.asObject(), message.asText(), itemsOf(args))
107
+ },
108
+ call: {
109
+ mode: "suspending",
110
+ args: [
111
+ peerShape,
112
+ shape.text,
113
+ argsShape
114
+ ],
115
+ result: shape.any,
116
+ errors: [{
117
+ code: "send failed",
118
+ fields: {
119
+ reason: shape.text,
120
+ error: {
121
+ optional: true,
122
+ shape: shape.any
123
+ }
124
+ }
125
+ }],
126
+ cost: costOf(costs, "call"),
127
+ start: (call, peer, message, args) => impl.call(call, peer.asObject(), message.asText(), itemsOf(args))
128
+ },
129
+ caller: {
130
+ mode: "immediate",
131
+ args: [],
132
+ result: shape.any,
133
+ errors: [],
134
+ cost: costOf(costs, "caller"),
135
+ do: (call) => impl.caller(call)
136
+ }
137
+ };
138
+ const hostErrors = {
139
+ expose: ["bad address", "name in use"],
140
+ reach: ["bad address", "not exposed"],
141
+ call: ["send failed"]
142
+ };
143
+ for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
144
+ error: (code) => hostErrors[name]?.includes(code) ?? false,
145
+ ...name === "expose" || name === "reach" || name === "unexpose" ? { arguments: (args) => nonEmpty(name, args[0]) } : name === "post" || name === "call" ? { arguments: checkRemoteSend } : {}
146
+ });
147
+ const release = impl.release === void 0 ? void 0 : (context) => impl.release(context);
148
+ return fixed(defineValueCapability("peer", operations, void 0, release));
149
+ };
150
+ //#endregion
151
+ export { peerKind as a, peerCapability as i, PEER_KIND as n, PEER_POST as r, PEER_CALL as t };