@northtalk/ts 0.5.0 → 0.6.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 (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-C4ZiXVjv.d.ts} +1 -1
  4. package/{checker-DMI4LiRm.js → checker-CUhn2XaM.js} +4 -4
  5. package/{core-D_9OuTRE.d.ts → core-egHbNmve.d.ts} +1 -1
  6. package/{debug-nN5tQ_p4.d.ts → debug--Of4MSLw.d.ts} +35 -11
  7. package/debug.d.ts +1 -1
  8. package/debug.js +1 -1
  9. package/{driver-Bf-7Roq6.d.ts → driver-BIm1mL77.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-DbDcopGM.d.ts} +2 -2
  15. package/{errors-BKJES3Zu.js → errors-D11zizZg.js} +1580 -1481
  16. package/{group-Bz2wh72R.js → group-BpzTo0k4.js} +84 -40
  17. package/http-fetch-DFwVIOQg.js +517 -0
  18. package/http.d.ts +39 -2
  19. package/http.js +190 -7
  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-DiS9rUcn.d.ts +741 -0
  24. package/lean-aCvN6y52.js +47 -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-mpivREn-.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-DYq_YvaQ.d.ts} +5 -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-L90Hoa97.d.ts → readers-8WCimMop.d.ts} +1 -1
  38. package/{readers-B5e5bBrY.js → readers-CsvlahLi.js} +2 -2
  39. package/{request-pump-binary-BjnyqXV5.js → request-pump-binary-oqjWFqZA.js} +5 -4
  40. package/{router-CBuMIl6i.d.ts → router-BQsO8aPV.d.ts} +2 -2
  41. package/{router-BCHEfs4x.js → router-BZ-aYeXA.js} +4 -4
  42. package/session.d.ts +2 -2
  43. package/session.js +55 -16
  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 +8 -6
  69. package/wasm.js +19 -15
  70. package/capabilities-Bi5Qm6Fr.js +0 -1320
package/index.js CHANGED
@@ -1,52 +1,39 @@
1
1
 
2
- import { G as record, H as quantity, Kt as formatInstant, L as nothing, N as map, Q as text, R as num, T as instant, W as range, Yt as nowMicros, Zt as parseInstant, c as Decimal, d as bytes, dt as builtins, gt as units, i as ScriptError, k as list, l as Value, m as civilDate, n as LoadError, pt as grammar, r as MailboxFull, t as HostError, u as bool, un as unicodeVersion, v as dec } from "./errors-BKJES3Zu.js";
3
- import { t as defineObjectKind } from "./objects-BC4fS0vq.js";
4
- import { h as Lexer, i as defineCapability, p as validMessageSelector, t as LimitReached, u as shape } from "./capabilities-Bi5Qm6Fr.js";
5
- import { a as syntaxText, c as parseSource, i as syntaxSelector, l as parseSourceRecovering, o as ParseError, p as declarationStart, r as checkSyntax, s as parseEntry, t as checkSource, v as kindNames } from "./checker-DMI4LiRm.js";
6
- import { W as waitUs, ft as costModel, mt as languageVersion, r as NotImplementedError, tt as disassemble, u as canConvert } from "./base64-Dtqaz_0A.js";
7
- import { S as lowerTree, _ as deliver, b as compileSource, c as codeIdentity, d as stdlibSources, f as Run, g as defaultLimits, h as callFunction, i as restore, l as compileLibrary, m as UnitLoadError, n as TsScript, p as Script, r as newGroup, s as stateFingerprint, t as TsGroup, v as loadScript, x as exportsOf, y as LoweringError } from "./group-Bz2wh72R.js";
8
- import { n as exportManifest } from "./manifest-Dw-8Unmf.js";
9
- import { c as readDisplay, r as decodeValue } from "./readers-B5e5bBrY.js";
10
- import { t as encodeValue } from "./encoding-C3Q7pIC9.js";
11
- import { a as sqliteCapability, c as fromValue, i as httpCapability, l as toValue, n as createGroup$1, o as decodeJson, r as handlersOf, s as encodeJson, t as inlineGrants, u as talk } from "./inline-grants-Cx0Z9XAt.js";
12
- import { n as localeCapability, t as userCapability } from "./user-capability-5-IvCeZI.js";
13
- import { a as clockCapability, i as calendarCapability, l as timerCapability, o as consoleCapability, r as storeCapability, t as add } from "./store-capability-BxXgiRM7.js";
14
- //#region src/versions.ts
15
- const coreVersions = Object.freeze({
16
- language: languageVersion,
17
- costModel: String(costModel.version),
18
- unicode: unicodeVersion,
19
- core: "ts/0.5.0",
20
- saveFormat: String(1)
21
- });
2
+ import { text as text$1 } from "./stdlib/text.js";
3
+ import { bytes as bytes$1 } from "./stdlib/bytes.js";
4
+ import { date } from "./stdlib/date.js";
5
+ import { json } from "./stdlib/json.js";
6
+ import { list as list$1 } from "./stdlib/list.js";
7
+ import { map as map$1 } from "./stdlib/map.js";
8
+ import { units as units$1 } from "./stdlib/units.js";
9
+ import { Bt as formatInstant, G as record, Gt as parseInstant, H as quantity, L as nothing, N as map, Q as text, R as num, T as instant, Ut as nowMicros, W as range, an as builtins, c as Decimal, d as bytes, i as ScriptError, k as list, l as Value, m as civilDate, n as LoadError, r as MailboxFull, sn as grammar, t as HostError, u as bool, un as units, v as dec } from "./errors-D11zizZg.js";
10
+ import { S as registerStdlib, _ as loadScript, b as exportsOf, c as codeIdentity, d as Run, f as Script, g as deliver, h as defaultLimits, i as restore, l as compileLibrary, m as callFunction, n as TsScript, p as UnitLoadError, r as newGroup, t as TsGroup, v as LoweringError, w as stdlibNames, x as lowerTree, y as compileSource } from "./group-BpzTo0k4.js";
11
+ import { t as defineObjectKind } from "./objects-DmUc0lha.js";
12
+ import { $ as disassemble, Ct as validMessageSelector, H as waitUs, Tt as Lexer, _t as defineCapability, c as canConvert, ht as LimitReached, t as NotImplementedError, xt as shape } from "./operations-DnCcztkZ.js";
13
+ import { a as syntaxText, c as parseSource, i as syntaxSelector, l as parseSourceRecovering, o as ParseError, p as declarationStart, r as checkSyntax, s as parseEntry, t as checkSource, v as kindNames } from "./checker-CUhn2XaM.js";
14
+ import { n as exportManifest } from "./manifest-CCfpn0kC.js";
15
+ import { c as readDisplay, r as decodeValue } from "./readers-CsvlahLi.js";
16
+ import { t as encodeValue } from "./encoding-RUuES_e4.js";
17
+ import { a as sqliteCapability, c as talk, i as httpCapability, o as fromValue, r as handlersOf, s as toValue, t as inlineGrants } from "./inline-grants-XbX9HL_w.js";
18
+ import { o as decodeJson, s as encodeJson } from "./http-fetch-DFwVIOQg.js";
19
+ import { n as createCore, r as coreVersions, t as createGroup } from "./lean-aCvN6y52.js";
20
+ import { n as localeCapability, t as userCapability } from "./user-capability-BcRQyyEw.js";
21
+ import { a as clockCapability, i as calendarCapability, l as timerCapability, o as consoleCapability, r as storeCapability, t as add } from "./store-capability-BrUUAwVS.js";
22
+ //#region src/generated/stdlib.ts
23
+ /** Every stdlib Library. */
24
+ const allStdlib = [
25
+ bytes$1,
26
+ date,
27
+ json,
28
+ list$1,
29
+ map$1,
30
+ text$1,
31
+ units$1
32
+ ];
33
+ /** Every stdlib Library's source, by name. */
34
+ const stdlibSources = Object.fromEntries(allStdlib.map((l) => [l.name, l.source]));
22
35
  //#endregion
23
- //#region src/core.ts
24
- const core = Object.freeze({
25
- defineCapability,
26
- defineObjectKind,
27
- clockCapability,
28
- calendarCapability,
29
- localeCapability,
30
- timerCapability,
31
- consoleCapability,
32
- storeCapability,
33
- sqliteCapability,
34
- userCapability,
35
- httpCapability,
36
- compileLibrary,
37
- newGroup,
38
- restore,
39
- stateFingerprint,
40
- versions: coreVersions
41
- });
42
- /** Return the process-wide Core, also used by the free-function helpers. */
43
- const createCore = () => core;
36
+ //#region src/index.ts
37
+ registerStdlib(...allStdlib);
44
38
  //#endregion
45
- //#region src/create-group.ts
46
- /** Creates a driven Group that supports `await using` and explicit close(reason). */
47
- const createGroup = (o) => createGroup$1({
48
- ...o,
49
- core: o.core ?? createCore()
50
- });
51
- //#endregion
52
- export { Script as CompiledScript, Decimal, HostError, Lexer, LimitReached, LoadError, LoweringError, MailboxFull, NotImplementedError, ParseError, Run, ScriptError, TsGroup, TsScript, UnitLoadError, Value, add, bool, builtins, bytes, calendarCapability, callFunction, canConvert, checkSource, checkSyntax, civilDate, clockCapability, codeIdentity, compileLibrary, compileSource, consoleCapability, coreVersions, createCore, createGroup, dec, declarationStart, decodeJson, decodeValue, defaultLimits, defineCapability, defineObjectKind, deliver, disassemble, encodeJson, encodeValue, exportManifest, exportsOf, formatInstant, fromValue, grammar, handlersOf, httpCapability, inlineGrants, instant, kindNames, list, loadScript, localeCapability, lowerTree, map, newGroup, nothing, nowMicros, num, parseEntry, parseInstant, parseSource, parseSourceRecovering, quantity, range, readDisplay, record, restore, shape, sqliteCapability, stdlibSources, storeCapability, syntaxSelector, syntaxText, talk, text, timerCapability, toValue, units, userCapability, validMessageSelector, waitUs };
39
+ export { Script as CompiledScript, Decimal, HostError, Lexer, LimitReached, LoadError, LoweringError, MailboxFull, NotImplementedError, ParseError, Run, ScriptError, TsGroup, TsScript, UnitLoadError, Value, add, allStdlib, bool, builtins, bytes, calendarCapability, callFunction, canConvert, checkSource, checkSyntax, civilDate, clockCapability, codeIdentity, compileLibrary, compileSource, consoleCapability, coreVersions, createCore, createGroup, dec, declarationStart, decodeJson, decodeValue, defaultLimits, defineCapability, defineObjectKind, deliver, disassemble, encodeJson, encodeValue, exportManifest, exportsOf, formatInstant, fromValue, grammar, handlersOf, httpCapability, inlineGrants, instant, kindNames, list, loadScript, localeCapability, lowerTree, map, newGroup, nothing, nowMicros, num, parseEntry, parseInstant, parseSource, parseSourceRecovering, quantity, range, readDisplay, record, registerStdlib, restore, shape, sqliteCapability, stdlibNames, stdlibSources, storeCapability, syntaxSelector, syntaxText, talk, text, timerCapability, toValue, units, userCapability, validMessageSelector, waitUs };
@@ -1,9 +1,9 @@
1
1
 
2
- import { A as listValues, D as isDecimal, Dt as isInteger, Et as integerOf, G as record, L as nothing, N as map, Q as text, R as num, d as bytes, i as ScriptError, l as Value, o as invalidValue, on as normalizeNFC, q as requireValue, t as HostError, tn as characterBoundaries, u as bool, v as dec, y as decimalParts } from "./errors-BKJES3Zu.js";
3
- import { a as defineValueCapability, f as validComputedMessageName, i as defineCapability, m as validStaticMessageName, s as expectedOf, u as shape } from "./capabilities-Bi5Qm6Fr.js";
4
- import { i as ScriptError$1, pt as errorMessages } from "./base64-Dtqaz_0A.js";
5
- import { r as registerStandardChecks } from "./encoding-C3Q7pIC9.js";
6
- import { c as fixed, s as costOf } from "./store-capability-BxXgiRM7.js";
2
+ import { A as listValues, D as isDecimal, G as record, L as nothing, N as map, Q as text, R as num, bt as integerOf, d as bytes, i as ScriptError, l as Value, o as invalidValue, q as requireValue, t as HostError, u as bool, v as dec, xt as isInteger, y as decimalParts } from "./errors-D11zizZg.js";
3
+ import { St as validComputedMessageName, _t as defineCapability, n as ScriptError$1, vt as defineValueCapability, wt as validStaticMessageName, xt as shape, yt as expectedOf } from "./operations-DnCcztkZ.js";
4
+ import { r as registerStandardChecks } from "./encoding-RUuES_e4.js";
5
+ import { n as duplicateHeaderNames, r as fetchAnswerOk, s as encodeJson, t as checkFetch } from "./http-fetch-DFwVIOQg.js";
6
+ import { c as fixed, s as costOf } from "./store-capability-BrUUAwVS.js";
7
7
  import { asyncDispose, newDrivenGroup } from "./driver.js";
8
8
  //#region src/talk.ts
9
9
  const blank = /^[\t ]*$/;
@@ -119,287 +119,6 @@ const fromValue = (v, options = {}) => {
119
119
  return convert(v);
120
120
  };
121
121
  //#endregion
122
- //#region src/json.ts
123
- var JsonReader = class {
124
- source;
125
- i = 0;
126
- constructor(source) {
127
- this.source = source;
128
- }
129
- fail(at = this.i) {
130
- const scalar = Array.from(this.source, (c) => /^[\uD800-\uDFFF]$/.test(c) ? "�" : c).join("");
131
- const offset = characterBoundaries(scalar).filter((i) => i <= at).length;
132
- 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)]]));
133
- }
134
- space() {
135
- while (/[\t\n\r ]/.test(this.source[this.i] ?? "") && this.i < this.source.length) this.i++;
136
- }
137
- eat(c) {
138
- if (this.source[this.i] !== c) this.fail();
139
- this.i++;
140
- }
141
- hex4() {
142
- let n = 0;
143
- for (let k = 0; k < 4; k++) {
144
- const c = this.source[this.i];
145
- if (c === void 0 || !/[\dA-Fa-f]/.test(c)) this.fail();
146
- n = n * 16 + Number.parseInt(c, 16);
147
- this.i++;
148
- }
149
- return n;
150
- }
151
- string() {
152
- this.eat("\"");
153
- const parts = [];
154
- const escapes = {
155
- "\"": "\"",
156
- "\\": "\\",
157
- "/": "/",
158
- b: "\b",
159
- f: "\f",
160
- n: "\n",
161
- r: "\r",
162
- t: " "
163
- };
164
- while (this.i < this.source.length) {
165
- const start = this.i;
166
- const cp = this.source.codePointAt(this.i);
167
- const c = String.fromCodePoint(cp);
168
- if (c === "\"") {
169
- this.i++;
170
- return normalizeNFC(parts.join(""));
171
- }
172
- if (cp < 32 || cp >= 55296 && cp <= 57343) this.fail();
173
- this.i += c.length;
174
- if (c !== "\\") {
175
- parts.push(c);
176
- continue;
177
- }
178
- if (this.i === this.source.length) this.fail();
179
- const escape = this.source[this.i++];
180
- if (Object.hasOwn(escapes, escape)) {
181
- parts.push(escapes[escape]);
182
- continue;
183
- }
184
- if (escape !== "u") this.fail(this.i - 1);
185
- let u = this.hex4();
186
- if (u >= 56320 && u <= 57343) this.fail(start);
187
- if (u >= 55296 && u <= 56319) {
188
- const lowStart = this.i;
189
- if (this.source[this.i] !== "\\" || this.source[this.i + 1] !== "u") this.fail();
190
- this.i += 2;
191
- const low = this.hex4();
192
- if (low < 56320 || low > 57343) this.fail(lowStart);
193
- u = 65536 + (u - 55296) * 1024 + low - 56320;
194
- }
195
- parts.push(String.fromCodePoint(u));
196
- }
197
- return this.fail();
198
- }
199
- digits() {
200
- const start = this.i;
201
- while (this.i < this.source.length && /\d/.test(this.source[this.i])) this.i++;
202
- return this.source.slice(start, this.i);
203
- }
204
- number() {
205
- const start = this.i;
206
- let sign = "";
207
- if (this.source[this.i] === "-") {
208
- sign = "-";
209
- this.i++;
210
- }
211
- if (!/\d/.test(this.source[this.i] ?? "")) this.fail();
212
- let whole;
213
- if (this.source[this.i] === "0") {
214
- whole = "0";
215
- this.i++;
216
- } else whole = this.digits();
217
- let fraction = "";
218
- if (this.source[this.i] === ".") {
219
- this.i++;
220
- fraction = this.digits();
221
- if (!fraction) this.fail();
222
- }
223
- let exponent = "", negativeExponent = false;
224
- if (/[Ee]/.test(this.source[this.i] ?? "")) {
225
- this.i++;
226
- if (/[+-]/.test(this.source[this.i] ?? "")) negativeExponent = this.source[this.i++] === "-";
227
- exponent = this.digits();
228
- if (!exponent) this.fail();
229
- }
230
- const coefficient = whole + fraction;
231
- const significant = coefficient.replace(/^0+/, "");
232
- exponent = exponent.replace(/^0+/, "");
233
- if (exponent.length > 9) {
234
- if (!significant && !negativeExponent) return num(0);
235
- this.fail(start);
236
- }
237
- const q = (negativeExponent ? -1 : 1) * Number(exponent) - fraction.length;
238
- if (!significant && q >= 0) return num(0);
239
- if (significant.length > 34) this.fail(start);
240
- if (q >= 0) {
241
- if (significant.length + q > 34) this.fail(start);
242
- return dec(sign + significant + "0".repeat(q));
243
- }
244
- if (-q > 6176) this.fail(start);
245
- const digits = coefficient.padStart(-q + 1, "0");
246
- return dec(sign + digits.slice(0, q) + "." + digits.slice(q));
247
- }
248
- atom() {
249
- const c = this.source[this.i];
250
- if (c === "\"") return text(this.string());
251
- if (c === "-" || /\d/.test(c ?? "")) return this.number();
252
- for (const [literal, value] of [
253
- ["true", bool(true)],
254
- ["false", bool(false)],
255
- ["null", nothing]
256
- ]) {
257
- if (c !== literal[0]) continue;
258
- for (const ch of literal) this.eat(ch);
259
- return value;
260
- }
261
- return this.fail();
262
- }
263
- read() {
264
- const frames = [];
265
- let value;
266
- const key = (frame) => {
267
- this.space();
268
- const start = this.i;
269
- frame.key = this.string();
270
- if (frame.keys.has(frame.key)) this.fail(start);
271
- frame.keys.add(frame.key);
272
- this.space();
273
- this.eat(":");
274
- };
275
- for (;;) {
276
- if (!value) {
277
- this.space();
278
- const c = this.source[this.i];
279
- if (c === "[" || c === "{") {
280
- this.i++;
281
- this.space();
282
- const frame = c === "[" ? {
283
- kind: "list",
284
- values: []
285
- } : {
286
- kind: "map",
287
- pairs: [],
288
- keys: /* @__PURE__ */ new Set(),
289
- key: ""
290
- };
291
- if (this.source[this.i] === (c === "[" ? "]" : "}")) {
292
- this.i++;
293
- value = c === "[" ? listValues([]) : map([]);
294
- } else {
295
- if (frame.kind === "map") key(frame);
296
- frames.push(frame);
297
- continue;
298
- }
299
- } else value = this.atom();
300
- }
301
- const parent = frames.at(-1);
302
- this.space();
303
- if (!parent) {
304
- if (this.i !== this.source.length) this.fail();
305
- return value;
306
- }
307
- if (parent.kind === "list") parent.values.push(value);
308
- else parent.pairs.push([parent.key, value]);
309
- if (this.source[this.i] === ",") {
310
- this.i++;
311
- if (parent.kind === "map") key(parent);
312
- value = void 0;
313
- } else {
314
- this.eat(parent.kind === "list" ? "]" : "}");
315
- frames.pop();
316
- value = parent.kind === "list" ? listValues(parent.values) : map(parent.pairs);
317
- }
318
- }
319
- }
320
- };
321
- /** Read exact decimal digits, NFC strings and insertion-ordered maps. */
322
- const decodeJson = (source) => {
323
- if (typeof source !== "string") invalidValue("JSON must be text");
324
- return new JsonReader(source).read();
325
- };
326
- const quoteJson = (s) => {
327
- const short = {
328
- "\b": "b",
329
- " ": "t",
330
- "\n": "n",
331
- "\f": "f",
332
- "\r": "r"
333
- };
334
- 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")) + "\"";
335
- };
336
- /** Compact JSON, with canonical numbers and chapter 7's string escapes. */
337
- const encodeJson = (value) => {
338
- requireValue(value);
339
- const pending = [{
340
- value,
341
- path: void 0
342
- }];
343
- const output = [];
344
- while (pending.length) {
345
- const next = pending.pop();
346
- if (typeof next === "string") {
347
- output.push(next);
348
- continue;
349
- }
350
- const { value: v, path } = next;
351
- switch (v.kind) {
352
- case "nothing":
353
- output.push("null");
354
- break;
355
- case "boolean":
356
- case "number":
357
- output.push(v.toString());
358
- break;
359
- case "text":
360
- output.push(quoteJson(v.asText()));
361
- break;
362
- case "list":
363
- output.push("[");
364
- pending.push("]");
365
- for (let i = v.length; i >= 1; i--) {
366
- if (i < v.length) pending.push(",");
367
- pending.push({
368
- value: v.index(i),
369
- path: {
370
- key: i,
371
- parent: path
372
- }
373
- });
374
- }
375
- break;
376
- case "map": {
377
- output.push("{");
378
- pending.push("}");
379
- const entries = v.entries();
380
- for (let i = entries.length - 1; i >= 0; i--) {
381
- const [k, child] = entries[i];
382
- if (i < entries.length - 1) pending.push(",");
383
- pending.push({
384
- value: child,
385
- path: {
386
- key: k,
387
- parent: path
388
- }
389
- }, quoteJson(k) + ":");
390
- }
391
- break;
392
- }
393
- default: {
394
- const keys = [];
395
- for (let p = path; p; p = p.parent) keys.push(typeof p.key === "string" ? text(p.key) : num(p.key));
396
- throw new ScriptError("not encodable", errorMessages["not encodable"].replace("{kind}", text(v.kind).toString()), map([["kind", text(v.kind)], ["path", listValues(keys.reverse())]]));
397
- }
398
- }
399
- }
400
- return output.join("");
401
- };
402
- //#endregion
403
122
  //#region src/sqlite-capability.ts
404
123
  const isWhole = (n) => Number.isSafeInteger(n) && n >= 0;
405
124
  const INT64_MIN = -(2n ** 63n);
@@ -623,6 +342,19 @@ const addressShape = shape.map({
623
342
  host: shape.text,
624
343
  port: shape.number
625
344
  });
345
+ const textsShape = shape.openMap({});
346
+ const requestShape = shape.optional(shape.map({
347
+ method: optional(shape.text),
348
+ headers: optional(textsShape),
349
+ query: optional(textsShape),
350
+ body: optional(shape.oneOf(shape.text, shape.bytes)),
351
+ json: optional(shape.any)
352
+ }));
353
+ const fetchResultShape = shape.map({
354
+ status: shape.number,
355
+ headers: textsShape,
356
+ body: shape.bytes
357
+ });
626
358
  const whole = (value) => {
627
359
  const parts = value?.kind === "number" ? decimalParts(value.asDecimal()) : void 0;
628
360
  return parts && isInteger(parts) ? integerOf(parts) : void 0;
@@ -645,6 +377,7 @@ const checkResponse = (response) => {
645
377
  }
646
378
  const headers = given(response, "headers");
647
379
  if (headers?.kind === "map") {
380
+ if (duplicateHeaderNames(headers)) throw invalid("invalid response", "headers");
648
381
  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");
649
382
  }
650
383
  const json = given(response, "json");
@@ -664,15 +397,27 @@ const resolvedResponse = (response) => {
664
397
  if (!given(response, "json")) return response;
665
398
  return map(response.entries().map(([k, v]) => [k, k === "json" ? text(jsonText(v)) : v]));
666
399
  };
667
- /** Optional for Hosts. The binding is the Host's own description of the addresses a Grant may listen on. */
400
+ const SERVER = [
401
+ "serve",
402
+ "unserve",
403
+ "respond"
404
+ ];
405
+ /**
406
+ * Optional for Hosts. The binding is the Host's own description of the
407
+ * addresses a Grant may listen on and the origins it may fetch from.
408
+ */
668
409
  const httpCapability = (impl, costs) => {
669
- for (const name of [
670
- "serve",
671
- "unserve",
672
- "respond"
673
- ]) if (!impl || typeof impl[name] !== "function") throw new HostError("invalid value", `Http needs ${name}`);
674
- const operations = {
675
- serve: {
410
+ const has = (name) => typeof impl?.[name] === "function";
411
+ const serving = SERVER.filter(has).length;
412
+ if (serving !== 0 && serving !== SERVER.length) {
413
+ const missing = SERVER.find((name) => !has(name));
414
+ throw new HostError("invalid value", `Http needs ${missing}`);
415
+ }
416
+ if (serving === 0 && !has("fetch")) throw new HostError("invalid value", "Http needs serve, unserve and respond, fetch, or all four");
417
+ const server = impl;
418
+ const client = impl;
419
+ const all = {
420
+ serve: () => ({
676
421
  mode: "suspending",
677
422
  args: [
678
423
  shape.text,
@@ -684,20 +429,20 @@ const httpCapability = (impl, costs) => {
684
429
  errors: [{ code: "address in use" }, { code: "bad address" }],
685
430
  maxPendingMs: HTTP_MAX_PENDING_MS,
686
431
  cost: costOf(costs, "serve"),
687
- start: (call, ...args) => impl.serve(call, args[0].asText(), args[1].asText(), effectiveMessage(args), args[3]?.kind === "map" ? args[3] : map([]))
688
- },
689
- unserve: {
432
+ start: (call, ...args) => server.serve(call, args[0].asText(), args[1].asText(), effectiveMessage(args), args[3]?.kind === "map" ? args[3] : map([]))
433
+ }),
434
+ unserve: () => ({
690
435
  mode: "immediate",
691
436
  args: [shape.text],
692
437
  result: shape.nothing,
693
438
  errors: [],
694
439
  cost: costOf(costs, "unserve"),
695
440
  do: (call, name) => {
696
- impl.unserve(call, name.asText());
441
+ server.unserve(call, name.asText());
697
442
  return nothing;
698
443
  }
699
- },
700
- respond: {
444
+ }),
445
+ respond: () => ({
701
446
  mode: "immediate",
702
447
  args: [exchangeShape, responseShape],
703
448
  result: shape.nothing,
@@ -708,11 +453,28 @@ const httpCapability = (impl, costs) => {
708
453
  ],
709
454
  cost: costOf(costs, "respond"),
710
455
  do: (call, exchange, response) => {
711
- impl.respond(call, exchange.asObject(), resolvedResponse(response));
456
+ server.respond(call, exchange.asObject(), resolvedResponse(response));
712
457
  return nothing;
713
458
  }
714
- }
459
+ }),
460
+ fetch: () => ({
461
+ mode: "suspending",
462
+ args: [shape.text, requestShape],
463
+ result: fetchResultShape,
464
+ errors: [
465
+ { code: "bad address" },
466
+ { code: "network error" },
467
+ { code: "response too large" }
468
+ ],
469
+ cost: costOf(costs, "fetch"),
470
+ start: (call, ...args) => {
471
+ const { url, request } = checkFetch(args);
472
+ client.fetch(call, url, request);
473
+ }
474
+ })
715
475
  };
476
+ const operations = {};
477
+ for (const name of [...serving ? SERVER : [], ...has("fetch") ? ["fetch"] : []]) operations[name] = all[name]();
716
478
  const hostErrors = {
717
479
  serve: ["address in use", "bad address"],
718
480
  unserve: [],
@@ -720,15 +482,21 @@ const httpCapability = (impl, costs) => {
720
482
  "already responded",
721
483
  "exchange closed",
722
484
  "not owner"
485
+ ],
486
+ fetch: [
487
+ "bad address",
488
+ "network error",
489
+ "response too large"
723
490
  ]
724
491
  };
725
492
  for (const [name, op] of Object.entries(operations)) registerStandardChecks(op, {
726
493
  error: (code) => hostErrors[name].includes(code),
727
494
  arguments: (args) => {
728
495
  if (name === "respond") checkResponse(args[1]);
496
+ else if (name === "fetch") checkFetch(args);
729
497
  else checkServe(args, name === "serve");
730
498
  },
731
- ...name === "serve" ? { result: (answer) => answer.kind === "map" && whole(answer.get("port")) !== void 0 } : {}
499
+ ...name === "serve" ? { result: (answer) => answer.kind === "map" && whole(answer.get("port")) !== void 0 } : name === "fetch" ? { result: fetchAnswerOk } : {}
732
500
  });
733
501
  return fixed(defineValueCapability("http", operations));
734
502
  };
@@ -810,4 +578,4 @@ const inlineGrants = (capabilities) => Object.fromEntries(Object.entries(capabil
810
578
  return [name, defineCapability(name, ops).grant("all", void 0)];
811
579
  }));
812
580
  //#endregion
813
- export { sqliteCapability as a, fromValue as c, httpCapability as i, toValue as l, createGroup as n, decodeJson as o, handlersOf as r, encodeJson as s, inlineGrants as t, talk as u };
581
+ export { sqliteCapability as a, talk as c, httpCapability as i, createGroup as n, fromValue as o, handlersOf as r, toValue as s, inlineGrants as t };