@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,264 @@
1
+ /**
2
+ * Installation of a compiled Orb through its application-owned prepared adapter.
3
+ *
4
+ * Loaded lazily: hosts running only source Orbs never fetch this code. The artifact's metadata
5
+ * was accepted only because the browser verifier hashed its actual bytes to the adapter's digest
6
+ * (see `prepared.ts`). Every installation receives a fresh instance: JCO state, memories,
7
+ * tables, resources, WASI import objects, providers and limit globals.
8
+ */
9
+ import type { LoadOptions, OrbDefinition } from "../../authoring/types.ts";
10
+ import type { BrowserNetworkProviders } from "../browser-network.ts";
11
+ import type { FilesystemProvider } from "../filesystem.ts";
12
+ import { BrowserCapabilities } from "../io.ts";
13
+ import type { StdioProvider, StdioStreams } from "../standard-cli.ts";
14
+ import {
15
+ browserClocks,
16
+ browserRandom,
17
+ checkedClocks,
18
+ revisionRandom,
19
+ type SystemProviders,
20
+ } from "../standard-system.ts";
21
+ import { query, type ContractPort, type InstallationPlan } from "../types.ts";
22
+ import { referenceImport, referenceView, resourceImport } from "./host.ts";
23
+ import { instantiate, requireJspi, type CoreLimits } from "./instance.ts";
24
+ import { ComponentPort } from "./port.ts";
25
+ import type { PreparedRecord } from "./prepared.ts";
26
+ import type { LogObserver } from "./kernel.ts";
27
+ import {
28
+ compiledDescription,
29
+ ComponentRevision,
30
+ type CompiledRoles,
31
+ type Described,
32
+ } from "./revision.ts";
33
+ import { resourceDataFunction, resourceRoles } from "./resources.ts";
34
+ import { converters, type GraphFunction, type TypeGraph } from "./values.ts";
35
+ import { checkPublicWasi, publicWasi } from "./wasi.ts";
36
+
37
+ /** Browser options a compiled installation reads. */
38
+ export interface ComponentOptions {
39
+ providers?: BrowserNetworkProviders &
40
+ SystemProviders & {
41
+ filesystem?: Readonly<Record<string, FilesystemProvider>>;
42
+ stdio?: StdioProvider;
43
+ };
44
+ limits?: {
45
+ memoryBytes?: number;
46
+ timeoutMs?: number;
47
+ fuel?: number;
48
+ };
49
+ /** Receives the Orb's `tembra:guest/context` log records, as a source Orb's console. */
50
+ onLog?: LogObserver;
51
+ }
52
+
53
+ /** The verifier's digest-bound metadata of one compiled artifact. */
54
+ export interface PreparedContract extends ContractPort {
55
+ description(): string;
56
+ contributions(): string;
57
+ /** Declared hooks and their composition, by interface identity, as a JSON object. */
58
+ hooks(): string;
59
+ /** Service lifetimes and lingers, by interface identity, as a JSON object. */
60
+ services(): string;
61
+ digest(): string;
62
+ }
63
+
64
+ const PAGE = 1 << 16;
65
+
66
+ /** A limit is a positive safe integer; nothing else is coerced. */
67
+ function positive(name: string, value: number): number {
68
+ if (!Number.isSafeInteger(value) || value <= 0)
69
+ throw new Error(`limits.${name} must be a positive safe integer`);
70
+ return value;
71
+ }
72
+
73
+ /** Refuse an adapter whose generated JSPI wrapping does not cover what this revision calls. */
74
+ function checkAdapter(record: PreparedRecord, graph: Described, plan: InstallationPlan): void {
75
+ for (const entry of graph.exports)
76
+ for (const name of Object.keys(entry.functions ?? {}))
77
+ if (!record.promising.has(`${entry.binding}#${name}`))
78
+ throw new Error(`The prepared adapter does not wrap export ${entry.binding}#${name}`);
79
+ for (const name of record.imports) {
80
+ if (name.startsWith("wasi:")) continue;
81
+ const selected = graph.imports.find((item) => item.binding === name);
82
+ if (!selected) throw new Error(`The prepared adapter names unknown import ${name}`);
83
+ if (selected.type_only) continue;
84
+ // The kernel serves its own interfaces and the plans of the hooks this Orb declares.
85
+ const kind = plan.bindings[name]?.kind;
86
+ if (
87
+ kind !== "kernel" &&
88
+ kind !== "hook" &&
89
+ (kind !== "orb" || !Object.hasOwn(plan.importServices, name))
90
+ )
91
+ throw new Error(`Browser component execution cannot provide import ${name}`);
92
+ for (const fn of Object.keys(selected.functions ?? {}))
93
+ if (!record.suspending.has(`${name}#${fn}`))
94
+ throw new Error(`The prepared adapter does not suspend import ${name}#${fn}`);
95
+ }
96
+ }
97
+
98
+ /** Install one compiled Orb; `release` frees the verifier handle exactly once. */
99
+ export async function openComponent(
100
+ record: PreparedRecord,
101
+ contract: PreparedContract,
102
+ installation: LoadOptions,
103
+ options: ComponentOptions,
104
+ release: () => void,
105
+ ): Promise<OrbDefinition> {
106
+ requireJspi();
107
+ const identity = JSON.parse(contract.description()) as {
108
+ name: string;
109
+ apiVersion: number;
110
+ };
111
+ if (identity.name !== record.orb.name || identity.apiVersion !== record.orb.apiVersion)
112
+ throw new Error("The prepared adapter was generated for another Orb identity");
113
+ checkPublicWasi(record.imports);
114
+ const prepared = query<InstallationPlan>(contract, {
115
+ kind: "install",
116
+ name: identity.name,
117
+ apiVersion: identity.apiVersion,
118
+ requires: installation.requires ?? {},
119
+ grants: installation.grants ?? {},
120
+ filesystem: Object.keys(options.providers?.filesystem ?? {}),
121
+ // Network grants resolve only against socket providers and HTTP grants only against HTTP
122
+ // providers, so one registry never satisfies the other kind of grant.
123
+ network: Object.keys(options.providers?.network ?? {}),
124
+ http: Object.keys(options.providers?.http ?? {}),
125
+ });
126
+ const graph = query<Described>(contract, { kind: "describe" });
127
+ checkAdapter(record, graph, prepared);
128
+ const timeout = positive("timeoutMs", options.limits?.timeoutMs ?? 10000);
129
+ const memoryBytes = positive("memoryBytes", options.limits?.memoryBytes ?? 128 << 20);
130
+ const fuel = BigInt(positive("fuel", options.limits?.fuel ?? 100_000_000));
131
+ const maximumPages = Math.floor(memoryBytes / PAGE);
132
+ if (maximumPages < 1 || maximumPages > record.maximumPages)
133
+ throw new Error(
134
+ `limits.memoryBytes must hold between 1 and ${record.maximumPages} pages of 64 KiB`,
135
+ );
136
+ const grants = installation.grants ?? {};
137
+ const system = grants.system ?? [];
138
+ let capabilities: BrowserCapabilities | undefined;
139
+ let stdio: StdioStreams | undefined;
140
+ const port = new ComponentPort(
141
+ timeout,
142
+ async () => {
143
+ const cleanup: Promise<unknown>[] = [Promise.resolve().then(() => capabilities?.dispose())];
144
+ // The revision owns the stdio providers its factory returned and closes them last.
145
+ if (stdio)
146
+ for (const provider of new Set([stdio.stdin, stdio.stdout, stdio.stderr]))
147
+ cleanup.push(Promise.resolve().then(() => provider?.close?.()));
148
+ const settled = await Promise.allSettled(cleanup);
149
+ release();
150
+ const failed = settled.filter(
151
+ (result): result is PromiseRejectedResult => result.status === "rejected",
152
+ );
153
+ if (failed.length)
154
+ throw new AggregateError(
155
+ failed.map((result) => result.reason),
156
+ "Provider cleanup failed",
157
+ );
158
+ },
159
+ fuel,
160
+ );
161
+ try {
162
+ capabilities = await BrowserCapabilities.open(grants, options.providers ?? {});
163
+ if (system.includes("cli"))
164
+ stdio = options.providers?.stdio?.(identity.name, installation.cli ?? {}) ?? {};
165
+ const clocks = system.includes("clocks")
166
+ ? checkedClocks(options.providers?.clocks ?? browserClocks())
167
+ : undefined;
168
+ const random = system.includes("random")
169
+ ? revisionRandom(options.providers?.random ?? browserRandom())
170
+ : undefined;
171
+ // Each socket interface uses exactly the provider its import binding selected.
172
+ const bound = (name: string) => {
173
+ const entry = graph.imports.find((item) => item.contract === name);
174
+ const binding = entry && prepared.bindings[entry.binding];
175
+ return binding?.kind === "host" ? binding.provider : undefined;
176
+ };
177
+ const convert = converters(graph);
178
+ const revision = new ComponentRevision(port, contract, graph, timeout, {
179
+ orb: identity.name,
180
+ ...(options.onLog ? { observer: options.onLog } : {}),
181
+ });
182
+ const network = capabilities.network;
183
+ const imports: Record<string, unknown> = publicWasi(record.imports, {
184
+ clocks,
185
+ random,
186
+ ...(stdio ? { cli: { options: installation.cli ?? {}, stdio } } : {}),
187
+ mounts: () => capabilities?.mounts ?? [],
188
+ host: port.wasi,
189
+ http: network,
190
+ ingress: (bridge) => (revision.ingressBridge = bridge as never),
191
+ sockets: {
192
+ types: network.sockets(bound("wasi:sockets/types@0.3.0")),
193
+ lookup: network.sockets(bound("wasi:sockets/ip-name-lookup@0.3.0")),
194
+ },
195
+ });
196
+ for (const name of record.imports) {
197
+ if (Object.hasOwn(imports, name)) continue;
198
+ const selected = graph.imports.find((item) => item.binding === name);
199
+ const resourceGraph: TypeGraph = graph;
200
+ const resourceTypes = resourceGraph.types.flatMap(({ definition }) =>
201
+ definition.kind === "resource" &&
202
+ definition.owner === (selected?.contract ?? name) &&
203
+ definition.name
204
+ ? [{ interface: definition.owner, name: definition.name }]
205
+ : [],
206
+ );
207
+ if (selected?.type_only) {
208
+ imports[name] = resourceImport(port, name, [], resourceTypes);
209
+ continue;
210
+ }
211
+ if (!selected) throw new Error(`Browser component execution cannot provide import ${name}`);
212
+ const kind = prepared.bindings[name]?.kind;
213
+ if (kind === "kernel" || kind === "hook") {
214
+ imports[name] = revision.kernel.imports(name);
215
+ continue;
216
+ }
217
+ // `checkAdapter` admitted only Orb-bound dependency imports here.
218
+ const view = graph.references[name];
219
+ imports[name] = view
220
+ ? referenceImport(port, name, referenceView(graph, name, view, convert))
221
+ : resourceImport(
222
+ port,
223
+ name,
224
+ Object.entries(selected.functions ?? {}).map(([method, fn]) => {
225
+ const roles = resourceRoles(graph, selected.contract ?? name, {
226
+ ...fn,
227
+ name: method,
228
+ } as GraphFunction);
229
+ return {
230
+ name: method,
231
+ spelling: graph.javascriptNames[method]!,
232
+ roles,
233
+ values: convert(resourceDataFunction(fn as GraphFunction, roles)),
234
+ };
235
+ }),
236
+ resourceTypes,
237
+ );
238
+ }
239
+ // Pages are shared by all core modules. Instantiation has finite fuel; subsequent fuel
240
+ // resets occur only between groups of physically overlapping callbacks.
241
+ const limits: CoreLimits = {
242
+ fuel: new WebAssembly.Global({ value: "i64", mutable: true }, fuel),
243
+ pages: new WebAssembly.Global({ value: "i64", mutable: true }, BigInt(maximumPages)),
244
+ };
245
+ port.limits = limits;
246
+ const instance = await instantiate(record, imports, port.observer, limits);
247
+ // Fail closed when the glue never reported its task accessor: it is not instrumented.
248
+ if (!port.attached) throw new Error("The prepared component glue is not instrumented");
249
+ port.exports = instance as never;
250
+ const description = compiledDescription(graph, identity, {
251
+ contributions: JSON.parse(contract.contributions()) as CompiledRoles["contributions"],
252
+ hooks: JSON.parse(contract.hooks()) as NonNullable<CompiledRoles["hooks"]>,
253
+ services: JSON.parse(contract.services()) as NonNullable<CompiledRoles["services"]>,
254
+ });
255
+ return revision.definition(identity, prepared, description);
256
+ } catch (error) {
257
+ try {
258
+ await port.close();
259
+ } catch (disposal) {
260
+ throw new AggregateError([error, disposal], "Component initialization and disposal failed");
261
+ }
262
+ throw error;
263
+ }
264
+ }
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Typed Orb dependency imports of a compiled component.
3
+ *
4
+ * Each call acts for the callback that owns the guest's current root export task (read
5
+ * synchronously at import entry) and stays physically accounted to that callback until it
6
+ * settles. A plain import targets the root environment's default `main` reference; a reference
7
+ * view's methods target the claim their receiver names. Infrastructure failures (refusal,
8
+ * cancellation, a provider failure, a stale or foreign receiver) reject, which the generated
9
+ * suspending import turns into a trap: only the function's own WIT `result` is recoverable. A
10
+ * view's acquisition is the exception: its key is request data, so any failure to acquire is
11
+ * its WIT `err`, never a trap.
12
+ */
13
+ import type { ResourceCapability, ByteStreamCapability } from "#tembra-adapters";
14
+ import { receiveByteStream } from "./streams.ts";
15
+ import { failureText, type ComponentPort } from "./port.ts";
16
+ import type { Described } from "./revision.ts";
17
+ import type { ReferenceBinding } from "../types.ts";
18
+ import type { ReferenceClaim } from "./scope.ts";
19
+ import type { FunctionValues, GraphFunction } from "./values.ts";
20
+ import { bindingName } from "./names.ts";
21
+ import type { Nominal } from "./resources.ts";
22
+
23
+ interface ImportedResource {
24
+ wrap(owner: ResourceCapability): object;
25
+ move(value: object): ResourceCapability;
26
+ }
27
+ const resourceBindings = new WeakMap<ComponentPort, Map<string, ImportedResource>>();
28
+ const importedOwners = new WeakMap<ComponentPort, WeakMap<object, ResourceCapability>>();
29
+ const resourceKey = (nominal: Nominal) => `${nominal.interface}\0${nominal.name}`;
30
+ /** Resolve only the defining import's instance-specific class and ownership table. */
31
+ export function importedResource(port: ComponentPort, nominal: Nominal): ImportedResource {
32
+ const binding = resourceBindings.get(port)?.get(resourceKey(nominal));
33
+ if (!binding) throw new Error("Missing imported defining resource class");
34
+ return binding;
35
+ }
36
+
37
+ /** One typed import function and its conversions. */
38
+ export interface ImportedFunction {
39
+ /** The WIT function name. */
40
+ readonly name: string;
41
+ /** The JavaScript spelling the generated bindings call. */
42
+ readonly spelling: string;
43
+ readonly values: FunctionValues;
44
+ }
45
+
46
+ /** A dependency's refusal traps its caller, worded as the native worker's trap names it. */
47
+ function dependencyFailed(error: unknown): never {
48
+ throw new Error(`dependency call failed: ${failureText(error)}`, { cause: error });
49
+ }
50
+
51
+ /** The import object of one Orb dependency binding. */
52
+ export function dependencyImport(
53
+ port: ComponentPort,
54
+ binding: string,
55
+ functions: readonly ImportedFunction[],
56
+ ): Record<string, unknown> {
57
+ return Object.fromEntries(
58
+ functions.map(({ spelling, values }) => [
59
+ spelling,
60
+ (...args: unknown[]) => {
61
+ const callback = port.current();
62
+ const input = values.hostArguments(args);
63
+ return port
64
+ .physical(callback, callback.scope.call(binding, spelling, input))
65
+ .then(values.toGuest, dependencyFailed);
66
+ },
67
+ ]),
68
+ );
69
+ }
70
+
71
+ /**
72
+ * A view method's data signature: the implicit `self` receiver names a host-local reference and
73
+ * never travels as data, while the method keeps its original WIT slot.
74
+ */
75
+ export function viewMethod<F extends { readonly params: readonly unknown[] }>(fn: F): F {
76
+ if (!fn.params.length) throw new Error("A reference view method has no receiver");
77
+ return { ...fn, params: fn.params.slice(1) };
78
+ }
79
+
80
+ /** The checked shape of one reference-view import, with its generated JavaScript spellings. */
81
+ export interface ReferenceView {
82
+ /** The generated binding's name of the view's host resource class. */
83
+ readonly resource: string;
84
+ /** The acquisition function; its conversions cover only the key parameter. */
85
+ readonly acquire: ImportedFunction;
86
+ /** Methods by original WIT name, with conversions of their data parameters (no `self`). */
87
+ readonly methods: readonly ImportedFunction[];
88
+ }
89
+
90
+ /**
91
+ * The generated spellings and data conversions of one checked reference view: the resource
92
+ * class, the acquisition function (its key only) and each method without its `self` receiver.
93
+ */
94
+ export function referenceView(
95
+ graph: Described,
96
+ binding: string,
97
+ view: ReferenceBinding,
98
+ convert: (fn: GraphFunction) => FunctionValues,
99
+ ): ReferenceView {
100
+ const functions = graph.imports.find((item) => item.binding === binding)?.functions ?? {};
101
+ const acquire = functions[view.acquire];
102
+ if (!acquire) throw new Error(`Missing prepared signature for ${binding}#${view.acquire}`);
103
+ const spelling = graph.javascriptNames[view.acquire];
104
+ if (spelling === undefined) throw new Error(`Missing WIT JavaScript name for ${view.acquire}`);
105
+ const prefix = `[method]${view.resource.name}.`;
106
+ const names = Object.keys(functions);
107
+ if (names.length !== Object.keys(view.methods).length + 1)
108
+ throw new Error(`The reference view ${binding} declares unchecked functions`);
109
+ return {
110
+ resource: bindingName(view.resource.name, true),
111
+ // The acquisition result is a host-local handle, converted by the view itself.
112
+ acquire: {
113
+ name: view.acquire,
114
+ spelling,
115
+ values: convert({ params: acquire.params } as GraphFunction),
116
+ },
117
+ methods: Object.keys(view.methods).map((name) => {
118
+ const fn = functions[name];
119
+ if (!fn || !name.startsWith(prefix))
120
+ throw new Error(`The reference view ${binding} lacks method ${name}`);
121
+ return {
122
+ name,
123
+ spelling: bindingName(name.slice(prefix.length), false),
124
+ values: convert(viewMethod(fn) as GraphFunction),
125
+ };
126
+ }),
127
+ };
128
+ }
129
+
130
+ /** The text of an acquisition failure the guest receives as its WIT `err`. */
131
+ function failure(error: unknown): string {
132
+ return error instanceof Error ? error.message : String(error);
133
+ }
134
+
135
+ /**
136
+ * The import object of one reference-view binding: its acquisition function and the host
137
+ * resource class the generated bindings require.
138
+ *
139
+ * An instance is a host-local capability living only in this instance's generated handle table:
140
+ * it names one root claim and is never an inter-Orb guest resource. The guest dropping its own
141
+ * handle releases the claim; the claim's root ending invalidates it.
142
+ */
143
+ export function referenceImport(
144
+ port: ComponentPort,
145
+ binding: string,
146
+ view: ReferenceView,
147
+ ): Record<string, unknown> {
148
+ /** Live views; an object outside this map is dropped or was never issued. */
149
+ const held = new WeakMap<object, ReferenceClaim>();
150
+ const claimOf = (value: unknown): ReferenceClaim => {
151
+ const claim = typeof value === "object" && value !== null ? held.get(value) : undefined;
152
+ if (!claim) throw new Error("The reference handle is not live");
153
+ return claim;
154
+ };
155
+ const Resource = class {
156
+ constructor(claim: ReferenceClaim) {
157
+ held.set(this, claim);
158
+ }
159
+
160
+ /**
161
+ * The guest dropped its own handle, synchronously inside its drop. The release runs after the
162
+ * drop returns, accounted to the dropping callback, which settles only once it is done.
163
+ */
164
+ [Symbol.dispose](): void {
165
+ const claim = held.get(this);
166
+ if (!claim) return;
167
+ held.delete(this);
168
+ let callback;
169
+ try {
170
+ callback = port.current();
171
+ } catch {
172
+ // Outside any admitted callback the claim stays with its root, which releases it.
173
+ return;
174
+ }
175
+ port.wasi.cleanup(() => callback.scope.release(claim));
176
+ }
177
+ };
178
+ for (const { name, spelling, values } of view.methods) {
179
+ if (Object.hasOwn(Resource.prototype, spelling))
180
+ throw new Error(`Ambiguous reference method ${spelling}`);
181
+ Object.defineProperty(Resource.prototype, spelling, {
182
+ value(this: unknown, ...args: unknown[]) {
183
+ const claim = claimOf(this);
184
+ const callback = port.current();
185
+ const input = values.hostArguments(args);
186
+ return port
187
+ .physical(callback, callback.scope.invoke(claim, binding, name, input))
188
+ .then(values.toGuest, dependencyFailed);
189
+ },
190
+ });
191
+ }
192
+ const { values: key } = view.acquire;
193
+ const acquire = (...args: unknown[]) => {
194
+ const callback = port.current();
195
+ const [input] = key.hostArguments(args) as [readonly string[]];
196
+ const abandoned = new AbortController();
197
+ let issued: object | undefined;
198
+ const pending = port.physical(
199
+ callback,
200
+ callback.scope.acquire(binding, input, abandoned.signal).then(
201
+ (claim) => {
202
+ if (abandoned.signal.aborted) {
203
+ callback.scope.release(claim);
204
+ return { tag: "err", val: "acquisition abandoned" };
205
+ }
206
+ issued = new Resource(claim);
207
+ return { tag: "ok", val: issued };
208
+ },
209
+ (error: unknown) => ({ tag: "err", val: failure(error) }),
210
+ ),
211
+ );
212
+ // The generated bindings dispose a host result the guest abandoned before delivery: stop a
213
+ // pending readiness wait, or release a claim that was ready but never delivered.
214
+ return Object.assign(pending, {
215
+ [Symbol.dispose]() {
216
+ abandoned.abort(new Error("acquisition abandoned"));
217
+ const claim = issued && held.get(issued);
218
+ if (!claim) return;
219
+ held.delete(issued!);
220
+ callback.scope.release(claim);
221
+ },
222
+ });
223
+ };
224
+ return { [view.resource]: Resource, [view.acquire.spelling]: acquire };
225
+ }
226
+
227
+ /** Ordinary provider-owned WIT resources; keyed reference views use their separate adapter. */
228
+ export function resourceImport(
229
+ port: ComponentPort,
230
+ binding: string,
231
+ functions: readonly (ImportedFunction & {
232
+ readonly roles: import("./resources.ts").ResourceRoles;
233
+ })[],
234
+ types: readonly Nominal[] = [],
235
+ ): Record<string, unknown> {
236
+ let held = importedOwners.get(port);
237
+ if (!held) importedOwners.set(port, (held = new WeakMap()));
238
+ const classes = new Map<string, { new (...args: unknown[]): object }>();
239
+ const ownerOf = (value: object) => {
240
+ const owner = held.get(value);
241
+ if (!owner) throw new Error("Resource is not live");
242
+ return owner;
243
+ };
244
+ const invoke = (
245
+ fn: (typeof functions)[number],
246
+ args: unknown[],
247
+ receiver?: ResourceCapability,
248
+ ): Promise<unknown> & Disposable => {
249
+ const callback = port.current();
250
+ const converted = fn.values.hostArguments(args);
251
+ const moved: ResourceCapability[] = [];
252
+ let input: unknown[];
253
+ try {
254
+ input = fn.roles.arguments
255
+ ? (fn.roles.arguments(converted, (nominal, value) => {
256
+ const owner = importedResource(port, nominal).move(value as object);
257
+ moved.push(owner);
258
+ return moved.length - 1;
259
+ }) as unknown[])
260
+ : converted;
261
+ } catch (error) {
262
+ for (const owner of moved) owner.close();
263
+ throw error;
264
+ }
265
+ const transfer = {
266
+ owners: moved,
267
+ accepted: false,
268
+ accept() {
269
+ this.accepted = true;
270
+ },
271
+ };
272
+ let abandoned = false;
273
+ const issued: ResourceCapability[] = [];
274
+ const pending = port.physical(
275
+ callback,
276
+ (async () => {
277
+ const result = await (
278
+ receiver
279
+ ? callback.scope.resource!(
280
+ receiver,
281
+ binding,
282
+ fn.spelling,
283
+ input,
284
+ ...(fn.roles.arguments ? ([transfer] as const) : []),
285
+ )
286
+ : callback.scope.call(
287
+ binding,
288
+ fn.spelling,
289
+ input,
290
+ ...(fn.roles.arguments ? ([transfer] as const) : []),
291
+ )
292
+ ).catch(dependencyFailed);
293
+ if (fn.roles.result) {
294
+ try {
295
+ const value = fn.roles.result(result, (nominal, value) => {
296
+ const owner = value as ResourceCapability;
297
+ if (
298
+ owner?.kind !== "resource" ||
299
+ owner.nominal.interface !== nominal.interface ||
300
+ owner.nominal.name !== nominal.name
301
+ )
302
+ throw new Error("Missing matching owned resource result");
303
+ issued.push(owner);
304
+ if (abandoned) throw new Error("Resource delivery abandoned");
305
+ const Resource = classes.get(nominal.name);
306
+ if (!Resource) throw new Error("Missing imported resource class");
307
+ const wrapper = Object.create(Resource.prototype) as object;
308
+ held.set(wrapper, owner);
309
+ return wrapper;
310
+ });
311
+ return fn.values.toGuest(value);
312
+ } catch (error) {
313
+ for (const owner of issued) owner.close();
314
+ throw error;
315
+ }
316
+ }
317
+ if (fn.roles.stream) {
318
+ // The stream's host adapter strips producer-private JCO representations.
319
+ return receiveByteStream(
320
+ result as ByteStreamCapability,
321
+ AbortSignal.any([
322
+ callback.ended.signal,
323
+ ...(callback.scope.signal ? [callback.scope.signal] : []),
324
+ ]),
325
+ (operation) => port.wasi.cleanup(operation),
326
+ (error) => callback.scope.report(error),
327
+ );
328
+ }
329
+ return fn.values.toGuest(result);
330
+ })().catch((error: unknown) => {
331
+ if (!transfer.accepted) for (const owner of moved) owner.close();
332
+ throw error;
333
+ }),
334
+ );
335
+ return Object.assign(pending, {
336
+ [Symbol.dispose]() {
337
+ abandoned = true;
338
+ if (!transfer.accepted) for (const owner of moved) owner.close();
339
+ for (const owner of issued) owner.close();
340
+ },
341
+ });
342
+ };
343
+ const nominals = [
344
+ ...types,
345
+ ...functions.flatMap((fn) => [
346
+ ...(fn.roles.resource ? [fn.roles.resource] : []),
347
+ ...(fn.roles.owned ?? []),
348
+ ]),
349
+ ];
350
+ for (const nominal of nominals) {
351
+ if (classes.has(nominal.name)) continue;
352
+ const constructor = functions.find(
353
+ (item) => item.roles.construct && item.roles.resource?.name === nominal.name,
354
+ );
355
+ const Resource = class {
356
+ constructor(...args: unknown[]) {
357
+ if (!constructor) throw new Error("Resource has no constructor");
358
+ return invoke(constructor, args) as never;
359
+ }
360
+ [Symbol.dispose](): void {
361
+ const owner = held.get(this);
362
+ if (!owner) return;
363
+ held.delete(this);
364
+ try {
365
+ port.current().scope.releaseResource(owner);
366
+ } catch {
367
+ owner.close();
368
+ }
369
+ }
370
+ };
371
+ classes.set(nominal.name, Resource);
372
+ let bindings = resourceBindings.get(port);
373
+ if (!bindings) resourceBindings.set(port, (bindings = new Map()));
374
+ bindings.set(resourceKey(nominal), {
375
+ wrap(owner) {
376
+ const wrapper = Object.create(Resource.prototype) as object;
377
+ held.set(wrapper, owner);
378
+ return wrapper;
379
+ },
380
+ move(value) {
381
+ const owner = ownerOf(value);
382
+ if (owner.nominal.interface !== nominal.interface || owner.nominal.name !== nominal.name)
383
+ throw new Error("Resource has another nominal type");
384
+ const next = owner.move();
385
+ held.delete(value);
386
+ return next;
387
+ },
388
+ });
389
+ }
390
+ const output: Record<string, unknown> = {};
391
+ for (const [name, Resource] of classes) output[bindingName(name, true)] = Resource;
392
+ for (const fn of functions) {
393
+ if (fn.roles.construct) continue;
394
+ if (!fn.roles.resource) {
395
+ output[fn.spelling] = (...args: unknown[]) => invoke(fn, args);
396
+ continue;
397
+ }
398
+ const Resource = classes.get(fn.roles.resource.name)!;
399
+ const target = fn.roles.receiver ? Resource.prototype : Resource;
400
+ const spelling = bindingName(fn.roles.member!, false);
401
+ if (Object.hasOwn(target, spelling)) throw new Error("Ambiguous imported resource method");
402
+ Object.defineProperty(target, spelling, {
403
+ value(this: object, ...args: unknown[]) {
404
+ return invoke(fn, args, fn.roles.receiver ? ownerOf(this) : undefined);
405
+ },
406
+ });
407
+ }
408
+ return output;
409
+ }