@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
package/src/guest.ts ADDED
@@ -0,0 +1,327 @@
1
+ import { utf8Decode, utf8Encode } from "./interpreter/standard-utf8.ts";
2
+
3
+ /** The guest observes cancellation without receiving an EventTarget or host context identity. */
4
+ export interface Signal {
5
+ readonly aborted: boolean;
6
+ throwIfAborted(): void;
7
+ }
8
+
9
+ export interface Context {
10
+ readonly principal: string;
11
+ check(): void;
12
+ cancel(): void;
13
+ /**
14
+ * Acquire a selected WIT Orb import by key for this context's root and principal. The host
15
+ * applies the installed requirement and waits for readiness; the claim ends with the root, and
16
+ * the reference is refused in every other root.
17
+ */
18
+ get<Interface>(
19
+ binding: string,
20
+ key: string | readonly string[],
21
+ ): Promise<WitReference<Interface>>;
22
+ }
23
+
24
+ export interface Readable<T> {
25
+ readonly value: Readonly<T>;
26
+ select<R>(compute: (value: Readonly<T>) => R): Readable<R>;
27
+ }
28
+
29
+ export interface State<T> extends Readable<T> {
30
+ update(context: Context, change: (current: Readonly<T>) => T): Readonly<T>;
31
+ }
32
+
33
+ export interface Resource<T> {
34
+ readonly value: T;
35
+ readonly version: number;
36
+ }
37
+
38
+ export type WitReference<Interface> = {
39
+ readonly ready: Promise<void>;
40
+ readonly status: string;
41
+ readonly state: Readable<unknown>;
42
+ release(): void;
43
+ } & {
44
+ [
45
+ Method in keyof Interface as Interface[Method] extends (...args: never[]) => unknown
46
+ ? Method
47
+ : never
48
+ ]: Interface[Method] extends (...args: infer Arguments) => infer Result
49
+ ? (...args: [...Arguments, context?: Context]) => Promise<Awaited<Result>>
50
+ : never;
51
+ };
52
+
53
+ export interface Declaration {
54
+ readonly key: readonly string[];
55
+ readonly principal: string;
56
+ readonly orb: unknown;
57
+ state<T>(
58
+ initial: T,
59
+ options?: { version?: number; validate?(value: Readonly<T>): boolean | void },
60
+ ): State<T>;
61
+ get<Interface>(binding: string, key?: string | readonly string[]): WitReference<Interface>;
62
+ hook<Input = unknown, Output = Input>(
63
+ name: string,
64
+ ): {
65
+ run(context: Context, input: Input): Promise<Output>;
66
+ };
67
+ resource<T>(
68
+ name: string,
69
+ options: {
70
+ version?: number;
71
+ deps?: readonly Resource<unknown>[];
72
+ open(signal: Signal): T | PromiseLike<T>;
73
+ close?(value: T, context: Context): unknown;
74
+ },
75
+ ): Resource<T>;
76
+ }
77
+
78
+ export type WitMethods<Interface, Environment> = {
79
+ [
80
+ Method in keyof Interface as Interface[Method] extends (...args: never[]) => unknown
81
+ ? Method
82
+ : never
83
+ ]: Interface[Method] extends (...args: infer Arguments) => infer Result
84
+ ? (
85
+ environment: Environment,
86
+ context: Context,
87
+ ...args: Arguments
88
+ ) => Awaited<Result> | PromiseLike<Awaited<Result>>
89
+ : never;
90
+ };
91
+
92
+ interface Service {
93
+ create?(self: Declaration): unknown;
94
+ methods: Record<string, (...args: never[]) => unknown>;
95
+ lifetime?: "referenced" | "host";
96
+ linger?: number;
97
+ }
98
+
99
+ export interface HookComposition {
100
+ readonly composition: "series" | "waterfall" | "bail";
101
+ }
102
+
103
+ /** Observe each contribution in the kernel's plan order. */
104
+ export function series(): HookComposition {
105
+ return { composition: "series" };
106
+ }
107
+ /** Pass each contribution's result to the next participant. */
108
+ export function waterfall(): HookComposition {
109
+ return { composition: "waterfall" };
110
+ }
111
+ /** Return the first defined contribution result. */
112
+ export function bail(): HookComposition {
113
+ return { composition: "bail" };
114
+ }
115
+
116
+ /**
117
+ * A source contribution receives the Orb root environment returned by `orb.create`, then the
118
+ * issued context and the hook input, like a service method. Annotate the environment with its
119
+ * actual type, for example `ReturnType<typeof create>`.
120
+ */
121
+ export type Contribution =
122
+ | ((environment: never, context: Context, input: never) => unknown)
123
+ | {
124
+ handle(environment: never, context: Context, input: never): unknown;
125
+ priority?: number;
126
+ };
127
+
128
+ /** Retain literal identity and callbacks; the outer host validates them against WIT before admission. */
129
+ export function orb<
130
+ const Definition extends {
131
+ name: string;
132
+ apiVersion: number;
133
+ create?(self: Declaration): unknown;
134
+ services?: Record<string, Service>;
135
+ hooks?: Readonly<Record<string, HookComposition>>;
136
+ contributes?: Readonly<Record<string, Contribution>>;
137
+ },
138
+ >(definition: Definition): Readonly<Definition> {
139
+ return Object.freeze(definition);
140
+ }
141
+
142
+ declare global {
143
+ interface Console {
144
+ log(...values: unknown[]): void;
145
+ debug(...values: unknown[]): void;
146
+ info(...values: unknown[]): void;
147
+ warn(...values: unknown[]): void;
148
+ error(...values: unknown[]): void;
149
+ }
150
+ var console: Console;
151
+ const tembra: {
152
+ wait(milliseconds: number): Promise<void>;
153
+ };
154
+ }
155
+
156
+ /** Chunk reader the interpreter attaches to every standard `stream<u8>` it issues. */
157
+ const READ_CHUNK = Symbol.for("tembra.wasi.stream.read-chunk");
158
+ /** Fallback batch size for byte streams that expose only per-byte iteration. */
159
+ const BATCH_BYTES = 64 << 10;
160
+
161
+ /**
162
+ * Iterate a standard WIT `stream<u8>` as `Uint8Array` chunks.
163
+ *
164
+ * jco declares `stream<u8>` as `AsyncIterable<number>`, and the interpreter's streams honor that
165
+ * contract, but awaiting one element per byte spends the callback's instruction budget on every
166
+ * byte. Streams issued by the interpreter already transfer bounded raw chunks (at most 64 KiB);
167
+ * this returns those chunks unchanged. Any other `AsyncIterable<number>` is batched.
168
+ */
169
+ export async function* readChunks(
170
+ stream: AsyncIterable<number>,
171
+ ): AsyncGenerator<Uint8Array, void, undefined> {
172
+ const read = (stream as { [READ_CHUNK]?: () => Promise<Uint8Array | undefined> })[READ_CHUNK];
173
+ if (typeof read === "function") {
174
+ try {
175
+ for (let chunk = await read.call(stream); chunk; chunk = await read.call(stream)) yield chunk;
176
+ } finally {
177
+ dropStream(stream);
178
+ }
179
+ return;
180
+ }
181
+ let batch = new Uint8Array(BATCH_BYTES);
182
+ let length = 0;
183
+ for await (const byte of stream) {
184
+ batch[length++] = byte;
185
+ if (length === BATCH_BYTES) {
186
+ yield batch;
187
+ batch = new Uint8Array(BATCH_BYTES);
188
+ length = 0;
189
+ }
190
+ }
191
+ if (length) yield batch.slice(0, length);
192
+ }
193
+
194
+ /** Chunk source the interpreter recognizes on a `stream<u8>` argument. */
195
+ const WRITE_CHUNKS = Symbol.for("tembra.wasi.stream.write-chunks");
196
+ /** Default bound of `readBytes`/`readText`. */
197
+ const READ_LIMIT = 16 << 20;
198
+
199
+ /**
200
+ * Pass `Uint8Array` chunks as a standard WIT `stream<u8>` argument.
201
+ *
202
+ * The result is the `AsyncIterable<number>` jco declares, so it type-checks wherever a
203
+ * `stream<u8>` is expected. The interpreter recognizes it and transfers each chunk in raw
204
+ * pieces of at most 64 KiB with backpressure instead of iterating bytes; any other consumer
205
+ * sees the bytes one by one. Chunks are read lazily; do not mutate one until the next is
206
+ * requested. The source's `return()` runs if the consumer stops early.
207
+ */
208
+ export function writeChunks(
209
+ chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>,
210
+ ): AsyncIterable<number> {
211
+ const iterator = () =>
212
+ Symbol.asyncIterator in chunks
213
+ ? (chunks as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]()
214
+ : (chunks as Iterable<Uint8Array>)[Symbol.iterator]();
215
+ return {
216
+ [WRITE_CHUNKS]: iterator,
217
+ async *[Symbol.asyncIterator]() {
218
+ for await (const chunk of chunks) yield* chunk;
219
+ },
220
+ } as AsyncIterable<number>;
221
+ }
222
+
223
+ /** jco's `result<_, error-code>` payload of a filesystem stream future. */
224
+ export type WasiResult = { tag: "ok"; val?: unknown } | { tag: "err"; val: unknown };
225
+
226
+ /** The part of a standard `wasi:filesystem` descriptor the read helpers use. */
227
+ export interface ReadableFile {
228
+ readViaStream(offset: bigint): readonly [AsyncIterable<number>, PromiseLike<WasiResult>];
229
+ }
230
+
231
+ /** The part of a standard `wasi:filesystem` descriptor the write helpers use. */
232
+ export interface WritableFile {
233
+ writeViaStream(data: AsyncIterable<number>, offset: bigint): PromiseLike<WasiResult>;
234
+ appendViaStream(data: AsyncIterable<number>): PromiseLike<WasiResult>;
235
+ }
236
+
237
+ /** A filesystem helper failed with a WASI `error-code`; `code` is its tag. */
238
+ export class FilesystemCallError extends Error {
239
+ readonly code: string;
240
+ constructor(readonly payload: unknown) {
241
+ const code = String((payload as { tag?: unknown } | null)?.tag ?? "other");
242
+ super(`filesystem call failed: ${code}`);
243
+ this.code = code;
244
+ }
245
+ }
246
+
247
+ /** Throw the error case of a stream future's result. */
248
+ function check(result: WasiResult): void {
249
+ if (result?.tag === "err") throw new FilesystemCallError(result.val);
250
+ }
251
+
252
+ /** Drop a stream or unread future handle now instead of waiting for collection. */
253
+ function dropStream(stream: unknown): void {
254
+ const dispose = (Symbol as { dispose?: symbol }).dispose ?? Symbol.for("Symbol.dispose");
255
+ (stream as Record<symbol, (() => void) | undefined>)[dispose]?.();
256
+ }
257
+
258
+ /**
259
+ * Read a file from `offset` (default `0n`) to its end through `read-via-stream`. More than
260
+ * `maxBytes` (default 16 MiB) is refused with a `RangeError` instead of growing without bound.
261
+ */
262
+ export async function readBytes(
263
+ file: ReadableFile,
264
+ options: { offset?: bigint; maxBytes?: number } = {},
265
+ ): Promise<Uint8Array> {
266
+ const limit = options.maxBytes ?? READ_LIMIT;
267
+ const [stream, done] = file.readViaStream(options.offset ?? 0n);
268
+ let consumed = false;
269
+ try {
270
+ const chunks: Uint8Array[] = [];
271
+ let total = 0;
272
+ for await (const chunk of readChunks(stream)) {
273
+ total += chunk.byteLength;
274
+ if (total > limit) throw new RangeError(`file exceeds the ${limit} byte read bound`);
275
+ chunks.push(chunk);
276
+ }
277
+ consumed = true;
278
+ check(await done);
279
+ if (chunks.length === 1) return chunks[0]!;
280
+ const bytes = new Uint8Array(total);
281
+ let offset = 0;
282
+ for (const chunk of chunks) {
283
+ bytes.set(chunk, offset);
284
+ offset += chunk.byteLength;
285
+ }
286
+ return bytes;
287
+ } finally {
288
+ dropStream(stream);
289
+ // An early failure leaves the completion future unread; drop it too.
290
+ if (!consumed) dropStream(done);
291
+ }
292
+ }
293
+
294
+ /** `readBytes`, then strict UTF-8 decoding; invalid UTF-8 is a `RangeError`. */
295
+ export async function readText(
296
+ file: ReadableFile,
297
+ options: { offset?: bigint; maxBytes?: number } = {},
298
+ ): Promise<string> {
299
+ return utf8Decode(await readBytes(file, options));
300
+ }
301
+
302
+ /**
303
+ * Write `bytes` at `offset` (default `0n`), or at the end of file with `append`, through
304
+ * `write-via-stream`/`append-via-stream`. It never truncates: open the file with the
305
+ * `truncate` flag to replace its contents.
306
+ */
307
+ export async function writeBytes(
308
+ file: WritableFile,
309
+ bytes: Uint8Array,
310
+ options: { offset?: bigint; append?: boolean } = {},
311
+ ): Promise<void> {
312
+ const data = writeChunks([bytes]);
313
+ check(
314
+ await (options.append
315
+ ? file.appendViaStream(data)
316
+ : file.writeViaStream(data, options.offset ?? 0n)),
317
+ );
318
+ }
319
+
320
+ /** Encode `text` as UTF-8 and `writeBytes` it. */
321
+ export function writeText(
322
+ file: WritableFile,
323
+ text: string,
324
+ options: { offset?: bigint; append?: boolean } = {},
325
+ ): Promise<void> {
326
+ return writeBytes(file, utf8Encode(text), options);
327
+ }
package/src/host.ts CHANGED
@@ -2,8 +2,9 @@ import { orb } from "./authoring/orb.ts";
2
2
  import type {
3
3
  AcquisitionOptions,
4
4
  Completion,
5
- OrbDefinition,
5
+ OrbInput,
6
6
  HostOptions,
7
+ LoadOptions,
7
8
  ReloadOptions,
8
9
  ResourceOptions,
9
10
  DynamicReference,
@@ -13,6 +14,19 @@ import type {
13
14
  import { KernelOp } from "./bridge/protocol.ts";
14
15
  import { Context } from "./runtime/context.ts";
15
16
  import { Session } from "./runtime/session.ts";
17
+ import {
18
+ checkedRequest,
19
+ HTTP_HANDLER,
20
+ IngressExchange,
21
+ type HandleHttpOptions,
22
+ type HttpHandlerResponse,
23
+ type IncomingHttpRequest,
24
+ } from "./interpreter/http-ingress.ts";
25
+ import {
26
+ fromFetchRequest,
27
+ isFetchRequest,
28
+ toFetchResponse,
29
+ } from "./interpreter/http-ingress-fetch.ts";
16
30
 
17
31
  /** The application facade. Platform entrypoints provide its metadata kernel and module loader. */
18
32
  export class Host {
@@ -34,25 +48,25 @@ export class Host {
34
48
  }
35
49
 
36
50
  /** Install new orbs and activate their required scopes. */
37
- install(definition: OrbDefinition | readonly OrbDefinition[]): Promise<void> {
38
- return this.session.orbs.install(
39
- Array.isArray(definition) ? definition : [definition as OrbDefinition],
51
+ install(definition: OrbInput | readonly OrbInput[]): Promise<void> {
52
+ return this.session.track(
53
+ this.session.orbs.install(Array.isArray(definition) ? definition : [definition as OrbInput]),
40
54
  );
41
55
  }
42
56
 
43
57
  /** Load an orb with the host's module loader, then install it. */
44
- async load(location: string | URL): Promise<void> {
58
+ async load(location: string | URL, options?: LoadOptions): Promise<void> {
45
59
  if (!this.session.options.load) throw new Error("This host has no module loader");
46
- await this.install(await this.session.options.load(location));
60
+ await this.install(await this.session.options.load(location, options));
47
61
  }
48
62
 
49
63
  /** Prepare and commit a replacement using the kernel's lifecycle order. */
50
- reload(definitions: readonly OrbDefinition[], options?: ReloadOptions) {
64
+ reload(definitions: readonly OrbInput[], options?: ReloadOptions) {
51
65
  return this.session.replacements.replace(definitions, options);
52
66
  }
53
67
 
54
68
  /** Build a replacement candidate without adopting it. */
55
- prepare(definitions: readonly OrbDefinition[], options?: ReloadOptions) {
69
+ prepare(definitions: readonly OrbInput[], options?: ReloadOptions) {
56
70
  return this.session.replacements.prepare(definitions, options);
57
71
  }
58
72
 
@@ -107,6 +121,77 @@ export class Host {
107
121
  return this.session.calls.root(operation, false, undefined, options.principal);
108
122
  }
109
123
 
124
+ /**
125
+ * Serve one incoming HTTP request with the named Orb's `wasi:http/handler` export. The
126
+ * application owns listening, routing and authentication; this only runs the handler.
127
+ *
128
+ * The promise resolves with the response head as soon as the handler returned it; the body is
129
+ * produced while it is read. The call runs in its own root, which stays open, with its
130
+ * authority, until the delivery ended and all physical work settled: reading the body and
131
+ * trailers to the end, calling `return()` on the body iterator (a client disconnect), or
132
+ * cancelling through `options.signal`. A failure before the head (the handler's
133
+ * `error-code` as `HttpHandlerError`, a trap, a refusal) is reported after that settlement.
134
+ * One request is one callback of the Orb's revision, and the revision timeout covers the
135
+ * whole exchange, body included; a timeout retires the revision.
136
+ *
137
+ * The raw form is lossless. A WHATWG `Request` is answered with a WHATWG `Response`, and a
138
+ * response that form cannot represent is refused.
139
+ */
140
+ handleHttp(
141
+ orb: string,
142
+ request: IncomingHttpRequest,
143
+ options?: HandleHttpOptions,
144
+ ): Promise<HttpHandlerResponse>;
145
+ handleHttp(orb: string, request: Request, options?: HandleHttpOptions): Promise<Response>;
146
+ handleHttp(
147
+ orb: string,
148
+ request: IncomingHttpRequest | Request,
149
+ options: HandleHttpOptions = {},
150
+ ): Promise<HttpHandlerResponse | Response> {
151
+ if (isFetchRequest(request)) {
152
+ try {
153
+ return this.handleHttp(orb, fromFetchRequest(request), options).then(toFetchResponse);
154
+ } catch (error) {
155
+ return Promise.reject(error);
156
+ }
157
+ }
158
+ let exchange: IngressExchange;
159
+ try {
160
+ exchange = new IngressExchange(checkedRequest(request));
161
+ } catch (error) {
162
+ return Promise.reject(error);
163
+ }
164
+ const session = this.session;
165
+ const { signal, principal } = options;
166
+ const served = session.calls.root(
167
+ async (ctx) => {
168
+ const cancel = () => ctx.cancel();
169
+ if (signal?.aborted) cancel();
170
+ else signal?.addEventListener("abort", cancel, { once: true });
171
+ try {
172
+ const reference = await ctx.get(`${orb}::${HTTP_HANDLER}`, ["main"]);
173
+ // The root stays open for the physical call, not for the caller's observation of it.
174
+ await session.calls.invokePhysical(
175
+ session.handles.reference(reference),
176
+ "handle",
177
+ [exchange],
178
+ ctx,
179
+ );
180
+ } finally {
181
+ signal?.removeEventListener("abort", cancel);
182
+ }
183
+ },
184
+ false,
185
+ undefined,
186
+ principal,
187
+ );
188
+ void session.track(served).then(
189
+ () => exchange.settle(),
190
+ (error) => exchange.settle(error),
191
+ );
192
+ return exchange.head;
193
+ }
194
+
110
195
  /** Declare a resource owned by this host. */
111
196
  resource<T>(name: string, options: ResourceOptions<T>) {
112
197
  return this.session.scopes.resource(name, options);
@@ -129,22 +214,20 @@ export class Host {
129
214
 
130
215
  /** Describe installed orbs without activating their services. */
131
216
  installedOrbs() {
132
- return this.session.kernel
133
- .command<import("./bridge/kernel.ts").KernelOrb[]>(KernelOp.Orbs)
134
- .map((info) => {
135
- const definition = this.session.orbs.records.get(info.id)?.definition;
136
- const description = Object.freeze({
137
- ...info,
138
- hookCapabilities: Object.fromEntries(
139
- info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]),
140
- ),
141
- });
142
- return Object.freeze({
143
- ...info,
144
- /** Return captured metadata without activating services. */
145
- describe: () => description,
146
- });
217
+ return this.session.kernel.command(KernelOp.Orbs).map((info) => {
218
+ const definition = this.session.orbs.records.get(info.id)?.definition;
219
+ const description = Object.freeze({
220
+ ...info,
221
+ hookCapabilities: Object.fromEntries(
222
+ info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]),
223
+ ),
224
+ });
225
+ return Object.freeze({
226
+ ...info,
227
+ /** Return captured metadata without activating services. */
228
+ describe: () => description,
147
229
  });
230
+ });
148
231
  }
149
232
 
150
233
  /** Wait for physical work and cleanup before releasing the kernel. */
@@ -170,4 +253,26 @@ export {
170
253
 
171
254
  export { Errors, type ErrorDescriptor } from "./errors.ts";
172
255
 
256
+ export {
257
+ HttpHandlerError,
258
+ type HandleHttpOptions,
259
+ type HttpHandlerResponse,
260
+ type IncomingHttpRequest,
261
+ } from "./interpreter/http-ingress.ts";
262
+ export type { HttpField } from "./interpreter/http-provider.ts";
263
+
173
264
  export type { KernelPort } from "./bridge/kernel.ts";
265
+
266
+ // Platform adapters share the isolated lifecycle without importing private implementation files.
267
+ export {
268
+ createMobileHost,
269
+ type MobileBackend,
270
+ type MobileArtifact,
271
+ type MobilePort,
272
+ type MobileExecutionOptions,
273
+ type MobileField,
274
+ type MobileIngressCarrier,
275
+ type MobileIngressEvent,
276
+ type MobileRequestChunk,
277
+ type MobileRequestHead,
278
+ } from "./interpreter/mobile.ts";
@@ -0,0 +1,87 @@
1
+ /** UTF-8 codecs use ECMAScript primitives available in every supported guest engine. */
2
+ export function encodeText(text: string): Uint8Array {
3
+ const bytes: number[] = [];
4
+ for (const character of text) {
5
+ let point = character.codePointAt(0)!;
6
+ if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
7
+ if (point < 0x80) bytes.push(point);
8
+ else if (point < 0x800) bytes.push(0xc0 | (point >> 6), 0x80 | (point & 63));
9
+ else if (point < 0x10000)
10
+ bytes.push(0xe0 | (point >> 12), 0x80 | ((point >> 6) & 63), 0x80 | (point & 63));
11
+ else
12
+ bytes.push(
13
+ 0xf0 | (point >> 18),
14
+ 0x80 | ((point >> 12) & 63),
15
+ 0x80 | ((point >> 6) & 63),
16
+ 0x80 | (point & 63),
17
+ );
18
+ }
19
+ return Uint8Array.from(bytes);
20
+ }
21
+
22
+ /** Replace invalid UTF-8 sequences and retain at most one partial scalar between chunks. */
23
+ export class Utf8Decoder {
24
+ #pending: number[] = [];
25
+
26
+ decode(bytes: Uint8Array = new Uint8Array(), final = false): string {
27
+ const input = this.#pending.length ? Uint8Array.from([...this.#pending, ...bytes]) : bytes;
28
+ this.#pending = [];
29
+ const output: string[] = [];
30
+ for (let index = 0; index < input.length;) {
31
+ const first = input[index]!;
32
+ const width =
33
+ first < 0x80
34
+ ? 1
35
+ : first >= 0xc2 && first <= 0xdf
36
+ ? 2
37
+ : first >= 0xe0 && first <= 0xef
38
+ ? 3
39
+ : first >= 0xf0 && first <= 0xf4
40
+ ? 4
41
+ : 0;
42
+ if (!width) {
43
+ output.push("\ufffd");
44
+ index++;
45
+ continue;
46
+ }
47
+ if (index + width > input.length && !final) {
48
+ this.#pending = [...input.subarray(index)];
49
+ break;
50
+ }
51
+ let point = first & (width === 1 ? 127 : (1 << (7 - width)) - 1);
52
+ let count = 1;
53
+ while (count < width) {
54
+ const next = input[index + count];
55
+ if (
56
+ next === undefined ||
57
+ (next & 0xc0) !== 0x80 ||
58
+ (count === 1 &&
59
+ ((first === 0xe0 && next < 0xa0) ||
60
+ (first === 0xed && next >= 0xa0) ||
61
+ (first === 0xf0 && next < 0x90) ||
62
+ (first === 0xf4 && next >= 0x90)))
63
+ )
64
+ break;
65
+ point = (point << 6) | (next & 63);
66
+ count++;
67
+ }
68
+ output.push(count === width ? String.fromCodePoint(point) : "\ufffd");
69
+ index += count;
70
+ }
71
+ return output.join("");
72
+ }
73
+ }
74
+
75
+ export async function decodeText(body: AsyncIterable<Uint8Array>, limit: number): Promise<string> {
76
+ const decoder = new Utf8Decoder();
77
+ const output: string[] = [];
78
+ let bytes = 0;
79
+ for await (const chunk of body) {
80
+ bytes += chunk.length;
81
+ if (bytes > limit)
82
+ throw new Error("HTTP text body exceeds the limit; consume the byte stream instead");
83
+ output.push(decoder.decode(chunk));
84
+ }
85
+ output.push(decoder.decode(undefined, true));
86
+ return output.join("");
87
+ }
@@ -0,0 +1,34 @@
1
+ import { createParser } from "eventsource-parser";
2
+ import { Utf8Decoder } from "./bytes.ts";
3
+
4
+ export interface ServerSentEvent {
5
+ readonly event: string;
6
+ readonly data: string;
7
+ readonly id: string;
8
+ }
9
+
10
+ /** Adapt the maintained SSE parser to a bounded byte stream; reconnection belongs to the caller. */
11
+ export async function* events(body: AsyncIterable<Uint8Array>): AsyncIterable<ServerSentEvent> {
12
+ const decoder = new Utf8Decoder();
13
+ const pending: ServerSentEvent[] = [];
14
+ let id = "";
15
+ const parser = createParser({
16
+ maxBufferSize: 1 << 20,
17
+ onId(value) {
18
+ id = value;
19
+ },
20
+ onEvent(event) {
21
+ pending.push({ event: event.event ?? "message", data: event.data, id: event.id ?? id });
22
+ },
23
+ onError(error) {
24
+ if (error.type === "max-buffer-size-exceeded") throw error;
25
+ },
26
+ });
27
+ for await (const bytes of body) {
28
+ parser.feed(decoder.decode(bytes));
29
+ yield* pending;
30
+ pending.length = 0;
31
+ }
32
+ parser.feed(decoder.decode(undefined, true));
33
+ yield* pending;
34
+ }