@syntropika/tembra-sdk 0.2.2 → 0.3.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 (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3332
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3310
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3321
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +7 -6
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +213 -90
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -301
@@ -0,0 +1,3234 @@
1
+ import {
2
+ Errors2,
3
+ isDescriptor,
4
+ TembraError2
5
+ } from "./index-c1w7z9hx.js";
6
+ import {
7
+ FilesystemError2,
8
+ SocketProviderError2,
9
+ NameLookupError2
10
+ } from "./index-n1wxzc9w.js";
11
+ import {
12
+ HttpHandlerError2,
13
+ CONNECTION_TERMINATED,
14
+ HttpProviderError2
15
+ } from "./index-h8t0n42q.js";
16
+ import {
17
+ fromWit,
18
+ toWit,
19
+ key,
20
+ unspecified,
21
+ isUnicast,
22
+ isRemote,
23
+ hasFamily,
24
+ checkedIpAddress,
25
+ parseHostName,
26
+ ok,
27
+ err,
28
+ internal,
29
+ done,
30
+ digits,
31
+ HttpFields,
32
+ HttpRequestOptions,
33
+ HttpRequest,
34
+ HttpResponse
35
+ } from "./index-v6heph77.js";
36
+ import {
37
+ bindingName
38
+ } from "./index-hfds9mzp.js";
39
+
40
+ // src/interpreter/component/values.ts
41
+ var TYPED = {
42
+ u8: Uint8Array,
43
+ s8: Int8Array,
44
+ u16: Uint16Array,
45
+ s16: Int16Array,
46
+ u32: Uint32Array,
47
+ s32: Int32Array,
48
+ u64: BigUint64Array,
49
+ s64: BigInt64Array,
50
+ f32: Float32Array,
51
+ f64: Float64Array
52
+ };
53
+ var IDENTITY = { guest: undefined, host: undefined };
54
+ var apply = (convert, value) => convert ? convert(value) : value;
55
+ function converters(graph) {
56
+ const kinds = new Map(graph.types.map(({ id, definition }) => [id, definition.kind]));
57
+ const memo = new Map;
58
+ const spelling = (name) => {
59
+ const value = graph.javascriptNames[name];
60
+ if (value === undefined)
61
+ throw new Error(`Missing WIT JavaScript name for ${name}`);
62
+ return value;
63
+ };
64
+ const kindOf = (type) => typeof type === "number" ? kinds.get(type) : undefined;
65
+ const resolve = (type) => {
66
+ let current = type;
67
+ for (let depth = 0;typeof current === "number"; depth++) {
68
+ const kind = kinds.get(current);
69
+ if (typeof kind !== "object" || kind.type === undefined || depth > 64)
70
+ break;
71
+ current = kind.type;
72
+ }
73
+ return current;
74
+ };
75
+ const compile = (type) => {
76
+ if (typeof type !== "number")
77
+ return IDENTITY;
78
+ const known = memo.get(type);
79
+ if (known)
80
+ return known;
81
+ memo.set(type, IDENTITY);
82
+ const pair = build(kindOf(type));
83
+ memo.set(type, pair);
84
+ return pair;
85
+ };
86
+ const build = (kind) => {
87
+ if (kind === undefined)
88
+ throw new Error("Unknown WIT type reference");
89
+ if (typeof kind === "string")
90
+ throw new Error(`WIT ${kind} values are unavailable in browser component execution`);
91
+ if (kind.type !== undefined)
92
+ return compile(kind.type);
93
+ if (kind.enum !== undefined || kind.flags !== undefined || kind.handle?.own !== undefined)
94
+ return IDENTITY;
95
+ if (kind.list !== undefined) {
96
+ const element = resolve(kind.list);
97
+ const Typed = typeof element === "string" ? TYPED[element] : undefined;
98
+ const item = compile(kind.list);
99
+ return {
100
+ guest: (value) => {
101
+ if (!Array.isArray(value))
102
+ throw new TypeError("WIT list requires an array");
103
+ const items = item.guest ? value.map(item.guest) : value;
104
+ return Typed ? new Typed(items) : items;
105
+ },
106
+ host: (value) => {
107
+ const items = ArrayBuffer.isView(value) ? Array.from(value) : Array.isArray(value) ? value : (() => {
108
+ throw new TypeError("WIT list requires an array");
109
+ })();
110
+ return item.host ? items.map(item.host) : [...items];
111
+ }
112
+ };
113
+ }
114
+ if (kind.option !== undefined) {
115
+ const inner = compile(kind.option);
116
+ const innerKind = kindOf(resolve(kind.option));
117
+ const nested = typeof innerKind === "object" && innerKind.option !== undefined;
118
+ return {
119
+ guest: (value) => value === null ? nested ? { tag: "none" } : undefined : nested ? { tag: "some", val: apply(inner.guest, value) } : apply(inner.guest, value),
120
+ host: (value) => {
121
+ if (nested) {
122
+ const tagged = value;
123
+ return tagged?.tag === "some" ? apply(inner.host, tagged.val) : null;
124
+ }
125
+ return value === undefined || value === null ? null : apply(inner.host, value);
126
+ }
127
+ };
128
+ }
129
+ if (kind.record) {
130
+ const fields = kind.record.fields.map(({ name, type }) => [spelling(name), compile(type)]);
131
+ if (fields.every(([, pair]) => pair === IDENTITY))
132
+ return IDENTITY;
133
+ const map = (side) => (value) => {
134
+ if (typeof value !== "object" || value === null)
135
+ throw new TypeError("WIT record requires an object");
136
+ const copy = { ...value };
137
+ for (const [name, pair] of fields)
138
+ if (Object.hasOwn(copy, name))
139
+ copy[name] = apply(pair[side], copy[name]);
140
+ return copy;
141
+ };
142
+ return { guest: map("guest"), host: map("host") };
143
+ }
144
+ if (kind.tuple) {
145
+ const items = kind.tuple.types.map(compile);
146
+ if (items.every((pair) => pair === IDENTITY))
147
+ return IDENTITY;
148
+ const map = (side) => (value) => {
149
+ if (!Array.isArray(value) || value.length !== items.length)
150
+ throw new TypeError("WIT tuple length differs");
151
+ return value.map((item, index) => apply(items[index][side], item));
152
+ };
153
+ return { guest: map("guest"), host: map("host") };
154
+ }
155
+ if (kind.variant || kind.result) {
156
+ const cases = new Map(kind.variant ? kind.variant.cases.map(({ name, type }) => [name, type]) : [
157
+ ["ok", kind.result.ok],
158
+ ["err", kind.result.err]
159
+ ]);
160
+ const pairs = new Map([...cases].map(([name, type]) => [name, type == null ? undefined : compile(type)]));
161
+ const map = (side) => (value) => {
162
+ if (typeof value !== "object" || value === null)
163
+ throw new TypeError("WIT tagged value requires an object");
164
+ const { tag, val } = value;
165
+ if (typeof tag !== "string" || !pairs.has(tag))
166
+ throw new TypeError("Unknown WIT case");
167
+ const pair = pairs.get(tag);
168
+ return pair === undefined ? { tag } : { tag, val: apply(pair[side], val) };
169
+ };
170
+ return { guest: map("guest"), host: map("host") };
171
+ }
172
+ const name = Object.keys(kind)[0] ?? "unknown";
173
+ throw new Error(`WIT ${name} values are unavailable in browser component execution`);
174
+ };
175
+ return (fn) => {
176
+ const params = fn.params.map(({ type }) => compile(type));
177
+ const result = compile(fn.result);
178
+ const resultKind = kindOf(resolve(fn.result));
179
+ const tagged = typeof resultKind === "object" && resultKind.result !== undefined;
180
+ const tags = tagged ? resultKind.result : undefined;
181
+ const ok = tags?.ok == null ? undefined : compile(tags.ok);
182
+ const err = tags?.err == null ? undefined : compile(tags.err);
183
+ const each = (side) => (args) => {
184
+ if (args.length !== params.length)
185
+ throw new TypeError("WIT argument count differs");
186
+ return args.map((value, index) => apply(params[index][side], value));
187
+ };
188
+ return {
189
+ tagged,
190
+ guestArguments: each("guest"),
191
+ hostArguments: each("host"),
192
+ fromGuest: async (call) => {
193
+ if (!tagged) {
194
+ const value = await call();
195
+ return fn.result == null ? null : apply(result.host, value);
196
+ }
197
+ try {
198
+ const value = await call();
199
+ return tags.ok == null ? { tag: "ok" } : { tag: "ok", val: apply(ok?.host, value) };
200
+ } catch (error) {
201
+ if (error === null || typeof error !== "object" || !Object.hasOwn(error, "payload"))
202
+ throw error;
203
+ const payload = error.payload;
204
+ return tags.err == null ? { tag: "err" } : { tag: "err", val: apply(err?.host, payload) };
205
+ }
206
+ },
207
+ toGuest: (value) => {
208
+ if (fn.result == null)
209
+ return;
210
+ return apply(result.guest, value);
211
+ }
212
+ };
213
+ };
214
+ }
215
+
216
+ // src/interpreter/component/wasi-host.ts
217
+ var ok2 = (val) => val === undefined ? { tag: "ok" } : { tag: "ok", val };
218
+ var err2 = (code) => ({ tag: "err", val: code });
219
+ var cancelled = () => new Error("Operation cancelled");
220
+ function abortable(operation, signal) {
221
+ if (!signal)
222
+ return operation;
223
+ if (signal.aborted)
224
+ return Promise.reject(cancelled());
225
+ return new Promise((resolve, reject) => {
226
+ const abort = () => reject(cancelled());
227
+ signal.addEventListener("abort", abort, { once: true });
228
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
229
+ });
230
+ }
231
+ function closing(host, operation) {
232
+ host.cleanup(operation);
233
+ }
234
+ function chunk(value) {
235
+ if (value instanceof Uint8Array)
236
+ return value;
237
+ if (Array.isArray(value))
238
+ return Uint8Array.from(value);
239
+ if (ArrayBuffer.isView(value))
240
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
241
+ if (value === undefined)
242
+ return new Uint8Array(0);
243
+ throw new TypeError("byte stream values must be bytes");
244
+ }
245
+ var STREAM_CHUNK = 64 * 1024;
246
+ function guestBytes(stream, retired) {
247
+ const source = stream;
248
+ if (typeof source?.read !== "function")
249
+ throw new TypeError("expected a guest byte stream");
250
+ let finished = false;
251
+ const finish = () => {
252
+ if (finished)
253
+ return;
254
+ finished = true;
255
+ try {
256
+ source[Symbol.dispose]?.();
257
+ } catch {}
258
+ };
259
+ const iterator = {
260
+ [Symbol.asyncIterator]: () => iterator,
261
+ async next() {
262
+ while (!finished) {
263
+ let result;
264
+ try {
265
+ result = await abortable(source.read({ count: STREAM_CHUNK }), retired);
266
+ } catch (error) {
267
+ finish();
268
+ throw error;
269
+ }
270
+ const bytes = chunk(result.value);
271
+ if (bytes.byteLength)
272
+ return { done: false, value: bytes };
273
+ if (result.done)
274
+ break;
275
+ }
276
+ finish();
277
+ return { done: true, value: undefined };
278
+ },
279
+ async return() {
280
+ finish();
281
+ return { done: true, value: undefined };
282
+ }
283
+ };
284
+ return iterator;
285
+ }
286
+ function hostBytes(next, close, retired) {
287
+ let ended = false;
288
+ const end = (how, failure) => {
289
+ if (ended)
290
+ return;
291
+ ended = true;
292
+ close(how, failure);
293
+ };
294
+ retired.addEventListener("abort", () => end("dropped"), { once: true });
295
+ const iterator = {
296
+ [Symbol.asyncIterator]: () => iterator,
297
+ async next() {
298
+ if (ended)
299
+ return { done: true, value: undefined };
300
+ try {
301
+ const bytes = await abortable(next(STREAM_CHUNK), retired);
302
+ if (bytes && bytes.byteLength)
303
+ return { done: false, value: bytes };
304
+ end("eof");
305
+ } catch (error) {
306
+ end(retired.aborted ? "dropped" : "failed", error);
307
+ }
308
+ return { done: true, value: undefined };
309
+ },
310
+ async return() {
311
+ end("dropped");
312
+ return { done: true, value: undefined };
313
+ }
314
+ };
315
+ return iterator;
316
+ }
317
+ function hostItems(next, close, retired) {
318
+ let ended = false;
319
+ const end = (how, failure) => {
320
+ if (ended)
321
+ return;
322
+ ended = true;
323
+ close(how, failure);
324
+ };
325
+ retired.addEventListener("abort", () => end("dropped"), { once: true });
326
+ const iterator = {
327
+ [Symbol.asyncIterator]: () => iterator,
328
+ async next() {
329
+ if (ended)
330
+ return { done: true, value: undefined };
331
+ try {
332
+ const item = await abortable(next(), retired);
333
+ if (item !== undefined)
334
+ return { done: false, value: item };
335
+ end("eof");
336
+ } catch (error) {
337
+ end(retired.aborted ? "dropped" : "failed", error);
338
+ }
339
+ return { done: true, value: undefined };
340
+ },
341
+ async return() {
342
+ end("dropped");
343
+ return { done: true, value: undefined };
344
+ }
345
+ };
346
+ return iterator;
347
+ }
348
+
349
+ // src/interpreter/component/streams.ts
350
+ var sources = new WeakMap;
351
+
352
+ class ByteStreamOwner {
353
+ finished;
354
+ kind = "bytes";
355
+ constructor(finished, source) {
356
+ this.finished = finished;
357
+ sources.set(this, source);
358
+ }
359
+ static issue(stream, finished, signal) {
360
+ return new ByteStreamOwner(finished, new Source(stream, finished, signal));
361
+ }
362
+ bind(context) {
363
+ const source = claim(this);
364
+ context.check();
365
+ if (source.binding) {
366
+ if (source.binding.session !== context.session || source.binding.root !== context.root)
367
+ throw new Error("Byte stream belongs to another root");
368
+ return;
369
+ }
370
+ source.binding = { session: context.session, root: context.root };
371
+ source.attach(context.signal);
372
+ }
373
+ close() {
374
+ claim(this).close();
375
+ }
376
+ reportFailure(error, report) {
377
+ claim(this).reportFailure(error, report);
378
+ }
379
+ }
380
+ var issueByteStream = ByteStreamOwner.issue;
381
+ function claim(owner) {
382
+ const source = sources.get(owner);
383
+ if (!source)
384
+ throw new TypeError("Foreign byte stream capability");
385
+ return source;
386
+ }
387
+
388
+ class Source {
389
+ finished;
390
+ #iterator;
391
+ #stopped = new AbortController;
392
+ #detach = new Set;
393
+ #failed;
394
+ #queue = Promise.resolve();
395
+ #closed = false;
396
+ #failure;
397
+ #reported = false;
398
+ taken = false;
399
+ binding;
400
+ constructor(stream, finished, signal) {
401
+ this.finished = finished;
402
+ this.#iterator = guestBytes(stream, this.#stopped.signal);
403
+ this.#failed = finished.then(() => new Promise(() => {}), (error) => {
404
+ this.#failure = { error };
405
+ this.close();
406
+ throw error;
407
+ });
408
+ this.#failed.catch(() => {});
409
+ this.attach(signal);
410
+ }
411
+ attach(signal) {
412
+ if (this.#closed)
413
+ return;
414
+ if (signal.aborted)
415
+ return this.close();
416
+ const close = () => this.close();
417
+ signal.addEventListener("abort", close, { once: true });
418
+ this.#detach.add(() => signal.removeEventListener("abort", close));
419
+ }
420
+ close() {
421
+ if (this.#closed)
422
+ return;
423
+ this.#closed = true;
424
+ this.#stopped.abort();
425
+ for (const detach of this.#detach)
426
+ detach();
427
+ this.#detach.clear();
428
+ this.#iterator.return?.().catch(() => {});
429
+ }
430
+ #checkFailure() {
431
+ if (this.#failure)
432
+ throw this.#failure.error;
433
+ }
434
+ reportFailure(error, report) {
435
+ if (this.#reported)
436
+ return;
437
+ this.#reported = true;
438
+ report(error);
439
+ }
440
+ read() {
441
+ const next = this.#queue.then(async () => {
442
+ this.#checkFailure();
443
+ if (this.#closed)
444
+ return;
445
+ try {
446
+ const result = await Promise.race([this.#iterator.next(), this.#failed]);
447
+ this.#checkFailure();
448
+ if (this.#closed)
449
+ return;
450
+ if (result.done) {
451
+ await abortable(this.finished, this.#stopped.signal);
452
+ this.close();
453
+ return;
454
+ }
455
+ if (result.value.byteLength > STREAM_CHUNK)
456
+ throw new Error("Byte stream chunk exceeds the 64 KiB bound");
457
+ return result.value.slice();
458
+ } catch (error) {
459
+ const dropped = this.#closed;
460
+ this.close();
461
+ this.#checkFailure();
462
+ if (dropped)
463
+ return;
464
+ throw error;
465
+ }
466
+ });
467
+ this.#queue = next.then(() => {}, () => {});
468
+ return next;
469
+ }
470
+ }
471
+ function receiveByteStream(owner, ended, cleanup, failed) {
472
+ const source = claim(owner);
473
+ if (source.taken)
474
+ throw new Error("Byte stream capability was already consumed");
475
+ source.taken = true;
476
+ source.attach(ended);
477
+ const report = (error) => {
478
+ owner.reportFailure(error, failed);
479
+ };
480
+ return hostBytes(() => source.read(), (end, failure) => {
481
+ owner.close();
482
+ if (end === "failed")
483
+ report(failure);
484
+ cleanup(() => owner.finished.catch(report));
485
+ }, ended);
486
+ }
487
+
488
+ // src/interpreter/component/port.ts
489
+ function executorFault(error) {
490
+ return isDescriptor(error) && error.reason === Errors2.Unavailable.WasmExecutor.reason;
491
+ }
492
+ function failureText(error) {
493
+ try {
494
+ if (isDescriptor(error))
495
+ return `${error.code}/${error.reason}: ${error.message}`;
496
+ return error instanceof Error ? error.message : String(error);
497
+ } catch {
498
+ return "the component trapped";
499
+ }
500
+ }
501
+ function trapMessage(cause) {
502
+ if (executorFault(cause))
503
+ return cause.message;
504
+ return `component trap: ${cause === undefined ? "the component trapped" : failureText(cause)}`;
505
+ }
506
+ var faults = new WeakMap;
507
+ function fault(error) {
508
+ if (error instanceof TembraError2 && executorFault(error))
509
+ return error;
510
+ const object = typeof error === "object" && error !== null ? error : undefined;
511
+ const known = object && faults.get(object);
512
+ if (known)
513
+ return known;
514
+ const answer = executorFault(error) ? new TembraError2(error, error.message, { cause: error }) : new TembraError2(Errors2.Unavailable.WasmExecutor, trapMessage(error), { cause: error });
515
+ if (object)
516
+ faults.set(object, answer);
517
+ return answer;
518
+ }
519
+
520
+ class ComponentPort {
521
+ timeout;
522
+ dispose;
523
+ callFuel;
524
+ exports;
525
+ #active;
526
+ #callbacks = new Set;
527
+ #completions = new Set;
528
+ #destroying = false;
529
+ #destructorTasks = new Set;
530
+ #nestedDestructors = new Map;
531
+ #destructorPending = new Set;
532
+ #destructorExited;
533
+ #admitting;
534
+ #admitted = false;
535
+ #tasks = new Map;
536
+ #access;
537
+ #trap;
538
+ #rejectTrap;
539
+ observer = {
540
+ attach: (access) => {
541
+ this.#access = access;
542
+ },
543
+ taskStarted: ({ id, entry }) => {
544
+ if (this.#destroying) {
545
+ if (entry !== "<resource-drop>") {
546
+ this.poison(new Error("A destructor entered a non-destructor export task"));
547
+ return;
548
+ }
549
+ this.#destructorTasks.add(id);
550
+ return;
551
+ }
552
+ if (entry === "<resource-drop>") {
553
+ const parent = this.#access?.currentRootTask();
554
+ const callback2 = parent === null || parent === undefined ? undefined : this.#tasks.get(parent) ?? this.#nestedDestructors.get(parent)?.callback;
555
+ if (callback2) {
556
+ const exit = Promise.withResolvers();
557
+ this.#nestedDestructors.set(id, { callback: callback2, exited: exit.resolve });
558
+ this.physical(callback2, exit.promise);
559
+ return;
560
+ }
561
+ if (this.#admitted)
562
+ this.poison(new Error("A resource destructor started outside an admitted parent task"));
563
+ return;
564
+ }
565
+ const callback = this.#admitting;
566
+ if (!callback) {
567
+ if (this.#admitted)
568
+ this.poison(new Error("An export task started outside an admitted callback"));
569
+ return;
570
+ }
571
+ if (callback.task !== undefined) {
572
+ this.poison(new Error("One callback entered more than one export task"));
573
+ return;
574
+ }
575
+ callback.task = id;
576
+ this.#tasks.set(id, callback);
577
+ },
578
+ taskExited: ({ id, rejected, error }) => {
579
+ const nested = this.#nestedDestructors.get(id);
580
+ if (nested) {
581
+ this.#nestedDestructors.delete(id);
582
+ if (rejected || error !== undefined)
583
+ this.poison(error ?? new Error("A component resource destructor ended rejected"));
584
+ nested.exited();
585
+ return;
586
+ }
587
+ if (this.#destructorTasks.delete(id)) {
588
+ if (rejected || error !== undefined)
589
+ this.poison(error ?? new Error("A component resource destructor ended rejected"));
590
+ if (!this.#destructorTasks.size)
591
+ this.#destructorExited?.();
592
+ return;
593
+ }
594
+ const callback = this.#tasks.get(id);
595
+ if (!callback)
596
+ return;
597
+ if (rejected || error !== undefined)
598
+ this.poison(error ?? new Error("A component callback task ended rejected"));
599
+ callback.exited();
600
+ },
601
+ trapped: (error) => this.poison(error)
602
+ };
603
+ #closed = false;
604
+ #poisoned = false;
605
+ #retired = new AbortController;
606
+ #cause;
607
+ get attached() {
608
+ return this.#access !== undefined;
609
+ }
610
+ #physical = new Set;
611
+ wasi = {
612
+ physical: (operation) => {
613
+ if (this.#retired.signal.aborted)
614
+ return Promise.reject(new Error("The revision has retired"));
615
+ const work = Promise.resolve().then(operation);
616
+ this.#track(work);
617
+ const callback = this.#attributed();
618
+ if (!callback) {
619
+ this.#destructorPhysical(work);
620
+ return abortable(work, this.#retired.signal);
621
+ }
622
+ this.physical(callback, work);
623
+ return abortable(abortable(work, callback.ended.signal), callback.scope.signal);
624
+ },
625
+ cleanup: (operation) => {
626
+ const callback = this.#attributed();
627
+ const work = Promise.resolve().then(operation);
628
+ this.#track(work);
629
+ if (callback)
630
+ this.physical(callback, work);
631
+ else
632
+ this.#destructorPhysical(work);
633
+ work.catch((error) => this.poison(error));
634
+ },
635
+ retired: this.#retired.signal,
636
+ signal: () => {
637
+ const callback = this.#attributed();
638
+ const signals = [this.#retired.signal];
639
+ if (callback) {
640
+ signals.push(callback.ended.signal);
641
+ if (callback.scope.signal)
642
+ signals.push(callback.scope.signal);
643
+ }
644
+ return AbortSignal.any(signals);
645
+ }
646
+ };
647
+ #track(work) {
648
+ this.#physical.add(work);
649
+ const forget = () => this.#physical.delete(work);
650
+ work.then(forget, forget);
651
+ }
652
+ #destructorPhysical(work) {
653
+ const id = this.#access?.currentRootTask();
654
+ if (id === null || id === undefined)
655
+ return;
656
+ const nested = this.#nestedDestructors.get(id);
657
+ if (nested) {
658
+ this.physical(nested.callback, work);
659
+ return;
660
+ }
661
+ if (!this.#destructorTasks.has(id))
662
+ return;
663
+ this.#destructorPending.add(work);
664
+ const forget = () => this.#destructorPending.delete(work);
665
+ work.then(forget, forget);
666
+ }
667
+ limits;
668
+ constructor(timeout, dispose, callFuel = 100000000n) {
669
+ this.timeout = timeout;
670
+ this.dispose = dispose;
671
+ this.callFuel = callFuel;
672
+ this.#trap = new Promise((_, reject) => this.#rejectTrap = reject);
673
+ this.#trap.catch(() => {});
674
+ }
675
+ current() {
676
+ const id = this.#access?.currentRootTask();
677
+ if (id !== null && id !== undefined) {
678
+ if (this.#destructorTasks.has(id) || this.#nestedDestructors.has(id))
679
+ throw new Error("A resource destructor holds no call authority");
680
+ const owner = this.#tasks.get(id);
681
+ if (!owner)
682
+ throw new Error("Host import from a task outside any admitted callback");
683
+ return owner;
684
+ }
685
+ if (this.#destroying)
686
+ throw new Error("A resource destructor holds no call authority");
687
+ const active = this.#active;
688
+ if (!active)
689
+ throw new Error("No active host scope");
690
+ return active;
691
+ }
692
+ #attributed() {
693
+ try {
694
+ return this.current();
695
+ } catch {
696
+ return;
697
+ }
698
+ }
699
+ cleanup(operation) {
700
+ const work = Promise.resolve().then(operation);
701
+ this.#track(work);
702
+ work.catch((error) => this.poison(error));
703
+ return work;
704
+ }
705
+ async destroy(call) {
706
+ if (!this.usable)
707
+ return;
708
+ if (this.#destroying)
709
+ throw new Error("A resource destructor is already active");
710
+ this.#destroying = true;
711
+ const exited = Promise.withResolvers();
712
+ this.#destructorExited = exited.resolve;
713
+ const expired = () => new Error("Resource destructor exceeded its wall time limit");
714
+ const started = performance.now();
715
+ let timer;
716
+ const deadline = new Promise((_, reject) => {
717
+ timer = setTimeout(() => reject(expired()), this.timeout);
718
+ });
719
+ const physical = (async () => {
720
+ await exited.promise;
721
+ while (this.#destructorPending.size)
722
+ await Promise.allSettled([...this.#destructorPending]);
723
+ })();
724
+ let failure;
725
+ try {
726
+ if (this.limits && !this.#callbacks.size)
727
+ this.limits.fuel.value = this.callFuel;
728
+ call();
729
+ if (!this.#destructorTasks.size)
730
+ exited.resolve();
731
+ await Promise.race([physical, deadline, this.#trap]);
732
+ if (performance.now() - started > this.timeout)
733
+ throw expired();
734
+ if (this.#poisoned)
735
+ throw this.#cause ?? new Error("A resource destructor trapped");
736
+ } catch (error) {
737
+ this.poison(error);
738
+ failure = { error };
739
+ } finally {
740
+ clearTimeout(timer);
741
+ if (!this.#destructorTasks.size)
742
+ exited.resolve();
743
+ await physical;
744
+ this.#destructorTasks.clear();
745
+ this.#destructorExited = undefined;
746
+ this.#destroying = false;
747
+ }
748
+ if (failure)
749
+ throw failure.error;
750
+ }
751
+ guard(operation) {
752
+ return Promise.race([operation, this.#trap]);
753
+ }
754
+ physical(callback, operation) {
755
+ callback.pending.add(operation);
756
+ const forget = () => callback.pending.delete(operation);
757
+ operation.then(forget, forget);
758
+ return operation;
759
+ }
760
+ get usable() {
761
+ return !this.#closed && !this.#poisoned;
762
+ }
763
+ #quarantined() {
764
+ return new TembraError2(Errors2.Unavailable.WasmExecutorQuarantined, trapMessage(this.#cause), {
765
+ cause: this.#cause
766
+ });
767
+ }
768
+ poison(cause) {
769
+ if (!this.#poisoned) {
770
+ const trap = cause ?? new Error("the component trapped");
771
+ this.#rejectTrap(trap);
772
+ this.#cause = trap;
773
+ }
774
+ this.#poisoned = true;
775
+ this.#retired.abort();
776
+ }
777
+ async run(environment, scope, call, retain) {
778
+ const { result, finished, physical } = this.start(environment, scope, call);
779
+ retain?.(physical);
780
+ const value = await result;
781
+ await finished;
782
+ await physical;
783
+ return value;
784
+ }
785
+ start(environment, scope, call) {
786
+ if (this.#poisoned)
787
+ throw this.#quarantined();
788
+ if (this.#closed || this.#active || this.#destroying)
789
+ throw new TembraError2(Errors2.Unavailable.WasmExecutor, "Component is closed or busy");
790
+ if (!this.exports)
791
+ throw new TembraError2(Errors2.Unavailable.WasmExecutor, "Component is not instantiated");
792
+ const newGroup = this.#callbacks.size === 0;
793
+ let exited;
794
+ const exit = new Promise((resolve) => exited = resolve);
795
+ const callback = {
796
+ scope,
797
+ environment,
798
+ pending: new Set,
799
+ ended: new AbortController,
800
+ task: undefined,
801
+ exit,
802
+ exited
803
+ };
804
+ this.#callbacks.add(callback);
805
+ this.#active = callback;
806
+ let timeout;
807
+ const expired = () => {
808
+ if (!timeout) {
809
+ timeout = fault(new Error("Component callback exceeded its wall time limit"));
810
+ this.poison(timeout);
811
+ }
812
+ return timeout;
813
+ };
814
+ const started = performance.now();
815
+ let timer;
816
+ const deadline = new Promise((_, reject) => {
817
+ timer = setTimeout(() => reject(expired()), this.timeout);
818
+ });
819
+ deadline.catch(() => {});
820
+ const bounded = async (operation) => {
821
+ let outcome;
822
+ try {
823
+ outcome = { value: await Promise.race([operation, deadline, this.#trap]) };
824
+ } catch (error) {
825
+ outcome = { error };
826
+ }
827
+ if (performance.now() - started > this.timeout)
828
+ throw expired();
829
+ if ("error" in outcome)
830
+ throw outcome.error;
831
+ return outcome.value;
832
+ };
833
+ let ended = false;
834
+ const revoke = () => {
835
+ if (ended)
836
+ return;
837
+ ended = true;
838
+ clearTimeout(timer);
839
+ scope.cancel();
840
+ callback.ended.abort();
841
+ if (this.#active === callback)
842
+ this.#active = undefined;
843
+ };
844
+ const release = () => {
845
+ if (callback.task !== undefined)
846
+ this.#tasks.delete(callback.task);
847
+ this.#callbacks.delete(callback);
848
+ };
849
+ let pending;
850
+ try {
851
+ scope.check();
852
+ if (this.limits && newGroup)
853
+ this.limits.fuel.value = this.callFuel;
854
+ this.#admitting = callback;
855
+ this.#admitted = true;
856
+ try {
857
+ pending = Promise.resolve(call());
858
+ } finally {
859
+ this.#admitting = undefined;
860
+ }
861
+ } catch (error) {
862
+ pending = Promise.reject(error);
863
+ }
864
+ if (callback.task === undefined) {
865
+ const result = (async () => {
866
+ try {
867
+ await pending;
868
+ } finally {
869
+ revoke();
870
+ release();
871
+ }
872
+ const error = new TembraError2(Errors2.Unavailable.WasmExecutor, "No generated export task was observed for this callback");
873
+ this.poison(error);
874
+ throw error;
875
+ })();
876
+ const finished = result.then(() => {
877
+ return;
878
+ });
879
+ this.#completion(finished);
880
+ return {
881
+ result,
882
+ finished,
883
+ physical: finished,
884
+ park() {
885
+ throw new Error("No successful component result to park");
886
+ }
887
+ };
888
+ }
889
+ let published = false;
890
+ const result = bounded(pending).then((value) => {
891
+ published = true;
892
+ return value;
893
+ }, (error) => {
894
+ this.poison(error);
895
+ throw fault(error);
896
+ });
897
+ const finished = (async () => {
898
+ try {
899
+ await result.catch(() => {
900
+ return;
901
+ });
902
+ await bounded(callback.exit);
903
+ while (callback.pending.size)
904
+ await bounded(Promise.allSettled([...callback.pending]));
905
+ } catch (error) {
906
+ this.poison(error);
907
+ throw fault(error);
908
+ } finally {
909
+ revoke();
910
+ }
911
+ if (this.#poisoned)
912
+ throw this.#quarantined();
913
+ })();
914
+ result.catch(() => {
915
+ return;
916
+ });
917
+ finished.catch(() => {
918
+ return;
919
+ });
920
+ const physical = (async () => {
921
+ try {
922
+ await pending.catch(() => {
923
+ return;
924
+ });
925
+ await callback.exit;
926
+ while (callback.pending.size)
927
+ await Promise.allSettled([...callback.pending]);
928
+ await finished;
929
+ } finally {
930
+ release();
931
+ }
932
+ })();
933
+ physical.catch(() => {
934
+ return;
935
+ });
936
+ this.#completion(physical);
937
+ return {
938
+ result,
939
+ finished,
940
+ physical,
941
+ park: () => {
942
+ if (!published)
943
+ throw new Error("No successful component result to park");
944
+ if (this.#active === callback)
945
+ this.#active = undefined;
946
+ }
947
+ };
948
+ }
949
+ #completion(work) {
950
+ this.#completions.add(work);
951
+ const forget = () => this.#completions.delete(work);
952
+ work.then(forget, forget);
953
+ }
954
+ async settled() {
955
+ while (this.#completions.size || this.#physical.size)
956
+ await Promise.allSettled([...this.#completions, ...this.#physical]);
957
+ }
958
+ async close() {
959
+ if (this.#callbacks.size || this.#destroying)
960
+ throw new Error("Guest still owns physical work");
961
+ if (this.#closed)
962
+ return;
963
+ this.#closed = true;
964
+ this.exports = undefined;
965
+ this.#retired.abort();
966
+ while (this.#physical.size)
967
+ await Promise.allSettled([...this.#physical]);
968
+ await this.dispose();
969
+ }
970
+ }
971
+
972
+ // src/interpreter/component/host.ts
973
+ var resourceBindings = new WeakMap;
974
+ var importedOwners = new WeakMap;
975
+ var resourceKey = (nominal) => `${nominal.interface}\x00${nominal.name}`;
976
+ function importedResource(port, nominal) {
977
+ const binding = resourceBindings.get(port)?.get(resourceKey(nominal));
978
+ if (!binding)
979
+ throw new Error("Missing imported defining resource class");
980
+ return binding;
981
+ }
982
+ function dependencyFailed(error) {
983
+ throw new Error(`dependency call failed: ${failureText(error)}`, { cause: error });
984
+ }
985
+ function viewMethod(fn) {
986
+ if (!fn.params.length)
987
+ throw new Error("A reference view method has no receiver");
988
+ return { ...fn, params: fn.params.slice(1) };
989
+ }
990
+ function referenceView(graph, binding, view, convert) {
991
+ const functions = graph.imports.find((item) => item.binding === binding)?.functions ?? {};
992
+ const acquire = functions[view.acquire];
993
+ if (!acquire)
994
+ throw new Error(`Missing prepared signature for ${binding}#${view.acquire}`);
995
+ const spelling = graph.javascriptNames[view.acquire];
996
+ if (spelling === undefined)
997
+ throw new Error(`Missing WIT JavaScript name for ${view.acquire}`);
998
+ const prefix = `[method]${view.resource.name}.`;
999
+ const names = Object.keys(functions);
1000
+ if (names.length !== Object.keys(view.methods).length + 1)
1001
+ throw new Error(`The reference view ${binding} declares unchecked functions`);
1002
+ return {
1003
+ resource: bindingName(view.resource.name, true),
1004
+ acquire: {
1005
+ name: view.acquire,
1006
+ spelling,
1007
+ values: convert({ params: acquire.params })
1008
+ },
1009
+ methods: Object.keys(view.methods).map((name) => {
1010
+ const fn = functions[name];
1011
+ if (!fn || !name.startsWith(prefix))
1012
+ throw new Error(`The reference view ${binding} lacks method ${name}`);
1013
+ return {
1014
+ name,
1015
+ spelling: bindingName(name.slice(prefix.length), false),
1016
+ values: convert(viewMethod(fn))
1017
+ };
1018
+ })
1019
+ };
1020
+ }
1021
+ function failure(error) {
1022
+ return error instanceof Error ? error.message : String(error);
1023
+ }
1024
+ function referenceImport(port, binding, view) {
1025
+ const held = new WeakMap;
1026
+ const claimOf = (value) => {
1027
+ const claim = typeof value === "object" && value !== null ? held.get(value) : undefined;
1028
+ if (!claim)
1029
+ throw new Error("The reference handle is not live");
1030
+ return claim;
1031
+ };
1032
+ const Resource = class {
1033
+ constructor(claim) {
1034
+ held.set(this, claim);
1035
+ }
1036
+ [Symbol.dispose]() {
1037
+ const claim = held.get(this);
1038
+ if (!claim)
1039
+ return;
1040
+ held.delete(this);
1041
+ let callback;
1042
+ try {
1043
+ callback = port.current();
1044
+ } catch {
1045
+ return;
1046
+ }
1047
+ port.wasi.cleanup(() => callback.scope.release(claim));
1048
+ }
1049
+ };
1050
+ for (const { name, spelling, values } of view.methods) {
1051
+ if (Object.hasOwn(Resource.prototype, spelling))
1052
+ throw new Error(`Ambiguous reference method ${spelling}`);
1053
+ Object.defineProperty(Resource.prototype, spelling, {
1054
+ value(...args) {
1055
+ const claim = claimOf(this);
1056
+ const callback = port.current();
1057
+ const input = values.hostArguments(args);
1058
+ return port.physical(callback, callback.scope.invoke(claim, binding, name, input)).then(values.toGuest, dependencyFailed);
1059
+ }
1060
+ });
1061
+ }
1062
+ const { values: key } = view.acquire;
1063
+ const acquire = (...args) => {
1064
+ const callback = port.current();
1065
+ const [input] = key.hostArguments(args);
1066
+ const abandoned = new AbortController;
1067
+ let issued;
1068
+ const pending = port.physical(callback, callback.scope.acquire(binding, input, abandoned.signal).then((claim) => {
1069
+ if (abandoned.signal.aborted) {
1070
+ callback.scope.release(claim);
1071
+ return { tag: "err", val: "acquisition abandoned" };
1072
+ }
1073
+ issued = new Resource(claim);
1074
+ return { tag: "ok", val: issued };
1075
+ }, (error) => ({ tag: "err", val: failure(error) })));
1076
+ return Object.assign(pending, {
1077
+ [Symbol.dispose]() {
1078
+ abandoned.abort(new Error("acquisition abandoned"));
1079
+ const claim = issued && held.get(issued);
1080
+ if (!claim)
1081
+ return;
1082
+ held.delete(issued);
1083
+ callback.scope.release(claim);
1084
+ }
1085
+ });
1086
+ };
1087
+ return { [view.resource]: Resource, [view.acquire.spelling]: acquire };
1088
+ }
1089
+ function resourceImport(port, binding, functions, types = []) {
1090
+ let held = importedOwners.get(port);
1091
+ if (!held)
1092
+ importedOwners.set(port, held = new WeakMap);
1093
+ const classes = new Map;
1094
+ const ownerOf = (value) => {
1095
+ const owner = held.get(value);
1096
+ if (!owner)
1097
+ throw new Error("Resource is not live");
1098
+ return owner;
1099
+ };
1100
+ const invoke = (fn, args, receiver) => {
1101
+ const callback = port.current();
1102
+ const converted = fn.values.hostArguments(args);
1103
+ const moved = [];
1104
+ let input;
1105
+ try {
1106
+ input = fn.roles.arguments ? fn.roles.arguments(converted, (nominal, value) => {
1107
+ const owner = importedResource(port, nominal).move(value);
1108
+ moved.push(owner);
1109
+ return moved.length - 1;
1110
+ }) : converted;
1111
+ } catch (error) {
1112
+ for (const owner of moved)
1113
+ owner.close();
1114
+ throw error;
1115
+ }
1116
+ const transfer = {
1117
+ owners: moved,
1118
+ accepted: false,
1119
+ accept() {
1120
+ this.accepted = true;
1121
+ }
1122
+ };
1123
+ let abandoned = false;
1124
+ const issued = [];
1125
+ const pending = port.physical(callback, (async () => {
1126
+ const result = await (receiver ? callback.scope.resource(receiver, binding, fn.spelling, input, ...fn.roles.arguments ? [transfer] : []) : callback.scope.call(binding, fn.spelling, input, ...fn.roles.arguments ? [transfer] : [])).catch(dependencyFailed);
1127
+ if (fn.roles.result) {
1128
+ try {
1129
+ const value = fn.roles.result(result, (nominal, value) => {
1130
+ const owner = value;
1131
+ if (owner?.kind !== "resource" || owner.nominal.interface !== nominal.interface || owner.nominal.name !== nominal.name)
1132
+ throw new Error("Missing matching owned resource result");
1133
+ issued.push(owner);
1134
+ if (abandoned)
1135
+ throw new Error("Resource delivery abandoned");
1136
+ const Resource = classes.get(nominal.name);
1137
+ if (!Resource)
1138
+ throw new Error("Missing imported resource class");
1139
+ const wrapper = Object.create(Resource.prototype);
1140
+ held.set(wrapper, owner);
1141
+ return wrapper;
1142
+ });
1143
+ return fn.values.toGuest(value);
1144
+ } catch (error) {
1145
+ for (const owner of issued)
1146
+ owner.close();
1147
+ throw error;
1148
+ }
1149
+ }
1150
+ if (fn.roles.stream) {
1151
+ return receiveByteStream(result, AbortSignal.any([
1152
+ callback.ended.signal,
1153
+ ...callback.scope.signal ? [callback.scope.signal] : []
1154
+ ]), (operation) => port.wasi.cleanup(operation), (error) => callback.scope.report(error));
1155
+ }
1156
+ return fn.values.toGuest(result);
1157
+ })().catch((error) => {
1158
+ if (!transfer.accepted)
1159
+ for (const owner of moved)
1160
+ owner.close();
1161
+ throw error;
1162
+ }));
1163
+ return Object.assign(pending, {
1164
+ [Symbol.dispose]() {
1165
+ abandoned = true;
1166
+ if (!transfer.accepted)
1167
+ for (const owner of moved)
1168
+ owner.close();
1169
+ for (const owner of issued)
1170
+ owner.close();
1171
+ }
1172
+ });
1173
+ };
1174
+ const nominals = [
1175
+ ...types,
1176
+ ...functions.flatMap((fn) => [
1177
+ ...fn.roles.resource ? [fn.roles.resource] : [],
1178
+ ...fn.roles.owned ?? []
1179
+ ])
1180
+ ];
1181
+ for (const nominal of nominals) {
1182
+ if (classes.has(nominal.name))
1183
+ continue;
1184
+ const constructor = functions.find((item) => item.roles.construct && item.roles.resource?.name === nominal.name);
1185
+ const Resource = class {
1186
+ constructor(...args) {
1187
+ if (!constructor)
1188
+ throw new Error("Resource has no constructor");
1189
+ return invoke(constructor, args);
1190
+ }
1191
+ [Symbol.dispose]() {
1192
+ const owner = held.get(this);
1193
+ if (!owner)
1194
+ return;
1195
+ held.delete(this);
1196
+ try {
1197
+ port.current().scope.releaseResource(owner);
1198
+ } catch {
1199
+ owner.close();
1200
+ }
1201
+ }
1202
+ };
1203
+ classes.set(nominal.name, Resource);
1204
+ let bindings = resourceBindings.get(port);
1205
+ if (!bindings)
1206
+ resourceBindings.set(port, bindings = new Map);
1207
+ bindings.set(resourceKey(nominal), {
1208
+ wrap(owner) {
1209
+ const wrapper = Object.create(Resource.prototype);
1210
+ held.set(wrapper, owner);
1211
+ return wrapper;
1212
+ },
1213
+ move(value) {
1214
+ const owner = ownerOf(value);
1215
+ if (owner.nominal.interface !== nominal.interface || owner.nominal.name !== nominal.name)
1216
+ throw new Error("Resource has another nominal type");
1217
+ const next = owner.move();
1218
+ held.delete(value);
1219
+ return next;
1220
+ }
1221
+ });
1222
+ }
1223
+ const output = {};
1224
+ for (const [name, Resource] of classes)
1225
+ output[bindingName(name, true)] = Resource;
1226
+ for (const fn of functions) {
1227
+ if (fn.roles.construct)
1228
+ continue;
1229
+ if (!fn.roles.resource) {
1230
+ output[fn.spelling] = (...args) => invoke(fn, args);
1231
+ continue;
1232
+ }
1233
+ const Resource = classes.get(fn.roles.resource.name);
1234
+ const target = fn.roles.receiver ? Resource.prototype : Resource;
1235
+ const spelling = bindingName(fn.roles.member, false);
1236
+ if (Object.hasOwn(target, spelling))
1237
+ throw new Error("Ambiguous imported resource method");
1238
+ Object.defineProperty(target, spelling, {
1239
+ value(...args) {
1240
+ return invoke(fn, args, fn.roles.receiver ? ownerOf(this) : undefined);
1241
+ }
1242
+ });
1243
+ }
1244
+ return output;
1245
+ }
1246
+
1247
+ // src/interpreter/component/wasi-filesystem.ts
1248
+ var U64 = (1n << 64n) - 1n;
1249
+ var failure2 = (code) => err2({ tag: code });
1250
+ function code(error) {
1251
+ return error instanceof FilesystemError2 ? error.code : "io";
1252
+ }
1253
+ function refusal(path) {
1254
+ if (path.includes("\x00"))
1255
+ return "invalid";
1256
+ if (path.startsWith("/"))
1257
+ return "not-permitted";
1258
+ let depth = 0;
1259
+ for (const part of path.split("/")) {
1260
+ if (part === "" || part === ".")
1261
+ continue;
1262
+ if (part !== "..")
1263
+ depth++;
1264
+ else if (--depth < 0)
1265
+ return "not-permitted";
1266
+ }
1267
+ return;
1268
+ }
1269
+ function instant(milliseconds) {
1270
+ if (milliseconds === undefined || !Number.isFinite(milliseconds))
1271
+ return;
1272
+ const whole = Math.floor(milliseconds);
1273
+ const seconds = Math.floor(whole / 1000);
1274
+ return {
1275
+ seconds: BigInt(seconds),
1276
+ nanoseconds: (whole - seconds * 1000) * 1e6
1277
+ };
1278
+ }
1279
+ var descriptorType = (type) => ({
1280
+ tag: type === "file" ? "regular-file" : "directory"
1281
+ });
1282
+ var descriptorStat = (stat) => ({
1283
+ type: descriptorType(stat.type),
1284
+ linkCount: 1n,
1285
+ size: stat.size,
1286
+ dataAccessTimestamp: undefined,
1287
+ dataModificationTimestamp: instant(stat.modified),
1288
+ statusChangeTimestamp: undefined
1289
+ });
1290
+ function metadataHash(stat) {
1291
+ const hash = (seed) => {
1292
+ let value = seed;
1293
+ const mix = (word) => {
1294
+ for (let shift = 0n;shift < 64n; shift += 8n) {
1295
+ value ^= word >> shift & 0xffn;
1296
+ value = value * 0x100000001b3n & U64;
1297
+ }
1298
+ };
1299
+ mix(stat.type === "file" ? 1n : 2n);
1300
+ mix(BigInt.asUintN(64, stat.size));
1301
+ mix(stat.modified === undefined ? U64 : BigInt.asUintN(64, BigInt(Math.floor(stat.modified))));
1302
+ return value;
1303
+ };
1304
+ return { lower: hash(0xcbf29ce484222325n), upper: hash(0x84222325cbf29ce4n) };
1305
+ }
1306
+ function filesystemImports(host, mounts) {
1307
+
1308
+ class Descriptor {
1309
+ provider;
1310
+ flags;
1311
+ #users = 1;
1312
+ #closed = false;
1313
+ constructor(provider, flags) {
1314
+ this.provider = provider;
1315
+ this.flags = flags;
1316
+ }
1317
+ get file() {
1318
+ return this.provider.type === "file" ? this.provider : undefined;
1319
+ }
1320
+ get directory() {
1321
+ return this.provider.type === "directory" ? this.provider : undefined;
1322
+ }
1323
+ get mutable() {
1324
+ return this.provider.type === "directory" && this.flags.mutateDirectory;
1325
+ }
1326
+ retain() {
1327
+ this.#users++;
1328
+ }
1329
+ release() {
1330
+ if (--this.#users === 0)
1331
+ host.cleanup(() => this.provider.close());
1332
+ }
1333
+ [Symbol.dispose]() {
1334
+ if (this.#closed)
1335
+ return;
1336
+ this.#closed = true;
1337
+ this.release();
1338
+ }
1339
+ readViaStream(offset) {
1340
+ const file = this.file;
1341
+ if (!file || !this.flags.read)
1342
+ return failedOutput("bad-descriptor");
1343
+ let position = offset;
1344
+ return output(this, async (limit) => {
1345
+ const bytes = await host.physical(() => file.read(position, limit));
1346
+ position += BigInt(bytes.byteLength);
1347
+ return bytes;
1348
+ });
1349
+ }
1350
+ writeViaStream(data, offset) {
1351
+ return consume(this, data, offset);
1352
+ }
1353
+ appendViaStream(data) {
1354
+ return consume(this, data, undefined);
1355
+ }
1356
+ readDirectory() {
1357
+ const directory = this.directory;
1358
+ if (!directory)
1359
+ return [
1360
+ hostItems(async () => {
1361
+ return;
1362
+ }, () => {}, host.retired),
1363
+ Promise.resolve(failure2("not-directory"))
1364
+ ];
1365
+ let entries;
1366
+ try {
1367
+ entries = directory.readDirectory();
1368
+ } catch (error) {
1369
+ return [
1370
+ hostItems(async () => {
1371
+ return;
1372
+ }, () => {}, host.retired),
1373
+ Promise.resolve(failure2(code(error)))
1374
+ ];
1375
+ }
1376
+ let settle;
1377
+ const result = new Promise((resolve) => settle = resolve);
1378
+ let done = false;
1379
+ this.retain();
1380
+ const stream = hostItems(async () => {
1381
+ const next = await host.physical(() => entries.next());
1382
+ if (next.done) {
1383
+ done = true;
1384
+ return;
1385
+ }
1386
+ return {
1387
+ type: descriptorType(next.value.type),
1388
+ name: next.value.name
1389
+ };
1390
+ }, (end, error) => {
1391
+ if (!done)
1392
+ host.cleanup(() => entries.return?.());
1393
+ this.release();
1394
+ settle(end === "failed" ? failure2(code(error)) : ok2());
1395
+ }, host.retired);
1396
+ return [stream, result];
1397
+ }
1398
+ async advise() {
1399
+ return this.file ? ok2() : failure2("bad-descriptor");
1400
+ }
1401
+ sync() {
1402
+ return attempt(this.provider, (p) => p.sync());
1403
+ }
1404
+ syncData() {
1405
+ return attempt(this.provider, (p) => p.sync());
1406
+ }
1407
+ async getFlags() {
1408
+ return ok2({ ...this.flags });
1409
+ }
1410
+ async getType() {
1411
+ return ok2(descriptorType(this.provider.type));
1412
+ }
1413
+ setSize(size) {
1414
+ return attempt(this.file && this.flags.write ? this.file : failure2("bad-descriptor"), (file) => file.setSize(size));
1415
+ }
1416
+ async setTimes(accessed, modified) {
1417
+ if (this.file ? !this.flags.write : !this.mutable)
1418
+ return failure2(this.file ? "bad-descriptor" : "not-permitted");
1419
+ return accessed.tag === "no-change" && modified.tag === "no-change" ? ok2() : failure2("unsupported");
1420
+ }
1421
+ async setTimesAt(_flags, path, accessed, modified) {
1422
+ const checked = mutableAt(this, [path]);
1423
+ if (isResult(checked))
1424
+ return checked;
1425
+ if (accessed.tag !== "no-change" || modified.tag !== "no-change")
1426
+ return failure2("unsupported");
1427
+ return attempt(checked, (directory) => directory.statAt(path).then(() => {
1428
+ return;
1429
+ }));
1430
+ }
1431
+ stat() {
1432
+ return attempt(this.provider, (p) => p.stat().then(descriptorStat));
1433
+ }
1434
+ statAt(_flags, path) {
1435
+ return attempt(directoryAt(this, path), (directory) => directory.statAt(path).then(descriptorStat));
1436
+ }
1437
+ async openAt(_flags, path, open, flags) {
1438
+ const write = Boolean(flags.write || flags.mutateDirectory);
1439
+ const directory = this.directory;
1440
+ if (!directory)
1441
+ return failure2("not-directory");
1442
+ if ((open.create || open.truncate || write) && !this.mutable)
1443
+ return failure2("not-permitted");
1444
+ const refused = refusal(path);
1445
+ if (refused)
1446
+ return failure2(refused);
1447
+ let opened;
1448
+ try {
1449
+ opened = await host.physical(() => directory.openAt(path, {
1450
+ create: Boolean(open.create),
1451
+ exclusive: Boolean(open.exclusive),
1452
+ truncate: Boolean(open.truncate),
1453
+ directory: Boolean(open.directory),
1454
+ write
1455
+ }));
1456
+ } catch (error) {
1457
+ return failure2(code(error));
1458
+ }
1459
+ const granted = opened.writable && write;
1460
+ return ok2(new Descriptor(opened, {
1461
+ read: opened.type === "directory" || Boolean(flags.read),
1462
+ write: opened.type === "file" && granted,
1463
+ fileIntegritySync: Boolean(flags.fileIntegritySync),
1464
+ dataIntegritySync: Boolean(flags.dataIntegritySync),
1465
+ requestedWriteSync: Boolean(flags.requestedWriteSync),
1466
+ mutateDirectory: opened.type === "directory" && granted
1467
+ }));
1468
+ }
1469
+ async readlinkAt(path) {
1470
+ const result = await attempt(directoryAt(this, path), (directory) => directory.statAt(path));
1471
+ return result.tag === "ok" ? failure2("invalid") : result;
1472
+ }
1473
+ createDirectoryAt(path) {
1474
+ return attempt(mutableAt(this, [path]), (directory) => directory.createDirectoryAt(path));
1475
+ }
1476
+ removeDirectoryAt(path) {
1477
+ return attempt(mutableAt(this, [path]), (directory) => directory.removeDirectoryAt(path));
1478
+ }
1479
+ unlinkFileAt(path) {
1480
+ return attempt(mutableAt(this, [path]), (directory) => directory.unlinkFileAt(path));
1481
+ }
1482
+ renameAt(from, target, to) {
1483
+ own(target);
1484
+ return attempt(mutableAt(this, [from, to], target), (directory) => directory.renameAt(from, target.directory, to));
1485
+ }
1486
+ async linkAt(_flags, from, target, to) {
1487
+ own(target);
1488
+ const checked = mutableAt(this, [from, to], target);
1489
+ return isResult(checked) ? checked : failure2("unsupported");
1490
+ }
1491
+ async symlinkAt(_from, to) {
1492
+ const checked = mutableAt(this, [to]);
1493
+ return isResult(checked) ? checked : failure2("unsupported");
1494
+ }
1495
+ async isSameObject(other) {
1496
+ own(other);
1497
+ try {
1498
+ return await host.physical(() => this.provider.isSameObject(other.provider));
1499
+ } catch (error) {
1500
+ if (!(error instanceof FilesystemError2))
1501
+ throw error;
1502
+ return false;
1503
+ }
1504
+ }
1505
+ metadataHash() {
1506
+ return attempt(this.provider, (p) => p.stat().then(metadataHash));
1507
+ }
1508
+ metadataHashAt(_flags, path) {
1509
+ return attempt(directoryAt(this, path), (directory) => directory.statAt(path).then(metadataHash));
1510
+ }
1511
+ }
1512
+ const own = (value) => {
1513
+ if (!(value instanceof Descriptor))
1514
+ throw new TypeError("Foreign filesystem descriptor");
1515
+ };
1516
+ const isResult = (value) => typeof value === "object" && value !== null && ("tag" in value) && !(value instanceof Descriptor);
1517
+ function directoryAt(self, ...paths) {
1518
+ const directory = self.directory;
1519
+ if (!directory)
1520
+ return failure2("not-directory");
1521
+ for (const path of paths) {
1522
+ const refused = refusal(path);
1523
+ if (refused)
1524
+ return failure2(refused);
1525
+ }
1526
+ return directory;
1527
+ }
1528
+ function mutableAt(self, paths, other) {
1529
+ if (!self.directory || other && !other.directory)
1530
+ return failure2("not-directory");
1531
+ if (!self.mutable || other && !other.mutable)
1532
+ return failure2("not-permitted");
1533
+ return directoryAt(self, ...paths);
1534
+ }
1535
+ async function attempt(checked, operation) {
1536
+ if (isResult(checked))
1537
+ return checked;
1538
+ try {
1539
+ return ok2(await host.physical(() => operation(checked)));
1540
+ } catch (error) {
1541
+ if (!(error instanceof FilesystemError2) && host.retired.aborted)
1542
+ throw error;
1543
+ return failure2(code(error));
1544
+ }
1545
+ }
1546
+ function failedOutput(reason) {
1547
+ return [
1548
+ hostBytes(async () => {
1549
+ return;
1550
+ }, () => {}, host.retired),
1551
+ Promise.resolve(failure2(reason))
1552
+ ];
1553
+ }
1554
+ function output(self, next) {
1555
+ let settle;
1556
+ const result = new Promise((resolve) => settle = resolve);
1557
+ self.retain();
1558
+ const stream = hostBytes(next, (end, error) => {
1559
+ self.release();
1560
+ settle(end === "failed" ? failure2(code(error)) : ok2());
1561
+ }, host.retired);
1562
+ return [stream, result];
1563
+ }
1564
+ function consume(self, data, offset) {
1565
+ const input = guestBytes(data, host.retired);
1566
+ const file = self.file;
1567
+ if (!file || !self.flags.write) {
1568
+ input.return();
1569
+ return Promise.resolve(failure2("bad-descriptor"));
1570
+ }
1571
+ self.retain();
1572
+ const outcome = (async () => {
1573
+ try {
1574
+ if (file.writeStream) {
1575
+ await host.physical(() => file.writeStream(input, offset));
1576
+ return ok2();
1577
+ }
1578
+ let position = offset;
1579
+ for await (const bytes of input) {
1580
+ if (position === undefined)
1581
+ await host.physical(() => file.append(bytes));
1582
+ else {
1583
+ const at = position;
1584
+ await host.physical(() => file.write(at, bytes));
1585
+ position += BigInt(bytes.byteLength);
1586
+ }
1587
+ }
1588
+ return ok2();
1589
+ } catch (error) {
1590
+ return failure2(code(error));
1591
+ } finally {
1592
+ input.return();
1593
+ self.release();
1594
+ }
1595
+ })();
1596
+ host.cleanup(() => outcome);
1597
+ return outcome;
1598
+ }
1599
+ const root = (mount) => new Descriptor(mount.filesystem.openRoot(), {
1600
+ read: true,
1601
+ write: false,
1602
+ fileIntegritySync: false,
1603
+ dataIntegritySync: false,
1604
+ requestedWriteSync: false,
1605
+ mutateDirectory: mount.writable
1606
+ });
1607
+ return {
1608
+ types: {
1609
+ Descriptor,
1610
+ filesystemErrorCode: () => {
1611
+ return;
1612
+ }
1613
+ },
1614
+ preopens: {
1615
+ getDirectories: () => mounts().map((mount) => [root(mount), mount.path])
1616
+ }
1617
+ };
1618
+ }
1619
+
1620
+ // src/interpreter/component/wasi-http.ts
1621
+ var ERROR_TAGS = new Set([
1622
+ "DNS-timeout",
1623
+ "DNS-error",
1624
+ "destination-not-found",
1625
+ "destination-unavailable",
1626
+ "destination-IP-prohibited",
1627
+ "destination-IP-unroutable",
1628
+ "connection-refused",
1629
+ "connection-terminated",
1630
+ "connection-timeout",
1631
+ "connection-read-timeout",
1632
+ "connection-write-timeout",
1633
+ "connection-limit-reached",
1634
+ "TLS-protocol-error",
1635
+ "TLS-certificate-error",
1636
+ "TLS-alert-received",
1637
+ "HTTP-request-denied",
1638
+ "HTTP-request-length-required",
1639
+ "HTTP-request-body-size",
1640
+ "HTTP-request-method-invalid",
1641
+ "HTTP-request-URI-invalid",
1642
+ "HTTP-request-URI-too-long",
1643
+ "HTTP-request-header-section-size",
1644
+ "HTTP-request-header-size",
1645
+ "HTTP-request-trailer-section-size",
1646
+ "HTTP-request-trailer-size",
1647
+ "HTTP-response-incomplete",
1648
+ "HTTP-response-header-section-size",
1649
+ "HTTP-response-header-size",
1650
+ "HTTP-response-body-size",
1651
+ "HTTP-response-trailer-section-size",
1652
+ "HTTP-response-trailer-size",
1653
+ "HTTP-response-transfer-coding",
1654
+ "HTTP-response-content-coding",
1655
+ "HTTP-response-timeout",
1656
+ "HTTP-upgrade-failed",
1657
+ "HTTP-protocol-error",
1658
+ "loop-detected",
1659
+ "configuration-error",
1660
+ "internal-error"
1661
+ ]);
1662
+ function errorCode(error, fallback = internal) {
1663
+ if (error instanceof HttpProviderError2 || error instanceof HttpHandlerError2) {
1664
+ const code = error.code;
1665
+ if (typeof code?.tag === "string" && ERROR_TAGS.has(code.tag))
1666
+ return code;
1667
+ }
1668
+ return fallback(error instanceof Error ? error.message : String(error));
1669
+ }
1670
+ function millis(duration) {
1671
+ if (duration === undefined)
1672
+ return;
1673
+ const ms = (duration + 999999n) / 1000000n;
1674
+ return ms > 0x7fffffffn ? undefined : Number(ms);
1675
+ }
1676
+ async function readFuture(future, retired) {
1677
+ const value = future;
1678
+ if (typeof value?.then === "function")
1679
+ return await abortable(value, retired);
1680
+ if (typeof value?.read === "function") {
1681
+ const read = await abortable(value.read(), retired);
1682
+ return read && typeof read === "object" && "done" in read && "value" in read ? read.value : read;
1683
+ }
1684
+ throw new TypeError("expected a guest future");
1685
+ }
1686
+ function deadline(pending, signal, ms) {
1687
+ return new Promise((resolve, reject) => {
1688
+ let timer;
1689
+ const stop = () => {
1690
+ clearTimeout(timer);
1691
+ signal?.removeEventListener("abort", abort);
1692
+ };
1693
+ const abort = () => {
1694
+ stop();
1695
+ reject(cancelled());
1696
+ };
1697
+ pending.then((value) => (stop(), resolve(value)), (error) => (stop(), reject(error)));
1698
+ if (signal?.aborted)
1699
+ return abort();
1700
+ signal?.addEventListener("abort", abort, { once: true });
1701
+ if (ms !== undefined)
1702
+ timer = setTimeout(() => {
1703
+ stop();
1704
+ reject(new HttpProviderError2({ tag: "connection-read-timeout" }));
1705
+ }, ms);
1706
+ });
1707
+ }
1708
+ function framedLength(method, status, fields) {
1709
+ if (method === "HEAD" || status < 200 || status === 204 || status === 304)
1710
+ return;
1711
+ const declared = new Set(fields.get("content-length").map(digits));
1712
+ if (declared.size > 1)
1713
+ throw new HttpProviderError2(internal("the HTTP provider returned conflicting lengths"));
1714
+ const [length] = declared;
1715
+ return length === undefined ? undefined : BigInt(length);
1716
+ }
1717
+ function httpImports(host, client) {
1718
+
1719
+ class GuestBody {
1720
+ contents;
1721
+ trailers;
1722
+ result;
1723
+ #settle;
1724
+ #taken = false;
1725
+ #trailersTaken = false;
1726
+ constructor(contents, trailers) {
1727
+ this.contents = contents;
1728
+ this.trailers = trailers;
1729
+ this.result = new Promise((resolve) => this.#settle = resolve);
1730
+ }
1731
+ settle(outcome) {
1732
+ this.#settle(outcome);
1733
+ }
1734
+ #readTrailers() {
1735
+ this.#trailersTaken = true;
1736
+ return readFuture(this.trailers, host.retired);
1737
+ }
1738
+ consume(res) {
1739
+ this.#taken = true;
1740
+ readFuture(res, host.retired).then((outcome) => this.settle(outcome), () => this.settle(done));
1741
+ const contents = this.contents ?? hostBytes(async () => {
1742
+ return;
1743
+ }, () => {}, host.retired);
1744
+ return [contents, this.#readTrailers()];
1745
+ }
1746
+ discard() {
1747
+ if (!this.#taken) {
1748
+ this.#taken = true;
1749
+ try {
1750
+ this.contents?.[Symbol.dispose]?.();
1751
+ } catch {}
1752
+ }
1753
+ if (this.#trailersTaken)
1754
+ return;
1755
+ const trailers = this.trailers;
1756
+ if (typeof trailers?.then !== "function" && typeof trailers?.read !== "function") {
1757
+ this.#trailersTaken = true;
1758
+ return;
1759
+ }
1760
+ this.#readTrailers().then((value) => {
1761
+ if (value?.tag === "ok")
1762
+ value.val?.release();
1763
+ }, () => {});
1764
+ }
1765
+ upload(declared) {
1766
+ this.#taken = true;
1767
+ let complete;
1768
+ let fail;
1769
+ const completed = new Promise((resolve, reject) => (complete = resolve, fail = reject));
1770
+ completed.catch(() => {});
1771
+ const trailers = this.#readTrailers().then((value) => {
1772
+ if (value.tag === "err")
1773
+ throw new HttpProviderError2(value.val);
1774
+ const pairs = value.val?.pairs();
1775
+ value.val?.release();
1776
+ return pairs;
1777
+ });
1778
+ trailers.catch(() => {});
1779
+ if (this.contents === undefined) {
1780
+ if (declared !== undefined && declared !== 0n) {
1781
+ fail(new HttpProviderError2({
1782
+ tag: "HTTP-request-body-size",
1783
+ val: 0n
1784
+ }));
1785
+ } else
1786
+ trailers.then(() => complete(true), fail);
1787
+ return { body: null, trailers, completed, abort() {} };
1788
+ }
1789
+ const input = guestBytes(this.contents, host.retired);
1790
+ let sent = 0n;
1791
+ let stopped = false;
1792
+ let source;
1793
+ const body = new ReadableStream({
1794
+ start(controller) {
1795
+ source = controller;
1796
+ },
1797
+ async pull(controller) {
1798
+ try {
1799
+ const next = await input.next();
1800
+ if (stopped)
1801
+ return;
1802
+ if (next.done) {
1803
+ if (declared !== undefined && sent !== declared)
1804
+ throw new HttpProviderError2({
1805
+ tag: "HTTP-request-body-size",
1806
+ val: sent
1807
+ });
1808
+ await trailers;
1809
+ if (stopped)
1810
+ return;
1811
+ stopped = true;
1812
+ controller.close();
1813
+ complete(true);
1814
+ return;
1815
+ }
1816
+ sent += BigInt(next.value.byteLength);
1817
+ if (declared !== undefined && sent > declared)
1818
+ throw new HttpProviderError2({
1819
+ tag: "HTTP-request-body-size",
1820
+ val: sent
1821
+ });
1822
+ controller.enqueue(next.value);
1823
+ } catch (error) {
1824
+ if (stopped)
1825
+ return;
1826
+ stopped = true;
1827
+ input.return();
1828
+ fail(error);
1829
+ controller.error(error);
1830
+ }
1831
+ },
1832
+ cancel() {
1833
+ if (stopped)
1834
+ return;
1835
+ stopped = true;
1836
+ input.return();
1837
+ complete(false);
1838
+ }
1839
+ }, { highWaterMark: 0 });
1840
+ const abort = (reason) => {
1841
+ if (stopped)
1842
+ return;
1843
+ stopped = true;
1844
+ input.return();
1845
+ try {
1846
+ source?.error(reason);
1847
+ } catch {}
1848
+ fail(reason);
1849
+ };
1850
+ return { body, trailers, completed, abort };
1851
+ }
1852
+ close() {
1853
+ if (this.#taken)
1854
+ return;
1855
+ this.discard();
1856
+ this.settle(done);
1857
+ }
1858
+ }
1859
+
1860
+ class ReceivedBody {
1861
+ reader;
1862
+ trailers;
1863
+ length;
1864
+ between;
1865
+ exchange;
1866
+ abortUpload;
1867
+ #consumed = false;
1868
+ #released = false;
1869
+ #retire = () => this.#release();
1870
+ constructor(reader, trailers, length, between, exchange, abortUpload) {
1871
+ this.reader = reader;
1872
+ this.trailers = trailers;
1873
+ this.length = length;
1874
+ this.between = between;
1875
+ this.exchange = exchange;
1876
+ this.abortUpload = abortUpload;
1877
+ trailers?.catch(() => {});
1878
+ host.retired.addEventListener("abort", this.#retire, { once: true });
1879
+ }
1880
+ consume(res) {
1881
+ this.#consumed = true;
1882
+ readFuture(res, host.retired).then((outcome) => outcome.tag === "err" && this.#release(), () => this.#release());
1883
+ let received = 0n;
1884
+ let settle;
1885
+ const trailers = new Promise((resolve) => settle = resolve);
1886
+ const reader = this.reader;
1887
+ const stream = hostBytes(async () => {
1888
+ for (;; ) {
1889
+ const next = reader ? await host.physical(() => deadline(reader.read(), this.exchange.signal, this.between)) : { done: true, value: undefined };
1890
+ if (next.done) {
1891
+ if (this.length !== undefined && received !== this.length)
1892
+ throw new HttpProviderError2({ tag: "HTTP-response-incomplete" });
1893
+ return;
1894
+ }
1895
+ if (!(next.value instanceof Uint8Array))
1896
+ throw new HttpProviderError2(internal("the HTTP provider produced a non-byte chunk"));
1897
+ if (!next.value.byteLength)
1898
+ continue;
1899
+ received += BigInt(next.value.byteLength);
1900
+ if (this.length !== undefined && received > this.length)
1901
+ throw new HttpProviderError2({
1902
+ tag: "HTTP-response-body-size",
1903
+ val: received
1904
+ });
1905
+ return next.value;
1906
+ }
1907
+ }, (end, failure) => {
1908
+ if (end !== "eof") {
1909
+ this.#release();
1910
+ settle(err(end === "failed" ? errorCode(failure, (message) => ({ tag: "HTTP-protocol-error", val: message })) : internal("response body was dropped")));
1911
+ return;
1912
+ }
1913
+ abortable(Promise.resolve(this.trailers), host.retired).then((pairs) => settle(ok(pairs ? HttpFields.received(pairs) : undefined))).catch((error) => {
1914
+ this.#release();
1915
+ settle(err(errorCode(error)));
1916
+ }).finally(() => host.retired.removeEventListener("abort", this.#retire));
1917
+ }, host.retired);
1918
+ return [stream, trailers];
1919
+ }
1920
+ close() {
1921
+ if (this.#consumed)
1922
+ return;
1923
+ this.#consumed = true;
1924
+ this.#release();
1925
+ }
1926
+ #release() {
1927
+ if (this.#released)
1928
+ return;
1929
+ this.#released = true;
1930
+ host.retired.removeEventListener("abort", this.#retire);
1931
+ this.exchange.abort();
1932
+ this.abortUpload(new HttpProviderError2(internal("response was released before its request body completed")));
1933
+ const reader = this.reader;
1934
+ if (reader)
1935
+ closing(host, () => reader.cancel().catch(() => {}));
1936
+ }
1937
+ }
1938
+
1939
+ class Request extends HttpRequest {
1940
+ static new(headers, contents, trailers, options) {
1941
+ const body = new GuestBody(contents, trailers);
1942
+ return [new Request(headers.frozen(), options?.timeouts, body), body.result];
1943
+ }
1944
+ static consumeBody(self, res) {
1945
+ if (!(self instanceof Request))
1946
+ throw new TypeError("Foreign HTTP request");
1947
+ return self.take().consume(res);
1948
+ }
1949
+ [Symbol.dispose]() {
1950
+ this.release();
1951
+ }
1952
+ }
1953
+
1954
+ class Response extends HttpResponse {
1955
+ static new(headers, contents, trailers) {
1956
+ const body = new GuestBody(contents, trailers);
1957
+ return [new Response(headers.frozen(), body), body.result];
1958
+ }
1959
+ static consumeBody(self, res) {
1960
+ if (!(self instanceof Response))
1961
+ throw new TypeError("Foreign HTTP response");
1962
+ return self.take().consume(res);
1963
+ }
1964
+ [Symbol.dispose]() {
1965
+ this.release();
1966
+ }
1967
+ }
1968
+ function discard(response) {
1969
+ response?.trailers?.catch(() => {});
1970
+ const body = response?.body;
1971
+ if (body instanceof ReadableStream)
1972
+ closing(host, () => body.cancel().catch(() => {}));
1973
+ }
1974
+ async function send(request) {
1975
+ if (!(request instanceof Request))
1976
+ throw new TypeError("Foreign HTTP request");
1977
+ const body = request.take();
1978
+ const method = request.methodName;
1979
+ const timeouts = Object.freeze({ ...request.options });
1980
+ const target = request.target();
1981
+ if (target.tag === "err") {
1982
+ body.settle(err(target.val));
1983
+ body.discard();
1984
+ return target;
1985
+ }
1986
+ const provider = client?.provider(target.val.url);
1987
+ if (!provider) {
1988
+ body.settle(err({ tag: "HTTP-request-denied" }));
1989
+ body.discard();
1990
+ return err({ tag: "HTTP-request-denied" });
1991
+ }
1992
+ const declared = request.headers.get("content-length")[0];
1993
+ const upload = body.upload(declared && BigInt(digits(declared)));
1994
+ const exchange = new AbortController;
1995
+ const outgoing = Object.freeze({
1996
+ url: target.val.url,
1997
+ pathWithQuery: target.val.pathWithQuery,
1998
+ method,
1999
+ fields: request.headers.pairs(),
2000
+ body: upload.body,
2001
+ trailers: upload.trailers,
2002
+ timeouts,
2003
+ signal: exchange.signal
2004
+ });
2005
+ const fail = (code) => {
2006
+ exchange.abort();
2007
+ body.settle(err(code));
2008
+ upload.abort(new HttpProviderError2(code));
2009
+ return err(code);
2010
+ };
2011
+ upload.completed.catch((error) => fail(errorCode(error)));
2012
+ const signal = host.signal();
2013
+ if (signal.aborted)
2014
+ return fail(internal("request was cancelled"));
2015
+ let pending;
2016
+ let response;
2017
+ try {
2018
+ response = await deadline(host.physical(() => {
2019
+ if (signal.aborted)
2020
+ return Promise.reject(cancelled());
2021
+ return pending = provider.send(outgoing);
2022
+ }), signal, millis(timeouts.firstByte));
2023
+ } catch (error) {
2024
+ pending?.then(discard, () => {});
2025
+ if (signal.aborted) {
2026
+ return fail(internal("request was cancelled"));
2027
+ }
2028
+ return fail(errorCode(error));
2029
+ }
2030
+ let fields;
2031
+ let length;
2032
+ let reader;
2033
+ try {
2034
+ const status = response?.status;
2035
+ if (!Number.isInteger(status) || status < 100 || status > 999)
2036
+ throw new HttpProviderError2(internal("the HTTP provider returned an invalid status"));
2037
+ fields = HttpFields.received(response.fields);
2038
+ length = framedLength(method, status, fields);
2039
+ if (response.body !== null && !(response.body instanceof ReadableStream))
2040
+ throw new HttpProviderError2(internal("the HTTP provider returned an invalid body"));
2041
+ reader = response.body?.getReader();
2042
+ } catch (error) {
2043
+ discard(response);
2044
+ return fail(errorCode(error));
2045
+ }
2046
+ upload.completed.then(() => body.settle(done), () => {});
2047
+ const received = new ReceivedBody(reader, response.trailers, length, millis(timeouts.betweenBytes), exchange, upload.abort);
2048
+ return ok(new Response(fields, received, response.status));
2049
+ }
2050
+
2051
+ class IncomingBody {
2052
+ source;
2053
+ trailers;
2054
+ #iterator;
2055
+ #stopped = false;
2056
+ #finished = false;
2057
+ #terminated;
2058
+ #stop = new AbortController;
2059
+ delivering = false;
2060
+ callEnded = false;
2061
+ constructor(source, trailers) {
2062
+ this.source = source;
2063
+ this.trailers = trailers;
2064
+ if (typeof trailers?.then === "function")
2065
+ Promise.resolve(trailers).catch(() => {});
2066
+ }
2067
+ consume(res) {
2068
+ readFuture(res, host.retired).catch(() => {});
2069
+ let settle;
2070
+ const trailers = new Promise((resolve) => settle = resolve);
2071
+ const stream = hostBytes(() => this.#read(), (end, failure) => {
2072
+ if (end !== "eof") {
2073
+ this.#release();
2074
+ settle(end === "failed" ? err(errorCode(failure)) : ok(undefined));
2075
+ return;
2076
+ }
2077
+ this.#finished = true;
2078
+ if (!this.trailers)
2079
+ return settle(ok(undefined));
2080
+ Promise.resolve(this.trailers).then((pairs) => {
2081
+ try {
2082
+ settle(ok(pairs?.length ? HttpFields.received(pairs) : undefined));
2083
+ } catch (error) {
2084
+ settle(err(errorCode(error)));
2085
+ }
2086
+ }, (error) => settle(err(errorCode(error))));
2087
+ }, host.retired);
2088
+ return [stream, trailers];
2089
+ }
2090
+ async#read() {
2091
+ if (this.#terminated)
2092
+ throw new HttpProviderError2(this.#terminated);
2093
+ if (!this.source || this.#stopped)
2094
+ return;
2095
+ this.#iterator ??= this.source[Symbol.asyncIterator]();
2096
+ for (;; ) {
2097
+ let next;
2098
+ try {
2099
+ next = await abortable(this.#iterator.next(), this.#stop.signal);
2100
+ } catch (error) {
2101
+ if (this.#terminated)
2102
+ throw new HttpProviderError2(this.#terminated);
2103
+ throw error;
2104
+ }
2105
+ if (next.done) {
2106
+ this.#iterator = undefined;
2107
+ return;
2108
+ }
2109
+ if (!(next.value instanceof Uint8Array))
2110
+ throw new HttpProviderError2(internal("incoming request chunks must be Uint8Array"));
2111
+ if (next.value.byteLength)
2112
+ return next.value;
2113
+ }
2114
+ }
2115
+ #release() {
2116
+ if (this.#stopped)
2117
+ return;
2118
+ this.#stopped = true;
2119
+ const iterator = this.#iterator;
2120
+ const source = this.source;
2121
+ this.#iterator = undefined;
2122
+ if (iterator || source)
2123
+ Promise.resolve().then(() => (iterator ?? source[Symbol.asyncIterator]()).return?.()).catch(() => {});
2124
+ }
2125
+ terminate(code) {
2126
+ if (this.#terminated || this.#finished)
2127
+ return this.#release();
2128
+ this.#terminated = code;
2129
+ this.#stop.abort();
2130
+ this.#release();
2131
+ }
2132
+ close() {
2133
+ this.#release();
2134
+ }
2135
+ }
2136
+ const incomingFields = (pairs, what) => {
2137
+ try {
2138
+ return HttpFields.received(pairs);
2139
+ } catch {
2140
+ throw new TypeError(`invalid incoming ${what} field`);
2141
+ }
2142
+ };
2143
+ const incoming = new WeakMap;
2144
+ function deliver(published, exchange) {
2145
+ const status = published.getStatusCode();
2146
+ const pairs = published.headers.pairs();
2147
+ const body = published.take();
2148
+ published.release();
2149
+ const request = incoming.get(exchange.request);
2150
+ if (request)
2151
+ request.delivering = true;
2152
+ let transmitted;
2153
+ const transmission = new Promise((resolve) => transmitted = resolve);
2154
+ const [contents, future] = body.consume(transmission);
2155
+ const chunks = typeof contents.read === "function" ? guestBytes(contents, host.retired) : contents[Symbol.asyncIterator]();
2156
+ const written = future.then((result) => {
2157
+ if (result.tag === "err")
2158
+ throw new HttpHandlerError2(result.val);
2159
+ const fields = result.val?.pairs();
2160
+ result.val?.release();
2161
+ return fields?.length ? fields : undefined;
2162
+ });
2163
+ let stopTrailers;
2164
+ const stopped = new Promise((_, reject) => stopTrailers = reject);
2165
+ const trailers = Promise.race([written, stopped]);
2166
+ for (const promise of [written, stopped, trailers])
2167
+ promise.catch(() => {});
2168
+ let resolveEnd;
2169
+ let rejectEnd;
2170
+ const ended = new Promise((resolve, reject) => {
2171
+ resolveEnd = resolve;
2172
+ rejectEnd = reject;
2173
+ });
2174
+ ended.catch(() => {});
2175
+ let finished = false;
2176
+ let started = false;
2177
+ let failure;
2178
+ const finish = (outcome, error) => {
2179
+ if (finished)
2180
+ return;
2181
+ finished = true;
2182
+ signal.removeEventListener("abort", retire);
2183
+ transmitted(outcome);
2184
+ if (request) {
2185
+ request.delivering = false;
2186
+ if (outcome.tag === "err" || request.callEnded)
2187
+ request.terminate(CONNECTION_TERMINATED);
2188
+ }
2189
+ if (error === undefined)
2190
+ resolveEnd();
2191
+ else
2192
+ rejectEnd(error);
2193
+ };
2194
+ const disconnect = (reason) => {
2195
+ if (finished)
2196
+ return;
2197
+ failure = reason;
2198
+ chunks.return?.();
2199
+ stopTrailers(reason ?? new HttpHandlerError2(CONNECTION_TERMINATED));
2200
+ finish(err(CONNECTION_TERMINATED), reason);
2201
+ };
2202
+ const signal = host.signal();
2203
+ const retire = () => disconnect(cancelled());
2204
+ if (signal.aborted)
2205
+ queueMicrotask(retire);
2206
+ else
2207
+ signal.addEventListener("abort", retire, { once: true });
2208
+ host.physical(() => ended).catch(() => {});
2209
+ const next = async () => {
2210
+ if (finished) {
2211
+ if (failure !== undefined)
2212
+ throw failure;
2213
+ return { done: true, value: undefined };
2214
+ }
2215
+ let chunk;
2216
+ try {
2217
+ chunk = await chunks.next();
2218
+ } catch (error) {
2219
+ if (finished)
2220
+ throw failure ?? error;
2221
+ finish(err(errorCode(error)), error);
2222
+ throw error;
2223
+ }
2224
+ if (finished) {
2225
+ if (failure !== undefined)
2226
+ throw failure;
2227
+ return { done: true, value: undefined };
2228
+ }
2229
+ if (!chunk.done)
2230
+ return { done: false, value: chunk.value };
2231
+ try {
2232
+ await trailers;
2233
+ } catch (error) {
2234
+ if (finished)
2235
+ throw failure ?? error;
2236
+ finish(err(errorCode(error)), error);
2237
+ throw error;
2238
+ }
2239
+ if (finished) {
2240
+ if (failure !== undefined)
2241
+ throw failure;
2242
+ return { done: true, value: undefined };
2243
+ }
2244
+ finish(done);
2245
+ return { done: true, value: undefined };
2246
+ };
2247
+ exchange.respond(Object.freeze({
2248
+ status,
2249
+ fields: Object.freeze(pairs.map((pair) => Object.freeze(pair))),
2250
+ body: Object.freeze({
2251
+ [Symbol.asyncIterator]: () => {
2252
+ if (started)
2253
+ throw new TypeError("the response body is read once");
2254
+ started = true;
2255
+ return {
2256
+ next,
2257
+ return: async () => {
2258
+ disconnect();
2259
+ return { done: true, value: undefined };
2260
+ }
2261
+ };
2262
+ }
2263
+ }),
2264
+ trailers
2265
+ }));
2266
+ return ended;
2267
+ }
2268
+ const ingress = {
2269
+ request(parts) {
2270
+ const body = new IncomingBody(parts.body, parts.trailers);
2271
+ let headers;
2272
+ try {
2273
+ headers = incomingFields(parts.fields, "request");
2274
+ } catch (error) {
2275
+ body.close();
2276
+ throw error;
2277
+ }
2278
+ const request = new Request(headers, undefined, body);
2279
+ const refuse = (what) => {
2280
+ request.release();
2281
+ return new TypeError(`invalid incoming request ${what}`);
2282
+ };
2283
+ if (request.setMethod({ tag: "other", val: parts.method }).tag === "err")
2284
+ throw refuse("method");
2285
+ if (parts.scheme !== undefined && request.setScheme({ tag: "other", val: parts.scheme }).tag === "err")
2286
+ throw refuse("scheme");
2287
+ if (request.setAuthority(parts.authority).tag === "err")
2288
+ throw refuse("authority");
2289
+ if (request.setPathWithQuery(parts.pathWithQuery).tag === "err")
2290
+ throw refuse("path with query");
2291
+ incoming.set(parts, body);
2292
+ const ended = host.signal();
2293
+ const end = () => {
2294
+ body.callEnded = true;
2295
+ if (!body.delivering)
2296
+ body.terminate(CONNECTION_TERMINATED);
2297
+ };
2298
+ if (ended.aborted)
2299
+ end();
2300
+ else
2301
+ ended.addEventListener("abort", end, { once: true });
2302
+ return request;
2303
+ },
2304
+ respond(response, exchange) {
2305
+ if (!(response instanceof Response))
2306
+ return Promise.reject(new TypeError("Foreign HTTP response"));
2307
+ return deliver(response, exchange);
2308
+ }
2309
+ };
2310
+ return {
2311
+ types: {
2312
+ Fields: HttpFields,
2313
+ RequestOptions: HttpRequestOptions,
2314
+ Request,
2315
+ Response
2316
+ },
2317
+ client: { send },
2318
+ ingress
2319
+ };
2320
+ }
2321
+
2322
+ // src/interpreter/component/wasi-sockets.ts
2323
+ var callOf = (host) => ({
2324
+ host,
2325
+ signal: host.signal()
2326
+ });
2327
+ var MAX_DATAGRAM = 65535;
2328
+ var DEFAULT_BACKLOG = 128;
2329
+ var MAX_BACKLOG = 2147483647;
2330
+ var ok3 = (val) => ({ tag: "ok", val });
2331
+ var fail = (tag) => ({
2332
+ tag: "err",
2333
+ val: { tag }
2334
+ });
2335
+ var SOCKET_CODES = new Set([
2336
+ "access-denied",
2337
+ "not-supported",
2338
+ "invalid-argument",
2339
+ "out-of-memory",
2340
+ "timeout",
2341
+ "invalid-state",
2342
+ "address-not-bindable",
2343
+ "address-in-use",
2344
+ "remote-unreachable",
2345
+ "connection-refused",
2346
+ "connection-broken",
2347
+ "connection-reset",
2348
+ "connection-aborted",
2349
+ "datagram-too-large",
2350
+ "other"
2351
+ ]);
2352
+ var LOOKUP_CODES = new Set([
2353
+ "access-denied",
2354
+ "invalid-argument",
2355
+ "name-unresolvable",
2356
+ "temporary-resolver-failure",
2357
+ "permanent-resolver-failure",
2358
+ "other"
2359
+ ]);
2360
+ function code2(error, cases, typed) {
2361
+ const tag = typed?.tag;
2362
+ if (typeof tag === "string" && cases.has(tag) && (tag !== "other" || typeof typed.val === "string" || typed.val === undefined))
2363
+ return typed;
2364
+ return {
2365
+ tag: "other",
2366
+ val: error instanceof Error ? error.message : String(error)
2367
+ };
2368
+ }
2369
+ var socketCode = (error) => code2(error, SOCKET_CODES, error instanceof SocketProviderError2 ? error.code : undefined);
2370
+ var lookupCode = (error) => code2(error, LOOKUP_CODES, error instanceof NameLookupError2 ? error.code : undefined);
2371
+ var callCancelled = () => ({
2372
+ tag: "err",
2373
+ val: { tag: "other", val: "call cancelled" }
2374
+ });
2375
+ function attempt(operation) {
2376
+ try {
2377
+ return ok3(operation());
2378
+ } catch (error) {
2379
+ return { tag: "err", val: socketCode(error) };
2380
+ }
2381
+ }
2382
+ function localAddress(value) {
2383
+ if (value === undefined)
2384
+ return fail("invalid-state");
2385
+ const address = fromWit(value);
2386
+ return address ? ok3(toWit(address)) : { tag: "err", val: { tag: "other", val: "invalid provider address" } };
2387
+ }
2388
+ function provided(value) {
2389
+ const address = fromWit(value);
2390
+ if (!address)
2391
+ throw new Error("invalid provider address");
2392
+ return address;
2393
+ }
2394
+ var LIVE = new WeakMap;
2395
+
2396
+ class Shared {
2397
+ host;
2398
+ backend;
2399
+ #users = 1;
2400
+ #closed = false;
2401
+ #busy = new Set;
2402
+ constructor(host, backend) {
2403
+ this.host = host;
2404
+ this.backend = backend;
2405
+ let live = LIVE.get(host.retired);
2406
+ if (!live) {
2407
+ const revision = new Set;
2408
+ live = revision;
2409
+ LIVE.set(host.retired, live);
2410
+ host.retired.addEventListener("abort", () => {
2411
+ for (const shared of [...revision])
2412
+ shared.#close();
2413
+ }, { once: true });
2414
+ }
2415
+ if (host.retired.aborted)
2416
+ this.#close();
2417
+ else
2418
+ live.add(this);
2419
+ }
2420
+ busy(operation) {
2421
+ this.#busy.add(operation);
2422
+ const forget = () => this.#busy.delete(operation);
2423
+ operation.then(forget, forget);
2424
+ }
2425
+ retain() {
2426
+ this.#users++;
2427
+ }
2428
+ release() {
2429
+ if (--this.#users === 0)
2430
+ this.#close();
2431
+ }
2432
+ #close() {
2433
+ if (this.#closed)
2434
+ return;
2435
+ this.#closed = true;
2436
+ LIVE.get(this.host.retired)?.delete(this);
2437
+ closing(this.host, async () => {
2438
+ while (this.#busy.size)
2439
+ await Promise.allSettled([...this.#busy]);
2440
+ await this.backend.close();
2441
+ });
2442
+ }
2443
+ }
2444
+
2445
+ class SocketResource {
2446
+ #users = 1;
2447
+ retain() {
2448
+ this.#users++;
2449
+ }
2450
+ release() {
2451
+ if (--this.#users === 0)
2452
+ this.close();
2453
+ }
2454
+ [Symbol.dispose]() {
2455
+ this.release();
2456
+ }
2457
+ }
2458
+ function getOption(backend, name, valid) {
2459
+ if (!backend.getOption)
2460
+ return fail("not-supported");
2461
+ const value = attempt(() => backend.getOption(name));
2462
+ if (value.tag === "ok" && !valid(value.val))
2463
+ return {
2464
+ tag: "err",
2465
+ val: { tag: "other", val: `invalid provider ${String(name)}` }
2466
+ };
2467
+ return value;
2468
+ }
2469
+ function setOption(backend, name, value) {
2470
+ if (!backend.setOption)
2471
+ return fail("not-supported");
2472
+ return attempt(() => backend.setOption(name, value));
2473
+ }
2474
+ var isU8 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 255;
2475
+ var isU32 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 4294967295;
2476
+ var isU64 = (v) => typeof v === "bigint" && v > 0n && v < 1n << 64n;
2477
+ var isBool = (v) => typeof v === "boolean";
2478
+ function discardConnection(host, connection) {
2479
+ const discarded = Promise.allSettled([
2480
+ Promise.resolve().then(() => connection.readable.cancel()),
2481
+ Promise.resolve().then(() => connection.writable.abort())
2482
+ ]);
2483
+ closing(host, () => discarded);
2484
+ return discarded;
2485
+ }
2486
+ function checkedConnection(value) {
2487
+ const connection = value;
2488
+ if (!(connection?.readable instanceof ReadableStream) || !(connection.writable instanceof WritableStream))
2489
+ throw new Error("invalid provider connection");
2490
+ provided(connection.remote);
2491
+ return connection;
2492
+ }
2493
+
2494
+ class TcpSocket extends SocketResource {
2495
+ access;
2496
+ family;
2497
+ shared;
2498
+ #state;
2499
+ #bound;
2500
+ #backlog = DEFAULT_BACKLOG;
2501
+ #sent = false;
2502
+ #received = false;
2503
+ constructor(access, family, shared, connection) {
2504
+ super();
2505
+ this.access = access;
2506
+ this.family = family;
2507
+ this.shared = shared;
2508
+ this.#state = connection ? { kind: "connected", connection } : { kind: "default" };
2509
+ this.#bound = connection !== undefined;
2510
+ }
2511
+ close() {
2512
+ this.shared.release();
2513
+ }
2514
+ get #backend() {
2515
+ return this.shared.backend;
2516
+ }
2517
+ get #grants() {
2518
+ return this.access.grants;
2519
+ }
2520
+ bind(local) {
2521
+ if (this.#bound || this.#state.kind !== "default")
2522
+ return fail("invalid-state");
2523
+ const address = fromWit(local);
2524
+ if (!isUnicast(address) || !hasFamily(address, this.family))
2525
+ return fail("invalid-argument");
2526
+ if (!this.#grants.allows(address, "tcp-bind"))
2527
+ return fail("access-denied");
2528
+ const backend = this.#backend;
2529
+ if (!backend.bind)
2530
+ return fail("not-supported");
2531
+ const bound = attempt(() => backend.bind(toWit(address)));
2532
+ if (bound.tag === "ok")
2533
+ this.#bound = true;
2534
+ return bound;
2535
+ }
2536
+ async connect(remote, call = callOf(this.shared.host)) {
2537
+ if (this.#state.kind !== "default")
2538
+ return fail("invalid-state");
2539
+ const address = fromWit(remote);
2540
+ if (!isUnicast(address) || !isRemote(address) || !hasFamily(address, this.family))
2541
+ return fail("invalid-argument");
2542
+ if (!this.#bound && !this.#grants.allows(unspecified(this.family), "tcp-bind"))
2543
+ return fail("access-denied");
2544
+ if (!this.#grants.allows(address, "tcp-connect"))
2545
+ return fail("access-denied");
2546
+ this.#state = { kind: "connecting" };
2547
+ const abort = new AbortController;
2548
+ const stop = () => abort.abort();
2549
+ call.signal?.addEventListener("abort", stop, { once: true });
2550
+ const raw = Promise.resolve().then(() => this.#backend.connect(toWit(address), abort.signal));
2551
+ this.shared.busy(raw);
2552
+ const pending = call.host.physical(() => raw);
2553
+ try {
2554
+ const connection = checkedConnection(await abortable(pending, call.signal));
2555
+ this.#state = { kind: "connected", connection };
2556
+ this.#bound = true;
2557
+ return ok3(undefined);
2558
+ } catch (error) {
2559
+ this.#state = { kind: "closed", code: { tag: "invalid-state" } };
2560
+ if (!call.signal?.aborted) {
2561
+ const failure = socketCode(error);
2562
+ this.#state = { kind: "closed", code: failure };
2563
+ return { tag: "err", val: failure };
2564
+ }
2565
+ this.shared.busy(raw.then((late) => discardConnection(call.host, late), () => {}));
2566
+ return callCancelled();
2567
+ } finally {
2568
+ call.signal?.removeEventListener("abort", stop);
2569
+ }
2570
+ }
2571
+ listen(call = callOf(this.shared.host)) {
2572
+ if (this.#state.kind !== "default")
2573
+ return fail("invalid-state");
2574
+ const implicit = unspecified(this.family);
2575
+ if (this.#bound) {
2576
+ const local = localAddress(this.#backend.local);
2577
+ if (local.tag === "err")
2578
+ return local;
2579
+ if (!this.#grants.allows(fromWit(local.val), "tcp-listen"))
2580
+ return fail("access-denied");
2581
+ } else if (!this.#grants.allows(implicit, "tcp-bind") || !this.#grants.allows(implicit, "tcp-listen"))
2582
+ return fail("access-denied");
2583
+ const backend = this.#backend;
2584
+ if (!backend.listen)
2585
+ return fail("not-supported");
2586
+ const listened = attempt(() => backend.listen(this.#backlog));
2587
+ if (listened.tag === "err")
2588
+ return listened;
2589
+ const listener = listened.val;
2590
+ if (typeof listener?.accept !== "function")
2591
+ return {
2592
+ tag: "err",
2593
+ val: { tag: "other", val: "invalid provider listener" }
2594
+ };
2595
+ this.#state = { kind: "listening", listener };
2596
+ this.#bound = true;
2597
+ return ok3(this.#acceptStream(call.host, listener));
2598
+ }
2599
+ #acceptStream(host, listener) {
2600
+ this.shared.retain();
2601
+ const stop = new AbortController;
2602
+ let accepting;
2603
+ const next = async () => {
2604
+ for (;; ) {
2605
+ const call = callOf(host);
2606
+ const signal = call.signal ? AbortSignal.any([stop.signal, call.signal]) : stop.signal;
2607
+ const pull = Promise.resolve().then(() => listener.accept(signal));
2608
+ accepting = pull;
2609
+ this.shared.busy(pull);
2610
+ let accepted;
2611
+ try {
2612
+ accepted = await abortable(host.physical(() => pull), signal);
2613
+ } catch (error) {
2614
+ if (signal.aborted) {
2615
+ const discarded = pull.then(async ({ socket, connection }) => {
2616
+ await discardConnection(host, connection);
2617
+ await socket.close();
2618
+ }, () => {});
2619
+ this.shared.busy(discarded);
2620
+ closing(host, () => discarded);
2621
+ }
2622
+ throw error;
2623
+ }
2624
+ const { socket, connection } = accepted;
2625
+ let checked;
2626
+ try {
2627
+ checked = checkedConnection(connection);
2628
+ if (typeof socket?.close !== "function")
2629
+ throw new Error("invalid provider socket");
2630
+ } catch (error) {
2631
+ closing(host, () => socket?.close?.());
2632
+ throw error;
2633
+ }
2634
+ const Socket = this.constructor;
2635
+ const child = new Socket(this.access, this.family, new Shared(host, socket), checked);
2636
+ if (this.#grants.allows(provided(checked.remote), "tcp-accept"))
2637
+ return child;
2638
+ child.release();
2639
+ }
2640
+ };
2641
+ return hostItems(next, () => {
2642
+ stop.abort();
2643
+ const pending = accepting;
2644
+ closing(host, async () => {
2645
+ await pending?.then(() => {}, () => {});
2646
+ this.shared.release();
2647
+ });
2648
+ }, host.retired);
2649
+ }
2650
+ send(stream, call = callOf(this.shared.host)) {
2651
+ const data = guestBytes(stream, call.host.retired);
2652
+ if (this.#state.kind !== "connected" || this.#sent) {
2653
+ data.return();
2654
+ return Promise.resolve(fail("invalid-state"));
2655
+ }
2656
+ const connection = this.#state.connection;
2657
+ const locked = attempt(() => connection.writable.getWriter());
2658
+ if (locked.tag === "err") {
2659
+ data.return();
2660
+ return Promise.resolve(locked);
2661
+ }
2662
+ this.#sent = true;
2663
+ const host = call.host;
2664
+ const writer = locked.val;
2665
+ this.shared.retain();
2666
+ const value = (async () => {
2667
+ try {
2668
+ for await (const chunk of data)
2669
+ await host.physical(() => writer.write(chunk));
2670
+ const shutdown = writer.close();
2671
+ closing(host, () => shutdown);
2672
+ await shutdown;
2673
+ return ok3(undefined);
2674
+ } catch (error) {
2675
+ data.return();
2676
+ const aborting = writer.abort(error);
2677
+ closing(host, () => aborting);
2678
+ return { tag: "err", val: socketCode(error) };
2679
+ } finally {
2680
+ this.shared.release();
2681
+ }
2682
+ })();
2683
+ host.cleanup(() => value);
2684
+ return value;
2685
+ }
2686
+ receive(call = callOf(this.shared.host)) {
2687
+ const empty = () => hostBytes(async () => {
2688
+ return;
2689
+ }, () => {}, call.host.retired);
2690
+ if (this.#state.kind !== "connected" || this.#received)
2691
+ return [empty(), Promise.resolve(fail("invalid-state"))];
2692
+ const connection = this.#state.connection;
2693
+ const locked = attempt(() => connection.readable.getReader());
2694
+ if (locked.tag === "err")
2695
+ return [empty(), Promise.resolve(locked)];
2696
+ this.#received = true;
2697
+ const host = call.host;
2698
+ const reader = locked.val;
2699
+ this.shared.retain();
2700
+ let settle;
2701
+ const done = new Promise((resolve) => {
2702
+ settle = resolve;
2703
+ });
2704
+ const close = (end) => {
2705
+ closing(host, async () => {
2706
+ if (end !== "eof")
2707
+ await reader.cancel().catch(() => {});
2708
+ this.shared.release();
2709
+ });
2710
+ };
2711
+ const stream = hostBytes(async () => {
2712
+ for (;; ) {
2713
+ const { done: end, value } = await host.physical(() => reader.read());
2714
+ if (end)
2715
+ return;
2716
+ if (!(value instanceof Uint8Array))
2717
+ throw new Error("invalid provider chunk");
2718
+ if (value.byteLength)
2719
+ return value.slice();
2720
+ }
2721
+ }, (end, failure) => {
2722
+ close(end);
2723
+ settle(end === "failed" ? { tag: "err", val: socketCode(failure) } : ok3(undefined));
2724
+ }, host.retired);
2725
+ return [stream, done];
2726
+ }
2727
+ getLocalAddress() {
2728
+ if (this.#state.kind === "closed")
2729
+ return { tag: "err", val: this.#state.code };
2730
+ if (!this.#bound || this.#state.kind === "connecting")
2731
+ return fail("invalid-state");
2732
+ return localAddress(this.#backend.local);
2733
+ }
2734
+ getRemoteAddress() {
2735
+ if (this.#state.kind === "closed")
2736
+ return { tag: "err", val: this.#state.code };
2737
+ if (this.#state.kind !== "connected")
2738
+ return fail("invalid-state");
2739
+ return ok3(toWit(provided(this.#state.connection.remote)));
2740
+ }
2741
+ getIsListening() {
2742
+ return this.#state.kind === "listening";
2743
+ }
2744
+ getAddressFamily() {
2745
+ return this.family;
2746
+ }
2747
+ setListenBacklogSize(value) {
2748
+ if (value === 0n)
2749
+ return fail("invalid-argument");
2750
+ const backlog = value > BigInt(MAX_BACKLOG) ? MAX_BACKLOG : Number(value);
2751
+ switch (this.#state.kind) {
2752
+ case "default":
2753
+ this.#backlog = backlog;
2754
+ return ok3(undefined);
2755
+ case "listening":
2756
+ return setOption(this.#backend, "listenBacklogSize", BigInt(backlog));
2757
+ case "closed":
2758
+ return { tag: "err", val: this.#state.code };
2759
+ default:
2760
+ return fail("invalid-state");
2761
+ }
2762
+ }
2763
+ #get(name, valid) {
2764
+ if (this.#state.kind === "closed")
2765
+ return { tag: "err", val: this.#state.code };
2766
+ return getOption(this.#backend, name, valid);
2767
+ }
2768
+ #set(name, value, positive) {
2769
+ if (positive && (value === 0 || value === 0n))
2770
+ return fail("invalid-argument");
2771
+ if (this.#state.kind === "closed")
2772
+ return { tag: "err", val: this.#state.code };
2773
+ return setOption(this.#backend, name, value);
2774
+ }
2775
+ getKeepAliveEnabled() {
2776
+ return this.#get("keepAliveEnabled", isBool);
2777
+ }
2778
+ setKeepAliveEnabled(value) {
2779
+ return this.#set("keepAliveEnabled", value, false);
2780
+ }
2781
+ getKeepAliveIdleTime() {
2782
+ return this.#get("keepAliveIdleTime", isU64);
2783
+ }
2784
+ setKeepAliveIdleTime(value) {
2785
+ return this.#set("keepAliveIdleTime", value, true);
2786
+ }
2787
+ getKeepAliveInterval() {
2788
+ return this.#get("keepAliveInterval", isU64);
2789
+ }
2790
+ setKeepAliveInterval(value) {
2791
+ return this.#set("keepAliveInterval", value, true);
2792
+ }
2793
+ getKeepAliveCount() {
2794
+ return this.#get("keepAliveCount", isU32);
2795
+ }
2796
+ setKeepAliveCount(value) {
2797
+ return this.#set("keepAliveCount", value, true);
2798
+ }
2799
+ getHopLimit() {
2800
+ return this.#get("hopLimit", isU8);
2801
+ }
2802
+ setHopLimit(value) {
2803
+ return this.#set("hopLimit", value, true);
2804
+ }
2805
+ getReceiveBufferSize() {
2806
+ return this.#get("receiveBufferSize", isU64);
2807
+ }
2808
+ setReceiveBufferSize(value) {
2809
+ return this.#set("receiveBufferSize", value, true);
2810
+ }
2811
+ getSendBufferSize() {
2812
+ return this.#get("sendBufferSize", isU64);
2813
+ }
2814
+ setSendBufferSize(value) {
2815
+ return this.#set("sendBufferSize", value, true);
2816
+ }
2817
+ }
2818
+
2819
+ class UdpSocket extends SocketResource {
2820
+ access;
2821
+ family;
2822
+ shared;
2823
+ #bound = false;
2824
+ #remote;
2825
+ constructor(access, family, shared) {
2826
+ super();
2827
+ this.access = access;
2828
+ this.family = family;
2829
+ this.shared = shared;
2830
+ }
2831
+ close() {
2832
+ this.shared.release();
2833
+ }
2834
+ get #backend() {
2835
+ return this.shared.backend;
2836
+ }
2837
+ get #grants() {
2838
+ return this.access.grants;
2839
+ }
2840
+ bind(local) {
2841
+ if (this.#bound)
2842
+ return fail("invalid-state");
2843
+ const address = fromWit(local);
2844
+ if (!hasFamily(address, this.family))
2845
+ return fail("invalid-argument");
2846
+ if (!this.#grants.allows(address, "udp-bind"))
2847
+ return fail("access-denied");
2848
+ return this.#bind(address);
2849
+ }
2850
+ #bind(address) {
2851
+ const backend = this.#backend;
2852
+ if (!backend.bind)
2853
+ return fail("not-supported");
2854
+ const bound = attempt(() => backend.bind(toWit(address)));
2855
+ if (bound.tag === "ok")
2856
+ this.#bound = true;
2857
+ return bound;
2858
+ }
2859
+ connect(remote) {
2860
+ const address = fromWit(remote);
2861
+ if (!hasFamily(address, this.family) || !isRemote(address))
2862
+ return fail("invalid-argument");
2863
+ const implicit = unspecified(this.family);
2864
+ if (!this.#bound && !this.#grants.allows(implicit, "udp-bind"))
2865
+ return fail("access-denied");
2866
+ if (!this.#grants.allows(address, "udp-send") || !this.#grants.allows(address, "udp-receive"))
2867
+ return fail("access-denied");
2868
+ if (!this.#bound) {
2869
+ const bound = this.#bind(implicit);
2870
+ if (bound.tag === "err")
2871
+ return bound;
2872
+ }
2873
+ this.#remote = address;
2874
+ return ok3(undefined);
2875
+ }
2876
+ disconnect() {
2877
+ if (!this.#remote)
2878
+ return fail("invalid-state");
2879
+ this.#remote = undefined;
2880
+ return ok3(undefined);
2881
+ }
2882
+ async send(data, remote, call = callOf(this.shared.host)) {
2883
+ if (data.byteLength > MAX_DATAGRAM)
2884
+ return fail("datagram-too-large");
2885
+ let target;
2886
+ if (remote !== undefined) {
2887
+ target = fromWit(remote);
2888
+ if (!isRemote(target) || !hasFamily(target, this.family))
2889
+ return fail("invalid-argument");
2890
+ if (this.#remote && key(this.#remote) !== key(target))
2891
+ return fail("invalid-argument");
2892
+ } else if (this.#remote)
2893
+ target = this.#remote;
2894
+ else
2895
+ return fail("invalid-argument");
2896
+ if (!this.#bound && !this.#grants.allows(unspecified(this.family), "udp-bind"))
2897
+ return fail("access-denied");
2898
+ if (!this.#grants.allows(target, "udp-send"))
2899
+ return fail("access-denied");
2900
+ const abort = new AbortController;
2901
+ const stop = () => abort.abort();
2902
+ call.signal?.addEventListener("abort", stop, { once: true });
2903
+ try {
2904
+ await abortable(call.host.physical(() => this.#backend.send(data.slice(), toWit(target), abort.signal)), call.signal);
2905
+ this.#bound = true;
2906
+ return ok3(undefined);
2907
+ } catch (error) {
2908
+ if (call.signal?.aborted)
2909
+ return callCancelled();
2910
+ return { tag: "err", val: socketCode(error) };
2911
+ } finally {
2912
+ call.signal?.removeEventListener("abort", stop);
2913
+ }
2914
+ }
2915
+ async receive(call = callOf(this.shared.host)) {
2916
+ if (!this.#bound)
2917
+ return fail("invalid-state");
2918
+ const abort = new AbortController;
2919
+ const stop = () => abort.abort();
2920
+ call.signal?.addEventListener("abort", stop, { once: true });
2921
+ try {
2922
+ for (;; ) {
2923
+ const datagram = await abortable(call.host.physical(() => this.#backend.receive(abort.signal)), call.signal);
2924
+ const sender = provided(datagram?.remote);
2925
+ if (!(datagram.data instanceof Uint8Array) || datagram.data.byteLength > MAX_DATAGRAM)
2926
+ throw new Error("invalid provider datagram");
2927
+ if (this.#remote && key(this.#remote) !== key(sender))
2928
+ continue;
2929
+ if (!this.#grants.allows(sender, "udp-receive"))
2930
+ continue;
2931
+ return ok3([datagram.data.slice(), toWit(sender)]);
2932
+ }
2933
+ } catch (error) {
2934
+ if (call.signal?.aborted)
2935
+ return callCancelled();
2936
+ return { tag: "err", val: socketCode(error) };
2937
+ } finally {
2938
+ call.signal?.removeEventListener("abort", stop);
2939
+ }
2940
+ }
2941
+ getLocalAddress() {
2942
+ return this.#bound ? localAddress(this.#backend.local) : fail("invalid-state");
2943
+ }
2944
+ getRemoteAddress() {
2945
+ return this.#remote ? ok3(toWit(this.#remote)) : fail("invalid-state");
2946
+ }
2947
+ getAddressFamily() {
2948
+ return this.family;
2949
+ }
2950
+ #set(name, value) {
2951
+ if (value === 0 || value === 0n)
2952
+ return fail("invalid-argument");
2953
+ return setOption(this.#backend, name, value);
2954
+ }
2955
+ getUnicastHopLimit() {
2956
+ return getOption(this.#backend, "unicastHopLimit", isU8);
2957
+ }
2958
+ setUnicastHopLimit(value) {
2959
+ return this.#set("unicastHopLimit", value);
2960
+ }
2961
+ getReceiveBufferSize() {
2962
+ return getOption(this.#backend, "receiveBufferSize", isU64);
2963
+ }
2964
+ setReceiveBufferSize(value) {
2965
+ return this.#set("receiveBufferSize", value);
2966
+ }
2967
+ getSendBufferSize() {
2968
+ return getOption(this.#backend, "sendBufferSize", isU64);
2969
+ }
2970
+ setSendBufferSize(value) {
2971
+ return this.#set("sendBufferSize", value);
2972
+ }
2973
+ }
2974
+ async function resolveAddresses(access, name, call) {
2975
+ const failure = (tag) => ({
2976
+ tag: "err",
2977
+ val: { tag }
2978
+ });
2979
+ if (!access?.grants.resolve)
2980
+ return failure("access-denied");
2981
+ const parsed = parseHostName(name);
2982
+ if (!parsed)
2983
+ return failure("invalid-argument");
2984
+ if ("ip" in parsed)
2985
+ return ok3([parsed.ip]);
2986
+ const resolve = access.provider?.resolve;
2987
+ if (!resolve)
2988
+ return failure("permanent-resolver-failure");
2989
+ const abort = new AbortController;
2990
+ const stop = () => abort.abort();
2991
+ call.signal?.addEventListener("abort", stop, { once: true });
2992
+ try {
2993
+ const found = await abortable(call.host.physical(() => resolve.call(access.provider, parsed.domain, abort.signal)), call.signal);
2994
+ if (!Array.isArray(found))
2995
+ throw new Error("invalid provider result");
2996
+ const addresses = found.map(checkedIpAddress);
2997
+ if (addresses.some((address) => address === undefined))
2998
+ throw new Error("invalid provider address");
2999
+ if (!addresses.length)
3000
+ return failure("name-unresolvable");
3001
+ return ok3(addresses);
3002
+ } catch (error) {
3003
+ if (call.signal?.aborted)
3004
+ return callCancelled();
3005
+ return { tag: "err", val: lookupCode(error) };
3006
+ } finally {
3007
+ call.signal?.removeEventListener("abort", stop);
3008
+ }
3009
+ }
3010
+ function create(access, allowed, factory, family, host, make) {
3011
+ if (!access || !allowed)
3012
+ return fail("access-denied");
3013
+ if (!factory)
3014
+ return fail("not-supported");
3015
+ const created = attempt(() => factory.create(family));
3016
+ if (created.tag === "err")
3017
+ return created;
3018
+ if (typeof created.val?.close !== "function")
3019
+ return {
3020
+ tag: "err",
3021
+ val: { tag: "other", val: "invalid provider socket" }
3022
+ };
3023
+ return ok3(make(access, new Shared(host, created.val)));
3024
+ }
3025
+ function socketImports(host, bindings) {
3026
+ const types = bindings.types;
3027
+
3028
+ class Tcp extends TcpSocket {
3029
+ static create(family) {
3030
+ return create(types, types?.grants.tcp ?? false, types?.provider?.tcp, family, host, (access, shared) => new Tcp(access, family, shared));
3031
+ }
3032
+ }
3033
+
3034
+ class Udp extends UdpSocket {
3035
+ static create(family) {
3036
+ return create(types, types?.grants.udp ?? false, types?.provider?.udp, family, host, (access, shared) => new Udp(access, family, shared));
3037
+ }
3038
+ }
3039
+ return {
3040
+ types: { TcpSocket: Tcp, UdpSocket: Udp },
3041
+ "ip-name-lookup": {
3042
+ resolveAddresses: (name) => resolveAddresses(bindings.lookup, name, callOf(host))
3043
+ }
3044
+ };
3045
+ }
3046
+
3047
+ // src/interpreter/component/wasi.ts
3048
+ class RuntimeTrap extends Error {
3049
+ }
3050
+ var ok4 = (val) => val === undefined ? { tag: "ok" } : { tag: "ok", val };
3051
+ var BROWSER_WASI = new Set([
3052
+ "wasi:clocks/monotonic-clock@0.3.0",
3053
+ "wasi:clocks/system-clock@0.3.0",
3054
+ "wasi:clocks/types@0.3.0",
3055
+ "wasi:random/random@0.3.0",
3056
+ "wasi:random/insecure@0.3.0",
3057
+ "wasi:random/insecure-seed@0.3.0",
3058
+ "wasi:cli/environment@0.3.0",
3059
+ "wasi:cli/exit@0.3.0",
3060
+ "wasi:cli/stdin@0.3.0",
3061
+ "wasi:cli/stdout@0.3.0",
3062
+ "wasi:cli/stderr@0.3.0",
3063
+ "wasi:cli/types@0.3.0",
3064
+ "wasi:cli/terminal-input@0.3.0",
3065
+ "wasi:cli/terminal-output@0.3.0",
3066
+ "wasi:cli/terminal-stdin@0.3.0",
3067
+ "wasi:cli/terminal-stdout@0.3.0",
3068
+ "wasi:cli/terminal-stderr@0.3.0",
3069
+ "wasi:filesystem/types@0.3.0",
3070
+ "wasi:filesystem/preopens@0.3.0",
3071
+ "wasi:http/types@0.3.0",
3072
+ "wasi:http/client@0.3.0",
3073
+ "wasi:sockets/types@0.3.0",
3074
+ "wasi:sockets/ip-name-lookup@0.3.0"
3075
+ ]);
3076
+ function checkPublicWasi(names) {
3077
+ const missing = names.filter((name) => name.startsWith("wasi:") && !BROWSER_WASI.has(name));
3078
+ if (missing.length)
3079
+ throw new Error(`Browser component execution does not provide ${missing.join(", ")} yet; ` + "this Orb cannot be installed in the browser");
3080
+ }
3081
+ function publicWasi(names, providers) {
3082
+ const { clocks, random, cli, host } = providers;
3083
+ const signal = host.retired;
3084
+ const need = (value, grant) => {
3085
+ if (value === undefined)
3086
+ throw new Error(`The installation holds no ${grant} grant`);
3087
+ return value;
3088
+ };
3089
+ const randomBytes = (secure) => (length) => {
3090
+ const source = need(random, "random");
3091
+ const size = Number(length > 1n << 20n ? 1n << 20n : length);
3092
+ const bytes = secure ? source.secure(size) : source.insecure(size);
3093
+ if (!(bytes instanceof Uint8Array) || bytes.length !== size)
3094
+ throw new Error("random provider returned the wrong byte length");
3095
+ return bytes;
3096
+ };
3097
+ const randomU64 = (secure) => () => {
3098
+ const bytes = randomBytes(secure)(8n);
3099
+ return new DataView(bytes.buffer, bytes.byteOffset, 8).getBigUint64(0, true);
3100
+ };
3101
+ let seed;
3102
+ const writes = new Map;
3103
+ const write = (name) => async (data) => {
3104
+ const output = need(cli, "cli").stdio[name];
3105
+ const selected = cli.options[name];
3106
+ const cancel = host.signal();
3107
+ try {
3108
+ for await (const chunk of guestBytes(data, cancel))
3109
+ if (output && selected !== "discard") {
3110
+ const bytes = chunk.slice();
3111
+ const operation = (writes.get(output) ?? Promise.resolve()).then(() => {
3112
+ if (cancel.aborted)
3113
+ throw cancelled();
3114
+ return output.write(bytes, cancel);
3115
+ });
3116
+ const turn = operation.then(() => {}, () => {});
3117
+ writes.set(output, turn);
3118
+ turn.then(() => {
3119
+ if (writes.get(output) === turn)
3120
+ writes.delete(output);
3121
+ });
3122
+ await host.physical(() => operation);
3123
+ }
3124
+ return ok4();
3125
+ } catch {
3126
+ return { tag: "err", val: "io" };
3127
+ }
3128
+ };
3129
+ const waitUntil = async (when) => {
3130
+ const source = need(clocks, "clocks");
3131
+ const cancel = host.signal();
3132
+ try {
3133
+ await host.physical(() => source.waitUntil(when, cancel));
3134
+ } catch (error) {
3135
+ if (!cancel.aborted)
3136
+ throw error;
3137
+ }
3138
+ };
3139
+ const interfaces = {
3140
+ "wasi:clocks/types@0.3.0": {},
3141
+ "wasi:clocks/monotonic-clock@0.3.0": {
3142
+ now: () => need(clocks, "clocks").monotonicNow(),
3143
+ getResolution: () => need(clocks, "clocks").monotonicResolution(),
3144
+ waitUntil,
3145
+ waitFor: (duration) => waitUntil(need(clocks, "clocks").monotonicNow() + duration)
3146
+ },
3147
+ "wasi:clocks/system-clock@0.3.0": {
3148
+ now: () => need(clocks, "clocks").systemNow(),
3149
+ getResolution: () => need(clocks, "clocks").systemResolution()
3150
+ },
3151
+ "wasi:random/random@0.3.0": {
3152
+ getRandomBytes: randomBytes(true),
3153
+ getRandomU64: randomU64(true)
3154
+ },
3155
+ "wasi:random/insecure@0.3.0": {
3156
+ getInsecureRandomBytes: randomBytes(false),
3157
+ getInsecureRandomU64: randomU64(false)
3158
+ },
3159
+ "wasi:random/insecure-seed@0.3.0": {
3160
+ getInsecureSeed: () => seed ??= need(random, "random").insecureSeed()
3161
+ },
3162
+ "wasi:cli/types@0.3.0": {},
3163
+ "wasi:cli/environment@0.3.0": {
3164
+ getEnvironment: () => (cli?.options.environment ?? []).map(([key, value]) => [key, value]),
3165
+ getArguments: () => [...cli?.options.arguments ?? []],
3166
+ getInitialCwd: () => cli?.options.initialCwd
3167
+ },
3168
+ "wasi:cli/exit@0.3.0": {
3169
+ exit: (status) => {
3170
+ throw new RuntimeTrap(`orb exited with status ${status?.tag === "ok" ? 0 : 1}`);
3171
+ },
3172
+ exitWithCode: (code) => {
3173
+ throw new RuntimeTrap(`orb exited with status ${code}`);
3174
+ }
3175
+ },
3176
+ "wasi:cli/stdout@0.3.0": { writeViaStream: write("stdout") },
3177
+ "wasi:cli/stderr@0.3.0": { writeViaStream: write("stderr") },
3178
+ "wasi:cli/stdin@0.3.0": {
3179
+ readViaStream: () => {
3180
+ const options = need(cli, "cli").options.stdin;
3181
+ const input = cli.stdio.stdin;
3182
+ let settle;
3183
+ const result = new Promise((resolve) => settle = resolve);
3184
+ const fixed = typeof options === "object" && "bytes" in options ? options.bytes.slice() : undefined;
3185
+ let offset = 0;
3186
+ const readable = hostBytes(async (limit) => {
3187
+ if (options === "empty")
3188
+ return;
3189
+ if (fixed) {
3190
+ const chunk = fixed.subarray(offset, offset + limit);
3191
+ offset += chunk.length;
3192
+ return chunk.length ? chunk.slice() : undefined;
3193
+ }
3194
+ const cancel = host.signal();
3195
+ return input ? await host.physical(() => input.read(limit, cancel)) : undefined;
3196
+ }, (end) => settle(end === "failed" ? { tag: "err", val: "io" } : ok4()), signal);
3197
+ return [readable, result];
3198
+ }
3199
+ },
3200
+ "wasi:cli/terminal-input@0.3.0": { TerminalInput: class TerminalInput {
3201
+ } },
3202
+ "wasi:cli/terminal-output@0.3.0": {
3203
+ TerminalOutput: class TerminalOutput {
3204
+ }
3205
+ },
3206
+ "wasi:cli/terminal-stdin@0.3.0": { getTerminalStdin: () => {
3207
+ return;
3208
+ } },
3209
+ "wasi:cli/terminal-stdout@0.3.0": { getTerminalStdout: () => {
3210
+ return;
3211
+ } },
3212
+ "wasi:cli/terminal-stderr@0.3.0": { getTerminalStderr: () => {
3213
+ return;
3214
+ } }
3215
+ };
3216
+ const filesystem = filesystemImports(host, providers.mounts);
3217
+ interfaces["wasi:filesystem/types@0.3.0"] = filesystem.types;
3218
+ interfaces["wasi:filesystem/preopens@0.3.0"] = filesystem.preopens;
3219
+ const http = httpImports(host, providers.http);
3220
+ interfaces["wasi:http/types@0.3.0"] = http.types;
3221
+ interfaces["wasi:http/client@0.3.0"] = http.client;
3222
+ providers.ingress?.(http.ingress);
3223
+ const sockets = socketImports(host, providers.sockets);
3224
+ interfaces["wasi:sockets/types@0.3.0"] = sockets.types;
3225
+ interfaces["wasi:sockets/ip-name-lookup@0.3.0"] = sockets["ip-name-lookup"];
3226
+ checkPublicWasi(names);
3227
+ const imports = {};
3228
+ for (const name of names)
3229
+ if (interfaces[name])
3230
+ imports[name] = interfaces[name];
3231
+ return imports;
3232
+ }
3233
+
3234
+ export { issueByteStream, ComponentPort, importedResource, viewMethod, referenceView, referenceImport, resourceImport, converters, BROWSER_WASI, checkPublicWasi, publicWasi };