@northtalk/ts 0.5.0 → 0.5.1

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 (70) hide show
  1. package/README.md +11 -0
  2. package/base64-CDO-a06R.js +29 -0
  3. package/{binary-value-B3knLdHD.d.ts → binary-value-xvJoGg0C.d.ts} +1 -1
  4. package/{checker-DMI4LiRm.js → checker-CUhn2XaM.js} +4 -4
  5. package/{core-D_9OuTRE.d.ts → core-BuTAYRm-.d.ts} +1 -1
  6. package/{debug-nN5tQ_p4.d.ts → debug-DRhMZAxw.d.ts} +24 -8
  7. package/debug.d.ts +1 -1
  8. package/debug.js +1 -1
  9. package/{driver-Bf-7Roq6.d.ts → driver-CHDcuqUy.d.ts} +1 -1
  10. package/driver.d.ts +1 -1
  11. package/driver.js +1 -1
  12. package/{encoding-C3Q7pIC9.js → encoding-RUuES_e4.js} +2 -2
  13. package/{engine-BpdGfAND.js → engine-CXf5FCwi.js} +6 -6
  14. package/{engine-CQqt4rTB.d.ts → engine-Cc3yofGM.d.ts} +2 -2
  15. package/{errors-BKJES3Zu.js → errors-D11zizZg.js} +1580 -1481
  16. package/{group-Bz2wh72R.js → group-BflSou2n.js} +45 -33
  17. package/http-fetch-DFwVIOQg.js +517 -0
  18. package/http.d.ts +39 -2
  19. package/http.js +189 -6
  20. package/index.d.ts +10 -660
  21. package/index.js +36 -49
  22. package/{inline-grants-Cx0Z9XAt.js → inline-grants-XbX9HL_w.js} +72 -304
  23. package/lean-BebPaTMK.js +47 -0
  24. package/lean-CjWVuOrC.d.ts +741 -0
  25. package/lean.d.ts +8 -0
  26. package/lean.js +15 -0
  27. package/{manifest-Dw-8Unmf.js → manifest-CCfpn0kC.js} +3 -4
  28. package/{manifest-DYAbIyQm.d.ts → manifest-DVrx-pT2.d.ts} +2 -2
  29. package/message-layer.d.ts +2 -2
  30. package/message-layer.js +2 -2
  31. package/notify.d.ts +1 -1
  32. package/notify.js +1 -1
  33. package/{objects-BRcpeXwZ.d.ts → objects-DC6HjzBY.d.ts} +1 -1
  34. package/{objects-BC4fS0vq.js → objects-DmUc0lha.js} +1 -1
  35. package/{base64-Dtqaz_0A.js → operations-DnCcztkZ.js} +1632 -32
  36. package/package.json +36 -2
  37. package/{readers-B5e5bBrY.js → readers-CsvlahLi.js} +2 -2
  38. package/{readers-L90Hoa97.d.ts → readers-MmyZ_d0w.d.ts} +1 -1
  39. package/{request-pump-binary-BjnyqXV5.js → request-pump-binary-oqjWFqZA.js} +5 -4
  40. package/{router-BCHEfs4x.js → router-BZ-aYeXA.js} +4 -4
  41. package/{router-CBuMIl6i.d.ts → router-D56rSkU8.d.ts} +2 -2
  42. package/session.d.ts +2 -2
  43. package/session.js +54 -15
  44. package/setup.d.ts +1 -1
  45. package/setup.js +4 -4
  46. package/sqlite.d.ts +2 -2
  47. package/sqlite.js +5 -5
  48. package/stdlib/bytes.d.ts +6 -0
  49. package/stdlib/bytes.js +11 -0
  50. package/stdlib/date.d.ts +6 -0
  51. package/stdlib/date.js +11 -0
  52. package/stdlib/json.d.ts +6 -0
  53. package/stdlib/json.js +11 -0
  54. package/stdlib/list.d.ts +6 -0
  55. package/stdlib/list.js +10 -0
  56. package/stdlib/map.d.ts +6 -0
  57. package/stdlib/map.js +10 -0
  58. package/stdlib/text.d.ts +6 -0
  59. package/stdlib/text.js +10 -0
  60. package/stdlib/units.d.ts +6 -0
  61. package/stdlib/units.js +10 -0
  62. package/stdlib-registry-BwitI3Ox.d.ts +18 -0
  63. package/{store-DTQa0lyE.js → store-DHlo6fP5.js} +2 -2
  64. package/{store-capability-BxXgiRM7.js → store-capability-BrUUAwVS.js} +3 -4
  65. package/store.d.ts +2 -2
  66. package/store.js +2 -2
  67. package/{user-capability-5-IvCeZI.js → user-capability-BcRQyyEw.js} +4 -5
  68. package/wasm.d.ts +5 -5
  69. package/wasm.js +12 -11
  70. package/capabilities-Bi5Qm6Fr.js +0 -1320
@@ -1,1320 +0,0 @@
1
-
2
- import { A as listValues, D as isDecimal, L as nothing, N as map, Q as text, R as num, T as instant, at as parseUnit, d as bytes, en as assertScalarText, ht as unitKinds, l as Value, lt as unitEntry, o as invalidValue, pt as grammar, t as HostError, tt as UnitError, u as bool, ut as unitText, v as dec } from "./errors-BKJES3Zu.js";
3
- //#region src/tasks.ts
4
- const runTask = (root) => {
5
- const stack = [root];
6
- let value;
7
- let throwing = false;
8
- while (stack.length) {
9
- const task = stack.at(-1);
10
- try {
11
- const step = throwing ? task.throw(value) : task.next(value);
12
- throwing = false;
13
- if (step.done) {
14
- stack.pop();
15
- value = step.value;
16
- } else {
17
- stack.push(step.value);
18
- value = void 0;
19
- }
20
- } catch (error) {
21
- stack.pop();
22
- value = error;
23
- throwing = true;
24
- }
25
- }
26
- if (throwing) throw value;
27
- return value;
28
- };
29
- //#endregion
30
- //#region src/lexer.ts
31
- const RESERVED = new Set(grammar.reserved);
32
- const UNIT_SHAPE = /^(?:1\/)?[A-Za-z]+(?:\^[+-]?\d*)?(?:[*/][A-Za-z]+(?:\^[+-]?\d*)?)*(?!\w)/;
33
- const NAME = /^[A-Z_a-z]\w*/;
34
- const NUMBER = /^(?:0x[\dA-Fa-f]+|\d+(?:\.\d+)?)/;
35
- const OPS = [
36
- "...",
37
- "..",
38
- "&",
39
- "=",
40
- "+",
41
- "-",
42
- "*",
43
- "/",
44
- "^",
45
- "(",
46
- ")",
47
- "[",
48
- "]",
49
- "{",
50
- "}",
51
- ",",
52
- ":"
53
- ];
54
- const unitProblem = (text) => {
55
- try {
56
- parseUnit(text);
57
- return null;
58
- } catch (error) {
59
- if (error instanceof UnitError) return error.message;
60
- throw error;
61
- }
62
- };
63
- var Lexer = class {
64
- src;
65
- fences = /* @__PURE__ */ new Map();
66
- lineStarts = [0];
67
- surrogateOffsets = [];
68
- constructor(src) {
69
- this.src = src;
70
- assertScalarText(src);
71
- for (let i = 0; i < src.length; i++) {
72
- const code = src.charCodeAt(i);
73
- if (code >= 56320 && code <= 57343) this.surrogateOffsets.push(i);
74
- if (src[i] === "\n" || src[i] === "\r" && src[i + 1] !== "\n") this.lineStarts.push(i + 1);
75
- }
76
- }
77
- lastLine = 0;
78
- where(pos) {
79
- const starts = this.lineStarts;
80
- let lo = this.lastLine;
81
- if (!(starts[lo] <= pos && (lo + 1 === starts.length || pos < starts[lo + 1]))) {
82
- lo = this.findLine(pos);
83
- this.lastLine = lo;
84
- }
85
- const start = starts[lo];
86
- const col = pos - start + 1 - (this.surrogateOffsets.length ? this.surrogatesBefore(pos) - this.surrogatesBefore(start) : 0);
87
- return {
88
- line: lo + 1,
89
- col
90
- };
91
- }
92
- findLine(pos) {
93
- let lo = 0;
94
- let hi = this.lineStarts.length - 1;
95
- while (lo < hi) {
96
- const mid = lo + hi + 1 >> 1;
97
- if (this.lineStarts[mid] <= pos) lo = mid;
98
- else hi = mid - 1;
99
- }
100
- return lo;
101
- }
102
- surrogatesBefore(pos) {
103
- let lo = 0;
104
- let hi = this.surrogateOffsets.length;
105
- while (lo < hi) {
106
- const mid = lo + hi >>> 1;
107
- if (this.surrogateOffsets[mid] < pos) lo = mid + 1;
108
- else hi = mid;
109
- }
110
- return lo;
111
- }
112
- tok(t, v, pos, end, spaceBefore, mode, code, leadingTrivia = []) {
113
- const { line, col } = this.where(pos);
114
- return {
115
- kind: "token",
116
- raw: this.src.slice(pos, end),
117
- leadingTrivia,
118
- t,
119
- v,
120
- code,
121
- pos,
122
- end,
123
- line,
124
- col,
125
- spaceBefore,
126
- mode
127
- };
128
- }
129
- trivia(start) {
130
- const s = this.src;
131
- let pos = start;
132
- const trivia = [];
133
- const add = (kind, from) => {
134
- const { line, col } = this.where(from);
135
- trivia.push({
136
- kind,
137
- pos: from,
138
- end: pos,
139
- raw: s.slice(from, pos),
140
- line,
141
- col
142
- });
143
- };
144
- if (pos === 0 && s.charCodeAt(0) === 65279) {
145
- pos++;
146
- add("bom", 0);
147
- }
148
- for (;;) {
149
- const from = pos;
150
- if (s[pos] === " " || s[pos] === " ") {
151
- do
152
- pos++;
153
- while (s[pos] === " " || s[pos] === " ");
154
- add("space", from);
155
- } else if (s[pos] === "-" && s[pos + 1] === "-") {
156
- while (pos < s.length && s[pos] !== "\n" && s[pos] !== "\r") pos++;
157
- add("comment", from);
158
- } else return {
159
- pos,
160
- trivia
161
- };
162
- }
163
- }
164
- *fenced(open, space, mode) {
165
- const cached = this.fences.get(open);
166
- if (cached) return {
167
- ...cached,
168
- spaceBefore: space,
169
- mode
170
- };
171
- const token = yield this.scanFenced(open, space, mode);
172
- this.fences.set(open, token);
173
- return token;
174
- }
175
- *scanFenced(open, space, mode) {
176
- const s = this.src;
177
- const raw = s[open] === "\"";
178
- let width = 1;
179
- if (raw) while (s[open + width] === "\"") width++;
180
- const begin = open + width;
181
- const block = s[begin] === "\r" || s[begin] === "\n";
182
- const parts = [];
183
- let start = begin;
184
- let i = begin;
185
- const error = (code, at, incomplete = false) => ({
186
- ...this.tok("error", code, at, Math.min(s.length, at + 1), space, mode, code),
187
- incomplete,
188
- parts: incomplete ? [] : parts.filter((p) => p.hole && p.hole.end < at)
189
- });
190
- while (i < s.length) {
191
- if (!raw && s[i] === "`" || raw && s[i] === "\"") {
192
- let count = 1;
193
- if (raw) while (s[i + count] === "\"") count++;
194
- if (raw && count > width) return error("invalid text delimiter", i);
195
- if (count === width) break;
196
- i += count;
197
- continue;
198
- }
199
- if (!raw && s[i] === "\\") {
200
- i++;
201
- if (s[i] === "\r" && s[i + 1] === "\n") i++;
202
- i++;
203
- continue;
204
- }
205
- if (!raw && s.startsWith("${", i)) {
206
- const at = i;
207
- let cursor = i + 2;
208
- let depth = 0;
209
- for (;;) {
210
- const next = this.trivia(cursor).pos;
211
- const t = s[next] === "`" || s.startsWith("\"\"\"", next) ? yield this.fenced(next, true, "operand") : this.lex(cursor, "operand");
212
- if (t.t === "error") return {
213
- ...t,
214
- parts: t.incomplete ? [] : [...parts.filter((p) => p.hole), ...t.parts ?? []]
215
- };
216
- if (t.t === "eof") return error("unterminated interpolation", at, true);
217
- if (t.t === "op" && t.v === "}" && depth === 0) {
218
- parts.push({
219
- start,
220
- end: at,
221
- value: "",
222
- hole: {
223
- at,
224
- start: at + 2,
225
- end: t.pos
226
- }
227
- });
228
- i = t.end;
229
- start = i;
230
- break;
231
- }
232
- if (t.t === "op" && t.v === "{") depth++;
233
- if (t.t === "op" && t.v === "}") depth--;
234
- cursor = t.end;
235
- }
236
- continue;
237
- }
238
- i++;
239
- }
240
- if (i >= s.length) return error("unterminated text", open, true);
241
- parts.push({
242
- start,
243
- end: i,
244
- value: ""
245
- });
246
- let margin = "";
247
- let closeLine = i;
248
- if (block) {
249
- while (closeLine > 0 && s[closeLine - 1] !== "\n" && s[closeLine - 1] !== "\r") closeLine--;
250
- margin = s.slice(closeLine, i);
251
- const mismatch = margin.search(/[^\t ]/);
252
- if (mismatch >= 0) return error("invalid text indentation", closeLine + mismatch);
253
- }
254
- for (const part of parts) {
255
- let from = part.start;
256
- let to = part.end;
257
- if (block && from === begin) from += s[from] === "\r" && s[from + 1] === "\n" ? 2 : 1;
258
- if (block && to === i) {
259
- to = closeLine;
260
- if (to > from && s[to - 1] === "\n") to--;
261
- if (to > from && s[to - 1] === "\r") to--;
262
- }
263
- const chars = [];
264
- const positions = [];
265
- for (let j = from; j < to;) {
266
- if (block && (j === 0 || s[j - 1] === "\n" || s[j - 1] === "\r")) {
267
- let k = 0;
268
- while (k < margin.length && j + k < to && s[j + k] === margin[k]) k++;
269
- if (k !== margin.length) {
270
- const c = s[j + k];
271
- if (!(c === "\n" || c === "\r" || j + k === to && !part.hole)) return error("invalid text indentation", j + k);
272
- }
273
- j += k;
274
- if (j >= to) break;
275
- }
276
- positions.push(j);
277
- if (s[j] === "\r") {
278
- chars.push("\n");
279
- j += s[j + 1] === "\n" ? 2 : 1;
280
- } else chars.push(s[j++]);
281
- }
282
- const text = chars.join("");
283
- if (raw) {
284
- part.value = text;
285
- continue;
286
- }
287
- let value = "";
288
- const origins = [];
289
- const append = (v, at) => {
290
- value += v;
291
- for (let n = 0; n < v.length; n++) origins.push(at);
292
- };
293
- for (let j = 0; j < text.length; j++) {
294
- const at = positions[j];
295
- if (text[j] !== "\\") {
296
- append(text[j], at);
297
- continue;
298
- }
299
- const c = text[++j];
300
- if (c === void 0) return error("invalid text escape", at);
301
- if (c === "\n" || c === "\u2028" || c === "\u2029") continue;
302
- if (c === "0") {
303
- if (/\d/.test(text[j + 1] ?? "")) return error("invalid text escape", at);
304
- append("\0", at);
305
- continue;
306
- }
307
- if (/[1-9]/.test(c)) return error("invalid text escape", at);
308
- const simple = {
309
- b: "\b",
310
- f: "\f",
311
- n: "\n",
312
- r: "\r",
313
- t: " ",
314
- v: "\v"
315
- };
316
- if (simple[c] !== void 0) {
317
- append(simple[c], at);
318
- continue;
319
- }
320
- if (c === "x" || c === "u") {
321
- let digits;
322
- if (c === "u" && text[j + 1] === "{") {
323
- const end = text.indexOf("}", j + 2);
324
- if (end < 0) return error("invalid text escape", at);
325
- digits = text.slice(j + 2, end);
326
- j = end;
327
- } else {
328
- const length = c === "x" ? 2 : 4;
329
- digits = text.slice(j + 1, j + 1 + length);
330
- j += length;
331
- if (digits.length !== length) return error("invalid text escape", at);
332
- }
333
- if (!/^[\dA-Fa-f]+$/.test(digits) || Number.parseInt(digits, 16) > 1114111) return error("invalid text escape", at);
334
- append(String.fromCodePoint(Number.parseInt(digits, 16)), at);
335
- continue;
336
- }
337
- append(c, at);
338
- }
339
- for (let j = 0; j < value.length; j++) {
340
- const c = value.charCodeAt(j);
341
- if (c >= 55296 && c <= 56319 && value.charCodeAt(j + 1) >= 56320 && value.charCodeAt(j + 1) <= 57343) {
342
- j++;
343
- continue;
344
- }
345
- if (c >= 55296 && c <= 57343) return error("invalid text escape", origins[j]);
346
- }
347
- part.value = value;
348
- }
349
- return {
350
- ...this.tok(parts.length === 1 ? "str" : "template", parts[0].value, open, i + width, space, mode),
351
- parts
352
- };
353
- }
354
- lex(start, mode) {
355
- const s = this.src;
356
- const { pos, trivia } = this.trivia(start);
357
- const sp = pos > start || pos === 0 || s[pos - 1] === "\n" || s[pos - 1] === "\r";
358
- const T = (t, v, len = v.length, code) => this.tok(t, v, pos, pos + len, sp, mode, code, trivia);
359
- if (pos >= s.length) return T("eof", "", 0);
360
- const c = s[pos];
361
- const rest = s.slice(pos);
362
- if (c === "\n") return T("nl", String.raw`\n`, 1);
363
- if (c === "\r") return T("nl", String.raw`\n`, s[pos + 1] === "\n" ? 2 : 1);
364
- if (mode === "unit" || mode === "type") {
365
- const m = UNIT_SHAPE.exec(rest);
366
- const first = m?.[0].startsWith("1/") ? "1" : m?.[0].match(/^[A-Za-z]+/)?.[0];
367
- const compound = m && /[*/^]/.test(m[0]);
368
- if (m && (first === "1" || unitEntry(first) !== void 0) && (mode === "unit" || compound)) {
369
- const problem = unitProblem(m[0]);
370
- if (problem) return T("error", problem, m[0].length, "bad unit");
371
- return T("unit", m[0]);
372
- }
373
- }
374
- if (c === "`" || rest.startsWith("\"\"\"")) return {
375
- ...runTask(this.fenced(pos, sp, mode)),
376
- leadingTrivia: trivia
377
- };
378
- if (c === "\"") {
379
- let i = pos + 1;
380
- while (i < s.length && s[i] !== "\"" && s[i] !== "\n" && s[i] !== "\r") i++;
381
- if (s[i] !== "\"") return T("error", "text has no closing quote on its line", i - pos, "unterminated text");
382
- return this.tok("str", s.slice(pos + 1, i), pos, i + 1, sp, mode, void 0, trivia);
383
- }
384
- if (/\d/.test(c)) return T("num", NUMBER.exec(rest)[0]);
385
- if (/[A-Z_a-z]/.test(c)) return T("word", NAME.exec(rest)[0]);
386
- if (c === "'" && s[pos + 1] === "s" && !/\w/.test(s[pos + 2] ?? "")) return T("op", "'s");
387
- const interpretation = mode === "unit" ? "operator" : mode === "type" ? "operand" : mode;
388
- if (c === "<") {
389
- if (interpretation === "pattern") return T("patopen", "<");
390
- if (interpretation === "operand") return s[pos + 1] === "<" ? T("binopen", "<<") : T("patopen", "<");
391
- for (const op of [
392
- "<<",
393
- "<=",
394
- "<>",
395
- "<"
396
- ]) if (rest.startsWith(op)) return T("op", op);
397
- }
398
- if (c === ">") {
399
- if (interpretation === "pattern") return T("patclose", ">");
400
- for (const op of [
401
- ">>",
402
- ">=",
403
- ">"
404
- ]) if (rest.startsWith(op)) return T("op", op);
405
- }
406
- for (const op of OPS) if (rest.startsWith(op)) return T("op", op);
407
- const ch = String.fromCodePoint(s.codePointAt(pos));
408
- return T("error", `${JSON.stringify(ch)} starts no token`, ch.length, "bad character");
409
- }
410
- };
411
- //#endregion
412
- //#region src/selectors.ts
413
- const reserved = new Set(grammar.reserved);
414
- const allowed = new Set(grammar.labels.reserved);
415
- const excluded = new Set(grammar.labels.excluded);
416
- const name = (part) => part !== "_" && /^[A-Z_a-z]\w*$/.exec(part)?.[0] === part;
417
- /** An Argument Label word: any Name, or an allowed Reserved Word, never an excluded one. */
418
- const validArgumentLabel = (part) => name(part) && (!reserved.has(part) || allowed.has(part)) && !excluded.has(part);
419
- const validMessageSelector = (message, arity) => {
420
- if (!message.includes(":")) return true;
421
- const parts = message.split(":");
422
- if (parts.pop() !== "" || parts.length < 2 || parts.length !== arity) return false;
423
- const first = parts.shift();
424
- return name(first) && first !== "all" && !reserved.has(first) && parts.every(validArgumentLabel);
425
- };
426
- const validComputedMessageName = (message, arity) => message.includes(":") ? validMessageSelector(message, arity) : name(message) && message !== "all" && !reserved.has(message);
427
- /** A Name or full Selector a static `send` could write, its arity from its colons. */
428
- const validStaticMessageName = (message) => validComputedMessageName(message, message.split(":").length - 1);
429
- //#endregion
430
- //#region src/capabilities.ts
431
- /** Only a suffix of directly Optional argument Shapes can be omitted. */
432
- const acceptsArgumentCount = (args, count) => count <= args.length && args.slice(count).every((s) => s.k === "optional");
433
- const kind = (k) => ({
434
- k: "kind",
435
- kind: k
436
- });
437
- const fieldsOf = (fields) => Object.entries(fields).map(([key, f]) => "shape" in f ? {
438
- key,
439
- optional: true,
440
- shape: f.shape
441
- } : {
442
- key,
443
- optional: false,
444
- shape: f
445
- });
446
- /** The Shape constructors of `talk.ts`. */
447
- const shape = {
448
- any: { k: "any" },
449
- value: { k: "value" },
450
- nothing: kind("nothing"),
451
- bool: kind("boolean"),
452
- number: kind("number"),
453
- text: kind("text"),
454
- bytes: kind("bytes"),
455
- instant: kind("instant"),
456
- civilDate: kind("civil date"),
457
- range: kind("range"),
458
- pattern: kind("pattern"),
459
- function: kind("function"),
460
- object: (kind) => ({
461
- k: "object",
462
- kind: kind.name
463
- }),
464
- quantityOf: (unit) => ({
465
- k: "quantity",
466
- unit: unitText(parseUnit(unit))
467
- }),
468
- quantityKind: (unitKind) => ({
469
- k: "unitKind",
470
- kind: unitKind
471
- }),
472
- listOf: (of) => ({
473
- k: "list",
474
- of
475
- }),
476
- map: (fields) => ({
477
- k: "map",
478
- fields: fieldsOf(fields),
479
- open: false
480
- }),
481
- openMap: (fields) => ({
482
- k: "map",
483
- fields: fieldsOf(fields),
484
- open: true
485
- }),
486
- oneOf: (...of) => ({
487
- k: "oneOf",
488
- of
489
- }),
490
- /** Supplied Nothing is null; an omitted trailing argument is undefined. */
491
- optional: (of) => ({
492
- k: "optional",
493
- of
494
- })
495
- };
496
- /** What a Shape expects, as `wrong kind` writes it. */
497
- const expectedOf = (s) => {
498
- switch (s.k) {
499
- case "any": return "any";
500
- case "value": return "value";
501
- case "kind":
502
- case "object": return s.kind;
503
- case "quantity": return s.unit;
504
- case "unitKind": return s.kind;
505
- case "list": return "list";
506
- case "map": return "map";
507
- case "oneOf": return s.of.map(expectedOf).join(" or ");
508
- case "optional": return `${expectedOf(s.of)} or nothing`;
509
- }
510
- };
511
- const nothingValue = (v) => v.kind === "nothing";
512
- const gotOf = (v, s) => (s.k === "quantity" || s.k === "unitKind") && v.kind === "quantity" ? unitText(v.asQuantityRef().unit) : v.kind;
513
- const mismatch = (v, s, path = []) => {
514
- const wrong = () => ({
515
- expected: expectedOf(s),
516
- got: gotOf(v, s),
517
- path,
518
- value: v
519
- });
520
- switch (s.k) {
521
- case "value": return null;
522
- case "any": return v.kind === "function" ? {
523
- ...wrong(),
524
- unencodable: true
525
- } : deepFunction(v, path);
526
- case "kind": return v.kind === s.kind ? null : wrong();
527
- case "object": return v.asObjectRef()?.kind === s.kind ? null : wrong();
528
- case "quantity": {
529
- const q = v.asQuantityRef();
530
- return q && unitText(q.unit) === s.unit ? null : wrong();
531
- }
532
- case "unitKind": {
533
- const q = v.asQuantityRef();
534
- const slot = q?.unit.length === 1 ? q.unit[0] : void 0;
535
- return slot && slot.exponent === 1 && unitEntry(slot.unit)?.kind === s.kind ? null : wrong();
536
- }
537
- case "list":
538
- if (v.kind !== "list") return wrong();
539
- for (let i = 1; i <= v.length; i++) {
540
- const m = mismatch(v.index(i), s.of, [...path, i]);
541
- if (m) return m;
542
- }
543
- return null;
544
- case "map": {
545
- if (v.kind !== "map") return wrong();
546
- const keys = new Set(v.entries().map(([k]) => k));
547
- for (const f of s.fields) {
548
- if (!keys.has(f.key)) {
549
- if (!f.optional) return {
550
- expected: expectedOf(f.shape),
551
- got: "nothing",
552
- path: [...path, f.key],
553
- value: nothing
554
- };
555
- continue;
556
- }
557
- const m = mismatch(v.get(f.key), f.shape, [...path, f.key]);
558
- if (m) return m;
559
- }
560
- const declared = new Set(s.fields.map((f) => f.key));
561
- for (const [key, item] of v.entries()) if (!declared.has(key)) {
562
- if (!s.open) return {
563
- expected: "nothing",
564
- got: item.kind,
565
- path: [...path, key],
566
- value: item
567
- };
568
- const m = deepFunction(item, [...path, key]);
569
- if (m) return m;
570
- }
571
- return null;
572
- }
573
- case "oneOf": return s.of.some((option) => !mismatch(v, option, path)) ? null : wrong();
574
- case "optional": {
575
- if (nothingValue(v)) return null;
576
- const m = mismatch(v, s.of, path);
577
- return m && m.path.length === path.length && !m.unencodable ? {
578
- ...m,
579
- expected: `${m.expected} or nothing`
580
- } : m;
581
- }
582
- }
583
- };
584
- const deepFunction = (v, path) => {
585
- if (v.kind === "function") return {
586
- expected: "any",
587
- got: "function",
588
- path,
589
- value: v,
590
- unencodable: true
591
- };
592
- if (v.kind === "list") for (let i = 1; i <= v.length; i++) {
593
- const m = deepFunction(v.index(i), [...path, i]);
594
- if (m) return m;
595
- }
596
- if (v.kind === "map") for (const [key, item] of v.entries()) {
597
- const m = deepFunction(item, [...path, key]);
598
- if (m) return m;
599
- }
600
- return null;
601
- };
602
- const scalarKinds = /* @__PURE__ */ new Set([
603
- "nothing",
604
- "boolean",
605
- "number",
606
- "quantity",
607
- "text",
608
- "bytes",
609
- "list",
610
- "map",
611
- "range",
612
- "instant",
613
- "civil date",
614
- "pattern",
615
- "function",
616
- "object"
617
- ]);
618
- const wrapperKeys = [
619
- "quantity",
620
- "unitKind",
621
- "object",
622
- "list",
623
- "oneOf",
624
- "optional",
625
- "map"
626
- ];
627
- const scalarsOf = (s) => [...s].length;
628
- /** Reads Shape data into a Shape, or gives the first definition error. */
629
- const decodeShape = (data) => {
630
- let scanned = 0;
631
- const results = [];
632
- const stack = [{
633
- data,
634
- path: [],
635
- t: "enter"
636
- }];
637
- const fail = (reason, path, value) => ({
638
- error: {
639
- path,
640
- reason,
641
- value
642
- },
643
- scanned
644
- });
645
- while (stack.length) {
646
- const frame = stack.pop();
647
- switch (frame.t) {
648
- case "wrap":
649
- results.push({
650
- k: frame.k,
651
- of: results.pop()
652
- });
653
- break;
654
- case "oneOf":
655
- results.push({
656
- k: "oneOf",
657
- of: results.splice(results.length - frame.n, frame.n)
658
- });
659
- break;
660
- case "mapDone":
661
- results.push({
662
- fields: frame.acc,
663
- k: "map",
664
- open: frame.open
665
- });
666
- break;
667
- case "fieldDone":
668
- frame.acc.push({
669
- key: frame.key,
670
- optional: frame.optional,
671
- shape: results.pop()
672
- });
673
- break;
674
- case "field": {
675
- const { data: decl, path } = frame;
676
- if (decl.kind !== "map") return fail("invalid field", path, decl);
677
- const entries = new Map(decl.entries());
678
- scanned += entries.size;
679
- const key = entries.get("key");
680
- if (key === void 0) return fail("invalid field key", path, decl);
681
- if (key.kind !== "text") return fail("invalid field key", [...path, "key"], key);
682
- const inner = entries.get("shape");
683
- if (inner === void 0) return fail("missing field shape", path, decl);
684
- const flag = entries.get("optional");
685
- if (flag !== void 0 && flag.kind !== "boolean") return fail("invalid flag", [...path, "optional"], flag);
686
- const name = key.asText();
687
- if (frame.seen.has(name)) return fail("duplicate field", [...path, "key"], key);
688
- frame.seen.add(name);
689
- stack.push({
690
- acc: frame.acc,
691
- key: name,
692
- optional: flag?.asBool() ?? false,
693
- t: "fieldDone"
694
- }, {
695
- data: inner,
696
- path: [...path, "shape"],
697
- t: "enter"
698
- });
699
- break;
700
- }
701
- case "enter": {
702
- const { data: node, path } = frame;
703
- scanned++;
704
- if (node.kind === "text") {
705
- const name = node.asText();
706
- scanned += scalarsOf(name);
707
- if (name === "any" || name === "value") results.push({ k: name });
708
- else if (scalarKinds.has(name)) results.push({
709
- k: "kind",
710
- kind: name
711
- });
712
- else return fail("unknown kind", path, node);
713
- break;
714
- }
715
- if (node.kind !== "map") return fail("not a shape", path, node);
716
- const entries = new Map(node.entries());
717
- scanned += entries.size;
718
- const present = wrapperKeys.filter((k) => entries.has(k));
719
- if (present.length === 0) return fail("not a shape", path, node);
720
- if (present.length > 1) return fail("ambiguous shape", path, node);
721
- const key = present[0];
722
- const payload = entries.get(key);
723
- switch (key) {
724
- case "quantity":
725
- if (payload.kind !== "text") return fail("invalid unit", [...path, key], payload);
726
- scanned += scalarsOf(payload.asText());
727
- try {
728
- results.push({
729
- k: "quantity",
730
- unit: unitText(parseUnit(payload.asText()))
731
- });
732
- } catch {
733
- return fail("invalid unit", [...path, key], payload);
734
- }
735
- break;
736
- case "unitKind":
737
- if (payload.kind === "text") scanned += scalarsOf(payload.asText());
738
- if (payload.kind !== "text" || !unitKinds.includes(payload.asText())) return fail("unknown unit kind", [...path, key], payload);
739
- results.push({
740
- k: "unitKind",
741
- kind: payload.asText()
742
- });
743
- break;
744
- case "object":
745
- if (payload.kind !== "text") return fail("invalid object kind", [...path, key], payload);
746
- results.push({
747
- k: "object",
748
- kind: payload.asText()
749
- });
750
- break;
751
- case "list":
752
- case "optional":
753
- stack.push({
754
- k: key,
755
- t: "wrap"
756
- }, {
757
- data: payload,
758
- path: [...path, key],
759
- t: "enter"
760
- });
761
- break;
762
- case "oneOf":
763
- if (payload.kind !== "list") return fail("invalid alternatives", [...path, key], payload);
764
- if (payload.length === 0) return fail("empty union", [...path, key], payload);
765
- stack.push({
766
- n: payload.length,
767
- t: "oneOf"
768
- });
769
- for (let i = payload.length; i >= 1; i--) stack.push({
770
- data: payload.index(i),
771
- path: [
772
- ...path,
773
- key,
774
- i
775
- ],
776
- t: "enter"
777
- });
778
- break;
779
- case "map": {
780
- const flag = entries.get("open");
781
- if (flag !== void 0 && flag.kind !== "boolean") return fail("invalid flag", [...path, "open"], flag);
782
- if (payload.kind !== "list") return fail("invalid fields", [...path, key], payload);
783
- const acc = [];
784
- const seen = /* @__PURE__ */ new Set();
785
- stack.push({
786
- acc,
787
- open: flag?.asBool() ?? false,
788
- t: "mapDone"
789
- });
790
- for (let i = payload.length; i >= 1; i--) stack.push({
791
- acc,
792
- data: payload.index(i),
793
- path: [
794
- ...path,
795
- key,
796
- i
797
- ],
798
- seen,
799
- t: "field"
800
- });
801
- break;
802
- }
803
- }
804
- break;
805
- }
806
- }
807
- }
808
- return {
809
- scanned,
810
- shape: results[0]
811
- };
812
- };
813
- /**
814
- * Every mismatch of `v` against `s`, or only the first when `first`:
815
- * the traversal of chapter 7, with failed union alternatives grouped.
816
- */
817
- const shapeDiagnostics = (v, s, first, scanned) => {
818
- const root = { diags: [] };
819
- const discarded = /* @__PURE__ */ new Set();
820
- let trials = 0;
821
- let halted = false;
822
- const deepInfo = /* @__PURE__ */ new Map();
823
- const infoOf = (rootValue) => {
824
- const pending = [rootValue];
825
- const order = [];
826
- const seen = /* @__PURE__ */ new Set();
827
- 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];
837
- let clean = value.kind !== "function";
838
- 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
- for (const child of children) {
841
- const info = deepInfo.get(child);
842
- clean = clean && info.clean;
843
- nodes += info.nodes;
844
- }
845
- deepInfo.set(value, {
846
- clean,
847
- nodes
848
- });
849
- }
850
- return deepInfo.get(rootValue);
851
- };
852
- const stack = [{
853
- path: [],
854
- s,
855
- sink: root,
856
- t: "node",
857
- trial: 0,
858
- v
859
- }];
860
- const emit = (sink, trial, diag) => {
861
- sink.diags.push(diag);
862
- if (!first) return;
863
- if (trial === 0) {
864
- halted = true;
865
- for (let i = stack.length - 1; i >= 0; i--) if (stack[i].t !== "adjust") stack.splice(i, 1);
866
- return;
867
- }
868
- discarded.add(trial);
869
- for (let i = stack.length - 1; i >= 0; i--) if (stack[i].trial === trial) stack.splice(i, 1);
870
- };
871
- const wrong = (sink, trial, value, shape, path) => emit(sink, trial, {
872
- expected: expectedOf(shape),
873
- got: gotOf(value, shape),
874
- path,
875
- value
876
- });
877
- while (stack.length) {
878
- const frame = stack.pop();
879
- if (discarded.has(frame.trial)) continue;
880
- switch (frame.t) {
881
- case "adjust":
882
- for (let i = frame.mark; i < frame.sink.diags.length; i++) {
883
- const d = frame.sink.diags[i];
884
- if (!d.unencodable && d.path.length === frame.path.length && d.path.every((p, j) => p === frame.path[j])) {
885
- d.expected += " or nothing";
886
- break;
887
- }
888
- }
889
- break;
890
- case "missing":
891
- scanned++;
892
- emit(frame.sink, frame.trial, {
893
- expected: frame.expected,
894
- got: "nothing",
895
- path: frame.path,
896
- value: nothing
897
- });
898
- break;
899
- case "deep": {
900
- const info = infoOf(frame.v);
901
- if (info.clean) {
902
- scanned += info.nodes;
903
- break;
904
- }
905
- scanned++;
906
- const { path, sink, trial, v: value } = frame;
907
- if (value.kind === "function") emit(sink, trial, {
908
- expected: "any",
909
- got: "function",
910
- path,
911
- unencodable: true,
912
- value
913
- });
914
- else if (value.kind === "list") for (let i = value.length; i >= 1; i--) stack.push({
915
- path: [...path, i],
916
- sink,
917
- t: "deep",
918
- trial,
919
- v: value.index(i)
920
- });
921
- else if (value.kind === "map") {
922
- const entries = value.entries();
923
- for (let i = entries.length - 1; i >= 0; i--) stack.push({
924
- path: [...path, entries[i][0]],
925
- sink,
926
- t: "deep",
927
- trial,
928
- v: entries[i][1]
929
- });
930
- }
931
- break;
932
- }
933
- case "extras": {
934
- const declared = new Set(frame.s.fields.map((f) => f.key));
935
- const deeps = [];
936
- for (const [key, item] of frame.v.entries()) {
937
- if (declared.has(key)) continue;
938
- if (!frame.s.open) {
939
- scanned++;
940
- emit(frame.sink, frame.trial, {
941
- expected: "nothing",
942
- got: item.kind,
943
- path: [...frame.path, key],
944
- value: item
945
- });
946
- if (halted || discarded.has(frame.trial)) break;
947
- } else deeps.push({
948
- path: [...frame.path, key],
949
- sink: frame.sink,
950
- t: "deep",
951
- trial: frame.trial,
952
- v: item
953
- });
954
- }
955
- for (let i = deeps.length - 1; i >= 0; i--) stack.push(deeps[i]);
956
- break;
957
- }
958
- case "union": {
959
- if (frame.current) {
960
- if (frame.current.diags.length === 0) break;
961
- frame.collected.push(frame.current.diags);
962
- frame.current = null;
963
- frame.index++;
964
- }
965
- if (frame.index >= frame.alts.length) {
966
- emit(frame.sink, frame.trial, {
967
- alternatives: frame.collected,
968
- expected: expectedOf(frame.s),
969
- got: gotOf(frame.v, frame.s),
970
- path: frame.path,
971
- value: frame.v
972
- });
973
- break;
974
- }
975
- const sink = { diags: [] };
976
- frame.current = sink;
977
- stack.push(frame, {
978
- path: frame.path,
979
- s: frame.alts[frame.index],
980
- sink,
981
- t: "node",
982
- trial: ++trials,
983
- v: frame.v
984
- });
985
- break;
986
- }
987
- case "node": {
988
- scanned++;
989
- const { path, s: shape, sink, trial, v: value } = frame;
990
- switch (shape.k) {
991
- case "value": break;
992
- case "any":
993
- stack.push({
994
- path,
995
- sink,
996
- t: "deep",
997
- trial,
998
- v: value
999
- });
1000
- break;
1001
- case "kind":
1002
- if (value.kind !== shape.kind) wrong(sink, trial, value, shape, path);
1003
- break;
1004
- case "object":
1005
- if (value.asObjectRef()?.kind !== shape.kind) wrong(sink, trial, value, shape, path);
1006
- break;
1007
- case "quantity": {
1008
- const q = value.asQuantityRef();
1009
- if (!q || unitText(q.unit) !== shape.unit) wrong(sink, trial, value, shape, path);
1010
- break;
1011
- }
1012
- case "unitKind": {
1013
- const q = value.asQuantityRef();
1014
- const slot = q?.unit.length === 1 ? q.unit[0] : void 0;
1015
- if (!slot || slot.exponent !== 1 || unitEntry(slot.unit)?.kind !== shape.kind) wrong(sink, trial, value, shape, path);
1016
- break;
1017
- }
1018
- case "list":
1019
- if (value.kind !== "list") {
1020
- wrong(sink, trial, value, shape, path);
1021
- break;
1022
- }
1023
- for (let i = value.length; i >= 1; i--) stack.push({
1024
- path: [...path, i],
1025
- s: shape.of,
1026
- sink,
1027
- t: "node",
1028
- trial,
1029
- v: value.index(i)
1030
- });
1031
- break;
1032
- case "map": {
1033
- if (value.kind !== "map") {
1034
- wrong(sink, trial, value, shape, path);
1035
- break;
1036
- }
1037
- stack.push({
1038
- path,
1039
- s: shape,
1040
- sink,
1041
- t: "extras",
1042
- trial,
1043
- v: value
1044
- });
1045
- const entries = new Map(value.entries());
1046
- for (let i = shape.fields.length - 1; i >= 0; i--) {
1047
- const f = shape.fields[i];
1048
- const item = entries.get(f.key);
1049
- if (item !== void 0) stack.push({
1050
- path: [...path, f.key],
1051
- s: f.shape,
1052
- sink,
1053
- t: "node",
1054
- trial,
1055
- v: item
1056
- });
1057
- else if (!f.optional) stack.push({
1058
- expected: expectedOf(f.shape),
1059
- path: [...path, f.key],
1060
- sink,
1061
- t: "missing",
1062
- trial
1063
- });
1064
- }
1065
- break;
1066
- }
1067
- case "oneOf":
1068
- stack.push({
1069
- alts: shape.of,
1070
- collected: [],
1071
- current: null,
1072
- index: 0,
1073
- path,
1074
- s: shape,
1075
- sink,
1076
- t: "union",
1077
- trial,
1078
- v: value
1079
- });
1080
- break;
1081
- case "optional":
1082
- if (nothingValue(value)) break;
1083
- stack.push({
1084
- mark: sink.diags.length,
1085
- path,
1086
- sink,
1087
- t: "adjust",
1088
- trial
1089
- }, {
1090
- path,
1091
- s: shape.of,
1092
- sink,
1093
- t: "node",
1094
- trial,
1095
- v: value
1096
- });
1097
- }
1098
- break;
1099
- }
1100
- }
1101
- }
1102
- return {
1103
- diags: root.diags,
1104
- scanned
1105
- };
1106
- };
1107
- /** A Value Path as a Script value: text keys and 1-based positions. */
1108
- const pathValue = (path) => listValues(path.map((p) => typeof p === "number" ? dec(String(p)) : text(p)));
1109
- /** One `explain` record: the error's fields as a plain map, without `message` or `at`. */
1110
- const diagnosticRecord = (d) => {
1111
- if (d.unencodable) return map([
1112
- ["code", text("not encodable")],
1113
- ["kind", text(d.got)],
1114
- ["path", pathValue(d.path)]
1115
- ]);
1116
- const fields = [
1117
- ["code", text("wrong kind")],
1118
- ["expected", text(d.expected)],
1119
- ["got", text(d.got)],
1120
- ["value", d.value]
1121
- ];
1122
- if (d.path.length) fields.push(["path", pathValue(d.path)]);
1123
- if (d.alternatives) fields.push(["alternatives", listValues(d.alternatives.map((alt) => listValues(alt.map(diagnosticRecord))))]);
1124
- return map(fields);
1125
- };
1126
- /** Thrown by `call.charge` when the Run's Fuel can't cover it. */
1127
- var LimitReached = class extends Error {
1128
- name = "LimitReached";
1129
- };
1130
- const refusedNames = /* @__PURE__ */ new Set([
1131
- "ask",
1132
- "tell",
1133
- "send",
1134
- "wait",
1135
- "end"
1136
- ]);
1137
- const scopeWord = (value) => typeof value === "string" && /^[A-Z_a-z]\w*$/.test(value);
1138
- const hasHooks = (lifecycle) => !!lifecycle && typeof lifecycle === "object" && [
1139
- "begin",
1140
- "commit",
1141
- "rollback"
1142
- ].every((phase) => typeof lifecycle[phase] === "function");
1143
- const checkMetering = (op) => {
1144
- if (op.metering === void 0) return;
1145
- if (op.metering === "read-only") {
1146
- if (op.mode === "fire-and-forget" || op.segmentBound || op.scope) invalidValue("read-only metering needs an immediate or suspending Operation without scope or segmentBound");
1147
- } else if (op.metering === "segment-bound") {
1148
- if (op.mode !== "immediate" || op.segmentBound !== true) invalidValue("segment-bound metering needs an immediate segmentBound Operation");
1149
- } else invalidValue("metering must be read-only or segment-bound");
1150
- };
1151
- /**
1152
- * Define a Capability whose Host functions take and return Values. The
1153
- * standard Capabilities and replay Stubs use this form.
1154
- */
1155
- const defineValueCapability = (name, ops, lifecycle, release) => {
1156
- 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`);
1158
- const coordinated = !!lifecycle && typeof lifecycle === "object" && "coordinator" in lifecycle ? lifecycle : void 0;
1159
- if (coordinated && typeof coordinated.coordinator !== "function") invalidValue("A coordinator mapping must be a function");
1160
- if (lifecycle !== void 0 && !coordinated && !hasHooks(lifecycle)) invalidValue("A participant requires synchronous begin, commit and rollback hooks");
1161
- const hooks = coordinated ? void 0 : lifecycle;
1162
- const scopes = /* @__PURE__ */ new Map();
1163
- const scopeEffects = /* @__PURE__ */ new Map();
1164
- for (const [opName, op] of Object.entries(ops)) {
1165
- 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`);
1167
- if (op.labels !== void 0) {
1168
- 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
- if (op.labels.length && op.labels.length !== (op.args?.length ?? 0) - 1) invalidValue("labels must have one entry per argument after the first");
1170
- }
1171
- if (op.description !== void 0 && typeof op.description !== "string") invalidValue("description must be text");
1172
- if (op.examples !== void 0 && (!Array.isArray(op.examples) || [...op.examples].some((example) => typeof example !== "string"))) invalidValue("examples must be a list of text");
1173
- const metadata = op;
1174
- checkMetering(metadata);
1175
- if (metadata.segmentBound !== void 0 && typeof metadata.segmentBound !== "boolean") invalidValue("segmentBound must be Boolean");
1176
- if (metadata.segmentBound && (op.mode !== "immediate" || !lifecycle)) invalidValue("Segment-bound Operations require immediate mode and lifecycle hooks");
1177
- const scope = metadata.scope;
1178
- if (scope === void 0) continue;
1179
- if (op.mode !== "immediate" || !scope || typeof scope !== "object") invalidValue("Scopes require immediate Operations");
1180
- const scopeName = "opens" in scope ? scope.opens : scope.closes;
1181
- const bound = metadata.segmentBound === true;
1182
- if (scopeEffects.has(scopeName) && scopeEffects.get(scopeName) !== bound) invalidValue("All lifecycle Operations of a scope must agree on segmentBound");
1183
- scopeEffects.set(scopeName, bound);
1184
- const keys = Object.keys(scope).sort().join(",");
1185
- if (keys === "abandon,opens" && "opens" in scope) {
1186
- if (!scopeWord(scope.opens) || !scopeWord(scope.abandon)) invalidValue("Invalid scope name or abandonment Operation");
1187
- const previous = scopes.get(scope.opens);
1188
- if (previous && previous !== scope.abandon) invalidValue("Scope openers must agree on abandonment");
1189
- scopes.set(scope.opens, scope.abandon);
1190
- } else if (keys === "closes" && "closes" in scope) {
1191
- if (!scopeWord(scope.closes)) invalidValue("Invalid scope name");
1192
- } else invalidValue(`Invalid scope declaration for ${opName}`);
1193
- }
1194
- for (const [scopeName, abandon] of scopes) {
1195
- const op = ops[abandon];
1196
- if (!op || op.mode !== "immediate" || !op.scope || !("closes" in op.scope) || op.scope.closes !== scopeName || (op.args?.length ?? 0) !== 0 || op.result?.k !== "kind" || op.result.kind !== "nothing") invalidValue("Abandonment must close its scope immediately, take no arguments and return Nothing");
1197
- }
1198
- for (const op of Object.values(ops)) if (op.mode === "immediate" && op.scope && "closes" in op.scope && !scopes.has(op.scope.closes)) invalidValue("A closing scope has no opener");
1199
- const operations = new Map(Object.keys(ops).sort().map((op) => {
1200
- const declaration = ops[op];
1201
- const stored = declaration.mode === "immediate" && declaration.scope ? {
1202
- ...declaration,
1203
- scope: Object.freeze({ ...declaration.scope })
1204
- } : Object.isExtensible(declaration) ? declaration : { ...declaration };
1205
- if (!(valueForm in stored)) Object.defineProperty(stored, valueForm, {
1206
- value: true,
1207
- enumerable: true
1208
- });
1209
- return [op, stored];
1210
- }));
1211
- const def = {
1212
- name,
1213
- operations,
1214
- ...release ? { release } : {},
1215
- ...hooks ? { lifecycle: Object.freeze({
1216
- begin: hooks.begin,
1217
- commit: hooks.commit,
1218
- rollback: hooks.rollback
1219
- }) } : {},
1220
- ...coordinated ? { coordinator: (binding) => coordinated.coordinator(binding) } : {},
1221
- grant: (granted, binding) => {
1222
- const names = granted === "all" ? [...operations.keys()] : granted;
1223
- for (const op of names) if (!operations.has(op)) throw new HostError("invalid value", `${name} has no Operation ${op}`);
1224
- for (const name of names) {
1225
- const op = operations.get(name);
1226
- if (op.mode === "immediate" && op.scope && "opens" in op.scope && !names.includes(op.scope.abandon)) invalidValue("An opener requires its abandonment Operation in the Grant");
1227
- }
1228
- const coordinator = def.coordinator?.(binding);
1229
- if (def.coordinator && !hasHooks(coordinator)) invalidValue("A Segment Coordinator requires synchronous begin, commit and rollback hooks");
1230
- return {
1231
- capability: def,
1232
- binding,
1233
- ops: new Set(names),
1234
- ...coordinator ? { coordinator } : {}
1235
- };
1236
- }
1237
- };
1238
- return def;
1239
- };
1240
- /** A checked argument as the JS form its Shape names (#1420). */
1241
- const plainArg = (s, v) => {
1242
- switch (s?.k) {
1243
- case "kind":
1244
- switch (s.kind) {
1245
- case "nothing": return null;
1246
- case "boolean": return v.asBool();
1247
- case "number": return v.asDecimal();
1248
- case "text": return v.asText();
1249
- case "bytes": return v.asBytes();
1250
- case "instant": return v.asInstant();
1251
- }
1252
- return v;
1253
- case "object": {
1254
- const ref = v.asObjectRef();
1255
- return v.asObject() ?? invalidValue(`No Host Object ${ref.kind} ${ref.id}`);
1256
- }
1257
- case "optional": return v.kind === "nothing" ? null : plainArg(s.of, v);
1258
- }
1259
- return v;
1260
- };
1261
- const isHostObject = (r) => "value" in r && Value.isValue(r.value) && r.value.kind === "object";
1262
- /**
1263
- * A Host function's result as a Value. A JS form that doesn't match the
1264
- * Shape is passed on unchanged, so the Core's result check refuses it.
1265
- */
1266
- const resultValue = (s, r) => {
1267
- if (s === void 0 || Value.isValue(r)) return r;
1268
- switch (s.k) {
1269
- case "kind":
1270
- switch (s.kind) {
1271
- case "nothing": return r === null || r === void 0 ? nothing : r;
1272
- case "boolean": return typeof r === "boolean" ? bool(r) : r;
1273
- case "number": return isDecimal(r) ? dec(r.toString()) : typeof r === "bigint" ? num(r) : r;
1274
- case "text": return typeof r === "string" ? text(r) : r;
1275
- case "bytes": return Object.prototype.toString.call(r) === "[object Uint8Array]" ? bytes(r) : r;
1276
- case "instant": return typeof r === "bigint" ? instant(r) : r;
1277
- }
1278
- return r;
1279
- case "object": return r && typeof r === "object" && isHostObject(r) ? r.value : r;
1280
- case "optional": return r === null || r === void 0 ? nothing : resultValue(s.of, r);
1281
- }
1282
- return r;
1283
- };
1284
- /**
1285
- * Marks a defined Capability's Operations as already in Value form. It is an
1286
- * enumerable symbol, so it survives `{ ...op }` when a Host reuses one.
1287
- */
1288
- const valueForm = Symbol("value form");
1289
- /** The Core's Value form of an Operation whose Host function is typed. */
1290
- const valueOperation = (op) => {
1291
- if (!op || typeof op !== "object" || valueForm in op) return op;
1292
- const { args = [], result } = op;
1293
- const plain = (vs) => vs.map((v, i) => plainArg(args[i], v));
1294
- const answering = (call) => Object.create(call, { answer: { value: (r, lateCost) => call.answer(resultValue(result, r), lateCost) } });
1295
- const fn = op;
1296
- const adapted = { ...op };
1297
- if (typeof fn.do === "function") {
1298
- const run = fn.do;
1299
- adapted.do = (call, ...vs) => resultValue(result, run.call(op, call, ...plain(vs)));
1300
- }
1301
- if (typeof fn.fire === "function") {
1302
- const run = fn.fire;
1303
- adapted.fire = (call, ...vs) => run.call(op, call, ...plain(vs));
1304
- }
1305
- if (typeof fn.run === "function") {
1306
- const run = fn.run;
1307
- adapted.run = async (call, ...vs) => resultValue(result, await run.call(op, call, ...plain(vs)));
1308
- }
1309
- if (typeof fn.start === "function") {
1310
- const run = fn.start;
1311
- adapted.start = (call, ...vs) => run.call(op, answering(call), ...plain(vs));
1312
- }
1313
- return adapted;
1314
- };
1315
- const defineTyped = (name, ops, lifecycle, release) => defineValueCapability(name, Object.fromEntries(Object.entries(ops).map(([op, declaration]) => [op, valueOperation(declaration)])), lifecycle, release);
1316
- function defineCapability(...input) {
1317
- return input.length === 0 ? defineTyped : defineTyped(...input);
1318
- }
1319
- //#endregion
1320
- export { runTask as _, defineValueCapability as a, mismatch as c, shapeDiagnostics as d, validComputedMessageName as f, RESERVED as g, Lexer as h, defineCapability as i, pathValue as l, validStaticMessageName as m, acceptsArgumentCount as n, diagnosticRecord as o, validMessageSelector as p, decodeShape as r, expectedOf as s, LimitReached as t, shape as u };