@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,1919 @@
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __toCommonJS = (from) => {
33
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
34
+ if (entry)
35
+ return entry;
36
+ entry = __defProp({}, "__esModule", { value: true });
37
+ if (from && typeof from === "object" || typeof from === "function") {
38
+ for (var key of __getOwnPropNames(from))
39
+ if (!__hasOwnProp.call(entry, key))
40
+ __defProp(entry, key, {
41
+ get: __accessProp.bind(from, key),
42
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
43
+ });
44
+ }
45
+ __moduleCache.set(from, entry);
46
+ return entry;
47
+ };
48
+ var __moduleCache;
49
+ var __returnValue = (v) => v;
50
+ function __exportSetter(name, newValue) {
51
+ this[name] = __returnValue.bind(null, newValue);
52
+ }
53
+ var __export = (target, all) => {
54
+ for (var name in all)
55
+ __defProp(target, name, {
56
+ get: all[name],
57
+ enumerable: true,
58
+ configurable: true,
59
+ set: __exportSetter.bind(all, name)
60
+ });
61
+ };
62
+
63
+ // src/internal/client/connection.ts
64
+ var exports_connection = {};
65
+ __export(exports_connection, {
66
+ isBenignDisposeError: () => isBenignDisposeError,
67
+ connect: () => connect
68
+ });
69
+ module.exports = __toCommonJS(exports_connection);
70
+ var import_node_net = require("node:net");
71
+ var import_node_path = __toESM(require("node:path"));
72
+ var import_request_context = require("../../bridge/request-context.cjs");
73
+ var import_protocol = require("../protocol/index.cjs");
74
+ var import_client = require("../playwright/client.cjs");
75
+ var isolateWsCallbacks = new Map;
76
+ var isolateClientWebSockets = new Map;
77
+ var isolateWebSocketCallbacks = new Map;
78
+ var isolateEventListeners = new Map;
79
+ async function connect(options = {}) {
80
+ const socket = await createSocket(options);
81
+ const state = {
82
+ socket,
83
+ pendingRequests: new Map,
84
+ callbacks: new Map,
85
+ callbacksNeedingRequestId: new Set,
86
+ nextRequestId: 1,
87
+ nextCallbackId: 1,
88
+ nextStreamId: 1,
89
+ connected: true,
90
+ streamResponses: new Map,
91
+ uploadStreams: new Map,
92
+ moduleSourceCache: new Map,
93
+ callbackStreamReaders: new Map,
94
+ activeCallbackInvocations: new Map,
95
+ callbackAbortControllers: new Map,
96
+ closing: false,
97
+ namespacedRuntimes: new Map
98
+ };
99
+ function setupSocket(sock) {
100
+ const parser = import_protocol.createFrameParser();
101
+ sock.on("data", (data) => {
102
+ try {
103
+ for (const frame of parser.feed(new Uint8Array(data))) {
104
+ handleMessage(frame.message, state);
105
+ }
106
+ } catch (err) {
107
+ console.error("Error parsing frame:", err);
108
+ }
109
+ });
110
+ sock.on("close", () => {
111
+ state.connected = false;
112
+ for (const [, pending] of state.pendingRequests) {
113
+ pending.reject(new Error("Connection closed"));
114
+ }
115
+ state.pendingRequests.clear();
116
+ for (const [, receiver] of state.streamResponses) {
117
+ receiver.state = "errored";
118
+ receiver.error = new Error("Connection closed");
119
+ const resolvers = receiver.pullResolvers.splice(0);
120
+ for (const resolver of resolvers) {
121
+ resolver();
122
+ }
123
+ }
124
+ state.streamResponses.clear();
125
+ for (const [, session] of state.uploadStreams) {
126
+ session.state = "closed";
127
+ if (session.creditResolver) {
128
+ session.creditResolver();
129
+ }
130
+ }
131
+ state.uploadStreams.clear();
132
+ for (const [, controller] of state.callbackAbortControllers) {
133
+ controller.abort();
134
+ }
135
+ state.callbackAbortControllers.clear();
136
+ state.activeCallbackInvocations.clear();
137
+ if (!state.closing && state.namespacedRuntimes.size > 0) {
138
+ state.reconnecting = reconnect(state, options).catch(() => {
139
+ state.namespacedRuntimes.clear();
140
+ state.reconnecting = undefined;
141
+ });
142
+ }
143
+ });
144
+ sock.on("error", (err) => {
145
+ if (!state.closing && state.namespacedRuntimes.size > 0)
146
+ return;
147
+ console.error("Socket error:", err);
148
+ });
149
+ }
150
+ setupSocket(socket);
151
+ async function reconnect(st, opts) {
152
+ try {
153
+ const newSocket = await createSocket(opts);
154
+ st.socket = newSocket;
155
+ st.connected = true;
156
+ setupSocket(newSocket);
157
+ for (const [namespaceId, descriptor] of st.namespacedRuntimes) {
158
+ const runtimeOptions = descriptor.runtimeOptions;
159
+ const callbacks = {};
160
+ if (runtimeOptions.console) {
161
+ callbacks.console = registerConsoleCallbacks(st, runtimeOptions.console);
162
+ }
163
+ if (runtimeOptions.fetch) {
164
+ callbacks.fetch = registerFetchCallback(st, runtimeOptions.fetch);
165
+ }
166
+ if (runtimeOptions.fs) {
167
+ callbacks.fs = registerFsCallbacks(st, runtimeOptions.fs);
168
+ }
169
+ if (runtimeOptions.moduleLoader) {
170
+ callbacks.moduleLoader = registerModuleLoaderCallback(st, runtimeOptions.moduleLoader);
171
+ }
172
+ if (runtimeOptions.customFunctions) {
173
+ callbacks.custom = registerCustomFunctions(st, runtimeOptions.customFunctions);
174
+ }
175
+ if (runtimeOptions.playwright) {
176
+ const playwrightHandler = runtimeOptions.playwright.handler;
177
+ if (playwrightHandler) {
178
+ const handlerCallbackId = st.nextCallbackId++;
179
+ st.callbacks.set(handlerCallbackId, async (opJson) => {
180
+ const op = JSON.parse(opJson);
181
+ const result2 = await playwrightHandler(op);
182
+ return JSON.stringify(result2);
183
+ });
184
+ callbacks.playwright = {
185
+ handlerCallbackId,
186
+ console: runtimeOptions.playwright.console && !runtimeOptions.console?.onEntry
187
+ };
188
+ }
189
+ }
190
+ let testEnvironmentOption;
191
+ if (runtimeOptions.testEnvironment) {
192
+ if (typeof runtimeOptions.testEnvironment === "object") {
193
+ const testEnvOptions = runtimeOptions.testEnvironment;
194
+ const testEnvCallbacks = {};
195
+ if (testEnvOptions.onEvent) {
196
+ const userOnEvent = testEnvOptions.onEvent;
197
+ const onEventCallbackId = registerEventCallback(st, (eventJson) => {
198
+ const event = JSON.parse(eventJson);
199
+ userOnEvent(event);
200
+ });
201
+ testEnvCallbacks.onEvent = {
202
+ callbackId: onEventCallbackId,
203
+ name: "testEnvironment.onEvent",
204
+ type: "sync"
205
+ };
206
+ }
207
+ testEnvironmentOption = {
208
+ callbacks: testEnvCallbacks,
209
+ testTimeout: testEnvOptions.testTimeout
210
+ };
211
+ } else {
212
+ testEnvironmentOption = true;
213
+ }
214
+ }
215
+ const playwrightOption = runtimeOptions.playwright?.timeout !== undefined ? { timeout: runtimeOptions.playwright.timeout } : undefined;
216
+ const requestId = st.nextRequestId++;
217
+ const request = {
218
+ type: import_protocol.MessageType.CREATE_RUNTIME,
219
+ requestId,
220
+ options: {
221
+ memoryLimitMB: runtimeOptions.memoryLimitMB,
222
+ executionTimeout: runtimeOptions.executionTimeout,
223
+ cwd: runtimeOptions.cwd,
224
+ callbacks,
225
+ testEnvironment: testEnvironmentOption,
226
+ playwright: playwrightOption,
227
+ namespaceId
228
+ }
229
+ };
230
+ const result = await sendRequest(st, request);
231
+ descriptor.isolateId = result.isolateId;
232
+ }
233
+ st.reconnecting = undefined;
234
+ } catch {
235
+ st.reconnecting = undefined;
236
+ throw new Error("Failed to reconnect to daemon");
237
+ }
238
+ }
239
+ return {
240
+ createRuntime: (runtimeOptions) => createRuntime(state, runtimeOptions),
241
+ createNamespace: (id) => ({
242
+ id,
243
+ createRuntime: (runtimeOptions) => createRuntime(state, runtimeOptions, id)
244
+ }),
245
+ close: async () => {
246
+ state.closing = true;
247
+ state.connected = false;
248
+ state.socket.destroy();
249
+ },
250
+ isConnected: () => state.connected
251
+ };
252
+ }
253
+ function createSocket(options) {
254
+ return new Promise((resolve, reject) => {
255
+ const timeout = options.timeout;
256
+ let socket;
257
+ const onError = (err) => {
258
+ reject(err);
259
+ };
260
+ const onConnect = () => {
261
+ socket.removeListener("error", onError);
262
+ resolve(socket);
263
+ };
264
+ if (options.socket) {
265
+ socket = import_node_net.connect(options.socket, onConnect);
266
+ } else {
267
+ socket = import_node_net.connect(options.port ?? 47891, options.host ?? "127.0.0.1", onConnect);
268
+ }
269
+ socket.on("error", onError);
270
+ if (timeout && timeout > 0) {
271
+ const timeoutId = setTimeout(() => {
272
+ socket.destroy();
273
+ reject(new Error("Connection timeout"));
274
+ }, timeout);
275
+ socket.once("connect", () => {
276
+ clearTimeout(timeoutId);
277
+ });
278
+ }
279
+ });
280
+ }
281
+ function handleMessage(message, state) {
282
+ switch (message.type) {
283
+ case import_protocol.MessageType.RESPONSE_OK: {
284
+ const response = message;
285
+ const pending = state.pendingRequests.get(response.requestId);
286
+ if (pending) {
287
+ state.pendingRequests.delete(response.requestId);
288
+ pending.resolve(response.data);
289
+ }
290
+ break;
291
+ }
292
+ case import_protocol.MessageType.RESPONSE_ERROR: {
293
+ const response = message;
294
+ const pending = state.pendingRequests.get(response.requestId);
295
+ if (pending) {
296
+ state.pendingRequests.delete(response.requestId);
297
+ const error = new Error(response.message);
298
+ if (response.details) {
299
+ error.name = response.details.name;
300
+ if (response.details.stack) {
301
+ error.stack = response.details.stack;
302
+ }
303
+ }
304
+ pending.reject(error);
305
+ }
306
+ break;
307
+ }
308
+ case import_protocol.MessageType.CALLBACK_INVOKE: {
309
+ const invoke = message;
310
+ handleCallbackInvoke(invoke, state);
311
+ break;
312
+ }
313
+ case import_protocol.MessageType.PONG:
314
+ break;
315
+ case import_protocol.MessageType.CALLBACK_STREAM_CANCEL: {
316
+ const streamId = message.streamId;
317
+ const reader = state.callbackStreamReaders.get(streamId);
318
+ if (reader) {
319
+ reader.cancel().catch(() => {});
320
+ }
321
+ break;
322
+ }
323
+ case import_protocol.MessageType.CALLBACK_ABORT: {
324
+ const msg = message;
325
+ const invocation = state.activeCallbackInvocations.get(msg.targetRequestId);
326
+ if (invocation) {
327
+ invocation.aborted = true;
328
+ }
329
+ const controller = state.callbackAbortControllers.get(msg.targetRequestId);
330
+ if (controller && !controller.signal.aborted) {
331
+ controller.abort();
332
+ }
333
+ break;
334
+ }
335
+ case import_protocol.MessageType.ISOLATE_EVENT: {
336
+ const msg = message;
337
+ handleIsolateEvent(msg, state);
338
+ break;
339
+ }
340
+ case import_protocol.MessageType.RESPONSE_STREAM_START: {
341
+ const msg = message;
342
+ const receiver = {
343
+ streamId: msg.streamId,
344
+ requestId: msg.requestId,
345
+ metadata: msg.metadata,
346
+ controller: null,
347
+ state: "active",
348
+ pendingChunks: [],
349
+ pullResolvers: [],
350
+ controllerFinalized: false
351
+ };
352
+ const readableStream = new ReadableStream({
353
+ start(controller) {
354
+ receiver.controller = controller;
355
+ },
356
+ pull(_controller) {
357
+ if (receiver.controllerFinalized) {
358
+ return;
359
+ }
360
+ while (receiver.pendingChunks.length > 0) {
361
+ const chunk = receiver.pendingChunks.shift();
362
+ receiver.controller.enqueue(chunk);
363
+ }
364
+ if (receiver.state === "closed") {
365
+ if (!receiver.controllerFinalized) {
366
+ receiver.controllerFinalized = true;
367
+ receiver.controller.close();
368
+ }
369
+ return Promise.resolve();
370
+ }
371
+ if (receiver.state === "errored") {
372
+ if (!receiver.controllerFinalized && receiver.error) {
373
+ receiver.controllerFinalized = true;
374
+ receiver.controller.error(receiver.error);
375
+ }
376
+ return Promise.resolve();
377
+ }
378
+ sendMessage(state.socket, {
379
+ type: import_protocol.MessageType.STREAM_PULL,
380
+ streamId: msg.streamId,
381
+ maxBytes: import_protocol.STREAM_DEFAULT_CREDIT
382
+ });
383
+ return new Promise((resolve) => {
384
+ receiver.pullResolvers.push(resolve);
385
+ });
386
+ },
387
+ cancel(_reason) {
388
+ receiver.state = "closed";
389
+ receiver.controllerFinalized = true;
390
+ const resolvers = receiver.pullResolvers.splice(0);
391
+ for (const resolver of resolvers) {
392
+ resolver();
393
+ }
394
+ sendMessage(state.socket, {
395
+ type: import_protocol.MessageType.STREAM_ERROR,
396
+ streamId: msg.streamId,
397
+ error: "Stream cancelled by consumer"
398
+ });
399
+ state.streamResponses.delete(msg.streamId);
400
+ return new Promise((resolve) => setTimeout(resolve, 0));
401
+ }
402
+ });
403
+ state.streamResponses.set(msg.streamId, receiver);
404
+ const pending = state.pendingRequests.get(msg.requestId);
405
+ if (pending) {
406
+ state.pendingRequests.delete(msg.requestId);
407
+ const response = new Response(readableStream, {
408
+ status: msg.metadata?.status ?? 200,
409
+ statusText: msg.metadata?.statusText ?? "OK",
410
+ headers: msg.metadata?.headers
411
+ });
412
+ pending.resolve({ response, __streaming: true });
413
+ }
414
+ sendMessage(state.socket, {
415
+ type: import_protocol.MessageType.STREAM_PULL,
416
+ streamId: msg.streamId,
417
+ maxBytes: import_protocol.STREAM_DEFAULT_CREDIT
418
+ });
419
+ break;
420
+ }
421
+ case import_protocol.MessageType.RESPONSE_STREAM_CHUNK: {
422
+ const msg = message;
423
+ const receiver = state.streamResponses.get(msg.streamId);
424
+ if (receiver && receiver.state === "active") {
425
+ if (receiver.pullResolvers.length > 0) {
426
+ receiver.controller.enqueue(msg.chunk);
427
+ const resolver = receiver.pullResolvers.shift();
428
+ resolver();
429
+ } else {
430
+ receiver.pendingChunks.push(msg.chunk);
431
+ }
432
+ }
433
+ break;
434
+ }
435
+ case import_protocol.MessageType.RESPONSE_STREAM_END: {
436
+ const msg = message;
437
+ const receiver = state.streamResponses.get(msg.streamId);
438
+ if (receiver) {
439
+ receiver.state = "closed";
440
+ while (receiver.pendingChunks.length > 0) {
441
+ const chunk = receiver.pendingChunks.shift();
442
+ receiver.controller.enqueue(chunk);
443
+ }
444
+ if (!receiver.controllerFinalized) {
445
+ receiver.controllerFinalized = true;
446
+ receiver.controller.close();
447
+ }
448
+ const resolvers = receiver.pullResolvers.splice(0);
449
+ for (const resolver of resolvers) {
450
+ resolver();
451
+ }
452
+ state.streamResponses.delete(msg.streamId);
453
+ }
454
+ break;
455
+ }
456
+ case import_protocol.MessageType.STREAM_PULL: {
457
+ const msg = message;
458
+ const session = state.uploadStreams.get(msg.streamId);
459
+ if (session) {
460
+ session.credit += msg.maxBytes;
461
+ if (session.creditResolver) {
462
+ session.creditResolver();
463
+ session.creditResolver = undefined;
464
+ }
465
+ }
466
+ break;
467
+ }
468
+ case import_protocol.MessageType.STREAM_ERROR: {
469
+ const msg = message;
470
+ const uploadSession = state.uploadStreams.get(msg.streamId);
471
+ if (uploadSession) {
472
+ uploadSession.state = "closed";
473
+ state.uploadStreams.delete(msg.streamId);
474
+ }
475
+ const receiver = state.streamResponses.get(msg.streamId);
476
+ if (receiver) {
477
+ receiver.state = "errored";
478
+ receiver.error = new Error(msg.error);
479
+ while (receiver.pendingChunks.length > 0) {
480
+ const chunk = receiver.pendingChunks.shift();
481
+ receiver.controller.enqueue(chunk);
482
+ }
483
+ const resolvers = receiver.pullResolvers.splice(0);
484
+ for (const resolver of resolvers) {
485
+ resolver();
486
+ }
487
+ state.streamResponses.delete(msg.streamId);
488
+ }
489
+ break;
490
+ }
491
+ default:
492
+ console.warn(`Unexpected message type: ${message.type}`);
493
+ }
494
+ }
495
+ async function handleCallbackInvoke(invoke, state) {
496
+ const callback = state.callbacks.get(invoke.callbackId);
497
+ const invocationState = { aborted: false };
498
+ state.activeCallbackInvocations.set(invoke.requestId, invocationState);
499
+ const abortController = new AbortController;
500
+ state.callbackAbortControllers.set(invoke.requestId, abortController);
501
+ const response = {
502
+ type: import_protocol.MessageType.CALLBACK_RESPONSE,
503
+ requestId: invoke.requestId
504
+ };
505
+ if (!callback) {
506
+ response.error = {
507
+ name: "Error",
508
+ message: `Unknown callback: ${invoke.callbackId}`
509
+ };
510
+ if (!invocationState.aborted) {
511
+ sendMessage(state.socket, response);
512
+ }
513
+ state.activeCallbackInvocations.delete(invoke.requestId);
514
+ state.callbackAbortControllers.delete(invoke.requestId);
515
+ } else {
516
+ try {
517
+ const invokeRegisteredCallback = async () => {
518
+ const needsRequestId = state.callbacksNeedingRequestId.has(invoke.callbackId);
519
+ return needsRequestId ? await callback(...invoke.args, invoke.requestId) : await callback(...invoke.args);
520
+ };
521
+ const result = invoke.context ? await import_request_context.withRequestContext({
522
+ requestId: invoke.context.requestId,
523
+ metadata: invoke.context.metadata,
524
+ signal: abortController.signal
525
+ }, invokeRegisteredCallback) : await import_request_context.withRequestContext({
526
+ signal: abortController.signal
527
+ }, invokeRegisteredCallback);
528
+ if (result && typeof result === "object" && result.__callbackStreaming) {
529
+ return;
530
+ }
531
+ if (invocationState.aborted) {
532
+ return;
533
+ }
534
+ response.result = result;
535
+ sendMessage(state.socket, response);
536
+ } catch (err) {
537
+ if (invocationState.aborted) {
538
+ return;
539
+ }
540
+ const error = err;
541
+ response.error = {
542
+ name: error.name,
543
+ message: error.message,
544
+ stack: error.stack
545
+ };
546
+ sendMessage(state.socket, response);
547
+ } finally {
548
+ state.activeCallbackInvocations.delete(invoke.requestId);
549
+ state.callbackAbortControllers.delete(invoke.requestId);
550
+ }
551
+ }
552
+ }
553
+ function sendMessage(socket, message) {
554
+ const frame = import_protocol.buildFrame(message);
555
+ socket.write(frame);
556
+ }
557
+ function sendRequest(state, message) {
558
+ return new Promise((resolve, reject) => {
559
+ if (!state.connected) {
560
+ reject(new Error("Not connected"));
561
+ return;
562
+ }
563
+ const requestId = message.requestId;
564
+ state.pendingRequests.set(requestId, {
565
+ resolve,
566
+ reject
567
+ });
568
+ sendMessage(state.socket, message);
569
+ });
570
+ }
571
+ function isBenignDisposeError(error) {
572
+ const message = error instanceof Error ? error.message : String(error ?? "");
573
+ return /isolate not owned by this connection|isolate not found|not connected|connection closed/i.test(message);
574
+ }
575
+ function normalizePlaywrightOptions(playwrightOptions) {
576
+ if (!playwrightOptions || playwrightOptions.timeout === undefined) {
577
+ return playwrightOptions;
578
+ }
579
+ const metadata = import_client.getDefaultPlaywrightHandlerMetadata(playwrightOptions.handler);
580
+ if (!metadata?.page) {
581
+ return playwrightOptions;
582
+ }
583
+ const currentTimeout = metadata.options?.timeout ?? 30000;
584
+ if (currentTimeout === playwrightOptions.timeout) {
585
+ return playwrightOptions;
586
+ }
587
+ return {
588
+ ...playwrightOptions,
589
+ handler: import_client.defaultPlaywrightHandler(metadata.page, {
590
+ ...metadata.options,
591
+ timeout: playwrightOptions.timeout
592
+ })
593
+ };
594
+ }
595
+ async function createRuntime(state, options = {}, namespaceId) {
596
+ const normalizedPlaywrightOptions = normalizePlaywrightOptions(options.playwright);
597
+ const runtimeOptionsForReconnect = normalizedPlaywrightOptions === options.playwright ? options : {
598
+ ...options,
599
+ playwright: normalizedPlaywrightOptions
600
+ };
601
+ const callbacks = {};
602
+ if (options.console) {
603
+ callbacks.console = registerConsoleCallbacks(state, options.console);
604
+ }
605
+ if (options.fetch) {
606
+ callbacks.fetch = registerFetchCallback(state, options.fetch);
607
+ }
608
+ if (options.fs) {
609
+ callbacks.fs = registerFsCallbacks(state, options.fs);
610
+ }
611
+ if (options.moduleLoader) {
612
+ callbacks.moduleLoader = registerModuleLoaderCallback(state, options.moduleLoader);
613
+ }
614
+ if (options.customFunctions) {
615
+ callbacks.custom = registerCustomFunctions(state, options.customFunctions);
616
+ }
617
+ let playwrightHandler;
618
+ const browserConsoleLogs = [];
619
+ const pageErrors = [];
620
+ const networkRequests = [];
621
+ const networkResponses = [];
622
+ const requestFailures = [];
623
+ const pageListenerCleanups = [];
624
+ if (normalizedPlaywrightOptions) {
625
+ playwrightHandler = normalizedPlaywrightOptions.handler;
626
+ if (!playwrightHandler) {
627
+ throw new Error("playwright.handler is required when using playwright options");
628
+ }
629
+ const page = import_client.getDefaultPlaywrightHandlerMetadata(playwrightHandler)?.page;
630
+ const handlerCallbackId = state.nextCallbackId++;
631
+ state.callbacks.set(handlerCallbackId, async (opJson) => {
632
+ const op = JSON.parse(opJson);
633
+ const result2 = await playwrightHandler(op);
634
+ return JSON.stringify(result2);
635
+ });
636
+ if (page) {
637
+ const requestIds = new WeakMap;
638
+ let nextRequestId = 1;
639
+ const getRequestId = (request2) => {
640
+ let requestId2 = requestIds.get(request2);
641
+ if (!requestId2) {
642
+ requestId2 = `req_${nextRequestId++}`;
643
+ requestIds.set(request2, requestId2);
644
+ }
645
+ return requestId2;
646
+ };
647
+ const toLocation = (location) => {
648
+ if (!location || !location.url && location.lineNumber == null && location.columnNumber == null) {
649
+ return;
650
+ }
651
+ return {
652
+ url: location.url || undefined,
653
+ lineNumber: location.lineNumber != null ? location.lineNumber + 1 : undefined,
654
+ columnNumber: location.columnNumber != null ? location.columnNumber + 1 : undefined
655
+ };
656
+ };
657
+ const onConsole = (msg) => {
658
+ const entry = {
659
+ level: msg.type(),
660
+ stdout: msg.text(),
661
+ location: toLocation(msg.location()),
662
+ timestamp: Date.now()
663
+ };
664
+ browserConsoleLogs.push(entry);
665
+ if (normalizedPlaywrightOptions.onEvent) {
666
+ normalizedPlaywrightOptions.onEvent({
667
+ type: "browserConsoleLog",
668
+ ...entry
669
+ });
670
+ }
671
+ if (normalizedPlaywrightOptions.console && options.console?.onEntry) {
672
+ options.console.onEntry({
673
+ type: "browserOutput",
674
+ ...entry
675
+ });
676
+ } else if (normalizedPlaywrightOptions.console) {
677
+ const prefix = entry.level === "error" ? "[browser:error]" : "[browser]";
678
+ console.log(prefix, entry.stdout);
679
+ }
680
+ };
681
+ const onRequest = (request2) => {
682
+ const info = {
683
+ requestId: getRequestId(request2),
684
+ url: request2.url(),
685
+ method: request2.method(),
686
+ headers: request2.headers(),
687
+ postData: request2.postData() ?? undefined,
688
+ resourceType: request2.resourceType(),
689
+ timestamp: Date.now()
690
+ };
691
+ networkRequests.push(info);
692
+ if (normalizedPlaywrightOptions.onEvent) {
693
+ normalizedPlaywrightOptions.onEvent({
694
+ type: "networkRequest",
695
+ ...info
696
+ });
697
+ }
698
+ };
699
+ const onResponse = (response) => {
700
+ const request2 = response.request();
701
+ const info = {
702
+ requestId: getRequestId(request2),
703
+ url: response.url(),
704
+ status: response.status(),
705
+ statusText: response.statusText(),
706
+ headers: response.headers(),
707
+ resourceType: request2.resourceType(),
708
+ timestamp: Date.now()
709
+ };
710
+ networkResponses.push(info);
711
+ if (normalizedPlaywrightOptions.onEvent) {
712
+ normalizedPlaywrightOptions.onEvent({
713
+ type: "networkResponse",
714
+ ...info
715
+ });
716
+ }
717
+ };
718
+ const onRequestFailed = (request2) => {
719
+ const info = {
720
+ requestId: getRequestId(request2),
721
+ url: request2.url(),
722
+ method: request2.method(),
723
+ failureText: request2.failure()?.errorText || "request failed",
724
+ resourceType: request2.resourceType(),
725
+ timestamp: Date.now()
726
+ };
727
+ requestFailures.push(info);
728
+ if (normalizedPlaywrightOptions.onEvent) {
729
+ normalizedPlaywrightOptions.onEvent({
730
+ type: "requestFailure",
731
+ ...info
732
+ });
733
+ }
734
+ };
735
+ const onPageError = (error) => {
736
+ const entry = {
737
+ name: error.name,
738
+ message: error.message,
739
+ stack: error.stack,
740
+ timestamp: Date.now()
741
+ };
742
+ pageErrors.push(entry);
743
+ if (normalizedPlaywrightOptions.onEvent) {
744
+ normalizedPlaywrightOptions.onEvent({
745
+ type: "pageError",
746
+ ...entry
747
+ });
748
+ }
749
+ };
750
+ page.on("console", onConsole);
751
+ page.on("request", onRequest);
752
+ page.on("response", onResponse);
753
+ page.on("requestfailed", onRequestFailed);
754
+ page.on("pageerror", onPageError);
755
+ pageListenerCleanups.push(() => page.removeListener("console", onConsole), () => page.removeListener("request", onRequest), () => page.removeListener("response", onResponse), () => page.removeListener("requestfailed", onRequestFailed), () => page.removeListener("pageerror", onPageError));
756
+ }
757
+ callbacks.playwright = {
758
+ handlerCallbackId,
759
+ console: normalizedPlaywrightOptions.console && !options.console?.onEntry
760
+ };
761
+ }
762
+ let testEnvironmentOption;
763
+ if (options.testEnvironment) {
764
+ if (typeof options.testEnvironment === "object") {
765
+ const testEnvOptions = options.testEnvironment;
766
+ const testEnvCallbacks = {};
767
+ if (testEnvOptions.onEvent) {
768
+ const userOnEvent = testEnvOptions.onEvent;
769
+ const onEventCallbackId = registerEventCallback(state, (eventJson) => {
770
+ const event = JSON.parse(eventJson);
771
+ userOnEvent(event);
772
+ });
773
+ testEnvCallbacks.onEvent = {
774
+ callbackId: onEventCallbackId,
775
+ name: "testEnvironment.onEvent",
776
+ type: "sync"
777
+ };
778
+ }
779
+ testEnvironmentOption = {
780
+ callbacks: testEnvCallbacks,
781
+ testTimeout: testEnvOptions.testTimeout
782
+ };
783
+ } else {
784
+ testEnvironmentOption = true;
785
+ }
786
+ }
787
+ const playwrightOption = normalizedPlaywrightOptions?.timeout !== undefined ? { timeout: normalizedPlaywrightOptions.timeout } : undefined;
788
+ const requestId = state.nextRequestId++;
789
+ const request = {
790
+ type: import_protocol.MessageType.CREATE_RUNTIME,
791
+ requestId,
792
+ options: {
793
+ memoryLimitMB: options.memoryLimitMB,
794
+ executionTimeout: options.executionTimeout,
795
+ cwd: options.cwd,
796
+ callbacks,
797
+ testEnvironment: testEnvironmentOption,
798
+ playwright: playwrightOption,
799
+ namespaceId
800
+ }
801
+ };
802
+ const result = await sendRequest(state, request);
803
+ const isolateId = result.isolateId;
804
+ const reused = result.reused ?? false;
805
+ if (namespaceId != null) {
806
+ state.namespacedRuntimes.set(namespaceId, {
807
+ isolateId,
808
+ runtimeOptions: runtimeOptionsForReconnect
809
+ });
810
+ }
811
+ const wsCommandCallbacks = new Set;
812
+ isolateWsCallbacks.set(isolateId, wsCommandCallbacks);
813
+ if (options.onWebSocketCommand) {
814
+ wsCommandCallbacks.add(options.onWebSocketCommand);
815
+ }
816
+ if (options.webSocket) {
817
+ isolateWebSocketCallbacks.set(isolateId, options.webSocket);
818
+ }
819
+ const fetchHandle = {
820
+ async dispatchRequest(req, opts) {
821
+ const signal = opts?.signal;
822
+ const requestSignal = req.signal;
823
+ const requestSignalInitiallyAborted = requestSignal?.aborted ?? false;
824
+ const reqId = state.nextRequestId++;
825
+ const serialized = await serializeRequestWithStreaming(state, req);
826
+ const { bodyStream, ...serializableRequest } = serialized;
827
+ const request2 = {
828
+ type: import_protocol.MessageType.DISPATCH_REQUEST,
829
+ requestId: reqId,
830
+ isolateId,
831
+ request: serializableRequest,
832
+ context: opts?.requestId || opts?.metadata ? {
833
+ requestId: opts.requestId,
834
+ metadata: opts.metadata
835
+ } : undefined
836
+ };
837
+ const handleResponse = (res) => {
838
+ if (res.__streaming && res.response instanceof Response) {
839
+ return res.response;
840
+ }
841
+ return import_protocol.deserializeResponse(res.response);
842
+ };
843
+ let abortSent = false;
844
+ const sendAbort = () => {
845
+ if (abortSent) {
846
+ return;
847
+ }
848
+ abortSent = true;
849
+ const abortMessage = {
850
+ type: import_protocol.MessageType.DISPATCH_REQUEST_ABORT,
851
+ isolateId,
852
+ targetRequestId: reqId
853
+ };
854
+ if (state.connected) {
855
+ sendMessage(state.socket, abortMessage);
856
+ }
857
+ };
858
+ let onAbort;
859
+ if (signal) {
860
+ onAbort = sendAbort;
861
+ signal.addEventListener("abort", onAbort, { once: true });
862
+ if (signal.aborted) {
863
+ sendAbort();
864
+ }
865
+ }
866
+ let onRequestAbort;
867
+ if (requestSignal && !requestSignalInitiallyAborted) {
868
+ onRequestAbort = sendAbort;
869
+ requestSignal.addEventListener("abort", onRequestAbort, { once: true });
870
+ if (requestSignal.aborted) {
871
+ sendAbort();
872
+ }
873
+ }
874
+ request2.request.signalAborted = (request2.request.signalAborted ?? false) || signal?.aborted === true;
875
+ try {
876
+ if (serialized.bodyStreamId !== undefined && bodyStream) {
877
+ const streamId = serialized.bodyStreamId;
878
+ const responsePromise = sendRequest(state, request2);
879
+ await sendBodyStream(state, streamId, bodyStream);
880
+ const res = await responsePromise;
881
+ return handleResponse(res);
882
+ } else {
883
+ const res = await sendRequest(state, request2);
884
+ return handleResponse(res);
885
+ }
886
+ } finally {
887
+ if (signal && onAbort) {
888
+ signal.removeEventListener("abort", onAbort);
889
+ }
890
+ if (requestSignal && onRequestAbort) {
891
+ requestSignal.removeEventListener("abort", onRequestAbort);
892
+ }
893
+ }
894
+ },
895
+ async getUpgradeRequest() {
896
+ const reqId = state.nextRequestId++;
897
+ const req = {
898
+ type: import_protocol.MessageType.FETCH_GET_UPGRADE_REQUEST,
899
+ requestId: reqId,
900
+ isolateId
901
+ };
902
+ return sendRequest(state, req);
903
+ },
904
+ async dispatchWebSocketOpen(connectionId) {
905
+ const reqId = state.nextRequestId++;
906
+ const req = {
907
+ type: import_protocol.MessageType.WS_OPEN,
908
+ requestId: reqId,
909
+ isolateId,
910
+ connectionId
911
+ };
912
+ await sendRequest(state, req);
913
+ },
914
+ async dispatchWebSocketMessage(connectionId, message) {
915
+ const reqId = state.nextRequestId++;
916
+ const data = message instanceof ArrayBuffer ? new Uint8Array(message) : message;
917
+ const req = {
918
+ type: import_protocol.MessageType.WS_MESSAGE,
919
+ requestId: reqId,
920
+ isolateId,
921
+ connectionId,
922
+ data
923
+ };
924
+ await sendRequest(state, req);
925
+ },
926
+ async dispatchWebSocketClose(connectionId, code, reason) {
927
+ const reqId = state.nextRequestId++;
928
+ const req = {
929
+ type: import_protocol.MessageType.WS_CLOSE,
930
+ requestId: reqId,
931
+ isolateId,
932
+ connectionId,
933
+ code,
934
+ reason
935
+ };
936
+ await sendRequest(state, req);
937
+ },
938
+ async dispatchWebSocketError(connectionId, error) {
939
+ const reqId = state.nextRequestId++;
940
+ const req = {
941
+ type: import_protocol.MessageType.FETCH_WS_ERROR,
942
+ requestId: reqId,
943
+ isolateId,
944
+ connectionId,
945
+ error: error.message
946
+ };
947
+ await sendRequest(state, req);
948
+ },
949
+ onWebSocketCommand(callback) {
950
+ wsCommandCallbacks.add(callback);
951
+ return () => {
952
+ wsCommandCallbacks.delete(callback);
953
+ };
954
+ },
955
+ async hasServeHandler() {
956
+ const reqId = state.nextRequestId++;
957
+ const req = {
958
+ type: import_protocol.MessageType.FETCH_HAS_SERVE_HANDLER,
959
+ requestId: reqId,
960
+ isolateId
961
+ };
962
+ return sendRequest(state, req);
963
+ },
964
+ async hasActiveConnections() {
965
+ const reqId = state.nextRequestId++;
966
+ const req = {
967
+ type: import_protocol.MessageType.FETCH_HAS_ACTIVE_CONNECTIONS,
968
+ requestId: reqId,
969
+ isolateId
970
+ };
971
+ return sendRequest(state, req);
972
+ }
973
+ };
974
+ const timersHandle = {
975
+ async clearAll() {
976
+ const reqId = state.nextRequestId++;
977
+ const req = {
978
+ type: import_protocol.MessageType.TIMERS_CLEAR_ALL,
979
+ requestId: reqId,
980
+ isolateId
981
+ };
982
+ await sendRequest(state, req);
983
+ }
984
+ };
985
+ const consoleHandle = {
986
+ async reset() {
987
+ const reqId = state.nextRequestId++;
988
+ const req = {
989
+ type: import_protocol.MessageType.CONSOLE_RESET,
990
+ requestId: reqId,
991
+ isolateId
992
+ };
993
+ await sendRequest(state, req);
994
+ },
995
+ async getTimers() {
996
+ const reqId = state.nextRequestId++;
997
+ const req = {
998
+ type: import_protocol.MessageType.CONSOLE_GET_TIMERS,
999
+ requestId: reqId,
1000
+ isolateId
1001
+ };
1002
+ const result2 = await sendRequest(state, req);
1003
+ return new Map(Object.entries(result2));
1004
+ },
1005
+ async getCounters() {
1006
+ const reqId = state.nextRequestId++;
1007
+ const req = {
1008
+ type: import_protocol.MessageType.CONSOLE_GET_COUNTERS,
1009
+ requestId: reqId,
1010
+ isolateId
1011
+ };
1012
+ const result2 = await sendRequest(state, req);
1013
+ return new Map(Object.entries(result2));
1014
+ },
1015
+ async getGroupDepth() {
1016
+ const reqId = state.nextRequestId++;
1017
+ const req = {
1018
+ type: import_protocol.MessageType.CONSOLE_GET_GROUP_DEPTH,
1019
+ requestId: reqId,
1020
+ isolateId
1021
+ };
1022
+ return sendRequest(state, req);
1023
+ }
1024
+ };
1025
+ const testEnvironmentEnabled = !!options.testEnvironment;
1026
+ const playwrightEnabled = !!normalizedPlaywrightOptions;
1027
+ const testEnvironmentHandle = {
1028
+ async runTests(timeout) {
1029
+ if (!testEnvironmentEnabled) {
1030
+ throw new Error("Test environment not enabled. Set testEnvironment: true in createRuntime options.");
1031
+ }
1032
+ const reqId = state.nextRequestId++;
1033
+ const req = {
1034
+ type: import_protocol.MessageType.RUN_TESTS,
1035
+ requestId: reqId,
1036
+ isolateId,
1037
+ timeout
1038
+ };
1039
+ try {
1040
+ return await sendRequest(state, req);
1041
+ } catch (err) {
1042
+ if (err instanceof Error && /connection closed|not connected/i.test(err.message) && state.reconnecting) {
1043
+ await state.reconnecting;
1044
+ const retryReqId = state.nextRequestId++;
1045
+ const retryReq = {
1046
+ type: import_protocol.MessageType.RUN_TESTS,
1047
+ requestId: retryReqId,
1048
+ isolateId,
1049
+ timeout
1050
+ };
1051
+ return sendRequest(state, retryReq);
1052
+ }
1053
+ throw err;
1054
+ }
1055
+ },
1056
+ async hasTests() {
1057
+ if (!testEnvironmentEnabled) {
1058
+ throw new Error("Test environment not enabled. Set testEnvironment: true in createRuntime options.");
1059
+ }
1060
+ const reqId = state.nextRequestId++;
1061
+ const req = {
1062
+ type: import_protocol.MessageType.HAS_TESTS,
1063
+ requestId: reqId,
1064
+ isolateId
1065
+ };
1066
+ return sendRequest(state, req);
1067
+ },
1068
+ async getTestCount() {
1069
+ if (!testEnvironmentEnabled) {
1070
+ throw new Error("Test environment not enabled. Set testEnvironment: true in createRuntime options.");
1071
+ }
1072
+ const reqId = state.nextRequestId++;
1073
+ const req = {
1074
+ type: import_protocol.MessageType.GET_TEST_COUNT,
1075
+ requestId: reqId,
1076
+ isolateId
1077
+ };
1078
+ return sendRequest(state, req);
1079
+ },
1080
+ async reset() {
1081
+ if (!testEnvironmentEnabled) {
1082
+ throw new Error("Test environment not enabled. Set testEnvironment: true in createRuntime options.");
1083
+ }
1084
+ const reqId = state.nextRequestId++;
1085
+ const req = {
1086
+ type: import_protocol.MessageType.RESET_TEST_ENV,
1087
+ requestId: reqId,
1088
+ isolateId
1089
+ };
1090
+ await sendRequest(state, req);
1091
+ }
1092
+ };
1093
+ const playwrightHandle = {
1094
+ getCollectedData() {
1095
+ if (!playwrightEnabled) {
1096
+ throw new Error("Playwright not configured. Provide playwright.handler in createRuntime options.");
1097
+ }
1098
+ return {
1099
+ browserConsoleLogs: [...browserConsoleLogs],
1100
+ pageErrors: [...pageErrors],
1101
+ networkRequests: [...networkRequests],
1102
+ networkResponses: [...networkResponses],
1103
+ requestFailures: [...requestFailures]
1104
+ };
1105
+ },
1106
+ clearCollectedData() {
1107
+ if (!playwrightEnabled) {
1108
+ throw new Error("Playwright not configured. Provide playwright.handler in createRuntime options.");
1109
+ }
1110
+ browserConsoleLogs.length = 0;
1111
+ pageErrors.length = 0;
1112
+ networkRequests.length = 0;
1113
+ networkResponses.length = 0;
1114
+ requestFailures.length = 0;
1115
+ }
1116
+ };
1117
+ return {
1118
+ id: isolateId,
1119
+ reused,
1120
+ fetch: fetchHandle,
1121
+ timers: timersHandle,
1122
+ console: consoleHandle,
1123
+ testEnvironment: testEnvironmentHandle,
1124
+ playwright: playwrightHandle,
1125
+ eval: async (code, filenameOrOptions) => {
1126
+ const reqId = state.nextRequestId++;
1127
+ const options2 = typeof filenameOrOptions === "string" ? { filename: filenameOrOptions } : filenameOrOptions;
1128
+ const req = {
1129
+ type: import_protocol.MessageType.EVAL,
1130
+ requestId: reqId,
1131
+ isolateId,
1132
+ code,
1133
+ filename: options2?.filename,
1134
+ executionTimeout: options2?.executionTimeout
1135
+ };
1136
+ await sendRequest(state, req);
1137
+ },
1138
+ on(event, callback) {
1139
+ let listeners = isolateEventListeners.get(isolateId);
1140
+ if (!listeners) {
1141
+ listeners = new Map;
1142
+ isolateEventListeners.set(isolateId, listeners);
1143
+ }
1144
+ let eventListeners = listeners.get(event);
1145
+ if (!eventListeners) {
1146
+ eventListeners = new Set;
1147
+ listeners.set(event, eventListeners);
1148
+ }
1149
+ eventListeners.add(callback);
1150
+ return () => {
1151
+ eventListeners.delete(callback);
1152
+ if (eventListeners.size === 0) {
1153
+ listeners.delete(event);
1154
+ if (listeners.size === 0) {
1155
+ isolateEventListeners.delete(isolateId);
1156
+ }
1157
+ }
1158
+ };
1159
+ },
1160
+ emit(event, payload) {
1161
+ sendMessage(state.socket, {
1162
+ type: import_protocol.MessageType.CLIENT_EVENT,
1163
+ isolateId,
1164
+ event,
1165
+ payload
1166
+ });
1167
+ },
1168
+ dispose: async (options2) => {
1169
+ for (const cleanup of pageListenerCleanups) {
1170
+ cleanup();
1171
+ }
1172
+ isolateWsCallbacks.delete(isolateId);
1173
+ isolateWebSocketCallbacks.delete(isolateId);
1174
+ isolateEventListeners.delete(isolateId);
1175
+ const clientSockets = isolateClientWebSockets.get(isolateId);
1176
+ if (clientSockets) {
1177
+ for (const ws of clientSockets.values()) {
1178
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
1179
+ ws.close(1000, "Isolate disposed");
1180
+ }
1181
+ }
1182
+ isolateClientWebSockets.delete(isolateId);
1183
+ }
1184
+ if (namespaceId != null) {
1185
+ state.namespacedRuntimes.delete(namespaceId);
1186
+ }
1187
+ const reqId = state.nextRequestId++;
1188
+ const req = {
1189
+ type: import_protocol.MessageType.DISPOSE_RUNTIME,
1190
+ requestId: reqId,
1191
+ isolateId,
1192
+ hard: options2?.hard === true ? true : undefined,
1193
+ reason: typeof options2?.reason === "string" && options2.reason.length > 0 ? options2.reason : undefined
1194
+ };
1195
+ try {
1196
+ await sendRequest(state, req);
1197
+ } catch (error) {
1198
+ if (!isBenignDisposeError(error)) {
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ }
1203
+ };
1204
+ }
1205
+ function registerEventCallback(state, handler) {
1206
+ const callbackId = state.nextCallbackId++;
1207
+ state.callbacks.set(callbackId, (data) => {
1208
+ handler(data);
1209
+ return;
1210
+ });
1211
+ return callbackId;
1212
+ }
1213
+ function registerConsoleCallbacks(state, callbacks) {
1214
+ const registrations = {};
1215
+ if (callbacks.onEntry) {
1216
+ const callbackId = state.nextCallbackId++;
1217
+ state.callbacks.set(callbackId, (entry) => {
1218
+ callbacks.onEntry(entry);
1219
+ });
1220
+ registrations.onEntry = { callbackId, name: "onEntry", type: "sync" };
1221
+ }
1222
+ return registrations;
1223
+ }
1224
+ var CALLBACK_STREAM_THRESHOLD = 64 * 1024;
1225
+ var NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
1226
+ function registerFetchCallback(state, callback) {
1227
+ const callbackId = state.nextCallbackId++;
1228
+ state.callbacksNeedingRequestId.add(callbackId);
1229
+ state.callbacks.set(callbackId, async (serialized, requestId) => {
1230
+ const data = serialized;
1231
+ const requestContext = import_request_context.getRequestContext();
1232
+ const signalController = new AbortController;
1233
+ const onContextAbort = () => {
1234
+ if (!signalController.signal.aborted) {
1235
+ signalController.abort(requestContext.signal?.reason ?? Object.assign(new Error("The operation was aborted."), {
1236
+ name: "AbortError"
1237
+ }));
1238
+ }
1239
+ };
1240
+ if (requestContext.signal) {
1241
+ requestContext.signal.addEventListener("abort", onContextAbort, {
1242
+ once: true
1243
+ });
1244
+ if (requestContext.signal.aborted) {
1245
+ onContextAbort();
1246
+ }
1247
+ }
1248
+ if (data.signalAborted) {
1249
+ signalController.abort();
1250
+ }
1251
+ try {
1252
+ const init = {
1253
+ method: data.method,
1254
+ headers: data.headers,
1255
+ rawBody: data.body ?? null,
1256
+ body: data.body ?? null,
1257
+ signal: signalController.signal
1258
+ };
1259
+ const response = await callback(data.url, init);
1260
+ const contentLength = response.headers.get("content-length");
1261
+ const knownSize = contentLength ? parseInt(contentLength, 10) : null;
1262
+ const isNetworkResponse = response.url && (response.url.startsWith("http://") || response.url.startsWith("https://"));
1263
+ const shouldStream = isNetworkResponse && !NULL_BODY_STATUSES.has(response.status) && !!response.body && (knownSize === null || knownSize > CALLBACK_STREAM_THRESHOLD);
1264
+ if (shouldStream && response.body) {
1265
+ const streamId = state.nextStreamId++;
1266
+ const headers = [];
1267
+ response.headers.forEach((value, key) => {
1268
+ headers.push([key, value]);
1269
+ });
1270
+ sendMessage(state.socket, {
1271
+ type: import_protocol.MessageType.CALLBACK_STREAM_START,
1272
+ requestId,
1273
+ streamId,
1274
+ metadata: {
1275
+ status: response.status,
1276
+ statusText: response.statusText,
1277
+ headers,
1278
+ url: response.url || undefined
1279
+ }
1280
+ });
1281
+ streamCallbackResponseBody(state, streamId, requestId, response.body);
1282
+ return { __callbackStreaming: true, streamId };
1283
+ }
1284
+ return import_protocol.serializeResponse(response);
1285
+ } finally {
1286
+ if (requestContext.signal) {
1287
+ requestContext.signal.removeEventListener("abort", onContextAbort);
1288
+ }
1289
+ }
1290
+ });
1291
+ return { callbackId, name: "fetch", type: "async" };
1292
+ }
1293
+ async function streamCallbackResponseBody(state, streamId, requestId, body) {
1294
+ const reader = body.getReader();
1295
+ state.callbackStreamReaders.set(streamId, reader);
1296
+ try {
1297
+ while (true) {
1298
+ const { done, value } = await reader.read();
1299
+ if (done) {
1300
+ sendMessage(state.socket, {
1301
+ type: import_protocol.MessageType.CALLBACK_STREAM_END,
1302
+ requestId,
1303
+ streamId
1304
+ });
1305
+ break;
1306
+ }
1307
+ for (let offset = 0;offset < value.length; offset += import_protocol.STREAM_CHUNK_SIZE) {
1308
+ const chunk = value.slice(offset, offset + import_protocol.STREAM_CHUNK_SIZE);
1309
+ sendMessage(state.socket, {
1310
+ type: import_protocol.MessageType.CALLBACK_STREAM_CHUNK,
1311
+ requestId,
1312
+ streamId,
1313
+ chunk
1314
+ });
1315
+ }
1316
+ }
1317
+ } catch (err) {
1318
+ if (!(err instanceof Error && err.message.includes("cancel"))) {
1319
+ sendMessage(state.socket, {
1320
+ type: import_protocol.MessageType.STREAM_ERROR,
1321
+ streamId,
1322
+ error: err.message
1323
+ });
1324
+ }
1325
+ } finally {
1326
+ state.callbackStreamReaders.delete(streamId);
1327
+ reader.releaseLock();
1328
+ }
1329
+ }
1330
+ function registerFsCallbacks(state, callbacks) {
1331
+ const registrations = {};
1332
+ if (callbacks.readFile) {
1333
+ const callbackId = state.nextCallbackId++;
1334
+ state.callbacks.set(callbackId, async (path2) => {
1335
+ const result = await callbacks.readFile(path2);
1336
+ return new Uint8Array(result);
1337
+ });
1338
+ registrations.readFile = { callbackId, name: "readFile", type: "async" };
1339
+ }
1340
+ if (callbacks.writeFile) {
1341
+ const callbackId = state.nextCallbackId++;
1342
+ state.callbacks.set(callbackId, async (path2, data) => {
1343
+ let buffer;
1344
+ if (data instanceof Uint8Array) {
1345
+ buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
1346
+ } else if (Array.isArray(data)) {
1347
+ buffer = new Uint8Array(data).buffer;
1348
+ } else if (data instanceof ArrayBuffer) {
1349
+ buffer = data;
1350
+ } else {
1351
+ buffer = new ArrayBuffer(0);
1352
+ }
1353
+ await callbacks.writeFile(path2, buffer);
1354
+ });
1355
+ registrations.writeFile = { callbackId, name: "writeFile", type: "async" };
1356
+ }
1357
+ if (callbacks.unlink) {
1358
+ const callbackId = state.nextCallbackId++;
1359
+ state.callbacks.set(callbackId, async (path2) => {
1360
+ await callbacks.unlink(path2);
1361
+ });
1362
+ registrations.unlink = { callbackId, name: "unlink", type: "async" };
1363
+ }
1364
+ if (callbacks.readdir) {
1365
+ const callbackId = state.nextCallbackId++;
1366
+ state.callbacks.set(callbackId, async (path2) => {
1367
+ return callbacks.readdir(path2);
1368
+ });
1369
+ registrations.readdir = { callbackId, name: "readdir", type: "async" };
1370
+ }
1371
+ if (callbacks.mkdir) {
1372
+ const callbackId = state.nextCallbackId++;
1373
+ state.callbacks.set(callbackId, async (path2, options) => {
1374
+ await callbacks.mkdir(path2, options);
1375
+ });
1376
+ registrations.mkdir = { callbackId, name: "mkdir", type: "async" };
1377
+ }
1378
+ if (callbacks.rmdir) {
1379
+ const callbackId = state.nextCallbackId++;
1380
+ state.callbacks.set(callbackId, async (path2) => {
1381
+ await callbacks.rmdir(path2);
1382
+ });
1383
+ registrations.rmdir = { callbackId, name: "rmdir", type: "async" };
1384
+ }
1385
+ if (callbacks.stat) {
1386
+ const callbackId = state.nextCallbackId++;
1387
+ state.callbacks.set(callbackId, async (path2) => {
1388
+ return callbacks.stat(path2);
1389
+ });
1390
+ registrations.stat = { callbackId, name: "stat", type: "async" };
1391
+ }
1392
+ if (callbacks.rename) {
1393
+ const callbackId = state.nextCallbackId++;
1394
+ state.callbacks.set(callbackId, async (from, to) => {
1395
+ await callbacks.rename(from, to);
1396
+ });
1397
+ registrations.rename = { callbackId, name: "rename", type: "async" };
1398
+ }
1399
+ return registrations;
1400
+ }
1401
+ function registerModuleLoaderCallback(state, callback) {
1402
+ const callbackId = state.nextCallbackId++;
1403
+ state.callbacks.set(callbackId, async (moduleName, importer) => {
1404
+ const specifier = moduleName;
1405
+ const importerInfo = importer;
1406
+ const result = await callback(specifier, importerInfo);
1407
+ const resolvedPath = import_node_path.default.posix.join(result.resolveDir, result.filename);
1408
+ state.moduleSourceCache.set(resolvedPath, result.code);
1409
+ return result;
1410
+ });
1411
+ return { callbackId, name: "moduleLoader", type: "async" };
1412
+ }
1413
+ var clientIteratorSessions = new Map;
1414
+ var nextClientIteratorId = 1;
1415
+ var returnedPromiseRegistry = new Map;
1416
+ var returnedIteratorRegistry = new Map;
1417
+ function registerCustomFunctions(state, customFunctions) {
1418
+ const registrations = {};
1419
+ for (const [name, def] of Object.entries(customFunctions)) {
1420
+ if (def.type === "asyncIterator") {
1421
+ const startCallbackId = state.nextCallbackId++;
1422
+ state.callbacks.set(startCallbackId, async (...args) => {
1423
+ try {
1424
+ const fn = def.fn;
1425
+ const iterator = fn(...args);
1426
+ const iteratorId = nextClientIteratorId++;
1427
+ clientIteratorSessions.set(iteratorId, { iterator });
1428
+ return { iteratorId };
1429
+ } catch (error) {
1430
+ throw error;
1431
+ }
1432
+ });
1433
+ const nextCallbackId = state.nextCallbackId++;
1434
+ state.callbacks.set(nextCallbackId, async (iteratorId) => {
1435
+ const session = clientIteratorSessions.get(iteratorId);
1436
+ if (!session) {
1437
+ throw new Error(`Iterator session ${iteratorId} not found`);
1438
+ }
1439
+ try {
1440
+ const result = await session.iterator.next();
1441
+ if (result.done) {
1442
+ clientIteratorSessions.delete(iteratorId);
1443
+ }
1444
+ return { done: result.done, value: await import_protocol.marshalValue(result.value) };
1445
+ } catch (error) {
1446
+ clientIteratorSessions.delete(iteratorId);
1447
+ throw error;
1448
+ }
1449
+ });
1450
+ const returnCallbackId = state.nextCallbackId++;
1451
+ state.callbacks.set(returnCallbackId, async (iteratorId, value) => {
1452
+ const session = clientIteratorSessions.get(iteratorId);
1453
+ if (!session) {
1454
+ return { done: true, value: await import_protocol.marshalValue(undefined) };
1455
+ }
1456
+ try {
1457
+ const result = await session.iterator.return?.(value);
1458
+ clientIteratorSessions.delete(iteratorId);
1459
+ return { done: true, value: await import_protocol.marshalValue(result?.value) };
1460
+ } catch (error) {
1461
+ clientIteratorSessions.delete(iteratorId);
1462
+ throw error;
1463
+ }
1464
+ });
1465
+ const throwCallbackId = state.nextCallbackId++;
1466
+ state.callbacks.set(throwCallbackId, async (iteratorId, errorData) => {
1467
+ const session = clientIteratorSessions.get(iteratorId);
1468
+ if (!session) {
1469
+ throw new Error(`Iterator session ${iteratorId} not found`);
1470
+ }
1471
+ try {
1472
+ const errInfo = errorData;
1473
+ const error = Object.assign(new Error(errInfo.message), { name: errInfo.name });
1474
+ const result = await session.iterator.throw?.(error);
1475
+ clientIteratorSessions.delete(iteratorId);
1476
+ return { done: result?.done ?? true, value: await import_protocol.marshalValue(result?.value) };
1477
+ } catch (error) {
1478
+ clientIteratorSessions.delete(iteratorId);
1479
+ throw error;
1480
+ }
1481
+ });
1482
+ registrations[`${name}:start`] = { callbackId: startCallbackId, name: `${name}:start`, type: "async" };
1483
+ registrations[`${name}:next`] = { callbackId: nextCallbackId, name: `${name}:next`, type: "async" };
1484
+ registrations[`${name}:return`] = { callbackId: returnCallbackId, name: `${name}:return`, type: "async" };
1485
+ registrations[`${name}:throw`] = { callbackId: throwCallbackId, name: `${name}:throw`, type: "async" };
1486
+ registrations[name] = {
1487
+ callbackId: startCallbackId,
1488
+ name,
1489
+ type: "asyncIterator"
1490
+ };
1491
+ } else {
1492
+ const callbackId = state.nextCallbackId++;
1493
+ state.callbacks.set(callbackId, async (...args) => {
1494
+ const result = await def.fn(...args);
1495
+ const addCallbackIdsToRefs = (value) => {
1496
+ if (value === null || typeof value !== "object") {
1497
+ return value;
1498
+ }
1499
+ if (import_protocol.isPromiseRef(value)) {
1500
+ const resolveCallbackId = state.nextCallbackId++;
1501
+ state.callbacks.set(resolveCallbackId, async (...args2) => {
1502
+ const promiseId = args2[0];
1503
+ const promise = returnedPromiseRegistry.get(promiseId);
1504
+ if (!promise) {
1505
+ throw new Error(`Promise ${promiseId} not found`);
1506
+ }
1507
+ const promiseResult = await promise;
1508
+ returnedPromiseRegistry.delete(promiseId);
1509
+ const marshalledResult = await import_protocol.marshalValue(promiseResult, marshalCtx);
1510
+ return addCallbackIdsToRefs(marshalledResult);
1511
+ });
1512
+ return {
1513
+ ...value,
1514
+ __resolveCallbackId: resolveCallbackId
1515
+ };
1516
+ }
1517
+ if (import_protocol.isAsyncIteratorRef(value)) {
1518
+ const nextCallbackId = state.nextCallbackId++;
1519
+ state.callbacks.set(nextCallbackId, async (...args2) => {
1520
+ const iteratorId = args2[0];
1521
+ const iterator = returnedIteratorRegistry.get(iteratorId);
1522
+ if (!iterator) {
1523
+ throw new Error(`Iterator ${iteratorId} not found`);
1524
+ }
1525
+ const iterResult = await iterator.next();
1526
+ if (iterResult.done) {
1527
+ returnedIteratorRegistry.delete(iteratorId);
1528
+ }
1529
+ const marshalledValue = await import_protocol.marshalValue(iterResult.value, marshalCtx);
1530
+ return {
1531
+ done: iterResult.done,
1532
+ value: addCallbackIdsToRefs(marshalledValue)
1533
+ };
1534
+ });
1535
+ const returnCallbackId = state.nextCallbackId++;
1536
+ state.callbacks.set(returnCallbackId, async (...args2) => {
1537
+ const iteratorId = args2[0];
1538
+ const returnValue = args2[1];
1539
+ const iterator = returnedIteratorRegistry.get(iteratorId);
1540
+ returnedIteratorRegistry.delete(iteratorId);
1541
+ if (!iterator || !iterator.return) {
1542
+ return { done: true, value: undefined };
1543
+ }
1544
+ const iterResult = await iterator.return(returnValue);
1545
+ const marshalledValue = await import_protocol.marshalValue(iterResult.value, marshalCtx);
1546
+ return {
1547
+ done: true,
1548
+ value: addCallbackIdsToRefs(marshalledValue)
1549
+ };
1550
+ });
1551
+ const throwCallbackId = state.nextCallbackId++;
1552
+ state.callbacks.set(throwCallbackId, async (...args2) => {
1553
+ const iteratorId = args2[0];
1554
+ const errorValue = args2[1];
1555
+ const iterator = returnedIteratorRegistry.get(iteratorId);
1556
+ if (!iterator) {
1557
+ throw new Error(`Iterator ${iteratorId} not found`);
1558
+ }
1559
+ try {
1560
+ if (!iterator.throw) {
1561
+ throw Object.assign(new Error(errorValue?.message ?? "Iterator does not support throw()"), { name: errorValue?.name ?? "Error", stack: errorValue?.stack });
1562
+ }
1563
+ const thrownError = Object.assign(new Error(errorValue?.message ?? "Iterator throw()"), { name: errorValue?.name ?? "Error", stack: errorValue?.stack });
1564
+ const iterResult = await iterator.throw(thrownError);
1565
+ if (iterResult.done) {
1566
+ returnedIteratorRegistry.delete(iteratorId);
1567
+ }
1568
+ const marshalledValue = await import_protocol.marshalValue(iterResult.value, marshalCtx);
1569
+ return {
1570
+ done: iterResult.done,
1571
+ value: addCallbackIdsToRefs(marshalledValue)
1572
+ };
1573
+ } catch (error) {
1574
+ returnedIteratorRegistry.delete(iteratorId);
1575
+ throw error;
1576
+ }
1577
+ });
1578
+ return {
1579
+ ...value,
1580
+ __nextCallbackId: nextCallbackId,
1581
+ __returnCallbackId: returnCallbackId,
1582
+ __throwCallbackId: throwCallbackId
1583
+ };
1584
+ }
1585
+ if (Array.isArray(value)) {
1586
+ return value.map((item) => addCallbackIdsToRefs(item));
1587
+ }
1588
+ const objResult = {};
1589
+ for (const key of Object.keys(value)) {
1590
+ objResult[key] = addCallbackIdsToRefs(value[key]);
1591
+ }
1592
+ return objResult;
1593
+ };
1594
+ const marshalCtx = {
1595
+ registerCallback: (fn) => {
1596
+ const returnedCallbackId = state.nextCallbackId++;
1597
+ state.callbacks.set(returnedCallbackId, async (...args2) => {
1598
+ const fnResult = await fn(...args2);
1599
+ const marshalledResult = await import_protocol.marshalValue(fnResult, marshalCtx);
1600
+ return addCallbackIdsToRefs(marshalledResult);
1601
+ });
1602
+ return returnedCallbackId;
1603
+ },
1604
+ registerPromise: (promise) => {
1605
+ const promiseId = state.nextCallbackId++;
1606
+ returnedPromiseRegistry.set(promiseId, promise);
1607
+ return promiseId;
1608
+ },
1609
+ registerIterator: (iterator) => {
1610
+ const iteratorId = state.nextCallbackId++;
1611
+ returnedIteratorRegistry.set(iteratorId, iterator);
1612
+ return iteratorId;
1613
+ }
1614
+ };
1615
+ const marshalled = await import_protocol.marshalValue(result, marshalCtx);
1616
+ const withCallbackIds = addCallbackIdsToRefs(marshalled);
1617
+ return withCallbackIds;
1618
+ });
1619
+ registrations[name] = {
1620
+ callbackId,
1621
+ name,
1622
+ type: def.type
1623
+ };
1624
+ }
1625
+ }
1626
+ return registrations;
1627
+ }
1628
+ async function serializeRequestWithStreaming(state, request) {
1629
+ const headers = [];
1630
+ request.headers.forEach((value, key) => {
1631
+ headers.push([key, value]);
1632
+ });
1633
+ let body = null;
1634
+ let bodyStreamId;
1635
+ let bodyStream;
1636
+ if (request.body) {
1637
+ const contentLength = request.headers.get("content-length");
1638
+ const knownSize = contentLength ? parseInt(contentLength, 10) : null;
1639
+ if (knownSize !== null && knownSize > import_protocol.STREAM_THRESHOLD) {
1640
+ bodyStreamId = state.nextStreamId++;
1641
+ bodyStream = request.body;
1642
+ } else {
1643
+ const clonedRequest = request.clone();
1644
+ try {
1645
+ body = new Uint8Array(await request.arrayBuffer());
1646
+ if (body.length > import_protocol.STREAM_THRESHOLD) {
1647
+ bodyStreamId = state.nextStreamId++;
1648
+ bodyStream = clonedRequest.body;
1649
+ body = null;
1650
+ }
1651
+ } catch {
1652
+ bodyStreamId = state.nextStreamId++;
1653
+ bodyStream = clonedRequest.body;
1654
+ }
1655
+ }
1656
+ }
1657
+ const result = {
1658
+ method: request.method,
1659
+ url: request.url,
1660
+ headers,
1661
+ body,
1662
+ signalAborted: request.signal?.aborted ?? false
1663
+ };
1664
+ if (bodyStreamId !== undefined) {
1665
+ result.bodyStreamId = bodyStreamId;
1666
+ result.bodyStream = bodyStream;
1667
+ }
1668
+ return result;
1669
+ }
1670
+ function waitForUploadCredit(session) {
1671
+ return new Promise((resolve) => {
1672
+ session.creditResolver = resolve;
1673
+ });
1674
+ }
1675
+ async function sendBodyStream(state, streamId, body) {
1676
+ const session = {
1677
+ streamId,
1678
+ requestId: 0,
1679
+ state: "active",
1680
+ bytesTransferred: 0,
1681
+ credit: 0
1682
+ };
1683
+ state.uploadStreams.set(streamId, session);
1684
+ const reader = body.getReader();
1685
+ try {
1686
+ while (true) {
1687
+ if (session.state !== "active") {
1688
+ throw new Error("Stream cancelled");
1689
+ }
1690
+ while (session.credit < import_protocol.STREAM_CHUNK_SIZE && session.state === "active") {
1691
+ await waitForUploadCredit(session);
1692
+ }
1693
+ if (session.state !== "active") {
1694
+ throw new Error("Stream cancelled");
1695
+ }
1696
+ const { done, value } = await reader.read();
1697
+ if (done) {
1698
+ sendMessage(state.socket, {
1699
+ type: import_protocol.MessageType.STREAM_CLOSE,
1700
+ streamId
1701
+ });
1702
+ break;
1703
+ }
1704
+ for (let offset = 0;offset < value.length; offset += import_protocol.STREAM_CHUNK_SIZE) {
1705
+ const chunk = value.slice(offset, offset + import_protocol.STREAM_CHUNK_SIZE);
1706
+ sendMessage(state.socket, {
1707
+ type: import_protocol.MessageType.STREAM_PUSH,
1708
+ streamId,
1709
+ chunk
1710
+ });
1711
+ session.credit -= chunk.length;
1712
+ session.bytesTransferred += chunk.length;
1713
+ }
1714
+ }
1715
+ } catch (err) {
1716
+ sendMessage(state.socket, {
1717
+ type: import_protocol.MessageType.STREAM_ERROR,
1718
+ streamId,
1719
+ error: err.message
1720
+ });
1721
+ throw err;
1722
+ } finally {
1723
+ reader.releaseLock();
1724
+ state.uploadStreams.delete(streamId);
1725
+ }
1726
+ }
1727
+ function handleIsolateEvent(message, state) {
1728
+ switch (message.event) {
1729
+ case import_protocol.IsolateEvents.WS_COMMAND: {
1730
+ const payload = message.payload;
1731
+ const callbacks = isolateWsCallbacks.get(message.isolateId);
1732
+ if (callbacks) {
1733
+ let data;
1734
+ if (payload.data instanceof Uint8Array) {
1735
+ data = payload.data.buffer.slice(payload.data.byteOffset, payload.data.byteOffset + payload.data.byteLength);
1736
+ } else {
1737
+ data = payload.data;
1738
+ }
1739
+ const cmd = {
1740
+ type: payload.type,
1741
+ connectionId: payload.connectionId,
1742
+ data,
1743
+ code: payload.code,
1744
+ reason: payload.reason
1745
+ };
1746
+ for (const cb of callbacks) {
1747
+ cb(cmd);
1748
+ }
1749
+ }
1750
+ break;
1751
+ }
1752
+ case import_protocol.IsolateEvents.WS_CLIENT_CONNECT: {
1753
+ const payload = message.payload;
1754
+ handleClientWsConnect(message.isolateId, payload, state);
1755
+ break;
1756
+ }
1757
+ case import_protocol.IsolateEvents.WS_CLIENT_SEND: {
1758
+ const payload = message.payload;
1759
+ handleClientWsSend(message.isolateId, payload, state);
1760
+ break;
1761
+ }
1762
+ case import_protocol.IsolateEvents.WS_CLIENT_CLOSE: {
1763
+ const payload = message.payload;
1764
+ handleClientWsClose(message.isolateId, payload, state);
1765
+ break;
1766
+ }
1767
+ default: {
1768
+ const listeners = isolateEventListeners.get(message.isolateId);
1769
+ if (listeners) {
1770
+ const eventListeners = listeners.get(message.event);
1771
+ if (eventListeners) {
1772
+ for (const cb of eventListeners) {
1773
+ cb(message.payload);
1774
+ }
1775
+ }
1776
+ }
1777
+ break;
1778
+ }
1779
+ }
1780
+ }
1781
+ function handleClientWsConnect(isolateId, payload, state) {
1782
+ const { socketId, url, protocols } = payload;
1783
+ let sockets = isolateClientWebSockets.get(isolateId);
1784
+ if (!sockets) {
1785
+ sockets = new Map;
1786
+ isolateClientWebSockets.set(isolateId, sockets);
1787
+ }
1788
+ const setupWebSocket = (ws) => {
1789
+ sockets.set(socketId, ws);
1790
+ ws.onopen = () => {
1791
+ sendMessage(state.socket, {
1792
+ type: import_protocol.MessageType.CLIENT_EVENT,
1793
+ isolateId,
1794
+ event: import_protocol.ClientEvents.WS_CLIENT_OPENED,
1795
+ payload: { socketId, protocol: ws.protocol || "", extensions: ws.extensions || "" }
1796
+ });
1797
+ };
1798
+ ws.onmessage = (event) => {
1799
+ let data;
1800
+ if (typeof event.data === "string") {
1801
+ data = event.data;
1802
+ } else if (event.data instanceof ArrayBuffer) {
1803
+ data = new Uint8Array(event.data);
1804
+ } else if (event.data instanceof Blob) {
1805
+ event.data.arrayBuffer().then((buffer) => {
1806
+ sendMessage(state.socket, {
1807
+ type: import_protocol.MessageType.CLIENT_EVENT,
1808
+ isolateId,
1809
+ event: import_protocol.ClientEvents.WS_CLIENT_MESSAGE,
1810
+ payload: { socketId, data: new Uint8Array(buffer) }
1811
+ });
1812
+ });
1813
+ return;
1814
+ } else {
1815
+ data = String(event.data);
1816
+ }
1817
+ sendMessage(state.socket, {
1818
+ type: import_protocol.MessageType.CLIENT_EVENT,
1819
+ isolateId,
1820
+ event: import_protocol.ClientEvents.WS_CLIENT_MESSAGE,
1821
+ payload: { socketId, data }
1822
+ });
1823
+ };
1824
+ ws.onerror = () => {
1825
+ sendMessage(state.socket, {
1826
+ type: import_protocol.MessageType.CLIENT_EVENT,
1827
+ isolateId,
1828
+ event: import_protocol.ClientEvents.WS_CLIENT_ERROR,
1829
+ payload: { socketId }
1830
+ });
1831
+ };
1832
+ ws.onclose = (event) => {
1833
+ sendMessage(state.socket, {
1834
+ type: import_protocol.MessageType.CLIENT_EVENT,
1835
+ isolateId,
1836
+ event: import_protocol.ClientEvents.WS_CLIENT_CLOSED,
1837
+ payload: { socketId, code: event.code, reason: event.reason, wasClean: event.wasClean }
1838
+ });
1839
+ sockets?.delete(socketId);
1840
+ if (sockets?.size === 0) {
1841
+ isolateClientWebSockets.delete(isolateId);
1842
+ }
1843
+ };
1844
+ };
1845
+ const sendConnectionFailed = (reason) => {
1846
+ sendMessage(state.socket, {
1847
+ type: import_protocol.MessageType.CLIENT_EVENT,
1848
+ isolateId,
1849
+ event: import_protocol.ClientEvents.WS_CLIENT_ERROR,
1850
+ payload: { socketId }
1851
+ });
1852
+ sendMessage(state.socket, {
1853
+ type: import_protocol.MessageType.CLIENT_EVENT,
1854
+ isolateId,
1855
+ event: import_protocol.ClientEvents.WS_CLIENT_CLOSED,
1856
+ payload: { socketId, code: 1006, reason, wasClean: false }
1857
+ });
1858
+ };
1859
+ const callback = isolateWebSocketCallbacks.get(isolateId);
1860
+ if (callback) {
1861
+ try {
1862
+ const result = callback(url, protocols || []);
1863
+ if (result instanceof Promise) {
1864
+ result.then((ws) => {
1865
+ if (ws === null) {
1866
+ sendConnectionFailed("Connection blocked");
1867
+ } else {
1868
+ setupWebSocket(ws);
1869
+ }
1870
+ }).catch(() => {
1871
+ sendConnectionFailed("Callback error");
1872
+ });
1873
+ } else if (result === null) {
1874
+ sendConnectionFailed("Connection blocked");
1875
+ } else {
1876
+ setupWebSocket(result);
1877
+ }
1878
+ } catch {
1879
+ sendConnectionFailed("Callback error");
1880
+ }
1881
+ } else {
1882
+ try {
1883
+ const ws = protocols && protocols.length > 0 ? new WebSocket(url, protocols) : new WebSocket(url);
1884
+ setupWebSocket(ws);
1885
+ } catch {
1886
+ sendConnectionFailed("Connection failed");
1887
+ }
1888
+ }
1889
+ }
1890
+ function handleClientWsSend(isolateId, payload, state) {
1891
+ const { socketId, data } = payload;
1892
+ const sockets = isolateClientWebSockets.get(isolateId);
1893
+ const ws = sockets?.get(socketId);
1894
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
1895
+ return;
1896
+ }
1897
+ if (typeof data === "string" && data.startsWith("__BINARY__")) {
1898
+ const base64 = data.slice(10);
1899
+ const binary = Buffer.from(base64, "base64");
1900
+ ws.send(binary);
1901
+ } else if (data instanceof Uint8Array) {
1902
+ ws.send(Buffer.from(data));
1903
+ } else {
1904
+ ws.send(data);
1905
+ }
1906
+ }
1907
+ function handleClientWsClose(isolateId, payload, state) {
1908
+ const { socketId, code, reason } = payload;
1909
+ const sockets = isolateClientWebSockets.get(isolateId);
1910
+ const ws = sockets?.get(socketId);
1911
+ if (!ws) {
1912
+ return;
1913
+ }
1914
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
1915
+ ws.close(code ?? 1000, reason ?? "");
1916
+ }
1917
+ }
1918
+
1919
+ //# debugId=7D1BE4A52F267ED264756E2164756E21