@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,246 @@
1
+ /**
2
+ * Socket addresses for the browser `wasi:sockets` host, with the same meaning as the native
3
+ * host:
4
+ * - equality and grant matching use Rust `SocketAddr` identity (IP, port, IPv6 flow
5
+ * information and scope id), never textual spelling;
6
+ * - validity predicates mirror pinned `wasmtime-wasi` 51.0.0-rc.1 `sockets/mod.rs`;
7
+ * - grant strings parse as Rust `SocketAddr::from_str`;
8
+ * - name lookup input parses as `url::Host::parse`.
9
+ */
10
+ import type { IpAddress, IpAddressFamily, IpSocketAddress } from "wasi:sockets/types@0.3.0";
11
+
12
+ /** One socket address with exact numeric fields; IPv4 has four octets, IPv6 eight segments. */
13
+ export interface Address {
14
+ readonly family: IpAddressFamily;
15
+ readonly ip: readonly number[];
16
+ readonly port: number;
17
+ readonly flowInfo: number;
18
+ readonly scopeId: number;
19
+ }
20
+
21
+ const uint = (value: unknown, maximum: number): value is number =>
22
+ typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= maximum;
23
+
24
+ /** Read a WIT `ip-socket-address`, validating every field; `undefined` when malformed. */
25
+ export function fromWit(value: unknown): Address | undefined {
26
+ const tag = (value as { tag?: unknown })?.tag;
27
+ const val = (value as { val?: Record<string, unknown> })?.val;
28
+ if (!val || (tag !== "ipv4" && tag !== "ipv6")) return undefined;
29
+ const ip = val.address;
30
+ const width = tag === "ipv4" ? 4 : 8;
31
+ const maximum = tag === "ipv4" ? 0xff : 0xffff;
32
+ if (!Array.isArray(ip) || ip.length !== width || !ip.every((part) => uint(part, maximum)))
33
+ return undefined;
34
+ if (!uint(val.port, 0xffff)) return undefined;
35
+ if (tag === "ipv4")
36
+ return { family: "ipv4", ip: [...ip], port: val.port, flowInfo: 0, scopeId: 0 };
37
+ if (!uint(val.flowInfo, 0xffffffff) || !uint(val.scopeId, 0xffffffff)) return undefined;
38
+ return {
39
+ family: "ipv6",
40
+ ip: [...ip],
41
+ port: val.port,
42
+ flowInfo: val.flowInfo,
43
+ scopeId: val.scopeId,
44
+ };
45
+ }
46
+
47
+ /** A fresh WIT value; never shares arrays with host state. */
48
+ export function toWit(address: Address): IpSocketAddress {
49
+ return address.family === "ipv4"
50
+ ? {
51
+ tag: "ipv4",
52
+ val: { port: address.port, address: [...address.ip] as [number, number, number, number] },
53
+ }
54
+ : {
55
+ tag: "ipv6",
56
+ val: {
57
+ port: address.port,
58
+ flowInfo: address.flowInfo,
59
+ address: [...address.ip] as [
60
+ number,
61
+ number,
62
+ number,
63
+ number,
64
+ number,
65
+ number,
66
+ number,
67
+ number,
68
+ ],
69
+ scopeId: address.scopeId,
70
+ },
71
+ };
72
+ }
73
+
74
+ /** Rust `SocketAddr` identity: equal keys are equal addresses. */
75
+ export const key = (address: Address): string =>
76
+ `${address.family}|${address.ip.join(".")}|${address.port}|${address.flowInfo}|${address.scopeId}`;
77
+
78
+ export const unspecified = (family: IpAddressFamily): Address => ({
79
+ family,
80
+ ip: new Array<number>(family === "ipv4" ? 4 : 8).fill(0),
81
+ port: 0,
82
+ flowInfo: 0,
83
+ scopeId: 0,
84
+ });
85
+
86
+ const isZero = (ip: readonly number[]) => ip.every((part) => part === 0);
87
+
88
+ /** The IPv4 address an IPv6 `::ffff:a.b.c.d` maps (Rust `to_ipv4_mapped`). */
89
+ function mappedIpv4(address: Address): readonly number[] | undefined {
90
+ const [a, b, c, d, e, f, g, h] = address.ip as number[];
91
+ if (address.family !== "ipv6" || a || b || c || d || e || f !== 0xffff) return undefined;
92
+ return [g! >> 8, g! & 0xff, h! >> 8, h! & 0xff];
93
+ }
94
+
95
+ /** Rust `IpAddr::to_canonical`: an IPv4-mapped IPv6 address becomes IPv4. */
96
+ function canonicalIp(address: Address): { family: IpAddressFamily; ip: readonly number[] } {
97
+ const mapped = mappedIpv4(address);
98
+ return mapped ? { family: "ipv4", ip: mapped } : address;
99
+ }
100
+
101
+ /** Upstream `is_valid_unicast_address`. */
102
+ export function isUnicast(address: Address): boolean {
103
+ const { family, ip } = canonicalIp(address);
104
+ if (family === "ipv4") return !(ip[0]! >= 224 && ip[0]! <= 239) && !ip.every((o) => o === 255);
105
+ return ip[0]! >> 8 !== 0xff;
106
+ }
107
+
108
+ /** Upstream `is_valid_remote_address`. */
109
+ export const isRemote = (address: Address): boolean =>
110
+ !isZero(canonicalIp(address).ip) && address.port !== 0;
111
+
112
+ /** Upstream `is_valid_address_family`, including IPv4-compatible and mapped IPv6 refusal. */
113
+ export function hasFamily(address: Address, family: IpAddressFamily): boolean {
114
+ if (address.family !== family) return false;
115
+ if (family === "ipv4") return true;
116
+ const ip = address.ip;
117
+ const compatible =
118
+ ip.slice(0, 6).every((part) => part === 0) &&
119
+ !isZero(ip) &&
120
+ !(ip.slice(0, 7).every((part) => part === 0) && ip[7] === 1);
121
+ return !compatible && mappedIpv4(address) === undefined;
122
+ }
123
+
124
+ /** An implicit bind by the OS uses the wildcard address and an ephemeral port. */
125
+ export const isImplicit = (address: Address): boolean => isZero(address.ip) && address.port === 0;
126
+
127
+ /** Strict dotted quad, as Rust `Ipv4Addr::from_str` (no leading zeros, no shorthand). */
128
+ export function parseIpv4(text: string): number[] | undefined {
129
+ const parts = text.split(".");
130
+ if (parts.length !== 4) return undefined;
131
+ const octets = parts.map((part) =>
132
+ /^(0|[1-9][0-9]{0,2})$/.test(part) ? Number(part) : Number.NaN,
133
+ );
134
+ return octets.every((octet) => octet <= 255) ? octets : undefined;
135
+ }
136
+
137
+ /** Rust `Ipv6Addr::from_str`: 1–4 hex digits per group, one `::` for at least one group. */
138
+ export function parseIpv6(text: string): number[] | undefined {
139
+ const halves = text.split("::");
140
+ if (halves.length > 2) return undefined;
141
+ const groups = (part: string): number[] | undefined => {
142
+ if (part === "") return [];
143
+ const pieces = part.split(":");
144
+ const out: number[] = [];
145
+ for (const [index, piece] of pieces.entries()) {
146
+ if (index === pieces.length - 1 && piece.includes(".")) {
147
+ const v4 = parseIpv4(piece);
148
+ if (!v4) return undefined;
149
+ out.push((v4[0]! << 8) | v4[1]!, (v4[2]! << 8) | v4[3]!);
150
+ } else if (/^[0-9a-fA-F]{1,4}$/.test(piece)) out.push(Number.parseInt(piece, 16));
151
+ else return undefined;
152
+ }
153
+ return out;
154
+ };
155
+ const head = groups(halves[0]!);
156
+ if (!head) return undefined;
157
+ if (halves.length === 1) return head.length === 8 ? head : undefined;
158
+ if (halves[0]!.includes(".")) return undefined;
159
+ const tail = groups(halves[1]!);
160
+ if (!tail || head.length + tail.length > 7) return undefined;
161
+ return [...head, ...new Array<number>(8 - head.length - tail.length).fill(0), ...tail];
162
+ }
163
+
164
+ /** A grant string as Rust `SocketAddr::from_str`: `a.b.c.d:port` or `[v6(%scope)]:port`. */
165
+ export function parseSocketAddress(text: string): Address | undefined {
166
+ const colon = text.lastIndexOf(":");
167
+ const portText = text.slice(colon + 1);
168
+ if (colon < 0 || !/^[0-9]{1,5}$/.test(portText) || Number(portText) > 0xffff) return undefined;
169
+ const port = Number(portText);
170
+ const host = text.slice(0, colon);
171
+ if (host.startsWith("[") && host.endsWith("]")) {
172
+ const [ipText, scopeText, extra] = host.slice(1, -1).split("%");
173
+ if (extra !== undefined) return undefined;
174
+ if (
175
+ scopeText !== undefined &&
176
+ !(/^[0-9]{1,10}$/.test(scopeText) && Number(scopeText) <= 0xffffffff)
177
+ )
178
+ return undefined;
179
+ const ip = parseIpv6(ipText!);
180
+ return ip && { family: "ipv6", ip, port, flowInfo: 0, scopeId: Number(scopeText ?? 0) };
181
+ }
182
+ const ip = parseIpv4(host);
183
+ return ip && { family: "ipv4", ip, port, flowInfo: 0, scopeId: 0 };
184
+ }
185
+
186
+ /** WIT `ip-address` of `family` and `ip`. */
187
+ const ipAddress = (family: IpAddressFamily, ip: readonly number[]): IpAddress =>
188
+ ({ tag: family, val: [...ip] }) as IpAddress;
189
+
190
+ /** Validate and canonicalize one provider lookup result; mapped IPv6 becomes IPv4. */
191
+ export function checkedIpAddress(value: unknown): IpAddress | undefined {
192
+ const tag = (value as { tag?: unknown })?.tag;
193
+ const ip = (value as { val?: unknown })?.val;
194
+ const width = tag === "ipv4" ? 4 : tag === "ipv6" ? 8 : 0;
195
+ const maximum = tag === "ipv4" ? 0xff : 0xffff;
196
+ if (!width || !Array.isArray(ip) || ip.length !== width || !ip.every((p) => uint(p, maximum)))
197
+ return undefined;
198
+ const canonical = canonicalIp({
199
+ family: tag as IpAddressFamily,
200
+ ip,
201
+ port: 0,
202
+ flowInfo: 0,
203
+ scopeId: 0,
204
+ });
205
+ return ipAddress(canonical.family, canonical.ip);
206
+ }
207
+
208
+ /**
209
+ * WHATWG forbidden domain code points (C0 controls, space, `"#%/:<>?@[\]^|`, DEL) other than
210
+ * `%`, which `url::Host::parse` percent-decodes first, exactly as the URL host parser does.
211
+ */
212
+ const FORBIDDEN_ASCII = new Set('#/:<>?@[\\]^|"');
213
+ const forbidden = (text: string): boolean =>
214
+ [...text].some((char) => {
215
+ const code = char.charCodeAt(0);
216
+ return code <= 0x20 || code === 0x7f || FORBIDDEN_ASCII.has(char);
217
+ });
218
+
219
+ /**
220
+ * Parse a `resolve-addresses` name as `url::Host::parse` with the bare IPv6 fallback upstream
221
+ * adds: an IP literal is answered directly; a domain is IDNA-processed to ASCII.
222
+ */
223
+ export function parseHostName(
224
+ name: string,
225
+ ): { readonly ip: IpAddress } | { readonly domain: string } | undefined {
226
+ if (name.startsWith("[")) {
227
+ if (!name.endsWith("]")) return undefined;
228
+ const ip = parseIpv6(name.slice(1, -1));
229
+ return ip && { ip: ipAddress("ipv6", ip) };
230
+ }
231
+ if (name.includes(":")) {
232
+ const ip = parseIpv6(name);
233
+ return ip && { ip: ipAddress("ipv6", ip) };
234
+ }
235
+ if (!name || forbidden(name)) return undefined;
236
+ let host: string;
237
+ try {
238
+ // The forbidden check above leaves nothing the URL parser could read as another component.
239
+ host = new URL(`http://${name}/`).hostname;
240
+ } catch {
241
+ return undefined;
242
+ }
243
+ if (!host || forbidden(host)) return undefined;
244
+ const ipv4 = parseIpv4(host);
245
+ return ipv4 ? { ip: ipAddress("ipv4", ipv4) } : { domain: host };
246
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The injectable host transport behind standard `wasi:sockets` and `wasi:sockets/ip-name-lookup`
3
+ * in the browser. Browsers have no raw sockets: an embedder supplies a provider, and every
4
+ * member is optional, so a provider may support only a subset. A missing member is a standard
5
+ * `not-supported` (`permanent-resolver-failure` for name lookup); it is never emulated.
6
+ *
7
+ * The standard host owns permissions, references and physical accounting. It checks the exact
8
+ * grant before calling a provider, and validates and copies everything a provider returns.
9
+ * Every promise below is physical work. The host tracks it until it settles, even after the
10
+ * guest's call was cancelled, so a provider must settle it once the work has really stopped,
11
+ * including releasing anything it produced late.
12
+ */
13
+ import type {
14
+ Duration,
15
+ ErrorCode as SocketErrorCode,
16
+ IpAddress,
17
+ IpAddressFamily,
18
+ IpSocketAddress,
19
+ } from "wasi:sockets/types@0.3.0";
20
+ import type { ErrorCode as NameLookupErrorCode } from "wasi:sockets/ip-name-lookup@0.3.0";
21
+
22
+ /** One named network provider, selected by the Orb's `wasi:sockets` import binding. */
23
+ export interface SocketProvider {
24
+ /** Synchronous: `tcp-socket.create`. Throw `SocketProviderError` for an unsupported family. */
25
+ readonly tcp?: { create(family: IpAddressFamily): TcpBackend };
26
+ /** Synchronous: `udp-socket.create`. */
27
+ readonly udp?: { create(family: IpAddressFamily): UdpBackend };
28
+ /** `resolve-addresses` for an ASCII (IDNA) domain name; IP literals never reach it. */
29
+ resolve?(name: string, signal: AbortSignal): Promise<readonly IpAddress[]>;
30
+ }
31
+
32
+ /** TCP socket options, by their standard getter and setter names. */
33
+ export interface TcpOptions {
34
+ keepAliveEnabled: boolean;
35
+ keepAliveIdleTime: Duration;
36
+ keepAliveInterval: Duration;
37
+ keepAliveCount: number;
38
+ hopLimit: number;
39
+ receiveBufferSize: bigint;
40
+ sendBufferSize: bigint;
41
+ /** Only after `listen`; before it, the host keeps the backlog as upstream Wasmtime does. */
42
+ listenBacklogSize: bigint;
43
+ }
44
+
45
+ /** UDP socket options, by their standard getter and setter names. */
46
+ export interface UdpOptions {
47
+ unicastHopLimit: number;
48
+ receiveBufferSize: bigint;
49
+ sendBufferSize: bigint;
50
+ }
51
+
52
+ /**
53
+ * Real option access. Getting and setting are supported independently; an absent method, or a
54
+ * thrown `not-supported`, is reported as `not-supported`. Setters receive values the host has
55
+ * already validated as WASI requires (for example, never 0 where 0 is invalid).
56
+ */
57
+ export interface SocketOptions<O> {
58
+ getOption?<K extends keyof O>(name: K): O[K];
59
+ setOption?<K extends keyof O>(name: K, value: O[K]): void;
60
+ }
61
+
62
+ /** A provider-owned TCP socket. The host closes it once its last reference is released. */
63
+ export interface TcpBackend extends SocketOptions<TcpOptions> {
64
+ /** The actual bound local address, or `undefined` before any explicit or implicit bind. */
65
+ readonly local: IpSocketAddress | undefined;
66
+ /** Synchronous explicit bind; returns only once bound. Absent means `not-supported`. */
67
+ bind?(local: IpSocketAddress): void;
68
+ /** Synchronous; binds implicitly when unbound. Absent means `not-supported`. */
69
+ listen?(backlog: number): TcpListener;
70
+ /** Binds implicitly when unbound. */
71
+ connect(remote: IpSocketAddress, signal: AbortSignal): Promise<TcpConnection>;
72
+ /** The last reference was released; the promise is the physical acknowledgement. */
73
+ close(): Promise<void>;
74
+ }
75
+
76
+ /** The accept side of a listening `TcpBackend`; listening ends when that backend closes. */
77
+ export interface TcpListener {
78
+ /**
79
+ * Accept one connection. The host keeps at most one call pending and aborts `signal` when
80
+ * nobody will take its result; a connection delivered anyway is closed by the host.
81
+ */
82
+ accept(signal: AbortSignal): Promise<{ socket: TcpBackend; connection: TcpConnection }>;
83
+ }
84
+
85
+ /** The byte directions of a connected socket. Each promise is a physical acknowledgement. */
86
+ export interface TcpConnection {
87
+ readonly remote: IpSocketAddress;
88
+ /** Read as the guest reads. `cancel()` is a read shutdown; empty chunks are allowed. */
89
+ readonly readable: ReadableStream<Uint8Array>;
90
+ /** `close()` is a write shutdown after the last write; `abort()` stops a failed send. */
91
+ readonly writable: WritableStream<Uint8Array>;
92
+ }
93
+
94
+ /** A provider-owned UDP socket. */
95
+ export interface UdpBackend extends SocketOptions<UdpOptions> {
96
+ readonly local: IpSocketAddress | undefined;
97
+ /** Synchronous explicit bind, also used for the implicit bind of `connect`. */
98
+ bind?(local: IpSocketAddress): void;
99
+ /** Binds implicitly when unbound; resolves once the datagram was handed to the network. */
100
+ send(data: Uint8Array, remote: IpSocketAddress, signal: AbortSignal): Promise<void>;
101
+ /** The next datagram from any peer; the host filters peers by grant and connection. */
102
+ receive(signal: AbortSignal): Promise<{ data: Uint8Array; remote: IpSocketAddress }>;
103
+ close(): Promise<void>;
104
+ }
105
+
106
+ /** A provider failure carrying a standard socket `error-code`. */
107
+ export class SocketProviderError extends Error {
108
+ constructor(
109
+ readonly code: SocketErrorCode,
110
+ message = `socket provider failed: ${code.tag}`,
111
+ ) {
112
+ super(message);
113
+ this.name = "SocketProviderError";
114
+ }
115
+ }
116
+
117
+ /** A provider failure carrying a standard name lookup `error-code`. */
118
+ export class NameLookupError extends Error {
119
+ constructor(
120
+ readonly code: NameLookupErrorCode,
121
+ message = `name lookup failed: ${code.tag}`,
122
+ ) {
123
+ super(message);
124
+ this.name = "NameLookupError";
125
+ }
126
+ }
@@ -0,0 +1,184 @@
1
+ /** Standard CLI over host-owned byte providers, with no inherited process environment. */
2
+ import type { CliOptions } from "../authoring/types.ts";
3
+ import { combinedSignal } from "../runtime/signals.ts";
4
+ import { GuestTrap } from "./core.ts";
5
+ import {
6
+ HostFuture,
7
+ type Implementation,
8
+ type InputStream,
9
+ OutputStream,
10
+ type StandardServices,
11
+ } from "./standard-streams.ts";
12
+
13
+ /** The promise owns the actual read until it returns, including after signal cancellation. */
14
+ export interface StdioInput {
15
+ read(maxBytes: number, signal: AbortSignal): Promise<Uint8Array | undefined>;
16
+ close?(): void | Promise<void>;
17
+ }
18
+
19
+ /** The promise settles only after the physical write has returned. Calls are serialized. */
20
+ export interface StdioOutput {
21
+ write(bytes: Uint8Array, signal: AbortSignal): Promise<void>;
22
+ close?(): void | Promise<void>;
23
+ }
24
+
25
+ /** A fresh set per revision; an output provider can be shared by stdout and stderr. */
26
+ export interface StdioStreams {
27
+ readonly stdin?: StdioInput;
28
+ readonly stdout?: StdioOutput;
29
+ readonly stderr?: StdioOutput;
30
+ }
31
+
32
+ /** The embedding chooses adapters; Tembra owns their operation promises and final close. */
33
+ export type StdioProvider = (orb: string, configuration: Readonly<CliOptions>) => StdioStreams;
34
+
35
+ const ok = () => ({ tag: "ok" });
36
+ const io = () => ({ tag: "err", val: "io" });
37
+
38
+ /** Reuse the revision's existing resource table and physical-work accounting for CLI streams. */
39
+ export class StandardCli {
40
+ readonly #input: StdioInput | undefined;
41
+ readonly #providers: Set<StdioInput | StdioOutput>;
42
+ readonly #writes = new Map<StdioOutput, Promise<void>>();
43
+ readonly #stopped = new AbortController();
44
+ #reading: Promise<void> = Promise.resolve();
45
+ #closed = false;
46
+ readonly methods: Record<string, Implementation>;
47
+
48
+ constructor(configuration: Readonly<CliOptions> = {}, streams: StdioStreams = {}) {
49
+ this.#providers = new Set();
50
+ for (const provider of [streams.stdin, streams.stdout, streams.stderr])
51
+ if (provider) this.#providers.add(provider);
52
+ const input = configuration.stdin;
53
+ if (typeof input === "object" && "file" in input && !streams.stdin)
54
+ throw new Error("Browser stdin files require an injected stdio provider");
55
+ if (input === "empty") this.#input = undefined;
56
+ else if (typeof input === "object" && "bytes" in input) {
57
+ const bytes = input.bytes.slice();
58
+ let offset = 0;
59
+ this.#input = {
60
+ async read(limit) {
61
+ if (offset === bytes.length) return undefined;
62
+ const next = bytes.subarray(offset, offset + limit);
63
+ offset += next.length;
64
+ return next;
65
+ },
66
+ };
67
+ } else this.#input = streams.stdin;
68
+ const output = (name: "stdout" | "stderr") => {
69
+ const selected = configuration[name];
70
+ if (selected === "discard") return undefined;
71
+ const stream = streams[name];
72
+ if (typeof selected === "object" && !stream)
73
+ throw new Error(`Browser ${name} files require an injected stdio provider`);
74
+ return stream;
75
+ };
76
+ const stdout = output("stdout"),
77
+ stderr = output("stderr");
78
+ const environment = configuration.environment?.map(([name, value]) => [name, value]);
79
+ const arguments_ = [...(configuration.arguments ?? [])];
80
+ const cwd = configuration.initialCwd;
81
+ this.methods = {
82
+ "wasi:cli/environment@0.3.0#getEnvironment": () =>
83
+ environment?.map((pair) => [...pair]) ?? [],
84
+ "wasi:cli/environment@0.3.0#getArguments": () => [...arguments_],
85
+ "wasi:cli/environment@0.3.0#getInitialCwd": () => cwd,
86
+ "wasi:cli/stdin@0.3.0#readViaStream": ({ host }) => this.read(host),
87
+ "wasi:cli/stdout@0.3.0#writeViaStream": ({ host }, [input]: [InputStream]) =>
88
+ this.write(host, stdout, input),
89
+ "wasi:cli/stderr@0.3.0#writeViaStream": ({ host }, [input]: [InputStream]) =>
90
+ this.write(host, stderr, input),
91
+ "wasi:cli/terminal-stdin@0.3.0#getTerminalStdin": () => undefined,
92
+ "wasi:cli/terminal-stdout@0.3.0#getTerminalStdout": () => undefined,
93
+ "wasi:cli/terminal-stderr@0.3.0#getTerminalStderr": () => undefined,
94
+ "wasi:cli/exit@0.3.0#exit": (_call, [status]: [{ tag: string }]) =>
95
+ this.exit(status.tag === "ok" ? 0 : 1),
96
+ "wasi:cli/exit@0.3.0#exitWithCode": (_call, [status]: [number]) => this.exit(status),
97
+ };
98
+ }
99
+
100
+ private exit(status: number): never {
101
+ throw new GuestTrap(`orb exited with status ${status}; revision retired`);
102
+ }
103
+
104
+ private read(host: StandardServices): [OutputStream, HostFuture] {
105
+ let settle!: (value: unknown) => void;
106
+ const completed = new Promise((resolve) => {
107
+ settle = resolve;
108
+ });
109
+ const dropped = new AbortController();
110
+ const signal = combinedSignal(this.#stopped.signal, dropped.signal);
111
+ const stream = new OutputStream(
112
+ {
113
+ next: async (limit) => {
114
+ // Serialize across all stdin streams; a cancelled physical read still owns its turn.
115
+ const operation = this.#reading.then(() =>
116
+ host.physical(signal, async () => {
117
+ const bytes = await this.#input?.read(limit, signal);
118
+ if (bytes !== undefined && (!(bytes instanceof Uint8Array) || bytes.length > limit))
119
+ throw new Error("stdin provider returned an invalid or oversized byte chunk");
120
+ return bytes;
121
+ }),
122
+ );
123
+ this.#reading = operation.then(
124
+ () => {},
125
+ () => {},
126
+ );
127
+ return operation;
128
+ },
129
+ close: () => dropped.abort(),
130
+ },
131
+ (failure) => settle(failure === undefined ? ok() : io()),
132
+ );
133
+ return [stream, new HostFuture(completed)];
134
+ }
135
+
136
+ private write(
137
+ host: StandardServices,
138
+ sink: StdioOutput | undefined,
139
+ input: InputStream,
140
+ ): HostFuture {
141
+ const value = (async () => {
142
+ try {
143
+ for (let bytes = await input.read(); bytes; bytes = await input.read()) {
144
+ if (sink) {
145
+ const chunk = bytes;
146
+ const operation = (this.#writes.get(sink) ?? Promise.resolve()).then(() =>
147
+ host.physical(this.#stopped.signal, () => sink.write(chunk, this.#stopped.signal)),
148
+ );
149
+ const turn = operation.then(
150
+ () => {},
151
+ () => {},
152
+ );
153
+ this.#writes.set(sink, turn);
154
+ try {
155
+ await operation;
156
+ } finally {
157
+ if (this.#writes.get(sink) === turn) this.#writes.delete(sink);
158
+ }
159
+ }
160
+ }
161
+ return input.cancelled ? io() : ok();
162
+ } catch {
163
+ return io();
164
+ } finally {
165
+ input.cancel();
166
+ }
167
+ })();
168
+ host.cleanup(() => value);
169
+ return new HostFuture(value, () => input.cancel());
170
+ }
171
+
172
+ /** Request cancellation first; physical promises remain accounted for until they return. */
173
+ retire(): void {
174
+ this.#stopped.abort();
175
+ }
176
+
177
+ /** Close providers only after their physical operations have returned. */
178
+ close(host: StandardServices): void {
179
+ if (this.#closed) return;
180
+ this.#closed = true;
181
+ for (const provider of this.#providers)
182
+ if (provider.close) host.cleanup(() => provider.close!());
183
+ }
184
+ }