@northtalk/ts 0.0.0-stage → 0.2.0

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