@ricsam/isolate 0.0.1 → 0.1.1

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 (299) hide show
  1. package/README.md +243 -34
  2. package/dist/cjs/bridge/diagnostics.cjs +58 -0
  3. package/dist/cjs/bridge/diagnostics.cjs.map +10 -0
  4. package/dist/cjs/bridge/legacy-adapters.cjs +242 -0
  5. package/dist/cjs/bridge/legacy-adapters.cjs.map +10 -0
  6. package/dist/cjs/bridge/request-context.cjs +59 -0
  7. package/dist/cjs/bridge/request-context.cjs.map +10 -0
  8. package/dist/cjs/bridge/runtime-bindings.cjs +367 -0
  9. package/dist/cjs/bridge/runtime-bindings.cjs.map +10 -0
  10. package/dist/cjs/browser/browser-runtime.cjs +157 -0
  11. package/dist/cjs/browser/browser-runtime.cjs.map +10 -0
  12. package/dist/cjs/daemon.cjs +91 -0
  13. package/dist/cjs/daemon.cjs.map +10 -0
  14. package/dist/cjs/files/index.cjs +140 -0
  15. package/dist/cjs/files/index.cjs.map +10 -0
  16. package/dist/cjs/host/create-isolate-host.cjs +235 -0
  17. package/dist/cjs/host/create-isolate-host.cjs.map +10 -0
  18. package/dist/cjs/host/index.cjs +47 -0
  19. package/dist/cjs/host/index.cjs.map +10 -0
  20. package/dist/cjs/index.cjs +55 -0
  21. package/dist/cjs/index.cjs.map +10 -0
  22. package/dist/cjs/internal/client/connection.cjs +1919 -0
  23. package/dist/cjs/internal/client/connection.cjs.map +10 -0
  24. package/dist/cjs/internal/client/index.cjs +48 -0
  25. package/dist/cjs/internal/client/index.cjs.map +10 -0
  26. package/dist/cjs/internal/client/types.cjs +30 -0
  27. package/dist/cjs/internal/client/types.cjs.map +9 -0
  28. package/dist/cjs/internal/console/index.cjs +506 -0
  29. package/dist/cjs/internal/console/index.cjs.map +10 -0
  30. package/dist/cjs/internal/console/utils.cjs +70 -0
  31. package/dist/cjs/internal/console/utils.cjs.map +10 -0
  32. package/dist/cjs/internal/core/index.cjs +2745 -0
  33. package/dist/cjs/internal/core/index.cjs.map +10 -0
  34. package/dist/cjs/internal/crypto/index.cjs +470 -0
  35. package/dist/cjs/internal/crypto/index.cjs.map +10 -0
  36. package/dist/cjs/internal/daemon/callback-fs-handler.cjs +355 -0
  37. package/dist/cjs/internal/daemon/callback-fs-handler.cjs.map +10 -0
  38. package/dist/cjs/internal/daemon/connection.cjs +1952 -0
  39. package/dist/cjs/internal/daemon/connection.cjs.map +10 -0
  40. package/dist/cjs/internal/daemon/daemon.cjs +98 -0
  41. package/dist/cjs/internal/daemon/daemon.cjs.map +10 -0
  42. package/dist/cjs/internal/daemon/index.cjs +145 -0
  43. package/dist/cjs/internal/daemon/index.cjs.map +10 -0
  44. package/dist/cjs/internal/daemon/runtime-pool.cjs +106 -0
  45. package/dist/cjs/internal/daemon/runtime-pool.cjs.map +10 -0
  46. package/dist/cjs/internal/daemon/types.cjs +30 -0
  47. package/dist/cjs/internal/daemon/types.cjs.map +9 -0
  48. package/dist/cjs/internal/encoding/index.cjs +419 -0
  49. package/dist/cjs/internal/encoding/index.cjs.map +10 -0
  50. package/dist/cjs/internal/fetch/consistency/origins.cjs +598 -0
  51. package/dist/cjs/internal/fetch/consistency/origins.cjs.map +10 -0
  52. package/dist/cjs/internal/fetch/index.cjs +2640 -0
  53. package/dist/cjs/internal/fetch/index.cjs.map +10 -0
  54. package/dist/cjs/internal/fetch/stream-state.cjs +256 -0
  55. package/dist/cjs/internal/fetch/stream-state.cjs.map +10 -0
  56. package/dist/cjs/internal/fs/index.cjs +847 -0
  57. package/dist/cjs/internal/fs/index.cjs.map +10 -0
  58. package/dist/cjs/internal/fs/node-adapter.cjs +254 -0
  59. package/dist/cjs/internal/fs/node-adapter.cjs.map +10 -0
  60. package/dist/cjs/internal/module-loader/bundle.cjs +482 -0
  61. package/dist/cjs/internal/module-loader/bundle.cjs.map +10 -0
  62. package/dist/cjs/internal/module-loader/index.cjs +240 -0
  63. package/dist/cjs/internal/module-loader/index.cjs.map +10 -0
  64. package/dist/cjs/internal/module-loader/mappings.cjs +120 -0
  65. package/dist/cjs/internal/module-loader/mappings.cjs.map +10 -0
  66. package/dist/cjs/internal/module-loader/resolve.cjs +177 -0
  67. package/dist/cjs/internal/module-loader/resolve.cjs.map +10 -0
  68. package/dist/cjs/internal/module-loader/strip-types.cjs +236 -0
  69. package/dist/cjs/internal/module-loader/strip-types.cjs.map +10 -0
  70. package/dist/cjs/internal/path/index.cjs +503 -0
  71. package/dist/cjs/internal/path/index.cjs.map +10 -0
  72. package/dist/cjs/internal/playwright/client.cjs +49 -0
  73. package/dist/cjs/internal/playwright/client.cjs.map +10 -0
  74. package/dist/cjs/internal/playwright/handler.cjs +1416 -0
  75. package/dist/cjs/internal/playwright/handler.cjs.map +10 -0
  76. package/dist/cjs/internal/playwright/index.cjs +1289 -0
  77. package/dist/cjs/internal/playwright/index.cjs.map +10 -0
  78. package/dist/cjs/internal/playwright/types.cjs +47 -0
  79. package/dist/cjs/internal/playwright/types.cjs.map +10 -0
  80. package/dist/cjs/internal/protocol/codec.cjs +510 -0
  81. package/dist/cjs/internal/protocol/codec.cjs.map +10 -0
  82. package/dist/cjs/internal/protocol/framing.cjs +141 -0
  83. package/dist/cjs/internal/protocol/framing.cjs.map +10 -0
  84. package/dist/cjs/internal/protocol/index.cjs +110 -0
  85. package/dist/cjs/internal/protocol/index.cjs.map +10 -0
  86. package/dist/cjs/internal/protocol/marshalValue.cjs +518 -0
  87. package/dist/cjs/internal/protocol/marshalValue.cjs.map +10 -0
  88. package/dist/cjs/internal/protocol/serialization.cjs +109 -0
  89. package/dist/cjs/internal/protocol/serialization.cjs.map +10 -0
  90. package/dist/cjs/internal/protocol/types.cjs +181 -0
  91. package/dist/cjs/internal/protocol/types.cjs.map +10 -0
  92. package/dist/cjs/internal/runtime/index.cjs +1235 -0
  93. package/dist/cjs/internal/runtime/index.cjs.map +10 -0
  94. package/dist/cjs/internal/server/index.cjs +223 -0
  95. package/dist/cjs/internal/server/index.cjs.map +10 -0
  96. package/dist/cjs/internal/test-environment/index.cjs +1415 -0
  97. package/dist/cjs/internal/test-environment/index.cjs.map +10 -0
  98. package/dist/cjs/internal/timers/index.cjs +200 -0
  99. package/dist/cjs/internal/timers/index.cjs.map +10 -0
  100. package/dist/cjs/internal/transform/index.cjs +361 -0
  101. package/dist/cjs/internal/transform/index.cjs.map +10 -0
  102. package/dist/cjs/internal/typecheck/index.cjs +60 -0
  103. package/dist/cjs/internal/typecheck/index.cjs.map +10 -0
  104. package/dist/cjs/internal/typecheck/isolate-types.cjs +2614 -0
  105. package/dist/cjs/internal/typecheck/isolate-types.cjs.map +10 -0
  106. package/dist/cjs/internal/typecheck/typecheck.cjs +131 -0
  107. package/dist/cjs/internal/typecheck/typecheck.cjs.map +10 -0
  108. package/dist/cjs/modules/index.cjs +160 -0
  109. package/dist/cjs/modules/index.cjs.map +10 -0
  110. package/dist/cjs/package.json +5 -0
  111. package/dist/cjs/runtime/script-runtime.cjs +97 -0
  112. package/dist/cjs/runtime/script-runtime.cjs.map +10 -0
  113. package/dist/cjs/server/app-server.cjs +158 -0
  114. package/dist/cjs/server/app-server.cjs.map +10 -0
  115. package/dist/cjs/testing/integration-helpers.cjs +127 -0
  116. package/dist/cjs/testing/integration-helpers.cjs.map +10 -0
  117. package/dist/cjs/typecheck/index.cjs +96 -0
  118. package/dist/cjs/typecheck/index.cjs.map +10 -0
  119. package/dist/cjs/types.cjs +30 -0
  120. package/dist/cjs/types.cjs.map +9 -0
  121. package/dist/mjs/bridge/diagnostics.mjs +18 -0
  122. package/dist/mjs/bridge/diagnostics.mjs.map +10 -0
  123. package/dist/mjs/bridge/legacy-adapters.mjs +178 -0
  124. package/dist/mjs/bridge/legacy-adapters.mjs.map +10 -0
  125. package/dist/mjs/bridge/request-context.mjs +19 -0
  126. package/dist/mjs/bridge/request-context.mjs.map +10 -0
  127. package/dist/mjs/bridge/runtime-bindings.mjs +303 -0
  128. package/dist/mjs/bridge/runtime-bindings.mjs.map +10 -0
  129. package/dist/mjs/browser/browser-runtime.mjs +93 -0
  130. package/dist/mjs/browser/browser-runtime.mjs.map +10 -0
  131. package/dist/mjs/daemon.mjs +91 -0
  132. package/dist/mjs/daemon.mjs.map +10 -0
  133. package/dist/mjs/files/index.mjs +76 -0
  134. package/dist/mjs/files/index.mjs.map +10 -0
  135. package/dist/mjs/host/create-isolate-host.mjs +171 -0
  136. package/dist/mjs/host/create-isolate-host.mjs.map +10 -0
  137. package/dist/mjs/host/index.mjs +7 -0
  138. package/dist/mjs/host/index.mjs.map +10 -0
  139. package/dist/mjs/index.mjs +15 -0
  140. package/dist/mjs/index.mjs.map +10 -0
  141. package/dist/mjs/internal/client/connection.mjs +1872 -0
  142. package/dist/mjs/internal/client/connection.mjs.map +10 -0
  143. package/dist/mjs/internal/client/index.mjs +8 -0
  144. package/dist/mjs/internal/client/index.mjs.map +10 -0
  145. package/dist/mjs/internal/client/types.mjs +2 -0
  146. package/dist/mjs/internal/client/types.mjs.map +9 -0
  147. package/dist/mjs/internal/console/index.mjs +442 -0
  148. package/dist/mjs/internal/console/index.mjs.map +10 -0
  149. package/dist/mjs/internal/console/utils.mjs +30 -0
  150. package/dist/mjs/internal/console/utils.mjs.map +10 -0
  151. package/dist/mjs/internal/core/index.mjs +2681 -0
  152. package/dist/mjs/internal/core/index.mjs.map +10 -0
  153. package/dist/mjs/internal/crypto/index.mjs +406 -0
  154. package/dist/mjs/internal/crypto/index.mjs.map +10 -0
  155. package/dist/mjs/internal/daemon/callback-fs-handler.mjs +315 -0
  156. package/dist/mjs/internal/daemon/callback-fs-handler.mjs.map +10 -0
  157. package/dist/mjs/internal/daemon/connection.mjs +1931 -0
  158. package/dist/mjs/internal/daemon/connection.mjs.map +10 -0
  159. package/dist/mjs/internal/daemon/daemon.mjs +98 -0
  160. package/dist/mjs/internal/daemon/daemon.mjs.map +10 -0
  161. package/dist/mjs/internal/daemon/index.mjs +105 -0
  162. package/dist/mjs/internal/daemon/index.mjs.map +10 -0
  163. package/dist/mjs/internal/daemon/runtime-pool.mjs +66 -0
  164. package/dist/mjs/internal/daemon/runtime-pool.mjs.map +10 -0
  165. package/dist/mjs/internal/daemon/types.mjs +2 -0
  166. package/dist/mjs/internal/daemon/types.mjs.map +9 -0
  167. package/dist/mjs/internal/encoding/index.mjs +379 -0
  168. package/dist/mjs/internal/encoding/index.mjs.map +10 -0
  169. package/dist/mjs/internal/fetch/consistency/origins.mjs +558 -0
  170. package/dist/mjs/internal/fetch/consistency/origins.mjs.map +10 -0
  171. package/dist/mjs/internal/fetch/index.mjs +2580 -0
  172. package/dist/mjs/internal/fetch/index.mjs.map +10 -0
  173. package/dist/mjs/internal/fetch/stream-state.mjs +216 -0
  174. package/dist/mjs/internal/fetch/stream-state.mjs.map +10 -0
  175. package/dist/mjs/internal/fs/index.mjs +783 -0
  176. package/dist/mjs/internal/fs/index.mjs.map +10 -0
  177. package/dist/mjs/internal/fs/node-adapter.mjs +190 -0
  178. package/dist/mjs/internal/fs/node-adapter.mjs.map +10 -0
  179. package/dist/mjs/internal/module-loader/bundle.mjs +418 -0
  180. package/dist/mjs/internal/module-loader/bundle.mjs.map +10 -0
  181. package/dist/mjs/internal/module-loader/index.mjs +185 -0
  182. package/dist/mjs/internal/module-loader/index.mjs.map +10 -0
  183. package/dist/mjs/internal/module-loader/mappings.mjs +80 -0
  184. package/dist/mjs/internal/module-loader/mappings.mjs.map +10 -0
  185. package/dist/mjs/internal/module-loader/resolve.mjs +113 -0
  186. package/dist/mjs/internal/module-loader/resolve.mjs.map +10 -0
  187. package/dist/mjs/internal/module-loader/strip-types.mjs +172 -0
  188. package/dist/mjs/internal/module-loader/strip-types.mjs.map +10 -0
  189. package/dist/mjs/internal/path/index.mjs +463 -0
  190. package/dist/mjs/internal/path/index.mjs.map +10 -0
  191. package/dist/mjs/internal/playwright/client.mjs +13 -0
  192. package/dist/mjs/internal/playwright/client.mjs.map +10 -0
  193. package/dist/mjs/internal/playwright/handler.mjs +1378 -0
  194. package/dist/mjs/internal/playwright/handler.mjs.map +10 -0
  195. package/dist/mjs/internal/playwright/index.mjs +1234 -0
  196. package/dist/mjs/internal/playwright/index.mjs.map +10 -0
  197. package/dist/mjs/internal/playwright/types.mjs +7 -0
  198. package/dist/mjs/internal/playwright/types.mjs.map +10 -0
  199. package/dist/mjs/internal/protocol/codec.mjs +470 -0
  200. package/dist/mjs/internal/protocol/codec.mjs.map +10 -0
  201. package/dist/mjs/internal/protocol/framing.mjs +101 -0
  202. package/dist/mjs/internal/protocol/framing.mjs.map +10 -0
  203. package/dist/mjs/internal/protocol/index.mjs +98 -0
  204. package/dist/mjs/internal/protocol/index.mjs.map +10 -0
  205. package/dist/mjs/internal/protocol/marshalValue.mjs +494 -0
  206. package/dist/mjs/internal/protocol/marshalValue.mjs.map +10 -0
  207. package/dist/mjs/internal/protocol/serialization.mjs +69 -0
  208. package/dist/mjs/internal/protocol/serialization.mjs.map +10 -0
  209. package/dist/mjs/internal/protocol/types.mjs +141 -0
  210. package/dist/mjs/internal/protocol/types.mjs.map +10 -0
  211. package/dist/mjs/internal/runtime/index.mjs +1198 -0
  212. package/dist/mjs/internal/runtime/index.mjs.map +10 -0
  213. package/dist/mjs/internal/server/index.mjs +183 -0
  214. package/dist/mjs/internal/server/index.mjs.map +10 -0
  215. package/dist/mjs/internal/test-environment/index.mjs +1351 -0
  216. package/dist/mjs/internal/test-environment/index.mjs.map +10 -0
  217. package/dist/mjs/internal/timers/index.mjs +136 -0
  218. package/dist/mjs/internal/timers/index.mjs.map +10 -0
  219. package/dist/mjs/internal/transform/index.mjs +321 -0
  220. package/dist/mjs/internal/transform/index.mjs.map +10 -0
  221. package/dist/mjs/internal/typecheck/index.mjs +35 -0
  222. package/dist/mjs/internal/typecheck/index.mjs.map +10 -0
  223. package/dist/mjs/internal/typecheck/isolate-types.mjs +2574 -0
  224. package/dist/mjs/internal/typecheck/isolate-types.mjs.map +10 -0
  225. package/dist/mjs/internal/typecheck/typecheck.mjs +91 -0
  226. package/dist/mjs/internal/typecheck/typecheck.mjs.map +10 -0
  227. package/dist/mjs/modules/index.mjs +96 -0
  228. package/dist/mjs/modules/index.mjs.map +10 -0
  229. package/dist/mjs/package.json +5 -0
  230. package/dist/mjs/runtime/script-runtime.mjs +57 -0
  231. package/dist/mjs/runtime/script-runtime.mjs.map +10 -0
  232. package/dist/mjs/server/app-server.mjs +118 -0
  233. package/dist/mjs/server/app-server.mjs.map +10 -0
  234. package/dist/mjs/testing/integration-helpers.mjs +63 -0
  235. package/dist/mjs/testing/integration-helpers.mjs.map +10 -0
  236. package/dist/mjs/typecheck/index.mjs +56 -0
  237. package/dist/mjs/typecheck/index.mjs.map +10 -0
  238. package/dist/mjs/types.mjs +2 -0
  239. package/dist/mjs/types.mjs.map +9 -0
  240. package/dist/types/bridge/diagnostics.d.ts +12 -0
  241. package/dist/types/bridge/legacy-adapters.d.ts +14 -0
  242. package/dist/types/bridge/request-context.d.ts +10 -0
  243. package/dist/types/bridge/runtime-bindings.d.ts +14 -0
  244. package/dist/types/browser/browser-runtime.d.ts +3 -0
  245. package/dist/types/daemon.d.ts +2 -0
  246. package/dist/types/files/index.d.ts +5 -0
  247. package/dist/types/host/create-isolate-host.d.ts +2 -0
  248. package/dist/types/host/index.d.ts +1 -0
  249. package/dist/types/index.d.ts +5 -0
  250. package/dist/types/internal/client/connection.d.ts +9 -0
  251. package/dist/types/internal/client/index.d.ts +8 -0
  252. package/dist/types/internal/client/types.d.ts +198 -0
  253. package/dist/types/internal/console/index.d.ts +108 -0
  254. package/dist/types/internal/console/utils.d.ts +27 -0
  255. package/dist/types/internal/core/index.d.ts +119 -0
  256. package/dist/types/internal/crypto/index.d.ts +18 -0
  257. package/dist/types/internal/daemon/callback-fs-handler.d.ts +28 -0
  258. package/dist/types/internal/daemon/connection.d.ts +9 -0
  259. package/dist/types/internal/daemon/daemon.d.ts +2 -0
  260. package/dist/types/internal/daemon/index.d.ts +14 -0
  261. package/dist/types/internal/daemon/runtime-pool.d.ts +16 -0
  262. package/dist/types/internal/daemon/types.d.ts +211 -0
  263. package/dist/types/internal/encoding/index.d.ts +21 -0
  264. package/dist/types/internal/fetch/consistency/origins.d.ts +179 -0
  265. package/dist/types/internal/fetch/index.d.ts +93 -0
  266. package/dist/types/internal/fetch/stream-state.d.ts +65 -0
  267. package/dist/types/internal/fs/index.d.ts +70 -0
  268. package/dist/types/internal/fs/node-adapter.d.ts +24 -0
  269. package/dist/types/internal/module-loader/bundle.d.ts +33 -0
  270. package/dist/types/internal/module-loader/index.d.ts +30 -0
  271. package/dist/types/internal/module-loader/mappings.d.ts +47 -0
  272. package/dist/types/internal/module-loader/resolve.d.ts +26 -0
  273. package/dist/types/internal/module-loader/strip-types.d.ts +19 -0
  274. package/dist/types/internal/path/index.d.ts +23 -0
  275. package/dist/types/internal/playwright/client.d.ts +7 -0
  276. package/dist/types/internal/playwright/handler.d.ts +44 -0
  277. package/dist/types/internal/playwright/index.d.ts +14 -0
  278. package/dist/types/internal/playwright/types.d.ts +145 -0
  279. package/dist/types/internal/protocol/codec.d.ts +242 -0
  280. package/dist/types/internal/protocol/framing.d.ts +89 -0
  281. package/dist/types/internal/protocol/index.d.ts +10 -0
  282. package/dist/types/internal/protocol/marshalValue.d.ts +79 -0
  283. package/dist/types/internal/protocol/serialization.d.ts +23 -0
  284. package/dist/types/internal/protocol/types.d.ts +996 -0
  285. package/dist/types/internal/runtime/index.d.ts +200 -0
  286. package/dist/types/internal/server/index.d.ts +42 -0
  287. package/dist/types/internal/test-environment/index.d.ts +112 -0
  288. package/dist/types/internal/timers/index.d.ts +22 -0
  289. package/dist/types/internal/transform/index.d.ts +36 -0
  290. package/dist/types/internal/typecheck/index.d.ts +7 -0
  291. package/dist/types/internal/typecheck/isolate-types.d.ts +94 -0
  292. package/dist/types/internal/typecheck/typecheck.d.ts +148 -0
  293. package/dist/types/modules/index.d.ts +2 -0
  294. package/dist/types/runtime/script-runtime.d.ts +6 -0
  295. package/dist/types/server/app-server.d.ts +3 -0
  296. package/dist/types/testing/integration-helpers.d.ts +9 -0
  297. package/dist/types/typecheck/index.d.ts +8 -0
  298. package/dist/types/types.d.ts +233 -0
  299. package/package.json +82 -6
@@ -0,0 +1,2580 @@
1
+ // src/internal/fetch/index.ts
2
+ import ivm from "isolated-vm";
3
+ import { setupCore, clearAllInstanceState } from "../core/index.mjs";
4
+ import {
5
+ getStreamRegistryForContext,
6
+ startNativeStreamReader,
7
+ clearStreamRegistryForContext
8
+ } from "./stream-state.mjs";
9
+ var instanceStateMap = new WeakMap;
10
+ var passthruBodies = new WeakMap;
11
+ var trackedGlobalHandles = new WeakMap;
12
+ var nextInstanceId = 1;
13
+ function getInstanceStateMapForContext(context) {
14
+ let map = instanceStateMap.get(context);
15
+ if (!map) {
16
+ map = new Map;
17
+ instanceStateMap.set(context, map);
18
+ }
19
+ return map;
20
+ }
21
+ function getPassthruBodiesForContext(context) {
22
+ let map = passthruBodies.get(context);
23
+ if (!map) {
24
+ map = new Map;
25
+ passthruBodies.set(context, map);
26
+ }
27
+ return map;
28
+ }
29
+ function getTrackedGlobalHandlesForContext(context) {
30
+ let handles = trackedGlobalHandles.get(context);
31
+ if (!handles) {
32
+ handles = new Set;
33
+ trackedGlobalHandles.set(context, handles);
34
+ }
35
+ return handles;
36
+ }
37
+ function setTrackedGlobal(context, name, value) {
38
+ if (value instanceof ivm.Callback || value instanceof ivm.Reference) {
39
+ getTrackedGlobalHandlesForContext(context).add(value);
40
+ }
41
+ context.global.setSync(name, value);
42
+ }
43
+ function releaseIfSupported(handle) {
44
+ const maybeHandle = handle;
45
+ if (typeof maybeHandle.release === "function") {
46
+ maybeHandle.release();
47
+ }
48
+ }
49
+ function releaseTrackedGlobalHandles(context) {
50
+ const handles = trackedGlobalHandles.get(context);
51
+ if (!handles)
52
+ return;
53
+ for (const handle of handles) {
54
+ try {
55
+ releaseIfSupported(handle);
56
+ } catch {}
57
+ }
58
+ handles.clear();
59
+ }
60
+ function clearPassthruBodiesForContext(context) {
61
+ const map = passthruBodies.get(context);
62
+ if (!map)
63
+ return;
64
+ map.clear();
65
+ passthruBodies.delete(context);
66
+ }
67
+ var headersCode = `
68
+ (function() {
69
+ class Headers {
70
+ #headers = new Map(); // lowercase key -> [originalCase, values[]]
71
+
72
+ constructor(init) {
73
+ if (init instanceof Headers) {
74
+ init.forEach((value, key) => this.append(key, value));
75
+ } else if (Array.isArray(init)) {
76
+ for (const pair of init) {
77
+ if (Array.isArray(pair) && pair.length >= 2) {
78
+ this.append(pair[0], pair[1]);
79
+ }
80
+ }
81
+ } else if (init && typeof init === 'object') {
82
+ for (const [key, value] of Object.entries(init)) {
83
+ this.append(key, value);
84
+ }
85
+ }
86
+ }
87
+
88
+ append(name, value) {
89
+ const key = String(name).toLowerCase();
90
+ const valueStr = String(value);
91
+ const existing = this.#headers.get(key);
92
+ if (existing) {
93
+ existing[1].push(valueStr);
94
+ } else {
95
+ this.#headers.set(key, [String(name), [valueStr]]);
96
+ }
97
+ }
98
+
99
+ delete(name) {
100
+ this.#headers.delete(String(name).toLowerCase());
101
+ }
102
+
103
+ get(name) {
104
+ const entry = this.#headers.get(String(name).toLowerCase());
105
+ return entry ? entry[1].join(', ') : null;
106
+ }
107
+
108
+ getSetCookie() {
109
+ const entry = this.#headers.get('set-cookie');
110
+ return entry ? [...entry[1]] : [];
111
+ }
112
+
113
+ has(name) {
114
+ return this.#headers.has(String(name).toLowerCase());
115
+ }
116
+
117
+ set(name, value) {
118
+ const key = String(name).toLowerCase();
119
+ this.#headers.set(key, [String(name), [String(value)]]);
120
+ }
121
+
122
+ forEach(callback, thisArg) {
123
+ const sortedKeys = [...this.#headers.keys()].sort();
124
+ for (const key of sortedKeys) {
125
+ const [, values] = this.#headers.get(key);
126
+ if (key === 'set-cookie') {
127
+ for (const value of values) {
128
+ callback.call(thisArg, value, key, this);
129
+ }
130
+ continue;
131
+ }
132
+ callback.call(thisArg, values.join(', '), key, this);
133
+ }
134
+ }
135
+
136
+ *entries() {
137
+ const sortedKeys = [...this.#headers.keys()].sort();
138
+ for (const key of sortedKeys) {
139
+ const [, values] = this.#headers.get(key);
140
+ if (key === 'set-cookie') {
141
+ for (const value of values) {
142
+ yield [key, value];
143
+ }
144
+ continue;
145
+ }
146
+ yield [key, values.join(', ')];
147
+ }
148
+ }
149
+
150
+ *keys() {
151
+ const sortedKeys = [...this.#headers.keys()].sort();
152
+ for (const key of sortedKeys) {
153
+ yield key;
154
+ }
155
+ }
156
+
157
+ *values() {
158
+ const sortedKeys = [...this.#headers.keys()].sort();
159
+ for (const key of sortedKeys) {
160
+ const [, values] = this.#headers.get(key);
161
+ if (key === 'set-cookie') {
162
+ for (const value of values) {
163
+ yield value;
164
+ }
165
+ continue;
166
+ }
167
+ yield values.join(', ');
168
+ }
169
+ }
170
+
171
+ [Symbol.iterator]() {
172
+ return this.entries();
173
+ }
174
+ }
175
+
176
+ globalThis.Headers = Headers;
177
+ })();
178
+ `;
179
+ var formDataCode = `
180
+ (function() {
181
+ class FormData {
182
+ #entries = []; // Array of [name, value]
183
+
184
+ append(name, value, filename) {
185
+ let finalValue = value;
186
+ if (value instanceof Blob && !(value instanceof File)) {
187
+ if (filename !== undefined) {
188
+ finalValue = new File([value], String(filename), { type: value.type });
189
+ }
190
+ } else if (value instanceof File && filename !== undefined) {
191
+ finalValue = new File([value], String(filename), {
192
+ type: value.type,
193
+ lastModified: value.lastModified
194
+ });
195
+ }
196
+ this.#entries.push([String(name), finalValue]);
197
+ }
198
+
199
+ delete(name) {
200
+ const nameStr = String(name);
201
+ this.#entries = this.#entries.filter(([n]) => n !== nameStr);
202
+ }
203
+
204
+ get(name) {
205
+ const nameStr = String(name);
206
+ const entry = this.#entries.find(([n]) => n === nameStr);
207
+ return entry ? entry[1] : null;
208
+ }
209
+
210
+ getAll(name) {
211
+ const nameStr = String(name);
212
+ return this.#entries.filter(([n]) => n === nameStr).map(([, v]) => v);
213
+ }
214
+
215
+ has(name) {
216
+ return this.#entries.some(([n]) => n === String(name));
217
+ }
218
+
219
+ set(name, value, filename) {
220
+ const nameStr = String(name);
221
+ this.delete(nameStr);
222
+ this.append(nameStr, value, filename);
223
+ }
224
+
225
+ *entries() {
226
+ for (const [name, value] of this.#entries) {
227
+ yield [name, value];
228
+ }
229
+ }
230
+
231
+ *keys() {
232
+ for (const [name] of this.#entries) {
233
+ yield name;
234
+ }
235
+ }
236
+
237
+ *values() {
238
+ for (const [, value] of this.#entries) {
239
+ yield value;
240
+ }
241
+ }
242
+
243
+ forEach(callback, thisArg) {
244
+ for (const [name, value] of this.#entries) {
245
+ callback.call(thisArg, value, name, this);
246
+ }
247
+ }
248
+
249
+ [Symbol.iterator]() {
250
+ return this.entries();
251
+ }
252
+ }
253
+
254
+ globalThis.FormData = FormData;
255
+ })();
256
+ `;
257
+ var multipartCode = `
258
+ (function() {
259
+ // Find byte sequence in Uint8Array
260
+ function findSequence(haystack, needle, start = 0) {
261
+ outer: for (let i = start; i <= haystack.length - needle.length; i++) {
262
+ for (let j = 0; j < needle.length; j++) {
263
+ if (haystack[i + j] !== needle[j]) continue outer;
264
+ }
265
+ return i;
266
+ }
267
+ return -1;
268
+ }
269
+
270
+ // Parse header lines into object
271
+ function parseHeaders(text) {
272
+ const headers = {};
273
+ for (const line of text.split(/\\r?\\n/)) {
274
+ const colonIdx = line.indexOf(':');
275
+ if (colonIdx > 0) {
276
+ const name = line.slice(0, colonIdx).trim().toLowerCase();
277
+ const value = line.slice(colonIdx + 1).trim();
278
+ headers[name] = value;
279
+ }
280
+ }
281
+ return headers;
282
+ }
283
+
284
+ // Parse multipart/form-data body into FormData
285
+ globalThis.__parseMultipartFormData = function(bodyBytes, contentType) {
286
+ const formData = new FormData();
287
+
288
+ // Extract boundary from Content-Type
289
+ const boundaryMatch = contentType.match(/boundary=([^;]+)/i);
290
+ if (!boundaryMatch) return formData;
291
+
292
+ const boundary = boundaryMatch[1].replace(/^["']|["']$/g, '');
293
+ const encoder = new TextEncoder();
294
+ const decoder = new TextDecoder();
295
+ const boundaryBytes = encoder.encode('--' + boundary);
296
+
297
+ // Find first boundary
298
+ let pos = findSequence(bodyBytes, boundaryBytes, 0);
299
+ if (pos === -1) return formData;
300
+ pos += boundaryBytes.length;
301
+
302
+ while (pos < bodyBytes.length) {
303
+ // Skip CRLF after boundary
304
+ if (bodyBytes[pos] === 0x0d && bodyBytes[pos + 1] === 0x0a) pos += 2;
305
+ else if (bodyBytes[pos] === 0x0a) pos += 1;
306
+
307
+ // Check for closing boundary (--)
308
+ if (bodyBytes[pos] === 0x2d && bodyBytes[pos + 1] === 0x2d) break;
309
+
310
+ // Find header/body separator (CRLFCRLF)
311
+ const crlfcrlf = encoder.encode('\\r\\n\\r\\n');
312
+ const headersEnd = findSequence(bodyBytes, crlfcrlf, pos);
313
+ if (headersEnd === -1) break;
314
+
315
+ // Parse headers
316
+ const headersText = decoder.decode(bodyBytes.slice(pos, headersEnd));
317
+ const headers = parseHeaders(headersText);
318
+ pos = headersEnd + 4;
319
+
320
+ // Find next boundary
321
+ const nextBoundary = findSequence(bodyBytes, boundaryBytes, pos);
322
+ if (nextBoundary === -1) break;
323
+
324
+ // Extract content (minus trailing CRLF)
325
+ let contentEnd = nextBoundary;
326
+ if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0a) contentEnd--;
327
+ if (contentEnd > 0 && bodyBytes[contentEnd - 1] === 0x0d) contentEnd--;
328
+ const content = bodyBytes.slice(pos, contentEnd);
329
+
330
+ // Parse Content-Disposition
331
+ const disposition = headers['content-disposition'] || '';
332
+ const nameMatch = disposition.match(/name="([^"]+)"/);
333
+ const filenameMatch = disposition.match(/filename="([^"]+)"/);
334
+
335
+ if (nameMatch) {
336
+ const name = nameMatch[1];
337
+ if (filenameMatch) {
338
+ const filename = filenameMatch[1];
339
+ const mimeType = headers['content-type'] || 'application/octet-stream';
340
+ const file = new File([content], filename, { type: mimeType });
341
+ formData.append(name, file);
342
+ } else {
343
+ formData.append(name, decoder.decode(content));
344
+ }
345
+ }
346
+
347
+ pos = nextBoundary + boundaryBytes.length;
348
+ }
349
+
350
+ return formData;
351
+ };
352
+
353
+ // Serialize FormData to multipart/form-data format
354
+ globalThis.__serializeFormData = function(formData) {
355
+ const boundary = '----FormDataBoundary' + Math.random().toString(36).slice(2) +
356
+ Math.random().toString(36).slice(2);
357
+ const encoder = new TextEncoder();
358
+ const parts = [];
359
+
360
+ for (const [name, value] of formData.entries()) {
361
+ if (value instanceof File) {
362
+ const header = [
363
+ '--' + boundary,
364
+ 'Content-Disposition: form-data; name="' + name + '"; filename="' + value.name + '"',
365
+ 'Content-Type: ' + (value.type || 'application/octet-stream'),
366
+ '',
367
+ ''
368
+ ].join('\\r\\n');
369
+ parts.push(encoder.encode(header));
370
+ // Use existing __Blob_bytes callback (File extends Blob)
371
+ parts.push(__Blob_bytes(value._getInstanceId()));
372
+ parts.push(encoder.encode('\\r\\n'));
373
+ } else if (value instanceof Blob) {
374
+ const header = [
375
+ '--' + boundary,
376
+ 'Content-Disposition: form-data; name="' + name + '"; filename="blob"',
377
+ 'Content-Type: ' + (value.type || 'application/octet-stream'),
378
+ '',
379
+ ''
380
+ ].join('\\r\\n');
381
+ parts.push(encoder.encode(header));
382
+ parts.push(__Blob_bytes(value._getInstanceId()));
383
+ parts.push(encoder.encode('\\r\\n'));
384
+ } else {
385
+ const header = [
386
+ '--' + boundary,
387
+ 'Content-Disposition: form-data; name="' + name + '"',
388
+ '',
389
+ ''
390
+ ].join('\\r\\n');
391
+ parts.push(encoder.encode(header));
392
+ parts.push(encoder.encode(String(value)));
393
+ parts.push(encoder.encode('\\r\\n'));
394
+ }
395
+ }
396
+
397
+ // Closing boundary
398
+ parts.push(encoder.encode('--' + boundary + '--\\r\\n'));
399
+
400
+ // Concatenate all parts
401
+ const totalLength = parts.reduce((sum, p) => sum + p.length, 0);
402
+ const body = new Uint8Array(totalLength);
403
+ let offset = 0;
404
+ for (const part of parts) {
405
+ body.set(part, offset);
406
+ offset += part.length;
407
+ }
408
+
409
+ return {
410
+ body: body,
411
+ contentType: 'multipart/form-data; boundary=' + boundary
412
+ };
413
+ };
414
+ })();
415
+ `;
416
+ function setupStreamCallbacks(context, streamRegistry) {
417
+ setTrackedGlobal(context, "__Stream_create", new ivm.Callback(() => {
418
+ return streamRegistry.create();
419
+ }));
420
+ setTrackedGlobal(context, "__Stream_push", new ivm.Callback((streamId, chunkArray) => {
421
+ const chunk = new Uint8Array(chunkArray);
422
+ return streamRegistry.push(streamId, chunk);
423
+ }));
424
+ setTrackedGlobal(context, "__Stream_close", new ivm.Callback((streamId) => {
425
+ streamRegistry.close(streamId);
426
+ }));
427
+ setTrackedGlobal(context, "__Stream_error", new ivm.Callback((streamId, message) => {
428
+ streamRegistry.error(streamId, new Error(message));
429
+ }));
430
+ setTrackedGlobal(context, "__Stream_isQueueFull", new ivm.Callback((streamId) => {
431
+ return streamRegistry.isQueueFull(streamId);
432
+ }));
433
+ setTrackedGlobal(context, "__Stream_cancel", new ivm.Callback((streamId) => {
434
+ streamRegistry.cancel(streamId);
435
+ }));
436
+ const pullRef = new ivm.Reference(async (streamId) => {
437
+ const result = await streamRegistry.pull(streamId);
438
+ if (result.done) {
439
+ return JSON.stringify({ done: true });
440
+ }
441
+ return JSON.stringify({ done: false, value: Array.from(result.value) });
442
+ });
443
+ setTrackedGlobal(context, "__Stream_pull_ref", pullRef);
444
+ }
445
+ var hostBackedStreamCode = `
446
+ (function() {
447
+ const _streamIds = new WeakMap();
448
+
449
+ // Polyfill values() on ReadableStream if not available (older V8 versions)
450
+ if (typeof ReadableStream.prototype.values !== 'function') {
451
+ ReadableStream.prototype.values = function(options) {
452
+ const reader = this.getReader();
453
+ return {
454
+ async next() {
455
+ const { value, done } = await reader.read();
456
+ if (done) {
457
+ reader.releaseLock();
458
+ return { value: undefined, done: true };
459
+ }
460
+ return { value, done: false };
461
+ },
462
+ async return(value) {
463
+ reader.releaseLock();
464
+ return { value, done: true };
465
+ },
466
+ [Symbol.asyncIterator]() {
467
+ return this;
468
+ }
469
+ };
470
+ };
471
+ }
472
+
473
+ // Create a proper ReadableStream subclass that reports as "ReadableStream"
474
+ class HostBackedReadableStream extends ReadableStream {
475
+ constructor(streamId) {
476
+ if (streamId === undefined) {
477
+ streamId = __Stream_create();
478
+ }
479
+
480
+ let closed = false;
481
+
482
+ super({
483
+ async pull(controller) {
484
+ if (closed) return;
485
+
486
+ const resultJson = await __Stream_pull_ref.apply(undefined, [streamId], { result: { promise: true, copy: true } });
487
+ const result = JSON.parse(resultJson);
488
+
489
+ if (result.done) {
490
+ closed = true;
491
+ controller.close();
492
+ return;
493
+ }
494
+ controller.enqueue(new Uint8Array(result.value));
495
+ },
496
+ cancel(reason) {
497
+ closed = true;
498
+ __Stream_cancel(streamId);
499
+ }
500
+ });
501
+
502
+ _streamIds.set(this, streamId);
503
+ }
504
+
505
+ // Override to report as ReadableStream for spec compliance
506
+ get [Symbol.toStringTag]() {
507
+ return 'ReadableStream';
508
+ }
509
+
510
+ _getStreamId() {
511
+ return _streamIds.get(this);
512
+ }
513
+
514
+ static _fromStreamId(streamId) {
515
+ return new HostBackedReadableStream(streamId);
516
+ }
517
+ }
518
+
519
+ // Make constructor.name return 'ReadableStream' for spec compliance
520
+ Object.defineProperty(HostBackedReadableStream, 'name', { value: 'ReadableStream' });
521
+
522
+ globalThis.HostBackedReadableStream = HostBackedReadableStream;
523
+ })();
524
+ `;
525
+ function setupResponse(context, stateMap, streamRegistry) {
526
+ setTrackedGlobal(context, "__Response_construct", new ivm.Callback((bodyBytes, status, statusText, headers) => {
527
+ const instanceId = nextInstanceId++;
528
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
529
+ const state = {
530
+ status,
531
+ statusText,
532
+ headers,
533
+ body,
534
+ bodyUsed: false,
535
+ type: "default",
536
+ url: "",
537
+ redirected: false,
538
+ streamId: null
539
+ };
540
+ stateMap.set(instanceId, state);
541
+ return instanceId;
542
+ }));
543
+ setTrackedGlobal(context, "__Response_constructStreaming", new ivm.Callback((streamId, status, statusText, headers) => {
544
+ const instanceId = nextInstanceId++;
545
+ const state = {
546
+ status,
547
+ statusText,
548
+ headers,
549
+ body: null,
550
+ bodyUsed: false,
551
+ type: "default",
552
+ url: "",
553
+ redirected: false,
554
+ streamId
555
+ };
556
+ stateMap.set(instanceId, state);
557
+ return instanceId;
558
+ }));
559
+ setTrackedGlobal(context, "__Response_constructFromFetch", new ivm.Callback((bodyBytes, status, statusText, headers, url, redirected) => {
560
+ const instanceId = nextInstanceId++;
561
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
562
+ const state = {
563
+ status,
564
+ statusText,
565
+ headers,
566
+ body,
567
+ bodyUsed: false,
568
+ type: "default",
569
+ url,
570
+ redirected,
571
+ streamId: null
572
+ };
573
+ stateMap.set(instanceId, state);
574
+ return instanceId;
575
+ }));
576
+ setTrackedGlobal(context, "__Response_get_status", new ivm.Callback((instanceId) => {
577
+ const state = stateMap.get(instanceId);
578
+ return state?.status ?? 200;
579
+ }));
580
+ setTrackedGlobal(context, "__Response_get_statusText", new ivm.Callback((instanceId) => {
581
+ const state = stateMap.get(instanceId);
582
+ return state?.statusText ?? "";
583
+ }));
584
+ setTrackedGlobal(context, "__Response_get_headers", new ivm.Callback((instanceId) => {
585
+ const state = stateMap.get(instanceId);
586
+ return state?.headers ?? [];
587
+ }));
588
+ setTrackedGlobal(context, "__Response_get_bodyUsed", new ivm.Callback((instanceId) => {
589
+ const state = stateMap.get(instanceId);
590
+ return state?.bodyUsed ?? false;
591
+ }));
592
+ setTrackedGlobal(context, "__Response_get_url", new ivm.Callback((instanceId) => {
593
+ const state = stateMap.get(instanceId);
594
+ return state?.url ?? "";
595
+ }));
596
+ setTrackedGlobal(context, "__Response_get_redirected", new ivm.Callback((instanceId) => {
597
+ const state = stateMap.get(instanceId);
598
+ return state?.redirected ?? false;
599
+ }));
600
+ setTrackedGlobal(context, "__Response_get_type", new ivm.Callback((instanceId) => {
601
+ const state = stateMap.get(instanceId);
602
+ return state?.type ?? "default";
603
+ }));
604
+ setTrackedGlobal(context, "__Response_get_nullBody", new ivm.Callback((instanceId) => {
605
+ const state = stateMap.get(instanceId);
606
+ return state?.nullBody ?? false;
607
+ }));
608
+ setTrackedGlobal(context, "__Response_setType", new ivm.Callback((instanceId, type) => {
609
+ const state = stateMap.get(instanceId);
610
+ if (state) {
611
+ state.type = type;
612
+ }
613
+ }));
614
+ setTrackedGlobal(context, "__Response_markBodyUsed", new ivm.Callback((instanceId) => {
615
+ const state = stateMap.get(instanceId);
616
+ if (state) {
617
+ if (state.bodyUsed) {
618
+ throw new Error("[TypeError]Body has already been consumed");
619
+ }
620
+ state.bodyUsed = true;
621
+ }
622
+ }));
623
+ setTrackedGlobal(context, "__Response_text", new ivm.Callback((instanceId) => {
624
+ const state = stateMap.get(instanceId);
625
+ if (!state || !state.body)
626
+ return "";
627
+ return new TextDecoder().decode(state.body);
628
+ }));
629
+ setTrackedGlobal(context, "__Response_arrayBuffer", new ivm.Callback((instanceId) => {
630
+ const state = stateMap.get(instanceId);
631
+ if (!state || !state.body) {
632
+ return new ivm.ExternalCopy(new ArrayBuffer(0)).copyInto();
633
+ }
634
+ return new ivm.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
635
+ }));
636
+ setTrackedGlobal(context, "__Response_clone", new ivm.Callback((instanceId) => {
637
+ const state = stateMap.get(instanceId);
638
+ if (!state) {
639
+ throw new Error("[TypeError]Cannot clone invalid Response");
640
+ }
641
+ if (state.streamId !== null) {
642
+ const streamId1 = streamRegistry.create();
643
+ const streamId2 = streamRegistry.create();
644
+ const origStreamId = state.streamId;
645
+ (async () => {
646
+ try {
647
+ while (true) {
648
+ const result = await streamRegistry.pull(origStreamId);
649
+ if (result.done) {
650
+ streamRegistry.close(streamId1);
651
+ streamRegistry.close(streamId2);
652
+ break;
653
+ }
654
+ streamRegistry.push(streamId1, new Uint8Array(result.value));
655
+ streamRegistry.push(streamId2, new Uint8Array(result.value));
656
+ }
657
+ } catch (err) {
658
+ streamRegistry.error(streamId1, err);
659
+ streamRegistry.error(streamId2, err);
660
+ }
661
+ })();
662
+ state.streamId = streamId1;
663
+ const newId2 = nextInstanceId++;
664
+ const newState2 = {
665
+ ...state,
666
+ streamId: streamId2,
667
+ body: state.body ? new Uint8Array(state.body) : null,
668
+ bodyUsed: false
669
+ };
670
+ stateMap.set(newId2, newState2);
671
+ return newId2;
672
+ }
673
+ const newId = nextInstanceId++;
674
+ const newState = {
675
+ ...state,
676
+ body: state.body ? new Uint8Array(state.body) : null,
677
+ bodyUsed: false
678
+ };
679
+ stateMap.set(newId, newState);
680
+ return newId;
681
+ }));
682
+ setTrackedGlobal(context, "__Response_getStreamId", new ivm.Callback((instanceId) => {
683
+ const state = stateMap.get(instanceId);
684
+ return state?.streamId ?? null;
685
+ }));
686
+ const responseCode = `
687
+ (function() {
688
+ const _responseInstanceIds = new WeakMap();
689
+
690
+ function __decodeError(err) {
691
+ if (!(err instanceof Error)) return err;
692
+ const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
693
+ if (match) {
694
+ const ErrorType = globalThis[match[1]] || Error;
695
+ return new ErrorType(match[2]);
696
+ }
697
+ return err;
698
+ }
699
+
700
+ function __prepareBody(body) {
701
+ if (body === null || body === undefined) return null;
702
+ if (typeof body === 'string') {
703
+ const encoder = new TextEncoder();
704
+ return Array.from(encoder.encode(body));
705
+ }
706
+ if (body instanceof ArrayBuffer) {
707
+ return Array.from(new Uint8Array(body));
708
+ }
709
+ if (body instanceof Uint8Array) {
710
+ return Array.from(body);
711
+ }
712
+ if (ArrayBuffer.isView(body)) {
713
+ return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
714
+ }
715
+ if (body instanceof Blob) {
716
+ // Mark as needing async Blob handling - will be read in constructor
717
+ return { __isBlob: true, blob: body };
718
+ }
719
+ // Handle HostBackedReadableStream specially - preserve streamId
720
+ if (body instanceof HostBackedReadableStream) {
721
+ return { __isHostStream: true, stream: body, streamId: body._getStreamId() };
722
+ }
723
+ // Handle native ReadableStream
724
+ if (body instanceof ReadableStream) {
725
+ return { __isStream: true, stream: body };
726
+ }
727
+ // Try to convert to string
728
+ return Array.from(new TextEncoder().encode(String(body)));
729
+ }
730
+
731
+ class Response {
732
+ #instanceId;
733
+ #headers;
734
+ #streamId = null;
735
+ #blobInitPromise = null; // For async Blob body initialization
736
+ #cachedBody = null; // Memoized body stream for spec compliance
737
+
738
+ constructor(body, init = {}) {
739
+ // Handle internal construction from instance ID
740
+ if (typeof body === 'number' && init === null) {
741
+ this.#instanceId = body;
742
+ this.#headers = new Headers(__Response_get_headers(body));
743
+ this.#streamId = __Response_getStreamId(body);
744
+ return;
745
+ }
746
+
747
+ const preparedBody = __prepareBody(body);
748
+
749
+ // Handle Blob body - create streaming response and push blob data
750
+ if (preparedBody && preparedBody.__isBlob) {
751
+ this.#streamId = __Stream_create();
752
+ const status = init.status ?? 200;
753
+ const statusText = init.statusText ?? '';
754
+ const headers = new Headers(init.headers);
755
+ const headersArray = Array.from(headers.entries());
756
+
757
+ this.#instanceId = __Response_constructStreaming(
758
+ this.#streamId,
759
+ status,
760
+ statusText,
761
+ headersArray
762
+ );
763
+ this.#headers = headers;
764
+
765
+ // Start async blob initialization and stream pumping
766
+ const streamId = this.#streamId;
767
+ const blob = preparedBody.blob;
768
+ this.#blobInitPromise = (async () => {
769
+ try {
770
+ const buffer = await blob.arrayBuffer();
771
+ __Stream_push(streamId, Array.from(new Uint8Array(buffer)));
772
+ __Stream_close(streamId);
773
+ } catch (error) {
774
+ __Stream_error(streamId, String(error));
775
+ }
776
+ })();
777
+ return;
778
+ }
779
+
780
+ // Handle HostBackedReadableStream - reuse existing streamId for pass-through
781
+ if (preparedBody && preparedBody.__isHostStream) {
782
+ // Reuse the existing streamId to preserve the pass-through body mapping
783
+ this.#streamId = preparedBody.streamId;
784
+ const status = init.status ?? 200;
785
+ const statusText = init.statusText ?? '';
786
+ const headers = new Headers(init.headers);
787
+ const headersArray = Array.from(headers.entries());
788
+
789
+ this.#instanceId = __Response_constructStreaming(
790
+ this.#streamId,
791
+ status,
792
+ statusText,
793
+ headersArray
794
+ );
795
+ this.#headers = headers;
796
+ // Don't pump - the body is already backed by this streamId
797
+ return;
798
+ }
799
+
800
+ // Handle native ReadableStream body
801
+ if (preparedBody && preparedBody.__isStream) {
802
+ this.#streamId = __Stream_create();
803
+ const status = init.status ?? 200;
804
+ const statusText = init.statusText ?? '';
805
+ const headers = new Headers(init.headers);
806
+ const headersArray = Array.from(headers.entries());
807
+
808
+ this.#instanceId = __Response_constructStreaming(
809
+ this.#streamId,
810
+ status,
811
+ statusText,
812
+ headersArray
813
+ );
814
+ this.#headers = headers;
815
+
816
+ // Start pumping the source stream to host queue (fire-and-forget)
817
+ this._startStreamPump(preparedBody.stream);
818
+ return;
819
+ }
820
+
821
+ // Existing buffered body handling
822
+ const bodyBytes = preparedBody;
823
+ const status = init.status ?? 200;
824
+ const statusText = init.statusText ?? '';
825
+ const headersInit = init.headers;
826
+ const headers = new Headers(headersInit);
827
+ const headersArray = Array.from(headers.entries());
828
+
829
+ this.#instanceId = __Response_construct(bodyBytes, status, statusText, headersArray);
830
+ this.#headers = headers;
831
+ }
832
+
833
+ async _startStreamPump(sourceStream) {
834
+ const streamId = this.#streamId;
835
+ try {
836
+ const reader = sourceStream.getReader();
837
+ while (true) {
838
+ // Check backpressure - wait if queue is full
839
+ while (__Stream_isQueueFull(streamId)) {
840
+ await new Promise(r => setTimeout(r, 1));
841
+ }
842
+
843
+ const { done, value } = await reader.read();
844
+ if (done) {
845
+ __Stream_close(streamId);
846
+ break;
847
+ }
848
+ if (value) {
849
+ __Stream_push(streamId, Array.from(value));
850
+ }
851
+ }
852
+ } catch (error) {
853
+ __Stream_error(streamId, String(error));
854
+ }
855
+ }
856
+
857
+ _getInstanceId() {
858
+ return this.#instanceId;
859
+ }
860
+
861
+ static _fromInstanceId(instanceId) {
862
+ return new Response(instanceId, null);
863
+ }
864
+
865
+ get status() {
866
+ return __Response_get_status(this.#instanceId);
867
+ }
868
+
869
+ get statusText() {
870
+ return __Response_get_statusText(this.#instanceId);
871
+ }
872
+
873
+ get ok() {
874
+ const status = this.status;
875
+ return status >= 200 && status < 300;
876
+ }
877
+
878
+ get headers() {
879
+ return this.#headers;
880
+ }
881
+
882
+ get bodyUsed() {
883
+ return __Response_get_bodyUsed(this.#instanceId);
884
+ }
885
+
886
+ get url() {
887
+ return __Response_get_url(this.#instanceId);
888
+ }
889
+
890
+ get redirected() {
891
+ return __Response_get_redirected(this.#instanceId);
892
+ }
893
+
894
+ get type() {
895
+ return __Response_get_type(this.#instanceId);
896
+ }
897
+
898
+ get body() {
899
+ // Null-body responses (204, 304, HEAD) must return null
900
+ if (__Response_get_nullBody(this.#instanceId)) {
901
+ return null;
902
+ }
903
+
904
+ // Return cached body if available (WHATWG spec requires same object on repeated access)
905
+ if (this.#cachedBody !== null) {
906
+ return this.#cachedBody;
907
+ }
908
+
909
+ const streamId = __Response_getStreamId(this.#instanceId);
910
+ if (streamId !== null) {
911
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(streamId);
912
+ return this.#cachedBody;
913
+ }
914
+
915
+ // Fallback: create host-backed stream from buffered body
916
+ const instanceId = this.#instanceId;
917
+ const newStreamId = __Stream_create();
918
+ const buffer = __Response_arrayBuffer(instanceId);
919
+
920
+ if (buffer.byteLength > 0) {
921
+ __Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
922
+ }
923
+ __Stream_close(newStreamId);
924
+
925
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(newStreamId);
926
+ return this.#cachedBody;
927
+ }
928
+
929
+ async text() {
930
+ try {
931
+ __Response_markBodyUsed(this.#instanceId);
932
+ } catch (err) {
933
+ throw __decodeError(err);
934
+ }
935
+ if (__Response_get_nullBody(this.#instanceId)) {
936
+ return "";
937
+ }
938
+ if (this.#streamId !== null) {
939
+ const reader = this.body.getReader();
940
+ const chunks = [];
941
+ while (true) {
942
+ const { done, value } = await reader.read();
943
+ if (done) break;
944
+ if (value) chunks.push(value);
945
+ }
946
+ const totalLength = chunks.reduce((acc, c) => acc + c.length, 0);
947
+ const result = new Uint8Array(totalLength);
948
+ let offset = 0;
949
+ for (const chunk of chunks) {
950
+ result.set(chunk, offset);
951
+ offset += chunk.length;
952
+ }
953
+ return new TextDecoder().decode(result);
954
+ }
955
+ return __Response_text(this.#instanceId);
956
+ }
957
+
958
+ async json() {
959
+ const text = await this.text();
960
+ return JSON.parse(text);
961
+ }
962
+
963
+ async arrayBuffer() {
964
+ try {
965
+ __Response_markBodyUsed(this.#instanceId);
966
+ } catch (err) {
967
+ throw __decodeError(err);
968
+ }
969
+
970
+ // For streaming responses (including Blob bodies), consume the stream
971
+ if (this.#streamId !== null) {
972
+ // Wait for blob init to complete if needed
973
+ if (this.#blobInitPromise) {
974
+ await this.#blobInitPromise;
975
+ this.#blobInitPromise = null;
976
+ }
977
+
978
+ const reader = this.body.getReader();
979
+ const chunks = [];
980
+ while (true) {
981
+ const { done, value } = await reader.read();
982
+ if (done) break;
983
+ if (value) chunks.push(value);
984
+ }
985
+ // Concatenate all chunks
986
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
987
+ const result = new Uint8Array(totalLength);
988
+ let offset = 0;
989
+ for (const chunk of chunks) {
990
+ result.set(chunk, offset);
991
+ offset += chunk.length;
992
+ }
993
+ return result.buffer;
994
+ }
995
+
996
+ return __Response_arrayBuffer(this.#instanceId);
997
+ }
998
+
999
+ async blob() {
1000
+ const buffer = await this.arrayBuffer();
1001
+ const contentType = this.headers.get('content-type') || '';
1002
+ return new Blob([buffer], { type: contentType });
1003
+ }
1004
+
1005
+ async formData() {
1006
+ const contentType = this.headers.get('content-type') || '';
1007
+
1008
+ // Parse multipart/form-data
1009
+ if (contentType.includes('multipart/form-data')) {
1010
+ const buffer = await this.arrayBuffer();
1011
+ return __parseMultipartFormData(new Uint8Array(buffer), contentType);
1012
+ }
1013
+
1014
+ // Parse application/x-www-form-urlencoded
1015
+ if (contentType.includes('application/x-www-form-urlencoded')) {
1016
+ const text = await this.text();
1017
+ const formData = new FormData();
1018
+ const params = new URLSearchParams(text);
1019
+ for (const [key, value] of params) {
1020
+ formData.append(key, value);
1021
+ }
1022
+ return formData;
1023
+ }
1024
+
1025
+ throw new TypeError('Unsupported content type for formData()');
1026
+ }
1027
+
1028
+ clone() {
1029
+ if (this.bodyUsed) {
1030
+ throw new TypeError('Cannot clone a Response that has already been used');
1031
+ }
1032
+ const newId = __Response_clone(this.#instanceId);
1033
+ const cloned = Response._fromInstanceId(newId);
1034
+ return cloned;
1035
+ }
1036
+
1037
+ static json(data, init = {}) {
1038
+ const body = JSON.stringify(data);
1039
+ const headers = new Headers(init.headers);
1040
+ if (!headers.has('content-type')) {
1041
+ headers.set('content-type', 'application/json');
1042
+ }
1043
+ return new Response(body, { ...init, headers });
1044
+ }
1045
+
1046
+ static redirect(url, status = 302) {
1047
+ if (![301, 302, 303, 307, 308].includes(status)) {
1048
+ throw new RangeError('Invalid redirect status code');
1049
+ }
1050
+ const headers = new Headers({ Location: String(url) });
1051
+ return new Response(null, { status, headers });
1052
+ }
1053
+
1054
+ static error() {
1055
+ const response = new Response(null, { status: 0, statusText: '' });
1056
+ __Response_setType(response._getInstanceId(), 'error');
1057
+ return response;
1058
+ }
1059
+ }
1060
+
1061
+ globalThis.Response = Response;
1062
+ })();
1063
+ `;
1064
+ context.evalSync(responseCode);
1065
+ }
1066
+ function setupRequest(context, stateMap) {
1067
+ setTrackedGlobal(context, "__Request_construct", new ivm.Callback((url, method, headers, bodyBytes, mode, credentials, cache, redirect, referrer, integrity) => {
1068
+ const instanceId = nextInstanceId++;
1069
+ const body = bodyBytes ? new Uint8Array(bodyBytes) : null;
1070
+ const state = {
1071
+ url,
1072
+ method,
1073
+ headers,
1074
+ body,
1075
+ bodyUsed: false,
1076
+ streamId: null,
1077
+ signalAborted: false,
1078
+ mode,
1079
+ credentials,
1080
+ cache,
1081
+ redirect,
1082
+ referrer,
1083
+ integrity
1084
+ };
1085
+ stateMap.set(instanceId, state);
1086
+ return instanceId;
1087
+ }));
1088
+ setTrackedGlobal(context, "__Request_get_method", new ivm.Callback((instanceId) => {
1089
+ const state = stateMap.get(instanceId);
1090
+ return state?.method ?? "GET";
1091
+ }));
1092
+ setTrackedGlobal(context, "__Request_get_url", new ivm.Callback((instanceId) => {
1093
+ const state = stateMap.get(instanceId);
1094
+ return state?.url ?? "";
1095
+ }));
1096
+ setTrackedGlobal(context, "__Request_get_headers", new ivm.Callback((instanceId) => {
1097
+ const state = stateMap.get(instanceId);
1098
+ return state?.headers ?? [];
1099
+ }));
1100
+ setTrackedGlobal(context, "__Request_get_bodyUsed", new ivm.Callback((instanceId) => {
1101
+ const state = stateMap.get(instanceId);
1102
+ return state?.bodyUsed ?? false;
1103
+ }));
1104
+ setTrackedGlobal(context, "__Request_get_mode", new ivm.Callback((instanceId) => {
1105
+ const state = stateMap.get(instanceId);
1106
+ return state?.mode ?? "cors";
1107
+ }));
1108
+ setTrackedGlobal(context, "__Request_get_credentials", new ivm.Callback((instanceId) => {
1109
+ const state = stateMap.get(instanceId);
1110
+ return state?.credentials ?? "same-origin";
1111
+ }));
1112
+ setTrackedGlobal(context, "__Request_get_cache", new ivm.Callback((instanceId) => {
1113
+ const state = stateMap.get(instanceId);
1114
+ return state?.cache ?? "default";
1115
+ }));
1116
+ setTrackedGlobal(context, "__Request_get_redirect", new ivm.Callback((instanceId) => {
1117
+ const state = stateMap.get(instanceId);
1118
+ return state?.redirect ?? "follow";
1119
+ }));
1120
+ setTrackedGlobal(context, "__Request_get_referrer", new ivm.Callback((instanceId) => {
1121
+ const state = stateMap.get(instanceId);
1122
+ return state?.referrer ?? "about:client";
1123
+ }));
1124
+ setTrackedGlobal(context, "__Request_get_integrity", new ivm.Callback((instanceId) => {
1125
+ const state = stateMap.get(instanceId);
1126
+ return state?.integrity ?? "";
1127
+ }));
1128
+ setTrackedGlobal(context, "__Request_markBodyUsed", new ivm.Callback((instanceId) => {
1129
+ const state = stateMap.get(instanceId);
1130
+ if (state) {
1131
+ if (state.bodyUsed) {
1132
+ throw new Error("[TypeError]Body has already been consumed");
1133
+ }
1134
+ state.bodyUsed = true;
1135
+ }
1136
+ }));
1137
+ setTrackedGlobal(context, "__Request_text", new ivm.Callback((instanceId) => {
1138
+ const state = stateMap.get(instanceId);
1139
+ if (!state || !state.body)
1140
+ return "";
1141
+ return new TextDecoder().decode(state.body);
1142
+ }));
1143
+ setTrackedGlobal(context, "__Request_arrayBuffer", new ivm.Callback((instanceId) => {
1144
+ const state = stateMap.get(instanceId);
1145
+ if (!state || !state.body) {
1146
+ return new ivm.ExternalCopy(new ArrayBuffer(0)).copyInto();
1147
+ }
1148
+ return new ivm.ExternalCopy(state.body.buffer.slice(state.body.byteOffset, state.body.byteOffset + state.body.byteLength)).copyInto();
1149
+ }));
1150
+ setTrackedGlobal(context, "__Request_getBodyBytes", new ivm.Callback((instanceId) => {
1151
+ const state = stateMap.get(instanceId);
1152
+ if (!state || !state.body)
1153
+ return null;
1154
+ return Array.from(state.body);
1155
+ }));
1156
+ setTrackedGlobal(context, "__Request_clone", new ivm.Callback((instanceId) => {
1157
+ const state = stateMap.get(instanceId);
1158
+ if (!state) {
1159
+ throw new Error("[TypeError]Cannot clone invalid Request");
1160
+ }
1161
+ const newId = nextInstanceId++;
1162
+ const newState = {
1163
+ ...state,
1164
+ body: state.body ? new Uint8Array(state.body) : null,
1165
+ bodyUsed: false
1166
+ };
1167
+ stateMap.set(newId, newState);
1168
+ return newId;
1169
+ }));
1170
+ setTrackedGlobal(context, "__Request_getStreamId", new ivm.Callback((instanceId) => {
1171
+ const state = stateMap.get(instanceId);
1172
+ return state?.streamId ?? null;
1173
+ }));
1174
+ setTrackedGlobal(context, "__Request_get_signalAborted", new ivm.Callback((instanceId) => {
1175
+ const state = stateMap.get(instanceId);
1176
+ return state?.signalAborted ?? false;
1177
+ }));
1178
+ const requestCode = `
1179
+ (function() {
1180
+ function __decodeError(err) {
1181
+ if (!(err instanceof Error)) return err;
1182
+ const match = err.message.match(/^\\[(TypeError|RangeError|SyntaxError|ReferenceError|URIError|EvalError|Error)\\](.*)$/);
1183
+ if (match) {
1184
+ const ErrorType = globalThis[match[1]] || Error;
1185
+ return new ErrorType(match[2]);
1186
+ }
1187
+ return err;
1188
+ }
1189
+
1190
+ function __prepareBody(body) {
1191
+ if (body === null || body === undefined) return null;
1192
+ if (typeof body === 'string') {
1193
+ const encoder = new TextEncoder();
1194
+ return Array.from(encoder.encode(body));
1195
+ }
1196
+ if (body instanceof ArrayBuffer) {
1197
+ return Array.from(new Uint8Array(body));
1198
+ }
1199
+ if (body instanceof Uint8Array) {
1200
+ return Array.from(body);
1201
+ }
1202
+ if (ArrayBuffer.isView(body)) {
1203
+ return Array.from(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
1204
+ }
1205
+ if (body instanceof URLSearchParams) {
1206
+ return Array.from(new TextEncoder().encode(body.toString()));
1207
+ }
1208
+ if (body instanceof FormData) {
1209
+ // Always serialize as multipart/form-data per spec
1210
+ const { body: bytes, contentType } = __serializeFormData(body);
1211
+ globalThis.__pendingFormDataContentType = contentType;
1212
+ return Array.from(bytes);
1213
+ }
1214
+ // Try to convert to string
1215
+ return Array.from(new TextEncoder().encode(String(body)));
1216
+ }
1217
+
1218
+ // Helper to consume a HostBackedReadableStream and concatenate all chunks
1219
+ async function __consumeStream(stream) {
1220
+ const reader = stream.getReader();
1221
+ const chunks = [];
1222
+ let totalLength = 0;
1223
+
1224
+ while (true) {
1225
+ const { done, value } = await reader.read();
1226
+ if (done) break;
1227
+ chunks.push(value);
1228
+ totalLength += value.length;
1229
+ }
1230
+
1231
+ // Concatenate all chunks
1232
+ const result = new Uint8Array(totalLength);
1233
+ let offset = 0;
1234
+ for (const chunk of chunks) {
1235
+ result.set(chunk, offset);
1236
+ offset += chunk.length;
1237
+ }
1238
+ return result;
1239
+ }
1240
+
1241
+ const __requestSignalControllers = new Map();
1242
+
1243
+ class Request {
1244
+ #instanceId;
1245
+ #headers;
1246
+ #signal;
1247
+ #streamId;
1248
+ #cachedBody = null;
1249
+
1250
+ constructor(input, init = {}) {
1251
+ // Handle internal construction from instance ID
1252
+ if (typeof input === 'number' && init === null) {
1253
+ const controller = new AbortController();
1254
+ if (__Request_get_signalAborted(input)) {
1255
+ controller.abort();
1256
+ }
1257
+ __requestSignalControllers.set(input, controller);
1258
+
1259
+ this.#instanceId = input;
1260
+ this.#headers = new Headers(__Request_get_headers(input));
1261
+ this.#signal = controller.signal;
1262
+ this.#streamId = __Request_getStreamId(input);
1263
+ return;
1264
+ }
1265
+
1266
+ let url;
1267
+ let method = 'GET';
1268
+ let headers;
1269
+ let body = null;
1270
+ let signal = new AbortController().signal;
1271
+ let mode = 'cors';
1272
+ let credentials = 'same-origin';
1273
+ let cache = 'default';
1274
+ let redirect = 'follow';
1275
+ let referrer = 'about:client';
1276
+ let integrity = '';
1277
+
1278
+ if (input instanceof Request) {
1279
+ url = input.url;
1280
+ method = input.method;
1281
+ headers = new Headers(input.headers);
1282
+ signal = input.signal;
1283
+ mode = input.mode;
1284
+ credentials = input.credentials;
1285
+ cache = input.cache;
1286
+ redirect = input.redirect;
1287
+ referrer = input.referrer;
1288
+ integrity = input.integrity;
1289
+ // Note: We don't copy the body from the input Request
1290
+ } else {
1291
+ url = String(input);
1292
+ headers = new Headers();
1293
+ }
1294
+
1295
+ // Apply init overrides
1296
+ if (init.method !== undefined) method = String(init.method).toUpperCase();
1297
+ if (init.headers !== undefined) headers = new Headers(init.headers);
1298
+ if (init.body !== undefined) body = init.body;
1299
+ if (init.signal !== undefined) signal = init.signal;
1300
+ if (init.mode !== undefined) mode = init.mode;
1301
+ if (init.credentials !== undefined) credentials = init.credentials;
1302
+ if (init.cache !== undefined) cache = init.cache;
1303
+ if (init.redirect !== undefined) redirect = init.redirect;
1304
+ if (init.referrer !== undefined) referrer = init.referrer;
1305
+ if (init.integrity !== undefined) integrity = init.integrity;
1306
+
1307
+ // Ensure signal is always a valid AbortSignal
1308
+ if (signal == null) {
1309
+ signal = new AbortController().signal;
1310
+ }
1311
+
1312
+ // Validate: body with GET/HEAD
1313
+ if (body !== null && (method === 'GET' || method === 'HEAD')) {
1314
+ throw new TypeError('Request with GET/HEAD method cannot have body');
1315
+ }
1316
+
1317
+ const bodyBytes = __prepareBody(body);
1318
+
1319
+ // Handle Content-Type for FormData
1320
+ if (globalThis.__pendingFormDataContentType) {
1321
+ headers.set('content-type', globalThis.__pendingFormDataContentType);
1322
+ delete globalThis.__pendingFormDataContentType;
1323
+ } else if (body instanceof URLSearchParams && !headers.has('content-type')) {
1324
+ headers.set('content-type', 'application/x-www-form-urlencoded');
1325
+ }
1326
+
1327
+ const headersArray = Array.from(headers.entries());
1328
+
1329
+ this.#instanceId = __Request_construct(
1330
+ url, method, headersArray, bodyBytes,
1331
+ mode, credentials, cache, redirect, referrer, integrity
1332
+ );
1333
+ this.#headers = headers;
1334
+ this.#signal = signal;
1335
+ this.#streamId = null;
1336
+ }
1337
+
1338
+ _getInstanceId() {
1339
+ return this.#instanceId;
1340
+ }
1341
+
1342
+ static _fromInstanceId(instanceId) {
1343
+ return new Request(instanceId, null);
1344
+ }
1345
+
1346
+ get method() {
1347
+ return __Request_get_method(this.#instanceId);
1348
+ }
1349
+
1350
+ get url() {
1351
+ return __Request_get_url(this.#instanceId);
1352
+ }
1353
+
1354
+ get headers() {
1355
+ return this.#headers;
1356
+ }
1357
+
1358
+ get bodyUsed() {
1359
+ return __Request_get_bodyUsed(this.#instanceId);
1360
+ }
1361
+
1362
+ get signal() {
1363
+ return this.#signal;
1364
+ }
1365
+
1366
+ get mode() {
1367
+ return __Request_get_mode(this.#instanceId);
1368
+ }
1369
+
1370
+ get credentials() {
1371
+ return __Request_get_credentials(this.#instanceId);
1372
+ }
1373
+
1374
+ get cache() {
1375
+ return __Request_get_cache(this.#instanceId);
1376
+ }
1377
+
1378
+ get redirect() {
1379
+ return __Request_get_redirect(this.#instanceId);
1380
+ }
1381
+
1382
+ get referrer() {
1383
+ return __Request_get_referrer(this.#instanceId);
1384
+ }
1385
+
1386
+ get integrity() {
1387
+ return __Request_get_integrity(this.#instanceId);
1388
+ }
1389
+
1390
+ get body() {
1391
+ // Per WHATWG Fetch spec: GET/HEAD requests cannot have a body
1392
+ const method = __Request_get_method(this.#instanceId);
1393
+ if (method === 'GET' || method === 'HEAD') {
1394
+ return null;
1395
+ }
1396
+
1397
+ // Return cached body if available
1398
+ if (this.#cachedBody !== null) {
1399
+ return this.#cachedBody;
1400
+ }
1401
+
1402
+ // If we have a stream ID, create and cache the stream
1403
+ if (this.#streamId !== null) {
1404
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(this.#streamId);
1405
+ return this.#cachedBody;
1406
+ }
1407
+
1408
+ // Check if there's any buffered body data
1409
+ const buffer = __Request_arrayBuffer(this.#instanceId);
1410
+ if (buffer.byteLength === 0) {
1411
+ return null; // Return null per WHATWG Fetch spec for empty body
1412
+ }
1413
+
1414
+ // Create stream from non-empty buffered body
1415
+ const newStreamId = __Stream_create();
1416
+ __Stream_push(newStreamId, Array.from(new Uint8Array(buffer)));
1417
+ __Stream_close(newStreamId);
1418
+
1419
+ this.#cachedBody = HostBackedReadableStream._fromStreamId(newStreamId);
1420
+ return this.#cachedBody;
1421
+ }
1422
+
1423
+ async text() {
1424
+ try {
1425
+ __Request_markBodyUsed(this.#instanceId);
1426
+ } catch (err) {
1427
+ throw __decodeError(err);
1428
+ }
1429
+
1430
+ // If streaming, consume the stream
1431
+ if (this.#streamId !== null) {
1432
+ const bytes = await __consumeStream(this.body);
1433
+ return new TextDecoder().decode(bytes);
1434
+ }
1435
+
1436
+ // Fallback to host callback for buffered body
1437
+ return __Request_text(this.#instanceId);
1438
+ }
1439
+
1440
+ async json() {
1441
+ const text = await this.text();
1442
+ return JSON.parse(text);
1443
+ }
1444
+
1445
+ async arrayBuffer() {
1446
+ try {
1447
+ __Request_markBodyUsed(this.#instanceId);
1448
+ } catch (err) {
1449
+ throw __decodeError(err);
1450
+ }
1451
+
1452
+ // If streaming, consume the stream
1453
+ if (this.#streamId !== null) {
1454
+ const bytes = await __consumeStream(this.body);
1455
+ return bytes.buffer;
1456
+ }
1457
+
1458
+ return __Request_arrayBuffer(this.#instanceId);
1459
+ }
1460
+
1461
+ async blob() {
1462
+ const buffer = await this.arrayBuffer();
1463
+ const contentType = this.headers.get('content-type') || '';
1464
+ return new Blob([buffer], { type: contentType });
1465
+ }
1466
+
1467
+ async formData() {
1468
+ const contentType = this.headers.get('content-type') || '';
1469
+
1470
+ // Parse multipart/form-data
1471
+ if (contentType.includes('multipart/form-data')) {
1472
+ const buffer = await this.arrayBuffer();
1473
+ return __parseMultipartFormData(new Uint8Array(buffer), contentType);
1474
+ }
1475
+
1476
+ // Parse application/x-www-form-urlencoded
1477
+ if (contentType.includes('application/x-www-form-urlencoded')) {
1478
+ const text = await this.text();
1479
+ const formData = new FormData();
1480
+ const params = new URLSearchParams(text);
1481
+ for (const [key, value] of params) {
1482
+ formData.append(key, value);
1483
+ }
1484
+ return formData;
1485
+ }
1486
+
1487
+ throw new TypeError('Unsupported content type for formData()');
1488
+ }
1489
+
1490
+ clone() {
1491
+ if (this.bodyUsed) {
1492
+ throw new TypeError('Cannot clone a Request that has already been used');
1493
+ }
1494
+ const newId = __Request_clone(this.#instanceId);
1495
+ const cloned = Request._fromInstanceId(newId);
1496
+ cloned.#signal = this.#signal;
1497
+ return cloned;
1498
+ }
1499
+
1500
+ _getBodyBytes() {
1501
+ return __Request_getBodyBytes(this.#instanceId);
1502
+ }
1503
+ }
1504
+
1505
+ globalThis.__Request_abortSignalByInstanceId = function(instanceId) {
1506
+ const controller = __requestSignalControllers.get(instanceId);
1507
+ if (controller && !controller.signal.aborted) {
1508
+ controller.abort();
1509
+ }
1510
+ };
1511
+
1512
+ globalThis.Request = Request;
1513
+ })();
1514
+ `;
1515
+ context.evalSync(requestCode);
1516
+ return context.evalSync("globalThis.__Request_abortSignalByInstanceId", { reference: true });
1517
+ }
1518
+ var FETCH_STREAM_THRESHOLD = 64 * 1024;
1519
+ function setupFetchFunction(context, stateMap, streamRegistry, options) {
1520
+ const fetchAbortControllers = new Map;
1521
+ setTrackedGlobal(context, "__fetch_abort", new ivm.Callback((fetchId) => {
1522
+ const controller = fetchAbortControllers.get(fetchId);
1523
+ if (controller) {
1524
+ setImmediate(() => controller.abort());
1525
+ }
1526
+ }));
1527
+ const fetchRef = new ivm.Reference(async (url, method, headersJson, bodyJson, signalAborted, fetchId) => {
1528
+ if (signalAborted) {
1529
+ throw new Error("[AbortError]The operation was aborted.");
1530
+ }
1531
+ const hostController = new AbortController;
1532
+ fetchAbortControllers.set(fetchId, hostController);
1533
+ const headers = JSON.parse(headersJson);
1534
+ const bodyBytes = bodyJson ? JSON.parse(bodyJson) : null;
1535
+ const rawBody = bodyBytes ? new Uint8Array(bodyBytes) : null;
1536
+ const init = {
1537
+ method,
1538
+ headers,
1539
+ rawBody,
1540
+ body: rawBody,
1541
+ signal: hostController.signal
1542
+ };
1543
+ const onFetch = options?.onFetch ?? ((url2, init2) => fetch(url2, {
1544
+ method: init2.method,
1545
+ headers: init2.headers,
1546
+ body: init2.body,
1547
+ signal: init2.signal
1548
+ }));
1549
+ try {
1550
+ let cleanupAbort;
1551
+ const abortPromise = new Promise((_, reject) => {
1552
+ if (hostController.signal.aborted) {
1553
+ reject(Object.assign(new Error("The operation was aborted."), { name: "AbortError" }));
1554
+ return;
1555
+ }
1556
+ const onAbort = () => {
1557
+ reject(Object.assign(new Error("The operation was aborted."), { name: "AbortError" }));
1558
+ };
1559
+ hostController.signal.addEventListener("abort", onAbort, { once: true });
1560
+ cleanupAbort = () => hostController.signal.removeEventListener("abort", onAbort);
1561
+ });
1562
+ abortPromise.catch(() => {});
1563
+ const nativeResponse = await Promise.race([onFetch(url, init), abortPromise]);
1564
+ cleanupAbort?.();
1565
+ const status = nativeResponse.status;
1566
+ const isNullBody = status === 204 || status === 304 || method.toUpperCase() === "HEAD";
1567
+ const isCallbackStream = nativeResponse.__isCallbackStream;
1568
+ const isNetworkResponse = nativeResponse.url && (nativeResponse.url.startsWith("http://") || nativeResponse.url.startsWith("https://"));
1569
+ const shouldStream = !isNullBody && nativeResponse.body && (isCallbackStream || isNetworkResponse);
1570
+ if (shouldStream && nativeResponse.body) {
1571
+ const streamId = streamRegistry.create();
1572
+ const streamCleanupFn = startNativeStreamReader(nativeResponse.body, streamId, streamRegistry);
1573
+ streamRegistry.setCleanup(streamId, streamCleanupFn);
1574
+ const instanceId2 = nextInstanceId++;
1575
+ const state2 = {
1576
+ status: nativeResponse.status,
1577
+ statusText: nativeResponse.statusText,
1578
+ headers: Array.from(nativeResponse.headers.entries()),
1579
+ body: new Uint8Array(0),
1580
+ bodyUsed: false,
1581
+ type: "default",
1582
+ url: nativeResponse.url,
1583
+ redirected: nativeResponse.redirected,
1584
+ streamId,
1585
+ nullBody: isNullBody
1586
+ };
1587
+ stateMap.set(instanceId2, state2);
1588
+ return instanceId2;
1589
+ }
1590
+ const responseBody = await nativeResponse.arrayBuffer();
1591
+ const responseBodyArray = Array.from(new Uint8Array(responseBody));
1592
+ const instanceId = nextInstanceId++;
1593
+ const state = {
1594
+ status: nativeResponse.status,
1595
+ statusText: nativeResponse.statusText,
1596
+ headers: Array.from(nativeResponse.headers.entries()),
1597
+ body: new Uint8Array(responseBodyArray),
1598
+ bodyUsed: false,
1599
+ type: "default",
1600
+ url: nativeResponse.url,
1601
+ redirected: nativeResponse.redirected,
1602
+ streamId: null,
1603
+ nullBody: isNullBody
1604
+ };
1605
+ stateMap.set(instanceId, state);
1606
+ return instanceId;
1607
+ } catch (err) {
1608
+ if (err instanceof Error && err.name === "AbortError") {
1609
+ throw new Error("[AbortError]The operation was aborted.");
1610
+ }
1611
+ throw err;
1612
+ } finally {
1613
+ fetchAbortControllers.delete(fetchId);
1614
+ }
1615
+ });
1616
+ setTrackedGlobal(context, "__fetch_ref", fetchRef);
1617
+ const fetchCode = `
1618
+ (function() {
1619
+ function __decodeError(err) {
1620
+ if (!(err instanceof Error)) return err;
1621
+ const match = err.message.match(/^\\[(TypeError|RangeError|AbortError|Error)\\](.*)$/);
1622
+ if (match) {
1623
+ if (match[1] === 'AbortError') {
1624
+ return new DOMException(match[2], 'AbortError');
1625
+ }
1626
+ const ErrorType = globalThis[match[1]] || Error;
1627
+ return new ErrorType(match[2]);
1628
+ }
1629
+ return err;
1630
+ }
1631
+
1632
+ let __nextFetchId = 1;
1633
+
1634
+ globalThis.fetch = async function(input, init = {}) {
1635
+ // Handle Blob and ReadableStream bodies before creating Request
1636
+ if (init.body instanceof Blob && !(init.body instanceof File)) {
1637
+ const buf = await init.body.arrayBuffer();
1638
+ init = Object.assign({}, init, { body: new Uint8Array(buf) });
1639
+ } else if (init.body instanceof ReadableStream) {
1640
+ const reader = init.body.getReader();
1641
+ const chunks = [];
1642
+ while (true) {
1643
+ const { done, value } = await reader.read();
1644
+ if (done) break;
1645
+ chunks.push(value);
1646
+ }
1647
+ const total = chunks.reduce((s, c) => s + c.length, 0);
1648
+ const buf = new Uint8Array(total);
1649
+ let off = 0;
1650
+ for (const c of chunks) { buf.set(c, off); off += c.length; }
1651
+ init = Object.assign({}, init, { body: buf });
1652
+ }
1653
+
1654
+ // Create Request from input
1655
+ const request = input instanceof Request ? input : new Request(input, init);
1656
+
1657
+ // Get signal info
1658
+ const signal = init.signal ?? request.signal;
1659
+ const signalAborted = signal?.aborted ?? false;
1660
+
1661
+ // Assign a fetch ID for abort tracking
1662
+ const fetchId = __nextFetchId++;
1663
+
1664
+ // Register abort listener if signal exists
1665
+ if (signal && !signalAborted) {
1666
+ signal.addEventListener('abort', () => { __fetch_abort(fetchId); });
1667
+ }
1668
+
1669
+ // Serialize headers and body to JSON for transfer
1670
+ const headersJson = JSON.stringify(Array.from(request.headers.entries()));
1671
+ const bodyBytes = request._getBodyBytes();
1672
+ const bodyJson = bodyBytes ? JSON.stringify(bodyBytes) : null;
1673
+
1674
+ // Short-circuit: if signal is already aborted, throw without calling host
1675
+ if (signalAborted) {
1676
+ throw new DOMException('The operation was aborted.', 'AbortError');
1677
+ }
1678
+
1679
+ // Call host - returns just the response instance ID
1680
+ try {
1681
+ const instanceId = await __fetch_ref.apply(undefined, [
1682
+ request.url,
1683
+ request.method,
1684
+ headersJson,
1685
+ bodyJson,
1686
+ signalAborted,
1687
+ fetchId
1688
+ ], { result: { promise: true, copy: true } });
1689
+
1690
+ // Construct Response from the instance ID
1691
+ return Response._fromInstanceId(instanceId);
1692
+ } catch (err) {
1693
+ throw __decodeError(err);
1694
+ }
1695
+ };
1696
+ })();
1697
+ `;
1698
+ context.evalSync(fetchCode);
1699
+ }
1700
+ function setupServer(context, serveState) {
1701
+ context.evalSync(`
1702
+ globalThis.__upgradeRegistry__ = new Map();
1703
+ globalThis.__upgradeIdCounter__ = 0;
1704
+ `);
1705
+ setTrackedGlobal(context, "__setPendingUpgrade__", new ivm.Callback((connectionId) => {
1706
+ serveState.pendingUpgrade = { requested: true, connectionId };
1707
+ }));
1708
+ context.evalSync(`
1709
+ (function() {
1710
+ class Server {
1711
+ upgrade(request, options) {
1712
+ const data = options?.data;
1713
+ const connectionId = String(++globalThis.__upgradeIdCounter__);
1714
+ globalThis.__upgradeRegistry__.set(connectionId, data);
1715
+ __setPendingUpgrade__(connectionId);
1716
+ return true;
1717
+ }
1718
+ }
1719
+ globalThis.__Server__ = Server;
1720
+ })();
1721
+ `);
1722
+ }
1723
+ function setupServerWebSocket(context, wsCommandCallbacks) {
1724
+ setTrackedGlobal(context, "__ServerWebSocket_send", new ivm.Callback((connectionId, data) => {
1725
+ const cmd = { type: "message", connectionId, data };
1726
+ for (const cb of wsCommandCallbacks)
1727
+ cb(cmd);
1728
+ }));
1729
+ setTrackedGlobal(context, "__ServerWebSocket_close", new ivm.Callback((connectionId, code, reason) => {
1730
+ const cmd = { type: "close", connectionId, code, reason };
1731
+ for (const cb of wsCommandCallbacks)
1732
+ cb(cmd);
1733
+ }));
1734
+ context.evalSync(`
1735
+ (function() {
1736
+ const _wsInstanceData = new WeakMap();
1737
+
1738
+ class ServerWebSocket {
1739
+ constructor(connectionId) {
1740
+ _wsInstanceData.set(this, { connectionId, readyState: 1 });
1741
+ }
1742
+
1743
+ get data() {
1744
+ const state = _wsInstanceData.get(this);
1745
+ return globalThis.__upgradeRegistry__.get(state.connectionId);
1746
+ }
1747
+
1748
+ get readyState() {
1749
+ return _wsInstanceData.get(this).readyState;
1750
+ }
1751
+
1752
+ send(message) {
1753
+ const state = _wsInstanceData.get(this);
1754
+ if (state.readyState !== 1) throw new Error("WebSocket is not open");
1755
+ // Convert ArrayBuffer/Uint8Array to string for transfer
1756
+ let data = message;
1757
+ if (message instanceof ArrayBuffer) {
1758
+ data = new TextDecoder().decode(message);
1759
+ } else if (message instanceof Uint8Array) {
1760
+ data = new TextDecoder().decode(message);
1761
+ }
1762
+ __ServerWebSocket_send(state.connectionId, data);
1763
+ }
1764
+
1765
+ close(code, reason) {
1766
+ const state = _wsInstanceData.get(this);
1767
+ if (state.readyState === 3) return;
1768
+ state.readyState = 2; // CLOSING
1769
+ __ServerWebSocket_close(state.connectionId, code, reason);
1770
+ }
1771
+
1772
+ _setReadyState(readyState) {
1773
+ _wsInstanceData.get(this).readyState = readyState;
1774
+ }
1775
+ }
1776
+
1777
+ globalThis.__ServerWebSocket__ = ServerWebSocket;
1778
+ })();
1779
+ `);
1780
+ }
1781
+ function setupClientWebSocket(context, clientWsCommandCallbacks) {
1782
+ setTrackedGlobal(context, "__WebSocket_connect", new ivm.Callback((socketId, url, protocols) => {
1783
+ const cmd = {
1784
+ type: "connect",
1785
+ socketId,
1786
+ url,
1787
+ protocols
1788
+ };
1789
+ for (const cb of clientWsCommandCallbacks)
1790
+ cb(cmd);
1791
+ }));
1792
+ setTrackedGlobal(context, "__WebSocket_send", new ivm.Callback((socketId, data) => {
1793
+ const cmd = { type: "send", socketId, data };
1794
+ for (const cb of clientWsCommandCallbacks)
1795
+ cb(cmd);
1796
+ }));
1797
+ setTrackedGlobal(context, "__WebSocket_close", new ivm.Callback((socketId, code, reason) => {
1798
+ const cmd = { type: "close", socketId, code, reason };
1799
+ for (const cb of clientWsCommandCallbacks)
1800
+ cb(cmd);
1801
+ }));
1802
+ context.evalSync(`
1803
+ (function() {
1804
+ // Socket ID counter
1805
+ let __nextSocketId = 1;
1806
+
1807
+ // Active sockets registry
1808
+ const __clientWebSockets = new Map();
1809
+
1810
+ // Simple Event class (if not defined globally)
1811
+ const _Event = globalThis.Event || class Event {
1812
+ constructor(type, options = {}) {
1813
+ this.type = type;
1814
+ this.bubbles = options.bubbles || false;
1815
+ this.cancelable = options.cancelable || false;
1816
+ this.defaultPrevented = false;
1817
+ this.timeStamp = Date.now();
1818
+ this.target = null;
1819
+ this.currentTarget = null;
1820
+ }
1821
+ preventDefault() {
1822
+ if (this.cancelable) this.defaultPrevented = true;
1823
+ }
1824
+ stopPropagation() {}
1825
+ stopImmediatePropagation() {}
1826
+ };
1827
+
1828
+ // MessageEvent class for WebSocket messages
1829
+ const _MessageEvent = globalThis.MessageEvent || class MessageEvent extends _Event {
1830
+ constructor(type, options = {}) {
1831
+ super(type, options);
1832
+ this.data = options.data !== undefined ? options.data : null;
1833
+ this.origin = options.origin || '';
1834
+ this.lastEventId = options.lastEventId || '';
1835
+ this.source = options.source || null;
1836
+ this.ports = options.ports || [];
1837
+ }
1838
+ };
1839
+
1840
+ // CloseEvent class for WebSocket close
1841
+ const _CloseEvent = globalThis.CloseEvent || class CloseEvent extends _Event {
1842
+ constructor(type, options = {}) {
1843
+ super(type, options);
1844
+ this.code = options.code !== undefined ? options.code : 0;
1845
+ this.reason = options.reason !== undefined ? options.reason : '';
1846
+ this.wasClean = options.wasClean !== undefined ? options.wasClean : false;
1847
+ }
1848
+ };
1849
+
1850
+ // Helper to dispatch events
1851
+ function dispatchEvent(ws, event) {
1852
+ const listeners = ws._listeners.get(event.type) || [];
1853
+ for (const listener of listeners) {
1854
+ try {
1855
+ listener.call(ws, event);
1856
+ } catch (e) {
1857
+ console.error('WebSocket event listener error:', e);
1858
+ }
1859
+ }
1860
+ // Also call on* handler if set
1861
+ const handler = ws['on' + event.type];
1862
+ if (typeof handler === 'function') {
1863
+ try {
1864
+ handler.call(ws, event);
1865
+ } catch (e) {
1866
+ console.error('WebSocket handler error:', e);
1867
+ }
1868
+ }
1869
+ }
1870
+
1871
+ class WebSocket {
1872
+ static CONNECTING = 0;
1873
+ static OPEN = 1;
1874
+ static CLOSING = 2;
1875
+ static CLOSED = 3;
1876
+
1877
+ #socketId;
1878
+ #url;
1879
+ #readyState = WebSocket.CONNECTING;
1880
+ #bufferedAmount = 0;
1881
+ #extensions = '';
1882
+ #protocol = '';
1883
+ #binaryType = 'blob';
1884
+ _listeners = new Map();
1885
+
1886
+ // Event handlers
1887
+ onopen = null;
1888
+ onmessage = null;
1889
+ onerror = null;
1890
+ onclose = null;
1891
+
1892
+ constructor(url, protocols) {
1893
+ // Validate URL
1894
+ let parsedUrl;
1895
+ try {
1896
+ parsedUrl = new URL(url);
1897
+ } catch (e) {
1898
+ throw new DOMException("Failed to construct 'WebSocket': The URL '" + url + "' is invalid.", 'SyntaxError');
1899
+ }
1900
+
1901
+ if (parsedUrl.protocol !== 'ws:' && parsedUrl.protocol !== 'wss:') {
1902
+ throw new DOMException("Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'.", 'SyntaxError');
1903
+ }
1904
+
1905
+ // Per WHATWG spec, fragments must be stripped from WebSocket URLs
1906
+ parsedUrl.hash = '';
1907
+ this.#url = parsedUrl.href;
1908
+ this.#socketId = String(__nextSocketId++);
1909
+
1910
+ // Normalize protocols to array
1911
+ let protocolArray = [];
1912
+ if (protocols !== undefined) {
1913
+ if (typeof protocols === 'string') {
1914
+ protocolArray = [protocols];
1915
+ } else if (Array.isArray(protocols)) {
1916
+ protocolArray = protocols;
1917
+ } else {
1918
+ protocolArray = [String(protocols)];
1919
+ }
1920
+ }
1921
+
1922
+ // Check for duplicate protocols
1923
+ const seen = new Set();
1924
+ for (const p of protocolArray) {
1925
+ if (seen.has(p)) {
1926
+ throw new DOMException("Failed to construct 'WebSocket': The subprotocol '" + p + "' is duplicated.", 'SyntaxError');
1927
+ }
1928
+ seen.add(p);
1929
+ }
1930
+
1931
+ // Register socket
1932
+ __clientWebSockets.set(this.#socketId, this);
1933
+
1934
+ // Call host to create connection
1935
+ __WebSocket_connect(this.#socketId, this.#url, protocolArray);
1936
+ }
1937
+
1938
+ get url() {
1939
+ return this.#url;
1940
+ }
1941
+
1942
+ get readyState() {
1943
+ return this.#readyState;
1944
+ }
1945
+
1946
+ get bufferedAmount() {
1947
+ return this.#bufferedAmount;
1948
+ }
1949
+
1950
+ get extensions() {
1951
+ return this.#extensions;
1952
+ }
1953
+
1954
+ get protocol() {
1955
+ return this.#protocol;
1956
+ }
1957
+
1958
+ get binaryType() {
1959
+ return this.#binaryType;
1960
+ }
1961
+
1962
+ set binaryType(value) {
1963
+ if (value !== 'blob' && value !== 'arraybuffer') {
1964
+ throw new DOMException("Failed to set the 'binaryType' property: '" + value + "' is not a valid value.", 'SyntaxError');
1965
+ }
1966
+ this.#binaryType = value;
1967
+ }
1968
+
1969
+ // ReadyState constants
1970
+ get CONNECTING() { return WebSocket.CONNECTING; }
1971
+ get OPEN() { return WebSocket.OPEN; }
1972
+ get CLOSING() { return WebSocket.CLOSING; }
1973
+ get CLOSED() { return WebSocket.CLOSED; }
1974
+
1975
+ send(data) {
1976
+ if (this.#readyState === WebSocket.CONNECTING) {
1977
+ throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", 'InvalidStateError');
1978
+ }
1979
+
1980
+ if (this.#readyState !== WebSocket.OPEN) {
1981
+ // Silently discard if not open (per spec)
1982
+ return;
1983
+ }
1984
+
1985
+ // Convert data to string for transfer
1986
+ let dataStr;
1987
+ if (typeof data === 'string') {
1988
+ dataStr = data;
1989
+ } else if (data instanceof ArrayBuffer) {
1990
+ // Convert ArrayBuffer to base64 for transfer
1991
+ const bytes = new Uint8Array(data);
1992
+ let binary = '';
1993
+ for (let i = 0; i < bytes.byteLength; i++) {
1994
+ binary += String.fromCharCode(bytes[i]);
1995
+ }
1996
+ dataStr = '__BINARY__' + btoa(binary);
1997
+ } else if (ArrayBuffer.isView(data)) {
1998
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1999
+ let binary = '';
2000
+ for (let i = 0; i < bytes.byteLength; i++) {
2001
+ binary += String.fromCharCode(bytes[i]);
2002
+ }
2003
+ dataStr = '__BINARY__' + btoa(binary);
2004
+ } else if (data instanceof Blob) {
2005
+ // Blob.arrayBuffer() is async, but send() is sync
2006
+ // For now, throw - this is a limitation
2007
+ throw new DOMException("Failed to execute 'send' on 'WebSocket': Blob data is not supported in this environment.", 'NotSupportedError');
2008
+ } else {
2009
+ dataStr = String(data);
2010
+ }
2011
+
2012
+ __WebSocket_send(this.#socketId, dataStr);
2013
+ }
2014
+
2015
+ close(code, reason) {
2016
+ if (code !== undefined) {
2017
+ if (typeof code !== 'number' || code !== Math.floor(code)) {
2018
+ throw new DOMException("Failed to execute 'close' on 'WebSocket': The code must be an integer.", 'InvalidAccessError');
2019
+ }
2020
+ if (code !== 1000 && (code < 3000 || code > 4999)) {
2021
+ throw new DOMException("Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999.", 'InvalidAccessError');
2022
+ }
2023
+ }
2024
+
2025
+ if (reason !== undefined) {
2026
+ const encoder = new TextEncoder();
2027
+ if (encoder.encode(reason).byteLength > 123) {
2028
+ throw new DOMException("Failed to execute 'close' on 'WebSocket': The message must not be greater than 123 bytes.", 'SyntaxError');
2029
+ }
2030
+ }
2031
+
2032
+ if (this.#readyState === WebSocket.CLOSING || this.#readyState === WebSocket.CLOSED) {
2033
+ return;
2034
+ }
2035
+
2036
+ this.#readyState = WebSocket.CLOSING;
2037
+ __WebSocket_close(this.#socketId, code ?? 1000, reason ?? '');
2038
+ }
2039
+
2040
+ // EventTarget interface
2041
+ addEventListener(type, listener, options) {
2042
+ if (typeof listener !== 'function') return;
2043
+ let listeners = this._listeners.get(type);
2044
+ if (!listeners) {
2045
+ listeners = [];
2046
+ this._listeners.set(type, listeners);
2047
+ }
2048
+ if (!listeners.includes(listener)) {
2049
+ listeners.push(listener);
2050
+ }
2051
+ }
2052
+
2053
+ removeEventListener(type, listener, options) {
2054
+ const listeners = this._listeners.get(type);
2055
+ if (!listeners) return;
2056
+ const index = listeners.indexOf(listener);
2057
+ if (index !== -1) {
2058
+ listeners.splice(index, 1);
2059
+ }
2060
+ }
2061
+
2062
+ dispatchEvent(event) {
2063
+ dispatchEvent(this, event);
2064
+ return !event.defaultPrevented;
2065
+ }
2066
+
2067
+ // Internal methods called from host
2068
+ _setProtocol(protocol) {
2069
+ this.#protocol = protocol;
2070
+ }
2071
+
2072
+ _setExtensions(extensions) {
2073
+ this.#extensions = extensions;
2074
+ }
2075
+
2076
+ _setReadyState(state) {
2077
+ this.#readyState = state;
2078
+ }
2079
+
2080
+ _dispatchOpen() {
2081
+ this.#readyState = WebSocket.OPEN;
2082
+ const event = new _Event('open');
2083
+ dispatchEvent(this, event);
2084
+ }
2085
+
2086
+ _dispatchMessage(data) {
2087
+ // Handle binary data
2088
+ let messageData = data;
2089
+ if (typeof data === 'string' && data.startsWith('__BINARY__')) {
2090
+ const base64 = data.slice(10);
2091
+ const binary = atob(base64);
2092
+ const bytes = new Uint8Array(binary.length);
2093
+ for (let i = 0; i < binary.length; i++) {
2094
+ bytes[i] = binary.charCodeAt(i);
2095
+ }
2096
+ if (this.#binaryType === 'arraybuffer') {
2097
+ messageData = bytes.buffer;
2098
+ } else {
2099
+ messageData = new Blob([bytes]);
2100
+ }
2101
+ }
2102
+
2103
+ const event = new _MessageEvent('message', { data: messageData });
2104
+ dispatchEvent(this, event);
2105
+ }
2106
+
2107
+ _dispatchError() {
2108
+ const event = new _Event('error');
2109
+ dispatchEvent(this, event);
2110
+ }
2111
+
2112
+ _dispatchClose(code, reason, wasClean) {
2113
+ this.#readyState = WebSocket.CLOSED;
2114
+ const event = new _CloseEvent('close', { code, reason, wasClean });
2115
+ dispatchEvent(this, event);
2116
+ __clientWebSockets.delete(this.#socketId);
2117
+ }
2118
+ }
2119
+
2120
+ // Helper to dispatch events from host to a socket by ID
2121
+ globalThis.__dispatchClientWebSocketEvent = function(socketId, eventType, data) {
2122
+ const ws = __clientWebSockets.get(socketId);
2123
+ if (!ws) return;
2124
+
2125
+ switch (eventType) {
2126
+ case 'open':
2127
+ ws._setProtocol(data.protocol || '');
2128
+ ws._setExtensions(data.extensions || '');
2129
+ ws._dispatchOpen();
2130
+ break;
2131
+ case 'message':
2132
+ ws._dispatchMessage(data.data);
2133
+ break;
2134
+ case 'error':
2135
+ ws._dispatchError();
2136
+ break;
2137
+ case 'close':
2138
+ ws._dispatchClose(data.code, data.reason, data.wasClean);
2139
+ break;
2140
+ }
2141
+ };
2142
+
2143
+ globalThis.WebSocket = WebSocket;
2144
+ })();
2145
+ `);
2146
+ }
2147
+ function setupServe(context) {
2148
+ context.evalSync(`
2149
+ (function() {
2150
+ globalThis.__serveOptions__ = null;
2151
+
2152
+ function serve(options) {
2153
+ globalThis.__serveOptions__ = options;
2154
+ }
2155
+
2156
+ globalThis.serve = serve;
2157
+ })();
2158
+ `);
2159
+ }
2160
+ async function setupFetch(context, options) {
2161
+ await setupCore(context);
2162
+ const stateMap = getInstanceStateMapForContext(context);
2163
+ const streamRegistry = getStreamRegistryForContext(context);
2164
+ context.evalSync(headersCode);
2165
+ context.evalSync(formDataCode);
2166
+ context.evalSync(multipartCode);
2167
+ setupStreamCallbacks(context, streamRegistry);
2168
+ context.evalSync(hostBackedStreamCode);
2169
+ setupResponse(context, stateMap, streamRegistry);
2170
+ const requestAbortSignalRef = setupRequest(context, stateMap);
2171
+ setupFetchFunction(context, stateMap, streamRegistry, options);
2172
+ const serveState = {
2173
+ pendingUpgrade: null,
2174
+ activeConnections: new Map
2175
+ };
2176
+ const wsCommandCallbacks = new Set;
2177
+ const clientWsCommandCallbacks = new Set;
2178
+ setupServer(context, serveState);
2179
+ setupServerWebSocket(context, wsCommandCallbacks);
2180
+ setupServe(context);
2181
+ setupClientWebSocket(context, clientWsCommandCallbacks);
2182
+ const eventCallbacks = new Set;
2183
+ setTrackedGlobal(context, "__emit", new ivm.Callback((eventName, payloadJson) => {
2184
+ const payload = JSON.parse(payloadJson);
2185
+ for (const cb of eventCallbacks)
2186
+ cb(eventName, payload);
2187
+ }));
2188
+ context.evalSync(`
2189
+ (function() {
2190
+ const __eventListeners = new Map();
2191
+
2192
+ globalThis.__on = function(event, callback) {
2193
+ let listeners = __eventListeners.get(event);
2194
+ if (!listeners) {
2195
+ listeners = new Set();
2196
+ __eventListeners.set(event, listeners);
2197
+ }
2198
+ listeners.add(callback);
2199
+ return function() {
2200
+ listeners.delete(callback);
2201
+ if (listeners.size === 0) {
2202
+ __eventListeners.delete(event);
2203
+ }
2204
+ };
2205
+ };
2206
+
2207
+ globalThis.__dispatchExternalEvent = function(event, payloadJson) {
2208
+ const listeners = __eventListeners.get(event);
2209
+ if (!listeners) return;
2210
+ const payload = JSON.parse(payloadJson);
2211
+ for (const cb of listeners) {
2212
+ try { cb(payload); } catch (e) { console.error('Event listener error:', e); }
2213
+ }
2214
+ };
2215
+ })();
2216
+ `);
2217
+ return {
2218
+ dispose() {
2219
+ stateMap.clear();
2220
+ clearPassthruBodiesForContext(context);
2221
+ clearStreamRegistryForContext(context);
2222
+ context.evalSync(`globalThis.__upgradeRegistry__.clear()`);
2223
+ serveState.activeConnections.clear();
2224
+ serveState.pendingUpgrade = null;
2225
+ releaseTrackedGlobalHandles(context);
2226
+ try {
2227
+ requestAbortSignalRef.release();
2228
+ } catch {}
2229
+ },
2230
+ async dispatchRequest(request, dispatchOptions) {
2231
+ if (serveState.pendingUpgrade) {
2232
+ const oldConnectionId = serveState.pendingUpgrade.connectionId;
2233
+ context.evalSync(`globalThis.__upgradeRegistry__.delete("${oldConnectionId}")`);
2234
+ serveState.pendingUpgrade = null;
2235
+ }
2236
+ const hasHandler = context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
2237
+ if (!hasHandler) {
2238
+ throw new Error("No serve() handler registered");
2239
+ }
2240
+ const forwardedSignal = dispatchOptions?.signal ?? request.signal;
2241
+ const forwardedSignalInitiallyAborted = forwardedSignal?.aborted ?? false;
2242
+ let requestStreamId = null;
2243
+ let requestInstanceId = null;
2244
+ let streamCleanup = null;
2245
+ let onForwardedSignalAbort;
2246
+ const canHaveBody = !["GET", "HEAD"].includes(request.method.toUpperCase());
2247
+ if (canHaveBody && request.body) {
2248
+ requestStreamId = streamRegistry.create();
2249
+ streamCleanup = startNativeStreamReader(request.body, requestStreamId, streamRegistry);
2250
+ }
2251
+ try {
2252
+ const headersArray = Array.from(request.headers.entries());
2253
+ requestInstanceId = nextInstanceId++;
2254
+ const requestState = {
2255
+ url: request.url,
2256
+ method: request.method,
2257
+ headers: headersArray,
2258
+ body: null,
2259
+ bodyUsed: false,
2260
+ streamId: requestStreamId,
2261
+ signalAborted: forwardedSignalInitiallyAborted,
2262
+ mode: request.mode,
2263
+ credentials: request.credentials,
2264
+ cache: request.cache,
2265
+ redirect: request.redirect,
2266
+ referrer: request.referrer,
2267
+ integrity: request.integrity
2268
+ };
2269
+ stateMap.set(requestInstanceId, requestState);
2270
+ if (forwardedSignal && !forwardedSignalInitiallyAborted) {
2271
+ onForwardedSignalAbort = () => {
2272
+ if (requestInstanceId == null)
2273
+ return;
2274
+ const currentState = stateMap.get(requestInstanceId);
2275
+ if (!currentState || currentState.signalAborted) {
2276
+ return;
2277
+ }
2278
+ currentState.signalAborted = true;
2279
+ try {
2280
+ requestAbortSignalRef.applyIgnored(undefined, [requestInstanceId], {
2281
+ arguments: { copy: true }
2282
+ });
2283
+ } catch {}
2284
+ };
2285
+ forwardedSignal.addEventListener("abort", onForwardedSignalAbort, { once: true });
2286
+ if (forwardedSignal.aborted) {
2287
+ onForwardedSignalAbort();
2288
+ }
2289
+ }
2290
+ const responseInstanceId = await context.eval(`
2291
+ (async function() {
2292
+ const request = Request._fromInstanceId(${requestInstanceId});
2293
+ const server = new __Server__();
2294
+ const response = await Promise.resolve(__serveOptions__.fetch(request, server));
2295
+ if (response == null) {
2296
+ throw new TypeError("fetch handler did not return a Response object (got " + (response === null ? "null" : "undefined") + ")");
2297
+ }
2298
+ if (typeof response._getInstanceId !== 'function') {
2299
+ throw new TypeError("fetch handler must return a Response object (got " + (typeof response) + ")");
2300
+ }
2301
+ return response._getInstanceId();
2302
+ })()
2303
+ `, { promise: true });
2304
+ const responseState = stateMap.get(responseInstanceId);
2305
+ if (!responseState) {
2306
+ throw new Error("Response state not found");
2307
+ }
2308
+ if (responseState.streamId !== null) {
2309
+ const passthruMap = getPassthruBodiesForContext(context);
2310
+ const passthruBody = passthruMap.get(responseState.streamId);
2311
+ if (passthruBody) {
2312
+ passthruMap.delete(responseState.streamId);
2313
+ const responseHeaders2 = new Headers(responseState.headers);
2314
+ const status2 = responseState.status === 101 ? 200 : responseState.status;
2315
+ const hasNullBodyStatus2 = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
2316
+ const response2 = new Response(hasNullBodyStatus2 ? null : passthruBody, {
2317
+ status: status2,
2318
+ statusText: responseState.statusText,
2319
+ headers: responseHeaders2
2320
+ });
2321
+ response2._originalStatus = responseState.status;
2322
+ return response2;
2323
+ }
2324
+ }
2325
+ if (responseState.streamId !== null) {
2326
+ const responseStreamId = responseState.streamId;
2327
+ let streamDone = false;
2328
+ const pumpedStream = new ReadableStream({
2329
+ async pull(controller) {
2330
+ if (streamDone)
2331
+ return;
2332
+ while (!streamDone) {
2333
+ const state = streamRegistry.get(responseStreamId);
2334
+ if (!state) {
2335
+ controller.close();
2336
+ streamDone = true;
2337
+ return;
2338
+ }
2339
+ if (state.queue.length > 0 || state.closed || state.errored) {
2340
+ break;
2341
+ }
2342
+ await new Promise((r) => setTimeout(r, 1));
2343
+ }
2344
+ try {
2345
+ const result = await streamRegistry.pull(responseStreamId);
2346
+ if (result.done) {
2347
+ controller.close();
2348
+ streamDone = true;
2349
+ streamRegistry.delete(responseStreamId);
2350
+ return;
2351
+ }
2352
+ controller.enqueue(result.value);
2353
+ } catch (error) {
2354
+ controller.error(error);
2355
+ streamDone = true;
2356
+ streamRegistry.delete(responseStreamId);
2357
+ }
2358
+ },
2359
+ cancel() {
2360
+ streamDone = true;
2361
+ streamRegistry.cancel(responseStreamId);
2362
+ }
2363
+ });
2364
+ const responseHeaders2 = new Headers(responseState.headers);
2365
+ const status2 = responseState.status === 101 ? 200 : responseState.status;
2366
+ const hasNullBodyStatus2 = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
2367
+ if (hasNullBodyStatus2) {
2368
+ streamRegistry.cancel(responseStreamId);
2369
+ streamRegistry.delete(responseStreamId);
2370
+ }
2371
+ const response2 = new Response(hasNullBodyStatus2 ? null : pumpedStream, {
2372
+ status: status2,
2373
+ statusText: responseState.statusText,
2374
+ headers: responseHeaders2
2375
+ });
2376
+ response2._originalStatus = responseState.status;
2377
+ return response2;
2378
+ }
2379
+ const responseHeaders = new Headers(responseState.headers);
2380
+ const hasNullBodyStatus = responseState.status === 101 || responseState.status === 103 || responseState.status === 204 || responseState.status === 205 || responseState.status === 304;
2381
+ const responseBody = hasNullBodyStatus ? null : responseState.body;
2382
+ const status = responseState.status === 101 ? 200 : responseState.status;
2383
+ const response = new Response(responseBody, {
2384
+ status,
2385
+ statusText: responseState.statusText,
2386
+ headers: responseHeaders
2387
+ });
2388
+ response._originalStatus = responseState.status;
2389
+ return response;
2390
+ } finally {
2391
+ if (forwardedSignal && onForwardedSignalAbort) {
2392
+ forwardedSignal.removeEventListener("abort", onForwardedSignalAbort);
2393
+ }
2394
+ if (requestStreamId !== null) {
2395
+ const startTime = Date.now();
2396
+ let streamState = streamRegistry.get(requestStreamId);
2397
+ while (streamState && !streamState.closed && !streamState.errored && Date.now() - startTime < 100) {
2398
+ await new Promise((resolve) => setTimeout(resolve, 5));
2399
+ streamState = streamRegistry.get(requestStreamId);
2400
+ }
2401
+ }
2402
+ if (streamCleanup) {
2403
+ await streamCleanup();
2404
+ }
2405
+ }
2406
+ },
2407
+ getUpgradeRequest() {
2408
+ const result = serveState.pendingUpgrade;
2409
+ return result;
2410
+ },
2411
+ dispatchWebSocketOpen(connectionId) {
2412
+ serveState.activeConnections.set(connectionId, { connectionId });
2413
+ const hasOpenHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.open`);
2414
+ context.evalSync(`
2415
+ (function() {
2416
+ const ws = new __ServerWebSocket__("${connectionId}");
2417
+ globalThis.__activeWs_${connectionId}__ = ws;
2418
+ })()
2419
+ `);
2420
+ if (hasOpenHandler) {
2421
+ context.evalSync(`
2422
+ (function() {
2423
+ const ws = globalThis.__activeWs_${connectionId}__;
2424
+ __serveOptions__.websocket.open(ws);
2425
+ })()
2426
+ `);
2427
+ }
2428
+ if (serveState.pendingUpgrade?.connectionId === connectionId) {
2429
+ serveState.pendingUpgrade = null;
2430
+ }
2431
+ },
2432
+ dispatchWebSocketMessage(connectionId, message) {
2433
+ if (!serveState.activeConnections.has(connectionId)) {
2434
+ return;
2435
+ }
2436
+ const hasMessageHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.message`);
2437
+ if (!hasMessageHandler) {
2438
+ return;
2439
+ }
2440
+ if (typeof message === "string") {
2441
+ context.evalSync(`
2442
+ (function() {
2443
+ const ws = globalThis.__activeWs_${connectionId}__;
2444
+ if (ws) __serveOptions__.websocket.message(ws, "${message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")}");
2445
+ })()
2446
+ `);
2447
+ } else {
2448
+ const bytes = Array.from(new Uint8Array(message));
2449
+ context.evalSync(`
2450
+ (function() {
2451
+ const ws = globalThis.__activeWs_${connectionId}__;
2452
+ if (ws) {
2453
+ const bytes = new Uint8Array([${bytes.join(",")}]);
2454
+ __serveOptions__.websocket.message(ws, bytes.buffer);
2455
+ }
2456
+ })()
2457
+ `);
2458
+ }
2459
+ },
2460
+ dispatchWebSocketClose(connectionId, code, reason) {
2461
+ if (!serveState.activeConnections.has(connectionId)) {
2462
+ return;
2463
+ }
2464
+ context.evalSync(`
2465
+ (function() {
2466
+ const ws = globalThis.__activeWs_${connectionId}__;
2467
+ if (ws) ws._setReadyState(3);
2468
+ })()
2469
+ `);
2470
+ const hasCloseHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.close`);
2471
+ if (hasCloseHandler) {
2472
+ const safeReason = reason.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
2473
+ context.evalSync(`
2474
+ (function() {
2475
+ const ws = globalThis.__activeWs_${connectionId}__;
2476
+ if (ws) __serveOptions__.websocket.close(ws, ${code}, "${safeReason}");
2477
+ })()
2478
+ `);
2479
+ }
2480
+ context.evalSync(`
2481
+ delete globalThis.__activeWs_${connectionId}__;
2482
+ globalThis.__upgradeRegistry__.delete("${connectionId}");
2483
+ `);
2484
+ serveState.activeConnections.delete(connectionId);
2485
+ },
2486
+ dispatchWebSocketError(connectionId, error) {
2487
+ if (!serveState.activeConnections.has(connectionId)) {
2488
+ return;
2489
+ }
2490
+ const hasErrorHandler = context.evalSync(`!!globalThis.__serveOptions__?.websocket?.error`);
2491
+ if (!hasErrorHandler) {
2492
+ return;
2493
+ }
2494
+ const safeName = error.name.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2495
+ const safeMessage = error.message.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
2496
+ context.evalSync(`
2497
+ (function() {
2498
+ const ws = globalThis.__activeWs_${connectionId}__;
2499
+ if (ws) {
2500
+ const error = { name: "${safeName}", message: "${safeMessage}" };
2501
+ __serveOptions__.websocket.error(ws, error);
2502
+ }
2503
+ })()
2504
+ `);
2505
+ },
2506
+ onWebSocketCommand(callback) {
2507
+ wsCommandCallbacks.add(callback);
2508
+ return () => wsCommandCallbacks.delete(callback);
2509
+ },
2510
+ hasServeHandler() {
2511
+ return context.evalSync(`!!globalThis.__serveOptions__?.fetch`);
2512
+ },
2513
+ hasActiveConnections() {
2514
+ return serveState.activeConnections.size > 0;
2515
+ },
2516
+ dispatchClientWebSocketOpen(socketId, protocol, extensions) {
2517
+ const safeProtocol = protocol.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2518
+ const safeExtensions = extensions.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2519
+ context.evalSync(`
2520
+ __dispatchClientWebSocketEvent("${socketId}", "open", {
2521
+ protocol: "${safeProtocol}",
2522
+ extensions: "${safeExtensions}"
2523
+ });
2524
+ `);
2525
+ },
2526
+ dispatchClientWebSocketMessage(socketId, data) {
2527
+ if (typeof data === "string") {
2528
+ const safeData = data.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
2529
+ context.evalSync(`
2530
+ __dispatchClientWebSocketEvent("${socketId}", "message", { data: "${safeData}" });
2531
+ `);
2532
+ } else {
2533
+ const bytes = new Uint8Array(data);
2534
+ let binary = "";
2535
+ for (let i = 0;i < bytes.byteLength; i++) {
2536
+ binary += String.fromCharCode(bytes[i]);
2537
+ }
2538
+ const base64 = Buffer.from(binary, "binary").toString("base64");
2539
+ context.evalSync(`
2540
+ __dispatchClientWebSocketEvent("${socketId}", "message", { data: "__BINARY__${base64}" });
2541
+ `);
2542
+ }
2543
+ },
2544
+ dispatchClientWebSocketClose(socketId, code, reason, wasClean) {
2545
+ const safeReason = reason.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
2546
+ context.evalIgnored(`
2547
+ __dispatchClientWebSocketEvent("${socketId}", "close", {
2548
+ code: ${code},
2549
+ reason: "${safeReason}",
2550
+ wasClean: ${wasClean}
2551
+ });
2552
+ `);
2553
+ },
2554
+ dispatchClientWebSocketError(socketId) {
2555
+ context.evalIgnored(`
2556
+ __dispatchClientWebSocketEvent("${socketId}", "error", {});
2557
+ `);
2558
+ },
2559
+ onClientWebSocketCommand(callback) {
2560
+ clientWsCommandCallbacks.add(callback);
2561
+ return () => clientWsCommandCallbacks.delete(callback);
2562
+ },
2563
+ onEvent(callback) {
2564
+ eventCallbacks.add(callback);
2565
+ return () => eventCallbacks.delete(callback);
2566
+ },
2567
+ dispatchEvent(event, payload) {
2568
+ const json = JSON.stringify(payload);
2569
+ const safeEvent = JSON.stringify(event);
2570
+ const safeJson = JSON.stringify(json);
2571
+ context.evalSync(`__dispatchExternalEvent(${safeEvent}, ${safeJson});`);
2572
+ }
2573
+ };
2574
+ }
2575
+ export {
2576
+ setupFetch,
2577
+ clearAllInstanceState
2578
+ };
2579
+
2580
+ //# debugId=E4E922B4BB22197964756E2164756E21