@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,728 @@
1
+
2
+ import { E as isDecimal, F as num, H as requireValue, K as text, M as map, Ot as integerOf, P as nothing, V as record, _ as dec, d as bytes, dt as characterBoundaries, ht as normalizeNFC, i as ScriptError, k as listValues, kt as isInteger, l as Value, o as invalidValue, t as HostError, u as bool, v as decimalParts } from "./errors-LYJZ_c8h.js";
3
+ import { a as defineValueCapability, f as validComputedMessageName, s as expectedOf, u as shape } from "./capabilities-CH0FkRMq.js";
4
+ import { i as ScriptError$1, lt as errorMessages } from "./base64-DORMd3Hv.js";
5
+ import { r as registerStandardChecks } from "./encoding-nlrpj-Pb.js";
6
+ import { c as fixed, s as costOf } from "./store-capability-OZp4hXmj.js";
7
+ //#region src/talk.ts
8
+ const blank = /^[\t ]*$/;
9
+ const commonPrefix = (a, b) => {
10
+ let i = 0;
11
+ while (i < a.length && i < b.length && a[i] === b[i]) i++;
12
+ return a.slice(0, i);
13
+ };
14
+ /**
15
+ * Dedents NorthTalk source; rejects JS interpolation.
16
+ *
17
+ * Write NorthTalk's own interpolation as `\${…}` and its backticks as `` \` ``.
18
+ * Pass values as Request arguments instead of splicing them into source. The
19
+ * longest whitespace prefix shared by every non-blank line is removed, compared
20
+ * exactly, so tabs and spaces never match each other.
21
+ */
22
+ const talk = (strings, ...values) => {
23
+ if (values.length > 0) throw new TypeError("talk source cannot interpolate JS values; write NorthTalk interpolation as \\${…} or pass the value as a Request argument");
24
+ const lines = strings.raw[0].replaceAll(/\\([\S\s])/g, (escape, c) => c === "`" || c === "$" ? c : escape).split("\n");
25
+ if (lines.length > 1 && blank.test(lines[0])) lines.shift();
26
+ if (lines.length > 1 && blank.test(lines.at(-1))) lines.pop();
27
+ let margin;
28
+ for (const line of lines) {
29
+ if (blank.test(line)) continue;
30
+ const indent = /^[\t ]*/.exec(line)[0];
31
+ margin = margin === void 0 ? indent : commonPrefix(margin, indent);
32
+ }
33
+ return lines.map((line) => blank.test(line) ? "" : line.slice(margin.length)).join("\n");
34
+ };
35
+ //#endregion
36
+ //#region src/plain.ts
37
+ const tagOf = (input) => Object.prototype.toString.call(input);
38
+ const isPlainObject = (input) => [null, Object.prototype].includes(Object.getPrototypeOf(input));
39
+ /**
40
+ * Plain JS data to a Value by the named constructors (ADR 0119). Anything
41
+ * the table doesn't name, and cyclic data, throws `invalid value`.
42
+ */
43
+ const toValue = (plain, options = {}) => {
44
+ const decimalNumbers = options.numbers === "decimal";
45
+ const open = /* @__PURE__ */ new Set();
46
+ const convert = (input) => {
47
+ switch (typeof input) {
48
+ case "undefined": return nothing;
49
+ case "boolean": return bool(input);
50
+ case "string": return text(input);
51
+ case "bigint": return num(input);
52
+ case "number": return decimalNumbers ? num(input) : invalidValue("A JS number needs { numbers: 'decimal' }, or num() or dec()");
53
+ case "object": break;
54
+ default: return invalidValue(`Not plain data: ${typeof input}`);
55
+ }
56
+ if (input === null) return nothing;
57
+ if (Value.isValue(input)) return input;
58
+ if (isDecimal(input)) return dec(input.toString());
59
+ if (tagOf(input) === "[object Uint8Array]") return bytes(input);
60
+ if (open.has(input)) return invalidValue("Cyclic data has no Value");
61
+ open.add(input);
62
+ let result;
63
+ if (Array.isArray(input)) {
64
+ const items = [];
65
+ for (let i = 0; i < input.length; i++) items.push(convert(input[i]));
66
+ result = listValues(items);
67
+ } else if (tagOf(input) === "[object Map]") result = map(Array.from(input, ([k, v]) => {
68
+ if (typeof k !== "string") invalidValue("Map keys must be text");
69
+ return [k, convert(v)];
70
+ }));
71
+ else if (isPlainObject(input)) {
72
+ const fields = Object.create(null);
73
+ for (const [k, v] of Object.entries(input)) Object.defineProperty(fields, k, {
74
+ value: convert(v),
75
+ enumerable: true
76
+ });
77
+ result = record(fields);
78
+ } else return invalidValue(`Not plain data: ${input.constructor?.name ?? "object"}`);
79
+ open.delete(input);
80
+ return result;
81
+ };
82
+ return convert(plain);
83
+ };
84
+ /** A Value as plain JS data (ADR 0119); kinds with no JS form stay Values. */
85
+ const fromValue = (v, options = {}) => {
86
+ if (!Value.isValue(v)) invalidValue("Expected a Value from a named constructor");
87
+ const convert = (value) => {
88
+ switch (value.kind) {
89
+ case "nothing": return null;
90
+ case "boolean": return value.asBool();
91
+ case "text": return value.asText();
92
+ case "number": {
93
+ const d = value.asDecimal();
94
+ return options.numbers === "string" ? d.toString() : d;
95
+ }
96
+ case "bytes": return value.asBytes();
97
+ case "list": {
98
+ const items = [];
99
+ for (let i = 1; i <= value.length; i++) items.push(convert(value.index(i)));
100
+ return items;
101
+ }
102
+ case "map": {
103
+ if (options.maps === "map") return new Map(value.entries().map(([k, x]) => [k, convert(x)]));
104
+ const fields = {};
105
+ for (const [k, x] of value.entries()) Object.defineProperty(fields, k, {
106
+ value: convert(x),
107
+ enumerable: true,
108
+ writable: true,
109
+ configurable: true
110
+ });
111
+ return fields;
112
+ }
113
+ default: return value;
114
+ }
115
+ };
116
+ return convert(v);
117
+ };
118
+ //#endregion
119
+ //#region src/json.ts
120
+ var JsonReader = class {
121
+ source;
122
+ i = 0;
123
+ constructor(source) {
124
+ this.source = source;
125
+ }
126
+ fail(at = this.i) {
127
+ const scalar = Array.from(this.source, (c) => /^[\uD800-\uDFFF]$/.test(c) ? "�" : c).join("");
128
+ const offset = characterBoundaries(scalar).filter((i) => i <= at).length;
129
+ throw new ScriptError("can't decode", errorMessages["can't decode"].replace("{format}", text("json").toString()).replace("{offset}", String(offset)), map([["format", text("json")], ["offset", num(offset)]]));
130
+ }
131
+ space() {
132
+ while (/[\t\n\r ]/.test(this.source[this.i] ?? "") && this.i < this.source.length) this.i++;
133
+ }
134
+ eat(c) {
135
+ if (this.source[this.i] !== c) this.fail();
136
+ this.i++;
137
+ }
138
+ hex4() {
139
+ let n = 0;
140
+ for (let k = 0; k < 4; k++) {
141
+ const c = this.source[this.i];
142
+ if (c === void 0 || !/[\dA-Fa-f]/.test(c)) this.fail();
143
+ n = n * 16 + Number.parseInt(c, 16);
144
+ this.i++;
145
+ }
146
+ return n;
147
+ }
148
+ string() {
149
+ this.eat("\"");
150
+ const parts = [];
151
+ const escapes = {
152
+ "\"": "\"",
153
+ "\\": "\\",
154
+ "/": "/",
155
+ b: "\b",
156
+ f: "\f",
157
+ n: "\n",
158
+ r: "\r",
159
+ t: " "
160
+ };
161
+ while (this.i < this.source.length) {
162
+ const start = this.i;
163
+ const cp = this.source.codePointAt(this.i);
164
+ const c = String.fromCodePoint(cp);
165
+ if (c === "\"") {
166
+ this.i++;
167
+ return normalizeNFC(parts.join(""));
168
+ }
169
+ if (cp < 32 || cp >= 55296 && cp <= 57343) this.fail();
170
+ this.i += c.length;
171
+ if (c !== "\\") {
172
+ parts.push(c);
173
+ continue;
174
+ }
175
+ if (this.i === this.source.length) this.fail();
176
+ const escape = this.source[this.i++];
177
+ if (Object.hasOwn(escapes, escape)) {
178
+ parts.push(escapes[escape]);
179
+ continue;
180
+ }
181
+ if (escape !== "u") this.fail(this.i - 1);
182
+ let u = this.hex4();
183
+ if (u >= 56320 && u <= 57343) this.fail(start);
184
+ if (u >= 55296 && u <= 56319) {
185
+ const lowStart = this.i;
186
+ if (this.source[this.i] !== "\\" || this.source[this.i + 1] !== "u") this.fail();
187
+ this.i += 2;
188
+ const low = this.hex4();
189
+ if (low < 56320 || low > 57343) this.fail(lowStart);
190
+ u = 65536 + (u - 55296) * 1024 + low - 56320;
191
+ }
192
+ parts.push(String.fromCodePoint(u));
193
+ }
194
+ return this.fail();
195
+ }
196
+ digits() {
197
+ const start = this.i;
198
+ while (this.i < this.source.length && /\d/.test(this.source[this.i])) this.i++;
199
+ return this.source.slice(start, this.i);
200
+ }
201
+ number() {
202
+ const start = this.i;
203
+ let sign = "";
204
+ if (this.source[this.i] === "-") {
205
+ sign = "-";
206
+ this.i++;
207
+ }
208
+ if (!/\d/.test(this.source[this.i] ?? "")) this.fail();
209
+ let whole;
210
+ if (this.source[this.i] === "0") {
211
+ whole = "0";
212
+ this.i++;
213
+ } else whole = this.digits();
214
+ let fraction = "";
215
+ if (this.source[this.i] === ".") {
216
+ this.i++;
217
+ fraction = this.digits();
218
+ if (!fraction) this.fail();
219
+ }
220
+ let exponent = "", negativeExponent = false;
221
+ if (/[Ee]/.test(this.source[this.i] ?? "")) {
222
+ this.i++;
223
+ if (/[+-]/.test(this.source[this.i] ?? "")) negativeExponent = this.source[this.i++] === "-";
224
+ exponent = this.digits();
225
+ if (!exponent) this.fail();
226
+ }
227
+ const coefficient = whole + fraction;
228
+ const significant = coefficient.replace(/^0+/, "");
229
+ exponent = exponent.replace(/^0+/, "");
230
+ if (exponent.length > 9) {
231
+ if (!significant && !negativeExponent) return num(0);
232
+ this.fail(start);
233
+ }
234
+ const q = (negativeExponent ? -1 : 1) * Number(exponent) - fraction.length;
235
+ if (!significant && q >= 0) return num(0);
236
+ if (significant.length > 34) this.fail(start);
237
+ if (q >= 0) {
238
+ if (significant.length + q > 34) this.fail(start);
239
+ return dec(sign + significant + "0".repeat(q));
240
+ }
241
+ if (-q > 6176) this.fail(start);
242
+ const digits = coefficient.padStart(-q + 1, "0");
243
+ return dec(sign + digits.slice(0, q) + "." + digits.slice(q));
244
+ }
245
+ atom() {
246
+ const c = this.source[this.i];
247
+ if (c === "\"") return text(this.string());
248
+ if (c === "-" || /\d/.test(c ?? "")) return this.number();
249
+ for (const [literal, value] of [
250
+ ["true", bool(true)],
251
+ ["false", bool(false)],
252
+ ["null", nothing]
253
+ ]) {
254
+ if (c !== literal[0]) continue;
255
+ for (const ch of literal) this.eat(ch);
256
+ return value;
257
+ }
258
+ return this.fail();
259
+ }
260
+ read() {
261
+ const frames = [];
262
+ let value;
263
+ const key = (frame) => {
264
+ this.space();
265
+ const start = this.i;
266
+ frame.key = this.string();
267
+ if (frame.keys.has(frame.key)) this.fail(start);
268
+ frame.keys.add(frame.key);
269
+ this.space();
270
+ this.eat(":");
271
+ };
272
+ for (;;) {
273
+ if (!value) {
274
+ this.space();
275
+ const c = this.source[this.i];
276
+ if (c === "[" || c === "{") {
277
+ this.i++;
278
+ this.space();
279
+ const frame = c === "[" ? {
280
+ kind: "list",
281
+ values: []
282
+ } : {
283
+ kind: "map",
284
+ pairs: [],
285
+ keys: /* @__PURE__ */ new Set(),
286
+ key: ""
287
+ };
288
+ if (this.source[this.i] === (c === "[" ? "]" : "}")) {
289
+ this.i++;
290
+ value = c === "[" ? listValues([]) : map([]);
291
+ } else {
292
+ if (frame.kind === "map") key(frame);
293
+ frames.push(frame);
294
+ continue;
295
+ }
296
+ } else value = this.atom();
297
+ }
298
+ const parent = frames.at(-1);
299
+ this.space();
300
+ if (!parent) {
301
+ if (this.i !== this.source.length) this.fail();
302
+ return value;
303
+ }
304
+ if (parent.kind === "list") parent.values.push(value);
305
+ else parent.pairs.push([parent.key, value]);
306
+ if (this.source[this.i] === ",") {
307
+ this.i++;
308
+ if (parent.kind === "map") key(parent);
309
+ value = void 0;
310
+ } else {
311
+ this.eat(parent.kind === "list" ? "]" : "}");
312
+ frames.pop();
313
+ value = parent.kind === "list" ? listValues(parent.values) : map(parent.pairs);
314
+ }
315
+ }
316
+ }
317
+ };
318
+ /** Read exact decimal digits, NFC strings and insertion-ordered maps. */
319
+ const decodeJson = (source) => {
320
+ if (typeof source !== "string") invalidValue("JSON must be text");
321
+ return new JsonReader(source).read();
322
+ };
323
+ const quoteJson = (s) => {
324
+ const short = {
325
+ "\b": "b",
326
+ " ": "t",
327
+ "\n": "n",
328
+ "\f": "f",
329
+ "\r": "r"
330
+ };
331
+ return "\"" + s.replaceAll(/[\u0000-\u001f"\\]/g, (c) => c === "\"" || c === "\\" ? "\\" + c : Object.hasOwn(short, c) ? "\\" + short[c] : String.raw`\u00` + c.charCodeAt(0).toString(16).padStart(2, "0")) + "\"";
332
+ };
333
+ /** Compact JSON, with canonical numbers and chapter 7's string escapes. */
334
+ const encodeJson = (value) => {
335
+ requireValue(value);
336
+ const pending = [{
337
+ value,
338
+ path: void 0
339
+ }];
340
+ const output = [];
341
+ while (pending.length) {
342
+ const next = pending.pop();
343
+ if (typeof next === "string") {
344
+ output.push(next);
345
+ continue;
346
+ }
347
+ const { value: v, path } = next;
348
+ switch (v.kind) {
349
+ case "nothing":
350
+ output.push("null");
351
+ break;
352
+ case "boolean":
353
+ case "number":
354
+ output.push(v.toString());
355
+ break;
356
+ case "text":
357
+ output.push(quoteJson(v.asText()));
358
+ break;
359
+ case "list":
360
+ output.push("[");
361
+ pending.push("]");
362
+ for (let i = v.length; i >= 1; i--) {
363
+ if (i < v.length) pending.push(",");
364
+ pending.push({
365
+ value: v.index(i),
366
+ path: {
367
+ key: i,
368
+ parent: path
369
+ }
370
+ });
371
+ }
372
+ break;
373
+ case "map": {
374
+ output.push("{");
375
+ pending.push("}");
376
+ const entries = v.entries();
377
+ for (let i = entries.length - 1; i >= 0; i--) {
378
+ const [k, child] = entries[i];
379
+ if (i < entries.length - 1) pending.push(",");
380
+ pending.push({
381
+ value: child,
382
+ path: {
383
+ key: k,
384
+ parent: path
385
+ }
386
+ }, quoteJson(k) + ":");
387
+ }
388
+ break;
389
+ }
390
+ default: {
391
+ const keys = [];
392
+ for (let p = path; p; p = p.parent) keys.push(typeof p.key === "string" ? text(p.key) : num(p.key));
393
+ throw new ScriptError("not encodable", errorMessages["not encodable"].replace("{kind}", text(v.kind).toString()), map([["kind", text(v.kind)], ["path", listValues(keys.reverse())]]));
394
+ }
395
+ }
396
+ }
397
+ return output.join("");
398
+ };
399
+ //#endregion
400
+ //#region src/sqlite-capability.ts
401
+ const MAX_WHOLE = Number.MAX_SAFE_INTEGER;
402
+ const isWhole = (n) => Number.isSafeInteger(n) && n >= 0;
403
+ const INT64_MIN = -(2n ** 63n);
404
+ const INT64_MAX = 2n ** 63n - 1n;
405
+ const paramsShape = shape.any;
406
+ const maxShape = shape.optional(shape.number);
407
+ const sqlShape = shape.oneOf(shape.nothing, shape.number, shape.text, shape.bytes, shape.bool);
408
+ const SQL_KINDS = /* @__PURE__ */ new Set([
409
+ "nothing",
410
+ "number",
411
+ "text",
412
+ "bytes",
413
+ "boolean"
414
+ ]);
415
+ const CONSTRAINTS = [
416
+ "unique",
417
+ "primary key",
418
+ "not null",
419
+ "check",
420
+ "foreign key",
421
+ "datatype",
422
+ "trigger",
423
+ "other"
424
+ ];
425
+ const isText = (data, field) => data.get(field).kind === "text";
426
+ const errorFields = {
427
+ sql: (data) => isText(data, "reason"),
428
+ constraint: (data) => CONSTRAINTS.includes(data.get("kind").asText() ?? ""),
429
+ "sqlite busy": () => true,
430
+ "not read-only": () => true,
431
+ "too many rows": (data) => data.get("max").kind === "number",
432
+ unrepresentable: (data) => isText(data, "column")
433
+ };
434
+ const errors = (...codes) => codes.map((code) => ({ code }));
435
+ const coreFailure = (code, field, value) => new ScriptError(code, "", map([[field, text(value)]]));
436
+ const checkBinding = (binding) => {
437
+ if (!binding || typeof binding !== "object" || typeof binding.database !== "string" || !isWhole(binding.maxRows) || binding.tables !== void 0 && (!Array.isArray(binding.tables) || !binding.tables.every((t) => typeof t === "string"))) throw new HostError("invalid value", "A sqlite binding is {database, tables, maxRows}");
438
+ };
439
+ const rowsAllowed = (max, binding) => {
440
+ if (max === void 0 || max.kind === "nothing") return binding.maxRows;
441
+ const [whole, fraction = ""] = max.asDecimal().toString().split(".");
442
+ if (whole.startsWith("-") || /[1-9]/.test(fraction) || BigInt(whole) > BigInt(binding.maxRows)) throw new ScriptError$1("out of range", [["field", text("max")], ["value", max]], true);
443
+ return Number(whole);
444
+ };
445
+ const sqlValueOf = (v) => {
446
+ switch (v.kind) {
447
+ case "nothing": return null;
448
+ case "boolean": return v.asBool() ? 1n : 0n;
449
+ case "text": return v.asText();
450
+ case "bytes": return v.asBytes();
451
+ default: {
452
+ const canonical = v.asDecimal().toString();
453
+ if (!canonical.includes(".")) {
454
+ const n = BigInt(canonical);
455
+ if (n >= INT64_MIN && n <= INT64_MAX) return n;
456
+ }
457
+ return Number(canonical);
458
+ }
459
+ }
460
+ };
461
+ const paramsOf = (params) => params.kind === "list" ? Array.from({ length: params.length }, (_, i) => sqlValueOf(params.index(i + 1))) : new Map(params.entries().map(([k, v]) => [k, sqlValueOf(v)]));
462
+ const checkParams = (params, named) => {
463
+ const wrongKind = (expected, item, path) => new ScriptError$1("wrong kind", [
464
+ ["expected", text(expected)],
465
+ ["got", text(item.kind)],
466
+ ["value", item],
467
+ ...named,
468
+ ["argument", dec("2")],
469
+ ...path
470
+ ], true);
471
+ if (params.kind !== "list" && params.kind !== "map") throw wrongKind("list or map", params, []);
472
+ const items = params.kind === "list" ? Array.from({ length: params.length }, (_, i) => [i + 1, params.index(i + 1)]) : params.entries();
473
+ for (const [at, item] of items) if (!SQL_KINDS.has(item.kind)) throw wrongKind(expectedOf(sqlShape), item, [["path", listValues([typeof at === "number" ? dec(String(at)) : text(at)])]]);
474
+ };
475
+ const checkForm = (result, max, changes) => {
476
+ if (!(!!result && typeof result === "object" && Array.isArray(result.columns) && result.columns.every((c) => typeof c === "string") && Array.isArray(result.rows) && result.rows.length <= max && result.rows.every((row) => Array.isArray(row) && row.length === result.columns.length) && (!changes || isWhole(result.changes)))) throw new Error("A sqlite implementation gave a malformed result");
477
+ };
478
+ const valueOf = (v, column) => {
479
+ const unrepresentable = () => coreFailure("unrepresentable", "column", column);
480
+ if (v === null) return nothing;
481
+ if (typeof v === "bigint") {
482
+ if (v < INT64_MIN || v > INT64_MAX) throw new Error("A sqlite INTEGER must fit 64 bits");
483
+ return dec(v.toString());
484
+ }
485
+ if (typeof v === "number") try {
486
+ return num(v);
487
+ } catch (error) {
488
+ if (error instanceof HostError) throw unrepresentable();
489
+ throw error;
490
+ }
491
+ if (typeof v === "string") {
492
+ if (/[\uD800-\uDFFF]/u.test(v)) throw unrepresentable();
493
+ return text(v);
494
+ }
495
+ if (ArrayBuffer.isView(v) && Object.prototype.toString.call(v) === "[object Uint8Array]") return bytes(v);
496
+ throw new Error("A sqlite value must be NULL, INTEGER, REAL, TEXT or BLOB");
497
+ };
498
+ const rowsOf = (result) => {
499
+ const columns = result.columns.map((c) => c.normalize("NFC"));
500
+ const seen = /* @__PURE__ */ new Set();
501
+ for (const column of columns) {
502
+ if (seen.has(column)) throw coreFailure("sql", "reason", `duplicate column ${column}`);
503
+ seen.add(column);
504
+ }
505
+ return listValues(result.rows.map((row) => map(columns.map((column, i) => [column, valueOf(row[i], column)]))));
506
+ };
507
+ /** Optional for Hosts. perRow is whole Fuel charged per row of max. */
508
+ const sqliteCapability = (impl, costs, perRow) => {
509
+ for (const name of [
510
+ "coordinator",
511
+ "query",
512
+ "change",
513
+ "begin",
514
+ "commit",
515
+ "rollback"
516
+ ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `sqlite needs ${name}`);
517
+ if (!isWhole(perRow)) throw new HostError("invalid value", "The per-row cost must be a whole number");
518
+ const chargeRows = (call, max) => call.charge(Math.min(max * perRow, MAX_WHOLE));
519
+ const statement = (run) => (call, ...args) => {
520
+ const max = rowsAllowed(args[2], call.binding);
521
+ chargeRows(call, max);
522
+ return run(call, args[0].asText(), paramsOf(args[1]), max);
523
+ };
524
+ const statementArgs = [
525
+ shape.text,
526
+ paramsShape,
527
+ maxShape
528
+ ];
529
+ const scoped = (name, scope, codes) => ({
530
+ mode: "immediate",
531
+ args: [],
532
+ result: shape.nothing,
533
+ errors: errors(...codes),
534
+ cost: costOf(costs, name),
535
+ segmentBound: true,
536
+ scope,
537
+ do: (call) => {
538
+ impl[name](call);
539
+ return nothing;
540
+ }
541
+ });
542
+ const operations = {
543
+ query: {
544
+ mode: "immediate",
545
+ args: statementArgs,
546
+ result: shape.listOf(shape.any),
547
+ errors: errors("sql", "not read-only", "too many rows", "unrepresentable"),
548
+ cost: costOf(costs, "query"),
549
+ do: statement((call, sql, params, max) => {
550
+ const result = impl.query(call, sql, params, max);
551
+ checkForm(result, max, false);
552
+ return rowsOf(result);
553
+ })
554
+ },
555
+ change: {
556
+ mode: "immediate",
557
+ args: statementArgs,
558
+ result: shape.map({
559
+ changes: shape.number,
560
+ rows: shape.listOf(shape.any)
561
+ }),
562
+ errors: errors("sql", "constraint", "sqlite busy", "too many rows", "unrepresentable"),
563
+ cost: costOf(costs, "change"),
564
+ segmentBound: true,
565
+ do: statement((call, sql, params, max) => {
566
+ const result = impl.change(call, sql, params, max);
567
+ checkForm(result, max, true);
568
+ const rows = rowsOf(result);
569
+ return map([["changes", dec(String(result.changes))], ["rows", rows]]);
570
+ })
571
+ },
572
+ begin: scoped("begin", {
573
+ opens: "transaction",
574
+ abandon: "rollback"
575
+ }, ["sqlite busy"]),
576
+ commit: scoped("commit", { closes: "transaction" }, []),
577
+ rollback: scoped("rollback", { closes: "transaction" }, [])
578
+ };
579
+ const capability = defineValueCapability("sqlite", operations, { coordinator: (binding) => {
580
+ checkBinding(binding);
581
+ return impl.coordinator(binding.database);
582
+ } });
583
+ for (const [name, op] of capability.operations) registerStandardChecks(op, {
584
+ error: (code, data) => Boolean(op.errors?.some((e) => e.code === code) && errorFields[code]?.(data)),
585
+ ...name === "query" || name === "change" ? { arguments: (args, binding, named) => {
586
+ rowsAllowed(args[2], binding);
587
+ checkParams(args[1], named);
588
+ } } : {}
589
+ });
590
+ return fixed(capability);
591
+ };
592
+ //#endregion
593
+ //#region src/http-capability.ts
594
+ /** A `serve` waits as long as `console`'s `read`. */
595
+ const HTTP_MAX_PENDING_MS = 2147483647;
596
+ const exchangeShape = {
597
+ k: "object",
598
+ kind: "httpExchange"
599
+ };
600
+ const optional = (s) => ({
601
+ optional: true,
602
+ shape: s
603
+ });
604
+ const responseShape = shape.map({
605
+ status: optional(shape.number),
606
+ headers: optional(shape.openMap({})),
607
+ body: optional(shape.oneOf(shape.text, shape.bytes)),
608
+ json: optional(shape.any)
609
+ });
610
+ const optionsShape = shape.optional(shape.map({
611
+ host: optional(shape.text),
612
+ port: optional(shape.number)
613
+ }));
614
+ const addressShape = shape.map({
615
+ host: shape.text,
616
+ port: shape.number
617
+ });
618
+ const whole = (value) => {
619
+ const parts = value?.kind === "number" ? decimalParts(value.asDecimal()) : void 0;
620
+ return parts && isInteger(parts) ? integerOf(parts) : void 0;
621
+ };
622
+ const given = (m, key) => m.entries().find(([k]) => k === key)?.[1];
623
+ const effectiveMessage = (args) => args[2]?.asText() ?? "httpRequest";
624
+ const invalid = (code, field) => new ScriptError$1(code, [["field", text(field)]], true);
625
+ const checkServe = (args, serving) => {
626
+ if (args[0].asText() === "") throw invalid("invalid serve", "name");
627
+ if (!serving) return;
628
+ if (!args[1].asText().startsWith("/")) throw invalid("invalid serve", "prefix");
629
+ const message = effectiveMessage(args);
630
+ if (message.includes(":") || !validComputedMessageName(message, 1)) throw invalid("invalid serve", "message");
631
+ };
632
+ const checkResponse = (response) => {
633
+ const status = given(response, "status");
634
+ if (status) {
635
+ const n = whole(status);
636
+ if (n === void 0 || n < 100n || n > 599n) throw invalid("invalid response", "status");
637
+ }
638
+ const headers = given(response, "headers");
639
+ if (headers?.kind === "map") {
640
+ for (const [, value] of headers.entries()) if (!(value.kind === "text" || value.kind === "list" && Array.from({ length: value.length }, (_, i) => value.index(i + 1).kind).every((kind) => kind === "text"))) throw invalid("invalid response", "headers");
641
+ }
642
+ const json = given(response, "json");
643
+ if (json) {
644
+ if (given(response, "body")) throw invalid("invalid response", "json");
645
+ jsonText(json);
646
+ }
647
+ };
648
+ const jsonText = (json) => {
649
+ try {
650
+ return encodeJson(json);
651
+ } catch {
652
+ throw invalid("invalid response", "json");
653
+ }
654
+ };
655
+ const resolvedResponse = (response) => {
656
+ if (!given(response, "json")) return response;
657
+ return map(response.entries().map(([k, v]) => [k, k === "json" ? text(jsonText(v)) : v]));
658
+ };
659
+ /** Optional for Hosts. The binding is the Host's own description of the addresses a Grant may listen on. */
660
+ const httpCapability = (impl, costs) => {
661
+ for (const name of [
662
+ "serve",
663
+ "unserve",
664
+ "respond"
665
+ ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Http needs ${name}`);
666
+ const operations = {
667
+ serve: {
668
+ mode: "suspending",
669
+ args: [
670
+ shape.text,
671
+ shape.text,
672
+ shape.optional(shape.text),
673
+ optionsShape
674
+ ],
675
+ result: addressShape,
676
+ errors: [{ code: "address in use" }, { code: "bad address" }],
677
+ maxPendingMs: HTTP_MAX_PENDING_MS,
678
+ cost: costOf(costs, "serve"),
679
+ start: (call, ...args) => impl.serve(call, args[0].asText(), args[1].asText(), effectiveMessage(args), args[3]?.kind === "map" ? args[3] : map([]))
680
+ },
681
+ unserve: {
682
+ mode: "immediate",
683
+ args: [shape.text],
684
+ result: shape.nothing,
685
+ errors: [],
686
+ cost: costOf(costs, "unserve"),
687
+ do: (call, name) => {
688
+ impl.unserve(call, name.asText());
689
+ return nothing;
690
+ }
691
+ },
692
+ respond: {
693
+ mode: "immediate",
694
+ args: [exchangeShape, responseShape],
695
+ result: shape.nothing,
696
+ errors: [
697
+ { code: "already responded" },
698
+ { code: "exchange closed" },
699
+ { code: "not owner" }
700
+ ],
701
+ cost: costOf(costs, "respond"),
702
+ do: (call, exchange, response) => {
703
+ impl.respond(call, exchange.asObject(), resolvedResponse(response));
704
+ return nothing;
705
+ }
706
+ }
707
+ };
708
+ const hostErrors = {
709
+ serve: ["address in use", "bad address"],
710
+ unserve: [],
711
+ respond: [
712
+ "already responded",
713
+ "exchange closed",
714
+ "not owner"
715
+ ]
716
+ };
717
+ for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
718
+ error: (code) => hostErrors[name].includes(code),
719
+ arguments: (args) => {
720
+ if (name === "respond") checkResponse(args[1]);
721
+ else checkServe(args, name === "serve");
722
+ },
723
+ ...name === "serve" ? { result: (answer) => answer.kind === "map" && whole(answer.get("port")) !== void 0 } : {}
724
+ });
725
+ return fixed(defineValueCapability("http", operations));
726
+ };
727
+ //#endregion
728
+ export { fromValue as a, encodeJson as i, sqliteCapability as n, toValue as o, decodeJson as r, talk as s, httpCapability as t };