devflare 1.0.0-next.7 → 1.0.0-next.71

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 (635) hide show
  1. package/LICENSE +21 -0
  2. package/LLM.md +17316 -2144
  3. package/README.md +398 -607
  4. package/bin/devflare.js +30 -14
  5. package/dist/_chunks/account-B9ULT9HA.js +462 -0
  6. package/dist/_chunks/account-resources-BdKj8q1h.js +159 -0
  7. package/dist/_chunks/ai-DKDn1iys.js +322 -0
  8. package/dist/_chunks/api-BKClUlUf.js +568 -0
  9. package/dist/_chunks/build-B9jQtUny.js +24 -0
  10. package/dist/_chunks/build-artifacts-C7AbI34o.js +484 -0
  11. package/dist/_chunks/cli-CBRR2-Xr.js +1214 -0
  12. package/dist/_chunks/cloudflare-D_5UWT84.js +157 -0
  13. package/dist/_chunks/colors-D0NVzAFN.js +13 -0
  14. package/dist/_chunks/command-utils-qlsHELwW.js +45 -0
  15. package/dist/_chunks/compiler-UxXQgEPq.js +521 -0
  16. package/dist/_chunks/config-CHdi5-5R.js +78 -0
  17. package/dist/_chunks/config-path-DzZbchb6.js +42 -0
  18. package/dist/_chunks/context-DGMev2AF.js +2515 -0
  19. package/dist/_chunks/decorators-eXNZ1S0N.js +19 -0
  20. package/dist/_chunks/dependencies-HLIhxbIe.js +57 -0
  21. package/dist/_chunks/deploy-dIZuouRW.js +1033 -0
  22. package/dist/_chunks/dev-CRW_hBA3.js +953 -0
  23. package/dist/_chunks/doctor-t8hKA53t.js +219 -0
  24. package/dist/_chunks/durable-object-DuMPM8re.js +234 -0
  25. package/dist/_chunks/env-D4uJqqgu.js +125 -0
  26. package/dist/_chunks/family-DHkROYgX.js +143 -0
  27. package/dist/_chunks/generated-artifacts-D_VIzDOi.js +31 -0
  28. package/dist/_chunks/generated-dir-DC2kM-mt.js +33 -0
  29. package/dist/_chunks/glob-DRw9sbfF.js +56 -0
  30. package/dist/_chunks/init-B9_QIZcO.js +165 -0
  31. package/dist/_chunks/loader-BC0skbnH.js +1330 -0
  32. package/dist/_chunks/local-dev-vars-BFLS-HoI.js +81 -0
  33. package/dist/_chunks/local-hyperdrive-CcORzo76.js +119 -0
  34. package/dist/_chunks/local-media-bindings-ZQe-epuw.js +335 -0
  35. package/dist/_chunks/local-secrets-C0n5oRgI.js +123 -0
  36. package/dist/_chunks/login-Ctw59McM.js +51 -0
  37. package/dist/_chunks/package-metadata-CLI488gB.js +39 -0
  38. package/dist/_chunks/preferences-CbYERA_m.js +241 -0
  39. package/dist/_chunks/preview-j9Kbx4-G.js +462 -0
  40. package/dist/_chunks/preview-registry-CTXU4mBc.js +1186 -0
  41. package/dist/_chunks/preview-resources-BNvfkfqP.js +359 -0
  42. package/dist/_chunks/previews-DXlf8SaQ.js +1133 -0
  43. package/dist/_chunks/productions-TkIy7b1Q.js +504 -0
  44. package/dist/_chunks/r2-presign-runtime-DlgH_FY8.js +291 -0
  45. package/dist/_chunks/ref-CYJNAAe_.js +178 -0
  46. package/dist/_chunks/remote-DB8SU7ea.js +79 -0
  47. package/dist/_chunks/remote-config-Bw6qIVM4.js +132 -0
  48. package/dist/_chunks/resolve-package-DeJUGxoE.js +152 -0
  49. package/dist/_chunks/rolldown-runtime-CvQ6eiug.js +14 -0
  50. package/dist/_chunks/routes-CRXB3-iw.js +851 -0
  51. package/dist/_chunks/runtime-BlKTWIgD.js +874 -0
  52. package/dist/_chunks/schema-normalization-CTdiY17P.js +667 -0
  53. package/dist/_chunks/secrets-CzSWX4-i.js +95 -0
  54. package/dist/_chunks/tail-DXKaqcPB.js +239 -0
  55. package/dist/_chunks/token-CEIRtse8.js +333 -0
  56. package/dist/_chunks/tokens-CE7-gV5E.js +221 -0
  57. package/dist/_chunks/types-BB15NBqw.js +484 -0
  58. package/dist/_chunks/ui-BhCdDC2N.js +103 -0
  59. package/dist/_chunks/usage-rRusKejc.js +272 -0
  60. package/dist/_chunks/vite-DTz2Pbtm.js +1267 -0
  61. package/dist/_chunks/vite-process-BhGXJ764.js +2928 -0
  62. package/dist/_chunks/vite-utils-D_VR07Ks.js +183 -0
  63. package/dist/_chunks/worker-CgIvLp-D.js +410 -0
  64. package/dist/_chunks/worker-bundler-CeMqQtBQ.js +457 -0
  65. package/dist/_chunks/worker-entrypoint-C8j23t6d.js +247 -0
  66. package/dist/_chunks/workerName-kEXwmV2m.js +23 -0
  67. package/dist/_chunks/workspace-CbollZBv.js +518 -0
  68. package/dist/_chunks/workspace-Ds3xMjOE.js +175 -0
  69. package/dist/bridge/client.d.ts +93 -8
  70. package/dist/bridge/client.d.ts.map +1 -1
  71. package/dist/bridge/do-rpc-dispatch.d.ts +23 -0
  72. package/dist/bridge/do-rpc-dispatch.d.ts.map +1 -0
  73. package/dist/bridge/do-websocket-connect.d.ts +33 -0
  74. package/dist/bridge/do-websocket-connect.d.ts.map +1 -0
  75. package/dist/bridge/gateway-runtime.d.ts +8 -0
  76. package/dist/bridge/gateway-runtime.d.ts.map +1 -0
  77. package/dist/bridge/index.d.ts +6 -6
  78. package/dist/bridge/index.d.ts.map +1 -1
  79. package/dist/bridge/log.d.ts +5 -0
  80. package/dist/bridge/log.d.ts.map +1 -0
  81. package/dist/bridge/miniflare-gateway.d.ts +45 -0
  82. package/dist/bridge/miniflare-gateway.d.ts.map +1 -0
  83. package/dist/bridge/miniflare.d.ts +92 -2
  84. package/dist/bridge/miniflare.d.ts.map +1 -1
  85. package/dist/bridge/proxy.d.ts +12 -11
  86. package/dist/bridge/proxy.d.ts.map +1 -1
  87. package/dist/bridge/r2-presign-runtime.d.ts +9 -0
  88. package/dist/bridge/r2-presign-runtime.d.ts.map +1 -0
  89. package/dist/bridge/server.d.ts +2 -1
  90. package/dist/bridge/server.d.ts.map +1 -1
  91. package/dist/bridge/v2/body-streams.d.ts +53 -0
  92. package/dist/bridge/v2/body-streams.d.ts.map +1 -0
  93. package/dist/bridge/v2/codec.d.ts +106 -0
  94. package/dist/bridge/v2/codec.d.ts.map +1 -0
  95. package/dist/bridge/v2/control-messages.d.ts +46 -0
  96. package/dist/bridge/v2/control-messages.d.ts.map +1 -0
  97. package/dist/bridge/v2/frames.d.ts +109 -0
  98. package/dist/bridge/v2/frames.d.ts.map +1 -0
  99. package/dist/bridge/v2/index.d.ts +11 -0
  100. package/dist/bridge/v2/index.d.ts.map +1 -0
  101. package/dist/bridge/v2/serialization.d.ts +48 -0
  102. package/dist/bridge/v2/serialization.d.ts.map +1 -0
  103. package/dist/bridge/v2/transport.d.ts +31 -0
  104. package/dist/bridge/v2/transport.d.ts.map +1 -0
  105. package/dist/bridge/v2/value-codec.d.ts +61 -0
  106. package/dist/bridge/v2/value-codec.d.ts.map +1 -0
  107. package/dist/bridge/v2/value-serialization.d.ts +139 -0
  108. package/dist/bridge/v2/value-serialization.d.ts.map +1 -0
  109. package/dist/bridge/{protocol.d.ts → v2/wire.d.ts} +32 -8
  110. package/dist/bridge/v2/wire.d.ts.map +1 -0
  111. package/dist/bridge/v2/ws-relay.d.ts +53 -0
  112. package/dist/bridge/v2/ws-relay.d.ts.map +1 -0
  113. package/dist/bridge/websocket-constructor.d.ts +38 -0
  114. package/dist/bridge/websocket-constructor.d.ts.map +1 -0
  115. package/dist/browser-shim/handler.d.ts +2 -2
  116. package/dist/browser-shim/handler.d.ts.map +1 -1
  117. package/dist/browser-shim/index.d.ts +2 -2
  118. package/dist/browser-shim/server.d.ts +63 -0
  119. package/dist/browser-shim/server.d.ts.map +1 -1
  120. package/dist/browser.d.ts +5778 -43
  121. package/dist/browser.d.ts.map +1 -1
  122. package/dist/browser.js +73 -142
  123. package/dist/bundler/defaults.d.ts +23 -0
  124. package/dist/bundler/defaults.d.ts.map +1 -0
  125. package/dist/bundler/do-bundler.d.ts +7 -0
  126. package/dist/bundler/do-bundler.d.ts.map +1 -1
  127. package/dist/bundler/index.d.ts +3 -1
  128. package/dist/bundler/index.d.ts.map +1 -1
  129. package/dist/bundler/rolldown-shared.d.ts +52 -0
  130. package/dist/bundler/rolldown-shared.d.ts.map +1 -0
  131. package/dist/bundler/worker-bundler.d.ts +13 -0
  132. package/dist/bundler/worker-bundler.d.ts.map +1 -0
  133. package/dist/bundler/worker-compat.d.ts +4 -0
  134. package/dist/bundler/worker-compat.d.ts.map +1 -0
  135. package/dist/cli/build-manifest.d.ts +66 -0
  136. package/dist/cli/build-manifest.d.ts.map +1 -0
  137. package/dist/cli/command-utils.d.ts +18 -0
  138. package/dist/cli/command-utils.d.ts.map +1 -0
  139. package/dist/cli/commands/account.d.ts +2 -2
  140. package/dist/cli/commands/account.d.ts.map +1 -1
  141. package/dist/cli/commands/ai.d.ts +1 -1
  142. package/dist/cli/commands/ai.d.ts.map +1 -1
  143. package/dist/cli/commands/build-artifacts.d.ts +40 -0
  144. package/dist/cli/commands/build-artifacts.d.ts.map +1 -0
  145. package/dist/cli/commands/build.d.ts +2 -2
  146. package/dist/cli/commands/build.d.ts.map +1 -1
  147. package/dist/cli/commands/config.d.ts +4 -0
  148. package/dist/cli/commands/config.d.ts.map +1 -0
  149. package/dist/cli/commands/deploy/metadata.d.ts +18 -0
  150. package/dist/cli/commands/deploy/metadata.d.ts.map +1 -0
  151. package/dist/cli/commands/deploy/prepare.d.ts +23 -0
  152. package/dist/cli/commands/deploy/prepare.d.ts.map +1 -0
  153. package/dist/cli/commands/deploy/runtime.d.ts +4 -0
  154. package/dist/cli/commands/deploy/runtime.d.ts.map +1 -0
  155. package/dist/cli/commands/deploy/verification.d.ts +36 -0
  156. package/dist/cli/commands/deploy/verification.d.ts.map +1 -0
  157. package/dist/cli/commands/deploy.d.ts +2 -2
  158. package/dist/cli/commands/deploy.d.ts.map +1 -1
  159. package/dist/cli/commands/dev.d.ts +9 -1
  160. package/dist/cli/commands/dev.d.ts.map +1 -1
  161. package/dist/cli/commands/doctor.d.ts +2 -2
  162. package/dist/cli/commands/doctor.d.ts.map +1 -1
  163. package/dist/cli/commands/init.d.ts +2 -2
  164. package/dist/cli/commands/init.d.ts.map +1 -1
  165. package/dist/cli/commands/login.d.ts +4 -0
  166. package/dist/cli/commands/login.d.ts.map +1 -0
  167. package/dist/cli/commands/previews-support/cleanup.d.ts +9 -0
  168. package/dist/cli/commands/previews-support/cleanup.d.ts.map +1 -0
  169. package/dist/cli/commands/previews-support/family.d.ts +10 -0
  170. package/dist/cli/commands/previews-support/family.d.ts.map +1 -0
  171. package/dist/cli/commands/previews-support/render.d.ts +8 -0
  172. package/dist/cli/commands/previews-support/render.d.ts.map +1 -0
  173. package/dist/cli/commands/previews-support/theme.d.ts +10 -0
  174. package/dist/cli/commands/previews-support/theme.d.ts.map +1 -0
  175. package/dist/cli/commands/previews-support/types.d.ts +70 -0
  176. package/dist/cli/commands/previews-support/types.d.ts.map +1 -0
  177. package/dist/cli/commands/previews.d.ts +4 -0
  178. package/dist/cli/commands/previews.d.ts.map +1 -0
  179. package/dist/cli/commands/productions.d.ts +4 -0
  180. package/dist/cli/commands/productions.d.ts.map +1 -0
  181. package/dist/cli/commands/remote.d.ts +1 -1
  182. package/dist/cli/commands/remote.d.ts.map +1 -1
  183. package/dist/cli/commands/secrets.d.ts +4 -0
  184. package/dist/cli/commands/secrets.d.ts.map +1 -0
  185. package/dist/cli/commands/tail.d.ts +44 -0
  186. package/dist/cli/commands/tail.d.ts.map +1 -0
  187. package/dist/cli/commands/token.d.ts +4 -0
  188. package/dist/cli/commands/token.d.ts.map +1 -0
  189. package/dist/cli/commands/type-generation/discovery.d.ts +7 -0
  190. package/dist/cli/commands/type-generation/discovery.d.ts.map +1 -0
  191. package/dist/cli/commands/type-generation/generator.d.ts +121 -0
  192. package/dist/cli/commands/type-generation/generator.d.ts.map +1 -0
  193. package/dist/cli/commands/type-generation/models.d.ts +27 -0
  194. package/dist/cli/commands/type-generation/models.d.ts.map +1 -0
  195. package/dist/cli/commands/types.d.ts +2 -2
  196. package/dist/cli/commands/types.d.ts.map +1 -1
  197. package/dist/cli/commands/worker.d.ts +4 -0
  198. package/dist/cli/commands/worker.d.ts.map +1 -0
  199. package/dist/cli/commands/workspace.d.ts +8 -0
  200. package/dist/cli/commands/workspace.d.ts.map +1 -0
  201. package/dist/cli/config-path.d.ts +6 -0
  202. package/dist/cli/config-path.d.ts.map +1 -0
  203. package/dist/cli/dependencies.d.ts +2 -1
  204. package/dist/cli/dependencies.d.ts.map +1 -1
  205. package/dist/cli/deploy-strategy.d.ts +17 -0
  206. package/dist/cli/deploy-strategy.d.ts.map +1 -0
  207. package/dist/cli/deploy-target.d.ts +17 -0
  208. package/dist/cli/deploy-target.d.ts.map +1 -0
  209. package/dist/cli/generated-artifacts.d.ts +12 -0
  210. package/dist/cli/generated-artifacts.d.ts.map +1 -0
  211. package/dist/cli/gradual-deploy.d.ts +49 -0
  212. package/dist/cli/gradual-deploy.d.ts.map +1 -0
  213. package/dist/cli/help-pages/pages/account.d.ts +3 -0
  214. package/dist/cli/help-pages/pages/account.d.ts.map +1 -0
  215. package/dist/cli/help-pages/pages/core.d.ts +4 -0
  216. package/dist/cli/help-pages/pages/core.d.ts.map +1 -0
  217. package/dist/cli/help-pages/pages/index.d.ts +3 -0
  218. package/dist/cli/help-pages/pages/index.d.ts.map +1 -0
  219. package/dist/cli/help-pages/pages/misc.d.ts +3 -0
  220. package/dist/cli/help-pages/pages/misc.d.ts.map +1 -0
  221. package/dist/cli/help-pages/pages/previews.d.ts +3 -0
  222. package/dist/cli/help-pages/pages/previews.d.ts.map +1 -0
  223. package/dist/cli/help-pages/pages/productions.d.ts +3 -0
  224. package/dist/cli/help-pages/pages/productions.d.ts.map +1 -0
  225. package/dist/cli/help-pages/render.d.ts +12 -0
  226. package/dist/cli/help-pages/render.d.ts.map +1 -0
  227. package/dist/cli/help-pages/shared.d.ts +15 -0
  228. package/dist/cli/help-pages/shared.d.ts.map +1 -0
  229. package/dist/cli/help-pages/types.d.ts +23 -0
  230. package/dist/cli/help-pages/types.d.ts.map +1 -0
  231. package/dist/cli/help.d.ts +6 -0
  232. package/dist/cli/help.d.ts.map +1 -0
  233. package/dist/cli/index.d.ts +1 -0
  234. package/dist/cli/index.d.ts.map +1 -1
  235. package/dist/cli/index.js +2 -0
  236. package/dist/cli/package-metadata.d.ts +16 -0
  237. package/dist/cli/package-metadata.d.ts.map +1 -0
  238. package/dist/cli/preview-bindings.d.ts +49 -0
  239. package/dist/cli/preview-bindings.d.ts.map +1 -0
  240. package/dist/cli/preview.d.ts +10 -0
  241. package/dist/cli/preview.d.ts.map +1 -0
  242. package/dist/cli/ui.d.ts +37 -0
  243. package/dist/cli/ui.d.ts.map +1 -0
  244. package/dist/cli/workspace-build-guard.d.ts +14 -0
  245. package/dist/cli/workspace-build-guard.d.ts.map +1 -0
  246. package/dist/cli/wrangler-auth.d.ts +1 -1
  247. package/dist/cloudflare/account-core.d.ts +6 -0
  248. package/dist/cloudflare/account-core.d.ts.map +1 -0
  249. package/dist/cloudflare/account-resources.d.ts +40 -0
  250. package/dist/cloudflare/account-resources.d.ts.map +1 -0
  251. package/dist/cloudflare/account-status.d.ts +11 -0
  252. package/dist/cloudflare/account-status.d.ts.map +1 -0
  253. package/dist/cloudflare/account-workers.d.ts +14 -0
  254. package/dist/cloudflare/account-workers.d.ts.map +1 -0
  255. package/dist/cloudflare/account.d.ts +7 -64
  256. package/dist/cloudflare/account.d.ts.map +1 -1
  257. package/dist/cloudflare/api.d.ts +71 -3
  258. package/dist/cloudflare/api.d.ts.map +1 -1
  259. package/dist/cloudflare/auth.d.ts +1 -1
  260. package/dist/cloudflare/auth.d.ts.map +1 -1
  261. package/dist/cloudflare/index.d.ts +61 -6
  262. package/dist/cloudflare/index.d.ts.map +1 -1
  263. package/dist/cloudflare/index.js +4 -13
  264. package/dist/cloudflare/known-permission-group-ids.generated.d.ts +10 -0
  265. package/dist/cloudflare/known-permission-group-ids.generated.d.ts.map +1 -0
  266. package/dist/cloudflare/kv-namespace.d.ts +4 -0
  267. package/dist/cloudflare/kv-namespace.d.ts.map +1 -0
  268. package/dist/cloudflare/preferences.d.ts +7 -0
  269. package/dist/cloudflare/preferences.d.ts.map +1 -1
  270. package/dist/cloudflare/preview-registry-cache.d.ts +6 -0
  271. package/dist/cloudflare/preview-registry-cache.d.ts.map +1 -0
  272. package/dist/cloudflare/preview-registry-inference.d.ts +14 -0
  273. package/dist/cloudflare/preview-registry-inference.d.ts.map +1 -0
  274. package/dist/cloudflare/preview-registry-records.d.ts +4 -0
  275. package/dist/cloudflare/preview-registry-records.d.ts.map +1 -0
  276. package/dist/cloudflare/preview-registry-shape.d.ts +47 -0
  277. package/dist/cloudflare/preview-registry-shape.d.ts.map +1 -0
  278. package/dist/cloudflare/preview-registry-store.d.ts +14 -0
  279. package/dist/cloudflare/preview-registry-store.d.ts.map +1 -0
  280. package/dist/cloudflare/preview-registry-transport.d.ts +4 -0
  281. package/dist/cloudflare/preview-registry-transport.d.ts.map +1 -0
  282. package/dist/cloudflare/preview-registry-types.d.ts +103 -0
  283. package/dist/cloudflare/preview-registry-types.d.ts.map +1 -0
  284. package/dist/cloudflare/preview-registry.d.ts +42 -0
  285. package/dist/cloudflare/preview-registry.d.ts.map +1 -0
  286. package/dist/cloudflare/preview-urls.d.ts +3 -0
  287. package/dist/cloudflare/preview-urls.d.ts.map +1 -0
  288. package/dist/cloudflare/registry-schema.d.ts +253 -0
  289. package/dist/cloudflare/registry-schema.d.ts.map +1 -0
  290. package/dist/cloudflare/remote-config.d.ts.map +1 -1
  291. package/dist/cloudflare/tokens.d.ts +44 -0
  292. package/dist/cloudflare/tokens.d.ts.map +1 -0
  293. package/dist/cloudflare/types.d.ts +124 -7
  294. package/dist/cloudflare/types.d.ts.map +1 -1
  295. package/dist/cloudflare/usage.d.ts +31 -3
  296. package/dist/cloudflare/usage.d.ts.map +1 -1
  297. package/dist/config/binding-resolution-helpers.d.ts +41 -0
  298. package/dist/config/binding-resolution-helpers.d.ts.map +1 -0
  299. package/dist/config/compatibility.d.ts +3 -0
  300. package/dist/config/compatibility.d.ts.map +1 -0
  301. package/dist/config/compiler/bindings.d.ts +14 -0
  302. package/dist/config/compiler/bindings.d.ts.map +1 -0
  303. package/dist/config/compiler/core-helpers.d.ts +6 -0
  304. package/dist/config/compiler/core-helpers.d.ts.map +1 -0
  305. package/dist/config/compiler/do-workers.d.ts +34 -0
  306. package/dist/config/compiler/do-workers.d.ts.map +1 -0
  307. package/dist/config/compiler/paths.d.ts +18 -0
  308. package/dist/config/compiler/paths.d.ts.map +1 -0
  309. package/dist/config/compiler/types.d.ts +308 -0
  310. package/dist/config/compiler/types.d.ts.map +1 -0
  311. package/dist/config/compiler.d.ts +22 -134
  312. package/dist/config/compiler.d.ts.map +1 -1
  313. package/dist/config/cron.d.ts +19 -0
  314. package/dist/config/cron.d.ts.map +1 -0
  315. package/dist/config/define.d.ts +8 -5
  316. package/dist/config/define.d.ts.map +1 -1
  317. package/dist/config/deploy-resources.d.ts +58 -0
  318. package/dist/config/deploy-resources.d.ts.map +1 -0
  319. package/dist/config/env-vars.d.ts +309 -0
  320. package/dist/config/env-vars.d.ts.map +1 -0
  321. package/dist/config/framework-providers.d.ts +9 -0
  322. package/dist/config/framework-providers.d.ts.map +1 -0
  323. package/dist/config/index.d.ts +13 -5
  324. package/dist/config/index.d.ts.map +1 -1
  325. package/dist/config/loader.d.ts +2 -1
  326. package/dist/config/loader.d.ts.map +1 -1
  327. package/dist/config/local-dev-vars.d.ts +15 -0
  328. package/dist/config/local-dev-vars.d.ts.map +1 -0
  329. package/dist/config/preview-resources.d.ts +83 -0
  330. package/dist/config/preview-resources.d.ts.map +1 -0
  331. package/dist/config/preview.d.ts +29 -0
  332. package/dist/config/preview.d.ts.map +1 -0
  333. package/dist/config/ref.d.ts +16 -25
  334. package/dist/config/ref.d.ts.map +1 -1
  335. package/dist/config/resolve-phased.d.ts +72 -0
  336. package/dist/config/resolve-phased.d.ts.map +1 -0
  337. package/dist/config/resolve.d.ts +11 -0
  338. package/dist/config/resolve.d.ts.map +1 -0
  339. package/dist/config/resource-resolution.d.ts +80 -0
  340. package/dist/config/resource-resolution.d.ts.map +1 -0
  341. package/dist/config/schema-bindings.d.ts +2124 -0
  342. package/dist/config/schema-bindings.d.ts.map +1 -0
  343. package/dist/config/schema-build.d.ts +67 -0
  344. package/dist/config/schema-build.d.ts.map +1 -0
  345. package/dist/config/schema-env.d.ts +3821 -0
  346. package/dist/config/schema-env.d.ts.map +1 -0
  347. package/dist/config/schema-normalization.d.ts +272 -0
  348. package/dist/config/schema-normalization.d.ts.map +1 -0
  349. package/dist/config/schema-runtime.d.ts +597 -0
  350. package/dist/config/schema-runtime.d.ts.map +1 -0
  351. package/dist/config/schema-types-bindings-platform.d.ts +520 -0
  352. package/dist/config/schema-types-bindings-platform.d.ts.map +1 -0
  353. package/dist/config/schema-types-bindings-resources.d.ts +802 -0
  354. package/dist/config/schema-types-bindings-resources.d.ts.map +1 -0
  355. package/dist/config/schema-types-bindings.d.ts +293 -0
  356. package/dist/config/schema-types-bindings.d.ts.map +1 -0
  357. package/dist/config/schema-types-build.d.ts +86 -0
  358. package/dist/config/schema-types-build.d.ts.map +1 -0
  359. package/dist/config/schema-types-runtime-server.d.ts +196 -0
  360. package/dist/config/schema-types-runtime-server.d.ts.map +1 -0
  361. package/dist/config/schema-types-runtime.d.ts +913 -0
  362. package/dist/config/schema-types-runtime.d.ts.map +1 -0
  363. package/dist/config/schema-types.d.ts +458 -0
  364. package/dist/config/schema-types.d.ts.map +1 -0
  365. package/dist/config/schema.d.ts +5796 -2023
  366. package/dist/config/schema.d.ts.map +1 -1
  367. package/dist/config/service-bindings-validation.d.ts +36 -0
  368. package/dist/config/service-bindings-validation.d.ts.map +1 -0
  369. package/dist/config/workspace.d.ts +282 -0
  370. package/dist/config/workspace.d.ts.map +1 -0
  371. package/dist/config-entry.d.ts +7 -0
  372. package/dist/config-entry.d.ts.map +1 -0
  373. package/dist/config-entry.js +3 -0
  374. package/dist/decorators/durable-object.d.ts.map +1 -1
  375. package/dist/decorators/index.d.ts +2 -2
  376. package/dist/decorators/index.js +2 -9
  377. package/dist/dev-server/d1-migrations.d.ts +36 -0
  378. package/dist/dev-server/d1-migrations.d.ts.map +1 -0
  379. package/dist/dev-server/dev-server-state.d.ts +59 -0
  380. package/dist/dev-server/dev-server-state.d.ts.map +1 -0
  381. package/dist/dev-server/gateway-script.d.ts +22 -0
  382. package/dist/dev-server/gateway-script.d.ts.map +1 -0
  383. package/dist/dev-server/index.d.ts +1 -1
  384. package/dist/dev-server/miniflare-bindings.d.ts +90 -0
  385. package/dist/dev-server/miniflare-bindings.d.ts.map +1 -0
  386. package/dist/dev-server/miniflare-dev-config.d.ts +57 -0
  387. package/dist/dev-server/miniflare-dev-config.d.ts.map +1 -0
  388. package/dist/dev-server/miniflare-log.d.ts +20 -0
  389. package/dist/dev-server/miniflare-log.d.ts.map +1 -0
  390. package/dist/dev-server/miniflare-worker-config.d.ts +100 -0
  391. package/dist/dev-server/miniflare-worker-config.d.ts.map +1 -0
  392. package/dist/dev-server/reload-queue.d.ts +13 -0
  393. package/dist/dev-server/reload-queue.d.ts.map +1 -0
  394. package/dist/dev-server/runtime-health.d.ts +79 -0
  395. package/dist/dev-server/runtime-health.d.ts.map +1 -0
  396. package/dist/dev-server/runtime-stdio.d.ts +8 -0
  397. package/dist/dev-server/runtime-stdio.d.ts.map +1 -0
  398. package/dist/dev-server/server-startup-helpers.d.ts +84 -0
  399. package/dist/dev-server/server-startup-helpers.d.ts.map +1 -0
  400. package/dist/dev-server/server.d.ts +2 -0
  401. package/dist/dev-server/server.d.ts.map +1 -1
  402. package/dist/dev-server/vite-process.d.ts +24 -0
  403. package/dist/dev-server/vite-process.d.ts.map +1 -0
  404. package/dist/dev-server/vite-utils.d.ts +19 -1
  405. package/dist/dev-server/vite-utils.d.ts.map +1 -1
  406. package/dist/dev-server/worker-source-watcher.d.ts +17 -0
  407. package/dist/dev-server/worker-source-watcher.d.ts.map +1 -0
  408. package/dist/dev-server/worker-surface-paths.d.ts +6 -0
  409. package/dist/dev-server/worker-surface-paths.d.ts.map +1 -0
  410. package/dist/dev-server/workspace/merge-config.d.ts +81 -0
  411. package/dist/dev-server/workspace/merge-config.d.ts.map +1 -0
  412. package/dist/dev-server/workspace/prepare-app.d.ts +84 -0
  413. package/dist/dev-server/workspace/prepare-app.d.ts.map +1 -0
  414. package/dist/dev-server/workspace/server.d.ts +47 -0
  415. package/dist/dev-server/workspace/server.d.ts.map +1 -0
  416. package/dist/env.d.ts +10 -0
  417. package/dist/env.d.ts.map +1 -1
  418. package/dist/index.d.ts +8 -12
  419. package/dist/index.d.ts.map +1 -1
  420. package/dist/index.js +10 -297
  421. package/dist/runtime/context-events.d.ts +13 -0
  422. package/dist/runtime/context-events.d.ts.map +1 -0
  423. package/dist/runtime/context-types.d.ts +82 -0
  424. package/dist/runtime/context-types.d.ts.map +1 -0
  425. package/dist/runtime/context.d.ts +20 -44
  426. package/dist/runtime/context.d.ts.map +1 -1
  427. package/dist/runtime/exports.d.ts +70 -55
  428. package/dist/runtime/exports.d.ts.map +1 -1
  429. package/dist/runtime/index.d.ts +11 -5
  430. package/dist/runtime/index.d.ts.map +1 -1
  431. package/dist/runtime/index.js +5 -184
  432. package/dist/runtime/middleware.d.ts +119 -67
  433. package/dist/runtime/middleware.d.ts.map +1 -1
  434. package/dist/runtime/r2-presign.d.ts +164 -0
  435. package/dist/runtime/r2-presign.d.ts.map +1 -0
  436. package/dist/runtime/router/index.d.ts +7 -0
  437. package/dist/runtime/router/index.d.ts.map +1 -0
  438. package/dist/runtime/router/types.d.ts +24 -0
  439. package/dist/runtime/router/types.d.ts.map +1 -0
  440. package/dist/runtime/validation.d.ts +18 -4
  441. package/dist/runtime/validation.d.ts.map +1 -1
  442. package/dist/secrets/local-secrets.d.ts +46 -0
  443. package/dist/secrets/local-secrets.d.ts.map +1 -0
  444. package/dist/shims/local-hyperdrive.d.ts +12 -0
  445. package/dist/shims/local-hyperdrive.d.ts.map +1 -0
  446. package/dist/shims/local-media-bindings.d.ts +19 -0
  447. package/dist/shims/local-media-bindings.d.ts.map +1 -0
  448. package/dist/shims/local-worker-loader.d.ts +3 -0
  449. package/dist/shims/local-worker-loader.d.ts.map +1 -0
  450. package/dist/sveltekit/index.d.ts +1 -1
  451. package/dist/sveltekit/index.d.ts.map +1 -1
  452. package/dist/sveltekit/index.js +377 -169
  453. package/dist/sveltekit/local-bindings.d.ts +4 -0
  454. package/dist/sveltekit/local-bindings.d.ts.map +1 -0
  455. package/dist/sveltekit/platform.d.ts +42 -2
  456. package/dist/sveltekit/platform.d.ts.map +1 -1
  457. package/dist/test/ai-search.d.ts +39 -0
  458. package/dist/test/ai-search.d.ts.map +1 -0
  459. package/dist/test/alarm.d.ts +55 -0
  460. package/dist/test/alarm.d.ts.map +1 -0
  461. package/dist/test/binding-hints.d.ts +10 -0
  462. package/dist/test/binding-hints.d.ts.map +1 -0
  463. package/dist/test/cf.d.ts +71 -35
  464. package/dist/test/cf.d.ts.map +1 -1
  465. package/dist/test/containers.d.ts +87 -0
  466. package/dist/test/containers.d.ts.map +1 -0
  467. package/dist/test/email.d.ts +16 -7
  468. package/dist/test/email.d.ts.map +1 -1
  469. package/dist/test/index.d.ts +20 -21
  470. package/dist/test/index.d.ts.map +1 -1
  471. package/dist/test/index.js +5115 -75
  472. package/dist/test/offline-bindings.d.ts +124 -0
  473. package/dist/test/offline-bindings.d.ts.map +1 -0
  474. package/dist/test/queue.d.ts.map +1 -1
  475. package/dist/test/remote-ai.d.ts.map +1 -1
  476. package/dist/test/remote-cloudflare.d.ts +13 -0
  477. package/dist/test/remote-cloudflare.d.ts.map +1 -0
  478. package/dist/test/remote-vectorize.d.ts.map +1 -1
  479. package/dist/test/resolve-service-bindings.d.ts +64 -4
  480. package/dist/test/resolve-service-bindings.d.ts.map +1 -1
  481. package/dist/test/scheduled.d.ts.map +1 -1
  482. package/dist/test/should-skip.d.ts +14 -18
  483. package/dist/test/should-skip.d.ts.map +1 -1
  484. package/dist/test/simple-context-bindings.d.ts +13 -0
  485. package/dist/test/simple-context-bindings.d.ts.map +1 -0
  486. package/dist/test/simple-context-durable-objects.d.ts +6 -0
  487. package/dist/test/simple-context-durable-objects.d.ts.map +1 -0
  488. package/dist/test/simple-context-env.d.ts +35 -0
  489. package/dist/test/simple-context-env.d.ts.map +1 -0
  490. package/dist/test/simple-context-gateway-script.d.ts +2 -0
  491. package/dist/test/simple-context-gateway-script.d.ts.map +1 -0
  492. package/dist/test/simple-context-handlers.d.ts +12 -0
  493. package/dist/test/simple-context-handlers.d.ts.map +1 -0
  494. package/dist/test/simple-context-lifecycle.d.ts +32 -0
  495. package/dist/test/simple-context-lifecycle.d.ts.map +1 -0
  496. package/dist/test/simple-context-mfconfig.d.ts +18 -0
  497. package/dist/test/simple-context-mfconfig.d.ts.map +1 -0
  498. package/dist/test/simple-context-multi-worker.d.ts +16 -0
  499. package/dist/test/simple-context-multi-worker.d.ts.map +1 -0
  500. package/dist/test/simple-context-paths.d.ts +40 -0
  501. package/dist/test/simple-context-paths.d.ts.map +1 -0
  502. package/dist/test/simple-context-runtime.d.ts +19 -0
  503. package/dist/test/simple-context-runtime.d.ts.map +1 -0
  504. package/dist/test/simple-context-startup.d.ts +11 -0
  505. package/dist/test/simple-context-startup.d.ts.map +1 -0
  506. package/dist/test/simple-context-transport.d.ts +14 -0
  507. package/dist/test/simple-context-transport.d.ts.map +1 -0
  508. package/dist/test/simple-context.d.ts +8 -27
  509. package/dist/test/simple-context.d.ts.map +1 -1
  510. package/dist/test/tail.d.ts +3 -2
  511. package/dist/test/tail.d.ts.map +1 -1
  512. package/dist/test/utilities/analytics-engine.d.ts +22 -0
  513. package/dist/test/utilities/analytics-engine.d.ts.map +1 -0
  514. package/dist/test/utilities/artifacts.d.ts +11 -0
  515. package/dist/test/utilities/artifacts.d.ts.map +1 -0
  516. package/dist/test/utilities/context.d.ts +39 -0
  517. package/dist/test/utilities/context.d.ts.map +1 -0
  518. package/dist/test/utilities/d1.d.ts +21 -0
  519. package/dist/test/utilities/d1.d.ts.map +1 -0
  520. package/dist/test/utilities/env.d.ts +45 -0
  521. package/dist/test/utilities/env.d.ts.map +1 -0
  522. package/dist/test/utilities/kv.d.ts +11 -0
  523. package/dist/test/utilities/kv.d.ts.map +1 -0
  524. package/dist/test/utilities/media.d.ts +16 -0
  525. package/dist/test/utilities/media.d.ts.map +1 -0
  526. package/dist/test/utilities/platform.d.ts +41 -0
  527. package/dist/test/utilities/platform.d.ts.map +1 -0
  528. package/dist/test/utilities/queue.d.ts +5 -0
  529. package/dist/test/utilities/queue.d.ts.map +1 -0
  530. package/dist/test/utilities/r2.d.ts +2 -0
  531. package/dist/test/utilities/r2.d.ts.map +1 -0
  532. package/dist/test/utilities/send-email.d.ts +27 -0
  533. package/dist/test/utilities/send-email.d.ts.map +1 -0
  534. package/dist/test/utilities/stream-flagship.d.ts +27 -0
  535. package/dist/test/utilities/stream-flagship.d.ts.map +1 -0
  536. package/dist/test/utilities/vectorize.d.ts +38 -0
  537. package/dist/test/utilities/vectorize.d.ts.map +1 -0
  538. package/dist/test/utilities/workflows.d.ts +26 -0
  539. package/dist/test/utilities/workflows.d.ts.map +1 -0
  540. package/dist/test/utilities.d.ts +14 -98
  541. package/dist/test/utilities.d.ts.map +1 -1
  542. package/dist/test/worker.d.ts +6 -0
  543. package/dist/test/worker.d.ts.map +1 -1
  544. package/dist/transform/durable-object.d.ts.map +1 -1
  545. package/dist/transform/index.d.ts +2 -2
  546. package/dist/transform/worker-entrypoint.d.ts +5 -0
  547. package/dist/transform/worker-entrypoint.d.ts.map +1 -1
  548. package/dist/utils/entrypoint-discovery.d.ts +6 -3
  549. package/dist/utils/entrypoint-discovery.d.ts.map +1 -1
  550. package/dist/utils/generated-dir.d.ts +25 -0
  551. package/dist/utils/generated-dir.d.ts.map +1 -0
  552. package/dist/utils/glob.d.ts.map +1 -1
  553. package/dist/utils/resolve-package.d.ts.map +1 -1
  554. package/dist/utils/send-email.d.ts +15 -0
  555. package/dist/utils/send-email.d.ts.map +1 -0
  556. package/dist/utils/send-email.js +163 -0
  557. package/dist/vite/config-file.d.ts +25 -0
  558. package/dist/vite/config-file.d.ts.map +1 -0
  559. package/dist/vite/index.d.ts +3 -2
  560. package/dist/vite/index.d.ts.map +1 -1
  561. package/dist/vite/index.js +2 -407
  562. package/dist/vite/plugin-config-hook.d.ts +28 -0
  563. package/dist/vite/plugin-config-hook.d.ts.map +1 -0
  564. package/dist/vite/plugin-context.d.ts +27 -0
  565. package/dist/vite/plugin-context.d.ts.map +1 -0
  566. package/dist/vite/plugin-durable-objects.d.ts +18 -0
  567. package/dist/vite/plugin-durable-objects.d.ts.map +1 -0
  568. package/dist/vite/plugin-programmatic.d.ts +44 -0
  569. package/dist/vite/plugin-programmatic.d.ts.map +1 -0
  570. package/dist/vite/plugin-service-bindings.d.ts +13 -0
  571. package/dist/vite/plugin-service-bindings.d.ts.map +1 -0
  572. package/dist/vite/plugin-transform.d.ts +41 -0
  573. package/dist/vite/plugin-transform.d.ts.map +1 -0
  574. package/dist/vite/plugin.d.ts +10 -41
  575. package/dist/vite/plugin.d.ts.map +1 -1
  576. package/dist/worker-entry/composed-worker.d.ts +5 -8
  577. package/dist/worker-entry/composed-worker.d.ts.map +1 -1
  578. package/dist/worker-entry/durable-object-discovery.d.ts +20 -0
  579. package/dist/worker-entry/durable-object-discovery.d.ts.map +1 -0
  580. package/dist/worker-entry/extensions.d.ts +5 -0
  581. package/dist/worker-entry/extensions.d.ts.map +1 -0
  582. package/dist/worker-entry/routes.d.ts +22 -0
  583. package/dist/worker-entry/routes.d.ts.map +1 -0
  584. package/dist/worker-entry/surface-paths.d.ts +26 -0
  585. package/dist/worker-entry/surface-paths.d.ts.map +1 -0
  586. package/dist/worker-entry/validate-fetch-style.d.ts +12 -0
  587. package/dist/worker-entry/validate-fetch-style.d.ts.map +1 -0
  588. package/dist/workflows/local-workflow-entrypoints.d.ts +7 -0
  589. package/dist/workflows/local-workflow-entrypoints.d.ts.map +1 -0
  590. package/package.json +160 -117
  591. package/R2.md +0 -170
  592. package/dist/account-rvrj687w.js +0 -397
  593. package/dist/ai-dx4fr9jh.js +0 -107
  594. package/dist/bridge/protocol.d.ts.map +0 -1
  595. package/dist/bridge/serialization.d.ts +0 -83
  596. package/dist/bridge/serialization.d.ts.map +0 -1
  597. package/dist/browser-shim/worker.d.ts +0 -14
  598. package/dist/browser-shim/worker.d.ts.map +0 -1
  599. package/dist/build-9myaxf07.js +0 -70
  600. package/dist/deploy-h1wz5p7m.js +0 -86
  601. package/dist/dev-rsdssknb.js +0 -2707
  602. package/dist/doctor-v7jy4s3r.js +0 -190
  603. package/dist/durable-object-t4kbb0yt.js +0 -13
  604. package/dist/index-18hvb6gb.js +0 -194
  605. package/dist/index-1xpj0m4r.js +0 -57
  606. package/dist/index-37x76zdn.js +0 -4
  607. package/dist/index-3t6rypgc.js +0 -13
  608. package/dist/index-62b3gt2g.js +0 -12
  609. package/dist/index-67qcae0f.js +0 -183
  610. package/dist/index-9ats0s83.js +0 -70
  611. package/dist/index-a0fjkq68.js +0 -198
  612. package/dist/index-a855bdsx.js +0 -18
  613. package/dist/index-ccrh4w3t.js +0 -1133
  614. package/dist/index-d8bdkx2h.js +0 -109
  615. package/dist/index-f8qh2tyh.js +0 -2152
  616. package/dist/index-gz1gndna.js +0 -307
  617. package/dist/index-hcex3rgh.js +0 -266
  618. package/dist/index-k7r18na8.js +0 -0
  619. package/dist/index-n3np2d6t.js +0 -462
  620. package/dist/index-n7rs26ft.js +0 -77
  621. package/dist/index-npc1c8jx.js +0 -44
  622. package/dist/index-p7g30wd2.js +0 -281
  623. package/dist/index-rbht7m9r.js +0 -36
  624. package/dist/index-tfyxa77h.js +0 -850
  625. package/dist/index-tk6ej9dj.js +0 -94
  626. package/dist/index-v8vvsn9x.js +0 -169
  627. package/dist/index-z14anrqp.js +0 -226
  628. package/dist/init-f9mgmew3.js +0 -186
  629. package/dist/remote-q59qk463.js +0 -97
  630. package/dist/test/bridge-context.d.ts +0 -76
  631. package/dist/test/bridge-context.d.ts.map +0 -1
  632. package/dist/test/multi-worker-context.d.ts +0 -114
  633. package/dist/test/multi-worker-context.d.ts.map +0 -1
  634. package/dist/types-wdcpnfvy.js +0 -487
  635. package/dist/worker-entrypoint-m9th0rg0.js +0 -13
@@ -0,0 +1,2515 @@
1
+ import { wrapEnvSendEmailBindings } from "../utils/send-email.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ //#region src/bridge/v2/wire.ts
4
+ /** Binary frame kinds */
5
+ const BinaryKind = {
6
+ StreamChunk: 1,
7
+ WsData: 2
8
+ };
9
+ /** Binary frame flags */
10
+ const BinaryFlags = {
11
+ FIN: 1,
12
+ TEXT: 2
13
+ };
14
+ /** Encode a binary frame */
15
+ function encodeBinaryFrame(kind, id, seq, flags, payload) {
16
+ const frame = new Uint8Array(10 + payload.byteLength);
17
+ const view = new DataView(frame.buffer);
18
+ view.setUint8(0, kind);
19
+ view.setUint32(1, id, true);
20
+ view.setUint32(5, seq, true);
21
+ view.setUint8(9, flags);
22
+ frame.set(payload, 10);
23
+ return frame;
24
+ }
25
+ /** Parse a JSON message from string */
26
+ function parseJsonMsg(data) {
27
+ const msg = JSON.parse(data);
28
+ if (typeof msg !== "object" || msg === null || !("t" in msg)) throw new Error("Invalid message: missing type field");
29
+ return msg;
30
+ }
31
+ /** Stringify a JSON message */
32
+ function stringifyJsonMsg(msg) {
33
+ return JSON.stringify(msg);
34
+ }
35
+ let streamIdCounter = 0;
36
+ let wsIdCounter = 0;
37
+ /** Generate unique stream ID */
38
+ function nextStreamId() {
39
+ return ++streamIdCounter;
40
+ }
41
+ /** Generate unique WebSocket proxy ID */
42
+ function nextWsId() {
43
+ return ++wsIdCounter;
44
+ }
45
+ /** Default chunk size for streaming (256 KB) */
46
+ const DEFAULT_CHUNK_SIZE = 256 * 1024;
47
+ /** Threshold for switching to HTTP transfer (512 KB — workerd ~1MB WS message limit). */
48
+ const HTTP_TRANSFER_THRESHOLD = 512 * 1024;
49
+ //#endregion
50
+ //#region src/bridge/websocket-constructor.ts
51
+ let wsPackageConstructorPromise = null;
52
+ /**
53
+ * Lazily import the `ws` package's WebSocket constructor (memoized). Used as the
54
+ * Node fallback and whenever custom upgrade headers are required — unlike the
55
+ * platform global, the `ws` constructor accepts an options object with headers.
56
+ *
57
+ * @returns The `ws` package WebSocket constructor.
58
+ * @throws When the `ws` package does not export a usable WebSocket implementation.
59
+ */
60
+ async function importWsPackageConstructor() {
61
+ if (!wsPackageConstructorPromise) wsPackageConstructorPromise = (async () => {
62
+ const wsModule = await new Function("specifier", [
63
+ "return ",
64
+ "import",
65
+ "(specifier)"
66
+ ].join(""))("ws");
67
+ const defaultExport = wsModule.default;
68
+ const wsConstructor = wsModule.WebSocket ?? (typeof defaultExport === "object" && defaultExport !== null ? defaultExport.WebSocket : void 0) ?? defaultExport;
69
+ if (typeof wsConstructor !== "function") throw new Error("Could not load a WebSocket client implementation from the ws package");
70
+ return wsConstructor;
71
+ })();
72
+ return wsPackageConstructorPromise;
73
+ }
74
+ /**
75
+ * Return the runtime's global WebSocket constructor, or null when the runtime
76
+ * has none (older Node without a global WebSocket).
77
+ *
78
+ * @param runtimeWebSocket - The candidate global (defaults to `globalThis.WebSocket`).
79
+ * @returns The global constructor, or null.
80
+ */
81
+ function getRuntimeWebSocketConstructor(runtimeWebSocket = globalThis.WebSocket) {
82
+ if (typeof runtimeWebSocket === "function") return runtimeWebSocket;
83
+ return null;
84
+ }
85
+ /**
86
+ * Resolve a WebSocket constructor for the bridge socket: prefer the runtime
87
+ * global, fall back to the `ws` package.
88
+ *
89
+ * @param runtimeWebSocket - The candidate global (defaults to `globalThis.WebSocket`).
90
+ * @returns A usable WebSocket constructor.
91
+ */
92
+ async function resolveBridgeWebSocketConstructor(runtimeWebSocket = globalThis.WebSocket) {
93
+ const runtimeConstructor = getRuntimeWebSocketConstructor(runtimeWebSocket);
94
+ if (runtimeConstructor) return runtimeConstructor;
95
+ return importWsPackageConstructor();
96
+ }
97
+ /**
98
+ * Resolve the WebSocket constructor for a Durable Object pass-through
99
+ * connection. Custom upgrade headers require the `ws` package (whose constructor
100
+ * accepts an options object); the global WebSocket (undici/Bun) cannot set
101
+ * request headers, so it is used only when there are no headers to forward.
102
+ *
103
+ * @param hasHeaders - Whether application headers must ride the upgrade request.
104
+ * @returns A WebSocket constructor suitable for the connection.
105
+ */
106
+ async function resolveDoWebSocketConstructor(hasHeaders) {
107
+ if (hasHeaders) return importWsPackageConstructor();
108
+ return resolveBridgeWebSocketConstructor();
109
+ }
110
+ //#endregion
111
+ //#region src/bridge/do-websocket-connect.ts
112
+ /**
113
+ * Hop-by-hop / WebSocket-control request headers that the WebSocket client sets
114
+ * itself. They must never be copied from the user's `connect(url, { headers })`
115
+ * onto the outgoing upgrade — a duplicate `Upgrade`/`Sec-WebSocket-*` breaks the
116
+ * handshake (the `ws` package rejects it). Auth/cookie headers are preserved.
117
+ */
118
+ const WS_CONTROL_HEADERS = new Set([
119
+ "upgrade",
120
+ "connection",
121
+ "host",
122
+ "sec-websocket-key",
123
+ "sec-websocket-version",
124
+ "sec-websocket-extensions",
125
+ "sec-websocket-protocol"
126
+ ]);
127
+ /**
128
+ * Strip WebSocket-control headers from user-supplied upgrade headers, leaving
129
+ * only the application headers (auth, cookies) worth forwarding to the DO.
130
+ *
131
+ * @param headers - Header tuples from `connect(url, { headers })`, or undefined.
132
+ * @returns A plain object of the forwardable headers (may be empty).
133
+ */
134
+ function forwardableUpgradeHeaders(headers) {
135
+ const out = {};
136
+ for (const [key, value] of headers ?? []) if (!WS_CONTROL_HEADERS.has(key.toLowerCase())) out[key] = value;
137
+ return out;
138
+ }
139
+ /**
140
+ * Normalize an inbound WebSocket payload to the `Uint8Array | string` contract
141
+ * the DO Socket facade expects: text frames stay strings, binary frames become
142
+ * a `Uint8Array` view regardless of whether the runtime delivered an
143
+ * `ArrayBuffer`, a `Buffer`, or another typed-array/DataView.
144
+ *
145
+ * @param data - The raw `MessageEvent.data` from the DO pass-through socket.
146
+ * @returns The payload as a string (text) or `Uint8Array` (binary).
147
+ */
148
+ function normalizeIncomingWsData(data) {
149
+ if (typeof data === "string") return data;
150
+ if (data instanceof Uint8Array) return data;
151
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
152
+ if (ArrayBuffer.isView(data)) {
153
+ const view = data;
154
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
155
+ }
156
+ return String(data);
157
+ }
158
+ /**
159
+ * Open a real pass-through WebSocket to a Durable Object through the gateway's
160
+ * `/_devflare/do-ws` endpoint. Unlike the legacy relay, this is a standalone
161
+ * connection with its own lifecycle, so it is unaffected by the bridge client's
162
+ * `disconnect()`/reconnect bookkeeping.
163
+ *
164
+ * @param bridgeUrl - The bridge/gateway base URL (e.g. `ws://127.0.0.1:8787`).
165
+ * @param binding - DO namespace binding name (e.g. `DOC_ROOM`).
166
+ * @param idHex - Already-resolved Durable Object id, hex form.
167
+ * @param targetUrl - The DO fetch URL the caller passed to `stub.connect(url)`.
168
+ * @param headers - Optional upgrade headers (auth/cookies) forwarded to the DO.
169
+ * @returns A proxy surface (send/close/onMessage/onClose) over the socket.
170
+ * @throws When the pass-through socket fails to open (bad binding/id, or the DO
171
+ * rejected the upgrade).
172
+ */
173
+ async function openDurableObjectWebSocket(bridgeUrl, binding, idHex, targetUrl, headers) {
174
+ const wsUrl = new URL(bridgeUrl);
175
+ wsUrl.pathname = "/_devflare/do-ws";
176
+ wsUrl.searchParams.set("binding", binding);
177
+ wsUrl.searchParams.set("id", idHex);
178
+ wsUrl.searchParams.set("u", targetUrl);
179
+ const forwardHeaders = forwardableUpgradeHeaders(headers);
180
+ const hasHeaders = Object.keys(forwardHeaders).length > 0;
181
+ const WebSocketCtor = await resolveDoWebSocketConstructor(hasHeaders);
182
+ const socket = hasHeaders ? new WebSocketCtor(wsUrl.toString(), { headers: forwardHeaders }) : new WebSocketCtor(wsUrl.toString());
183
+ socket.binaryType = "arraybuffer";
184
+ let opened = false;
185
+ let messageHandler = null;
186
+ let closeHandler = null;
187
+ const pendingMessages = [];
188
+ let pendingClose = null;
189
+ socket.onmessage = (event) => {
190
+ const data = normalizeIncomingWsData(event.data);
191
+ if (messageHandler) messageHandler(data);
192
+ else pendingMessages.push(data);
193
+ };
194
+ await new Promise((resolve, reject) => {
195
+ socket.onopen = () => {
196
+ opened = true;
197
+ resolve();
198
+ };
199
+ socket.onerror = () => {
200
+ if (!opened) reject(/* @__PURE__ */ new Error(`DO WebSocket connection failed: ${binding}/${idHex}`));
201
+ };
202
+ socket.onclose = (event) => {
203
+ if (!opened) {
204
+ reject(/* @__PURE__ */ new Error(`DO WebSocket closed before open: ${binding}/${idHex}`));
205
+ return;
206
+ }
207
+ if (closeHandler) closeHandler(event?.code, event?.reason);
208
+ else pendingClose = {
209
+ code: event?.code,
210
+ reason: event?.reason
211
+ };
212
+ };
213
+ });
214
+ return {
215
+ wid: nextWsId(),
216
+ send: (data) => socket.send(data),
217
+ close: (code, reason) => socket.close(code, reason),
218
+ onMessage: (handler) => {
219
+ messageHandler = handler;
220
+ if (pendingMessages.length > 0) for (const data of pendingMessages.splice(0)) handler(data);
221
+ },
222
+ onClose: (handler) => {
223
+ closeHandler = handler;
224
+ if (pendingClose) {
225
+ handler(pendingClose.code, pendingClose.reason);
226
+ pendingClose = null;
227
+ }
228
+ }
229
+ };
230
+ }
231
+ //#endregion
232
+ //#region src/bridge/log.ts
233
+ const isDebugEnabled = () => {
234
+ try {
235
+ const env = globalThis.process?.env;
236
+ return Boolean(env?.DEVFLARE_DEBUG_BRIDGE);
237
+ } catch {
238
+ return false;
239
+ }
240
+ };
241
+ const bridgeLog = {
242
+ warn(message, error) {
243
+ if (!isDebugEnabled()) return;
244
+ console.warn(`[devflare:bridge] ${message}`, error);
245
+ },
246
+ debug(message, error) {
247
+ if (!isDebugEnabled()) return;
248
+ console.debug(`[devflare:bridge] ${message}`, error);
249
+ }
250
+ };
251
+ /** WebSocket close code used when v2 ↔ v1 mismatch is detected at handshake. */
252
+ const TRANSPORT_V2_UNSUPPORTED_VERSION_CLOSE_CODE = 4001;
253
+ /**
254
+ * Binary frame kinds for v2. Values 1 (StreamChunk) and 2 (WsData) are
255
+ * deliberately stable with v1 so a future shared decoder can route either
256
+ * version's frames. Value 3 (BodyChunk) is new in v2 for HTTP body streams.
257
+ */
258
+ const TransportV2BinaryKind = {
259
+ StreamChunk: 1,
260
+ WsData: 2,
261
+ BodyChunk: 3
262
+ };
263
+ /** Binary frame flags for v2. */
264
+ const TransportV2BinaryFlags = {
265
+ FIN: 1,
266
+ TEXT: 2,
267
+ ABORT: 4
268
+ };
269
+ /** Decode a v2 binary frame. Pure; returns a view that aliases the input bytes. */
270
+ function decodeTransportV2BinaryFrame(frame) {
271
+ if (frame.byteLength < 10) throw new Error(`Invalid transport v2 binary frame: too short (${frame.byteLength} bytes, need at least 10)`);
272
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
273
+ const kind = view.getUint8(0);
274
+ if (kind !== TransportV2BinaryKind.StreamChunk && kind !== TransportV2BinaryKind.WsData && kind !== TransportV2BinaryKind.BodyChunk) throw new Error(`Invalid transport v2 binary frame: unknown kind ${kind}`);
275
+ return {
276
+ kind,
277
+ id: view.getUint32(1, true),
278
+ seq: view.getUint32(5, true),
279
+ flags: view.getUint8(9),
280
+ payload: frame.subarray(10)
281
+ };
282
+ }
283
+ /** True when the FIN flag is set on a v2 binary frame. */
284
+ function transportV2IsFin(flags) {
285
+ return (flags & TransportV2BinaryFlags.FIN) !== 0;
286
+ }
287
+ /** True when the ABORT flag is set on a v2 binary frame. */
288
+ function transportV2IsAbort(flags) {
289
+ return (flags & TransportV2BinaryFlags.ABORT) !== 0;
290
+ }
291
+ const KNOWN_V2_CONTROL_TYPES = new Set([
292
+ "hello",
293
+ "welcome",
294
+ "body.open",
295
+ "body.end",
296
+ "body.abort"
297
+ ]);
298
+ /**
299
+ * Parse a JSON string as a v2-specific control message. Returns the typed
300
+ * message or throws if the payload is not a recognised v2 control type.
301
+ *
302
+ * Callers that need to multiplex v1 `JsonMsg` and v2 control messages should
303
+ * inspect the `t` field first and dispatch accordingly; this helper is
304
+ * deliberately strict so that v2-only code paths never silently accept v1
305
+ * payloads.
306
+ */
307
+ function parseTransportV2ControlMsg(data) {
308
+ const msg = JSON.parse(data);
309
+ if (typeof msg !== "object" || msg === null || !("t" in msg)) throw new Error("Invalid transport v2 control message: missing type field");
310
+ if (!KNOWN_V2_CONTROL_TYPES.has(msg.t)) throw new Error(`Invalid transport v2 control message: unknown type "${msg.t}"`);
311
+ if (msg.t === "hello" || msg.t === "welcome") {
312
+ if (msg.protocolVersion !== 2) throw new Error(`Invalid transport v2 ${msg.t}: protocolVersion ${msg.protocolVersion} != 2`);
313
+ if (!Array.isArray(msg.capabilities)) throw new Error(`Invalid transport v2 ${msg.t}: capabilities must be an array`);
314
+ }
315
+ return msg;
316
+ }
317
+ /** Stringify a v2 control message. Pure. */
318
+ function stringifyTransportV2ControlMsg(msg) {
319
+ return JSON.stringify(msg);
320
+ }
321
+ /**
322
+ * Compute the capability intersection a server should announce in its
323
+ * `welcome` reply, given its own supported set and the client's `hello`
324
+ * advertisement. Order is deterministic (sorted) so the wire output is
325
+ * reproducible across runs.
326
+ */
327
+ function negotiateTransportV2Capabilities(supported, advertised) {
328
+ const supportedSet = new Set(supported);
329
+ const intersection = advertised.filter((cap) => supportedSet.has(cap));
330
+ return [...new Set(intersection)].sort();
331
+ }
332
+ //#endregion
333
+ //#region src/bridge/v2/body-streams.ts
334
+ /**
335
+ * Tracks in-flight v2 body streams on the reader side. The codec routes
336
+ * incoming `body.open` / `body.end` / `body.abort` control messages and
337
+ * `BodyChunk` binary frames here; consumers of v2 RPC results obtain a
338
+ * `ReadableStream<Uint8Array>` to attach to a `Request` / `Response`.
339
+ */
340
+ var TransportV2BodyReaderRegistry = class {
341
+ #streams = /* @__PURE__ */ new Map();
342
+ /** Register a new body stream and return the reader-side `ReadableStream`. Idempotent: returns the existing stream if `bid` is already registered. */
343
+ getOrOpen(bid) {
344
+ const existing = this.#streams.get(bid);
345
+ if (existing !== void 0) return existing.stream;
346
+ return this.open(bid);
347
+ }
348
+ /** Register a new body stream and return the reader-side `ReadableStream`. Throws if `bid` is already registered. */
349
+ open(bid) {
350
+ if (this.#streams.has(bid)) throw new Error(`v2 body reader already registered for bid ${bid}`);
351
+ const state = {
352
+ controller: null,
353
+ stream: null,
354
+ closed: false
355
+ };
356
+ state.stream = new ReadableStream({
357
+ start: (controller) => {
358
+ state.controller = controller;
359
+ },
360
+ cancel: () => {
361
+ state.closed = true;
362
+ this.#streams.delete(bid);
363
+ }
364
+ });
365
+ this.#streams.set(bid, state);
366
+ return state.stream;
367
+ }
368
+ /** Push a decoded BodyChunk frame to the matching reader. */
369
+ pushChunk(frame) {
370
+ if (frame.kind !== TransportV2BinaryKind.BodyChunk) throw new Error(`v2 body reader received non-BodyChunk frame (kind=${frame.kind})`);
371
+ const state = this.#streams.get(frame.id);
372
+ if (state === void 0 || state.closed) return;
373
+ const isFin = transportV2IsFin(frame.flags);
374
+ if (transportV2IsAbort(frame.flags)) {
375
+ state.closed = true;
376
+ state.controller?.error(/* @__PURE__ */ new Error(`v2 body stream ${frame.id} aborted by writer`));
377
+ this.#streams.delete(frame.id);
378
+ return;
379
+ }
380
+ if (frame.payload.byteLength > 0) state.controller?.enqueue(new Uint8Array(frame.payload));
381
+ if (isFin) {
382
+ state.closed = true;
383
+ state.controller?.close();
384
+ this.#streams.delete(frame.id);
385
+ }
386
+ }
387
+ /** Handle a `body.end` control message (writer signalled clean end). */
388
+ end(bid) {
389
+ const state = this.#streams.get(bid);
390
+ if (state === void 0 || state.closed) return;
391
+ state.closed = true;
392
+ state.controller?.close();
393
+ this.#streams.delete(bid);
394
+ }
395
+ /** Handle a `body.abort` control message. */
396
+ abort(bid, reason) {
397
+ const state = this.#streams.get(bid);
398
+ if (state === void 0 || state.closed) return;
399
+ state.closed = true;
400
+ state.controller?.error(new Error(reason ?? `v2 body stream ${bid} aborted`));
401
+ this.#streams.delete(bid);
402
+ }
403
+ /** Number of currently open reader-side body streams (for tests/diagnostics). */
404
+ get size() {
405
+ return this.#streams.size;
406
+ }
407
+ };
408
+ //#endregion
409
+ //#region src/bridge/v2/codec.ts
410
+ /**
411
+ * v2 codec attached to a single `WebSocketLike`. Owns handshake state, the
412
+ * frame demultiplexer, RPC pending-call table, and the body-stream registry.
413
+ */
414
+ var TransportV2Codec = class {
415
+ bodyReaders = new TransportV2BodyReaderRegistry();
416
+ #socket;
417
+ #capabilities;
418
+ #options;
419
+ #handshakeResolver = null;
420
+ #handshakePromise;
421
+ #sentHello = false;
422
+ #receivedHello = false;
423
+ #receivedWelcome = false;
424
+ #negotiated = null;
425
+ #pendingRpc = /* @__PURE__ */ new Map();
426
+ #nextBid = 1;
427
+ #nextRpcId = 1;
428
+ #closed = false;
429
+ constructor(socket, options = {}) {
430
+ this.#socket = socket;
431
+ this.#capabilities = options.capabilities ?? [];
432
+ this.#options = options;
433
+ this.#handshakePromise = new Promise((resolve, reject) => {
434
+ this.#handshakeResolver = {
435
+ resolve,
436
+ reject
437
+ };
438
+ });
439
+ socket.onmessage = (event) => this.#onMessage(event);
440
+ socket.onclose = () => this.#onClose();
441
+ socket.onerror = (event) => this.#onError(event.error);
442
+ }
443
+ /** Allocate a fresh body id (writer side). */
444
+ allocateBid() {
445
+ return this.#nextBid++;
446
+ }
447
+ /** Allocate a fresh RPC id (caller side). */
448
+ allocateRpcId() {
449
+ return `v2_rpc_${this.#nextRpcId++}`;
450
+ }
451
+ /** Send the `hello` frame. Called once by the side that initiates the handshake. */
452
+ sendHello() {
453
+ if (this.#sentHello) return;
454
+ this.#sentHello = true;
455
+ const hello = {
456
+ t: "hello",
457
+ protocolVersion: 2,
458
+ capabilities: [...this.#capabilities]
459
+ };
460
+ this.#socket.send(stringifyTransportV2ControlMsg(hello));
461
+ }
462
+ /** Promise that resolves once the handshake completes. */
463
+ get handshake() {
464
+ return this.#handshakePromise;
465
+ }
466
+ /** Negotiated capabilities once the handshake completes. */
467
+ get negotiated() {
468
+ return this.#negotiated;
469
+ }
470
+ sendText(message) {
471
+ if (this.#closed) throw new Error("cannot send on a closed v2 codec");
472
+ this.#socket.send(message);
473
+ }
474
+ sendBinary(frame) {
475
+ if (this.#closed) throw new Error("cannot send on a closed v2 codec");
476
+ this.#socket.send(frame);
477
+ }
478
+ /** Send a typed RPC call and resolve with the peer's `rpc.ok` result. */
479
+ call(method, params = []) {
480
+ const id = this.allocateRpcId();
481
+ const call = {
482
+ t: "rpc.call",
483
+ id,
484
+ method,
485
+ params
486
+ };
487
+ const promise = new Promise((resolve, reject) => {
488
+ this.#pendingRpc.set(id, {
489
+ resolve,
490
+ reject
491
+ });
492
+ });
493
+ this.sendText(JSON.stringify(call));
494
+ return promise;
495
+ }
496
+ /** Send an `rpc.ok` reply for a previously-received call. */
497
+ respondOk(id, result) {
498
+ const reply = {
499
+ t: "rpc.ok",
500
+ id,
501
+ result
502
+ };
503
+ this.sendText(JSON.stringify(reply));
504
+ }
505
+ /** Send an `rpc.err` reply for a previously-received call. */
506
+ respondErr(id, error) {
507
+ const reply = {
508
+ t: "rpc.err",
509
+ id,
510
+ error
511
+ };
512
+ this.sendText(JSON.stringify(reply));
513
+ }
514
+ /**
515
+ * Send an out-of-band structured `error` frame (B5-frame). Use for
516
+ * failures that are not scoped to a single RPC call id — e.g. malformed
517
+ * incoming frames, stream/ws aborts that need a typed cause, or gateway
518
+ * bookkeeping errors. Replaces silent `catch {}` fallthroughs.
519
+ */
520
+ sendWireError(err) {
521
+ const frame = {
522
+ t: "error",
523
+ ...err
524
+ };
525
+ this.sendText(JSON.stringify(frame));
526
+ }
527
+ /** Register a reader-side body stream. Returns the `ReadableStream`. Idempotent across the codec's `body.open` arrival. */
528
+ openBodyReader(bid) {
529
+ return this.bodyReaders.getOrOpen(bid);
530
+ }
531
+ /** Replace the `onRpcCall` handler after construction. Useful for one-shot tests and for higher RPC layers that build the handler lazily. */
532
+ setRpcCallHandler(handler) {
533
+ this.#options = {
534
+ ...this.#options,
535
+ onRpcCall: handler
536
+ };
537
+ }
538
+ /** Close the underlying transport with an optional code/reason. */
539
+ close(code, reason) {
540
+ if (this.#closed) return;
541
+ this.#closed = true;
542
+ this.#failPending(/* @__PURE__ */ new Error("v2 transport closed"));
543
+ this.#socket.close(code, reason);
544
+ }
545
+ get isClosed() {
546
+ return this.#closed;
547
+ }
548
+ #onMessage(event) {
549
+ const { data } = event;
550
+ if (typeof data === "string") this.#onText(data);
551
+ else if (data instanceof Uint8Array) this.#onBinary(data);
552
+ else if (data instanceof ArrayBuffer) this.#onBinary(new Uint8Array(data));
553
+ }
554
+ #onText(data) {
555
+ let msg;
556
+ try {
557
+ msg = parseTransportV2ControlMsg(data);
558
+ } catch {
559
+ const rpc = tryParseRpcMsg(data);
560
+ if (rpc !== null) {
561
+ this.#onRpcMessage(rpc);
562
+ return;
563
+ }
564
+ const wireErr = tryParseWireError(data);
565
+ if (wireErr !== null) {
566
+ this.#options.onWireError?.(wireErr);
567
+ return;
568
+ }
569
+ this.#options.onUnknownControl?.(data);
570
+ return;
571
+ }
572
+ switch (msg.t) {
573
+ case "hello":
574
+ this.#onHello(msg);
575
+ break;
576
+ case "welcome":
577
+ this.#onWelcome(msg);
578
+ break;
579
+ case "body.open":
580
+ this.bodyReaders.getOrOpen(msg.bid);
581
+ break;
582
+ case "body.end":
583
+ this.bodyReaders.end(msg.bid);
584
+ break;
585
+ case "body.abort":
586
+ this.bodyReaders.abort(msg.bid, msg.error);
587
+ break;
588
+ }
589
+ }
590
+ #onBinary(data) {
591
+ let frame;
592
+ try {
593
+ frame = decodeTransportV2BinaryFrame(data);
594
+ } catch {
595
+ return;
596
+ }
597
+ if (frame.kind === TransportV2BinaryKind.BodyChunk) {
598
+ this.bodyReaders.pushChunk(frame);
599
+ return;
600
+ }
601
+ this.#options.onUnknownBinary?.(frame);
602
+ }
603
+ #onRpcMessage(msg) {
604
+ switch (msg.t) {
605
+ case "rpc.call":
606
+ this.#options.onRpcCall?.(msg);
607
+ break;
608
+ case "rpc.ok": {
609
+ const pending = this.#pendingRpc.get(msg.id);
610
+ if (pending !== void 0) {
611
+ this.#pendingRpc.delete(msg.id);
612
+ pending.resolve(msg.result);
613
+ }
614
+ break;
615
+ }
616
+ case "rpc.err": {
617
+ const pending = this.#pendingRpc.get(msg.id);
618
+ if (pending !== void 0) {
619
+ this.#pendingRpc.delete(msg.id);
620
+ const err = new Error(msg.error.message);
621
+ Object.assign(err, {
622
+ code: msg.error.code,
623
+ details: msg.error.details
624
+ });
625
+ pending.reject(err);
626
+ }
627
+ break;
628
+ }
629
+ }
630
+ }
631
+ #onHello(msg) {
632
+ if (this.#receivedHello) {
633
+ this.close(TRANSPORT_V2_UNSUPPORTED_VERSION_CLOSE_CODE, "duplicate hello");
634
+ return;
635
+ }
636
+ this.#receivedHello = true;
637
+ const negotiated = negotiateTransportV2Capabilities(this.#capabilities, msg.capabilities);
638
+ const welcome = {
639
+ t: "welcome",
640
+ protocolVersion: 2,
641
+ capabilities: negotiated
642
+ };
643
+ this.#socket.send(stringifyTransportV2ControlMsg(welcome));
644
+ this.#completeHandshake({
645
+ protocolVersion: 2,
646
+ capabilities: negotiated
647
+ });
648
+ }
649
+ #onWelcome(msg) {
650
+ if (this.#receivedWelcome) return;
651
+ this.#receivedWelcome = true;
652
+ this.#completeHandshake({
653
+ protocolVersion: 2,
654
+ capabilities: msg.capabilities
655
+ });
656
+ }
657
+ #completeHandshake(result) {
658
+ if (this.#negotiated !== null) return;
659
+ this.#negotiated = result;
660
+ this.#handshakeResolver?.resolve(result);
661
+ this.#handshakeResolver = null;
662
+ }
663
+ #onClose() {
664
+ if (this.#closed) return;
665
+ this.#closed = true;
666
+ this.#failPending(/* @__PURE__ */ new Error("v2 transport closed"));
667
+ }
668
+ #onError(error) {
669
+ const wrapped = error instanceof Error ? error : new Error(String(error));
670
+ this.#failPending(wrapped);
671
+ }
672
+ #failPending(error) {
673
+ const resolver = this.#handshakeResolver;
674
+ if (resolver !== null) {
675
+ this.#handshakeResolver = null;
676
+ resolver.reject(error);
677
+ }
678
+ for (const pending of this.#pendingRpc.values()) pending.reject(error);
679
+ this.#pendingRpc.clear();
680
+ }
681
+ };
682
+ function tryParseRpcMsg(data) {
683
+ let parsed;
684
+ try {
685
+ parsed = JSON.parse(data);
686
+ } catch {
687
+ return null;
688
+ }
689
+ if (typeof parsed !== "object" || parsed === null || !("t" in parsed)) return null;
690
+ const t = parsed.t;
691
+ if (t === "rpc.call" || t === "rpc.ok" || t === "rpc.err") return parsed;
692
+ return null;
693
+ }
694
+ function tryParseWireError(data) {
695
+ let parsed;
696
+ try {
697
+ parsed = JSON.parse(data);
698
+ } catch {
699
+ return null;
700
+ }
701
+ if (typeof parsed !== "object" || parsed === null || !("t" in parsed)) return null;
702
+ const candidate = parsed;
703
+ if (candidate.t !== "error") return null;
704
+ const scope = candidate.scope;
705
+ if (scope !== "transport" && scope !== "rpc" && scope !== "stream" && scope !== "ws") return null;
706
+ const err = candidate.error;
707
+ if (!err || typeof err.code !== "string" || typeof err.message !== "string") return null;
708
+ return parsed;
709
+ }
710
+ //#endregion
711
+ //#region src/bridge/v2/value-serialization.ts
712
+ /**
713
+ * Read every `Set-Cookie` header value as a SEPARATE string.
714
+ *
715
+ * `Headers.forEach`/`entries()`/`get()` fold multiple `Set-Cookie` headers into
716
+ * one comma-joined value (the Fetch spec's sort-and-combine), which corrupts
717
+ * cookies: the second cookie's attributes bleed into the first. Only the
718
+ * dedicated accessors keep them apart — the standard `getSetCookie()` (Bun,
719
+ * Node, and workerd on a compatibility date ≥ 2023-08-01) or workerd's legacy
720
+ * `getAll('set-cookie')` (present on older compat dates that predate
721
+ * `getSetCookie`).
722
+ *
723
+ * @param headers - The header set to read.
724
+ * @returns Each `Set-Cookie` value in insertion order, or `null` when the
725
+ * runtime exposes neither accessor — the caller then keeps the combined value
726
+ * rather than dropping the header.
727
+ */
728
+ function readSetCookieValues(headers) {
729
+ const accessors = headers;
730
+ if (typeof accessors.getSetCookie === "function") {
731
+ const values = accessors.getSetCookie();
732
+ return Array.isArray(values) ? values : null;
733
+ }
734
+ if (typeof accessors.getAll === "function") try {
735
+ const values = accessors.getAll("set-cookie");
736
+ return Array.isArray(values) ? values : null;
737
+ } catch {
738
+ return null;
739
+ }
740
+ return null;
741
+ }
742
+ /**
743
+ * Flatten a `Headers` set to `[name, value]` pairs WITHOUT collapsing multiple
744
+ * `Set-Cookie` headers into one, so a response setting several cookies survives
745
+ * the bridge round-trip byte-faithfully.
746
+ *
747
+ * Non-cookie headers are emitted via `forEach` as before. `Set-Cookie` is
748
+ * enumerated separately (see `readSetCookieValues`) and appended as its own pair
749
+ * per cookie, so the reconstructing `new Headers(pairs)` re-`append`s each one.
750
+ * When the runtime can split neither (no `getSetCookie`/`getAll`), the combined
751
+ * `forEach` value is kept verbatim — graceful degradation, never a dropped
752
+ * header.
753
+ *
754
+ * @param headers - The header set to flatten.
755
+ * @returns `[name, value]` pairs safe to round-trip; each `Set-Cookie` is a
756
+ * distinct pair.
757
+ */
758
+ function serializeHeaders(headers) {
759
+ const setCookies = readSetCookieValues(headers);
760
+ const pairs = [];
761
+ headers.forEach((value, key) => {
762
+ if (setCookies !== null && key.toLowerCase() === "set-cookie") return;
763
+ pairs.push([key, value]);
764
+ });
765
+ if (setCookies) for (const cookie of setCookies) pairs.push(["set-cookie", cookie]);
766
+ return pairs;
767
+ }
768
+ /** Serialize a Request to a POJO */
769
+ async function serializeRequest(request, options) {
770
+ const streams = [];
771
+ const threshold = options?.httpThreshold ?? 524288;
772
+ const headers = serializeHeaders(request.headers);
773
+ let body = null;
774
+ if (request.body) {
775
+ const bytes = await request.arrayBuffer();
776
+ if (bytes.byteLength > threshold) throw new Error("Request body exceeds the bridge inline limit (~512 KB) and large request-body streaming is not yet supported over the local bridge. Send the payload in smaller chunks or via an R2 binding for now.");
777
+ if (bytes.byteLength > 0) body = {
778
+ type: "bytes",
779
+ data: base64Encode(new Uint8Array(bytes))
780
+ };
781
+ }
782
+ return {
783
+ serialized: {
784
+ url: request.url,
785
+ method: request.method,
786
+ headers,
787
+ body,
788
+ redirect: request.redirect
789
+ },
790
+ streams
791
+ };
792
+ }
793
+ /** Deserialize a Request from a POJO */
794
+ function deserializeRequest(serialized, getStream) {
795
+ let body = null;
796
+ if (serialized.body) switch (serialized.body.type) {
797
+ case "bytes":
798
+ body = base64Decode(serialized.body.data);
799
+ break;
800
+ case "stream":
801
+ if (getStream) body = getStream(serialized.body.sid) ?? null;
802
+ break;
803
+ }
804
+ return new Request(serialized.url, {
805
+ method: serialized.method,
806
+ headers: serialized.headers,
807
+ body,
808
+ redirect: serialized.redirect
809
+ });
810
+ }
811
+ /** Serialize a Response to a POJO */
812
+ async function serializeResponse(response, options) {
813
+ const streams = [];
814
+ const threshold = options?.httpThreshold ?? 524288;
815
+ const headers = serializeHeaders(response.headers);
816
+ let body = null;
817
+ if (response.body) {
818
+ const bytes = await response.arrayBuffer();
819
+ if (bytes.byteLength > threshold) {
820
+ const sid = nextStreamId();
821
+ const payload = new Uint8Array(bytes);
822
+ const frameSize = HTTP_TRANSFER_THRESHOLD;
823
+ const stream = new ReadableStream({ start(controller) {
824
+ for (let offset = 0; offset < payload.byteLength; offset += frameSize) controller.enqueue(payload.slice(offset, Math.min(offset + frameSize, payload.byteLength)));
825
+ controller.close();
826
+ } });
827
+ streams.push({
828
+ sid,
829
+ stream
830
+ });
831
+ body = {
832
+ type: "stream",
833
+ sid
834
+ };
835
+ } else if (bytes.byteLength > 0) body = {
836
+ type: "bytes",
837
+ data: base64Encode(new Uint8Array(bytes))
838
+ };
839
+ }
840
+ return {
841
+ serialized: {
842
+ status: response.status,
843
+ statusText: response.statusText,
844
+ headers,
845
+ body
846
+ },
847
+ streams
848
+ };
849
+ }
850
+ /** Deserialize a Response from a POJO */
851
+ function deserializeResponse(serialized, getStream) {
852
+ let body = null;
853
+ if (serialized.body) switch (serialized.body.type) {
854
+ case "bytes":
855
+ body = base64Decode(serialized.body.data);
856
+ break;
857
+ case "stream":
858
+ if (getStream) body = getStream(serialized.body.sid) ?? null;
859
+ break;
860
+ }
861
+ return new Response(body, {
862
+ status: serialized.status,
863
+ statusText: serialized.statusText,
864
+ headers: serialized.headers
865
+ });
866
+ }
867
+ /** Serialize a value that may contain special types */
868
+ async function serializeValue(value, options) {
869
+ const streams = [];
870
+ return {
871
+ value: await serializeValueInternal(value, streams, options),
872
+ streams
873
+ };
874
+ }
875
+ async function serializeValueInternal(value, streams, options) {
876
+ if (value === null || value === void 0) return value;
877
+ if (value instanceof Request) {
878
+ const { serialized, streams: reqStreams } = await serializeRequest(value, options);
879
+ streams.push(...reqStreams);
880
+ return {
881
+ __type: "Request",
882
+ ...serialized
883
+ };
884
+ }
885
+ if (value instanceof Response) {
886
+ const { serialized, streams: resStreams } = await serializeResponse(value, options);
887
+ streams.push(...resStreams);
888
+ return {
889
+ __type: "Response",
890
+ ...serialized
891
+ };
892
+ }
893
+ if (value instanceof ReadableStream) {
894
+ const sid = nextStreamId();
895
+ streams.push({
896
+ sid,
897
+ stream: value
898
+ });
899
+ return {
900
+ __type: "ReadableStream",
901
+ sid
902
+ };
903
+ }
904
+ if (value instanceof Uint8Array) return {
905
+ __type: "Uint8Array",
906
+ data: base64Encode(value)
907
+ };
908
+ if (value instanceof ArrayBuffer) return {
909
+ __type: "ArrayBuffer",
910
+ data: base64Encode(new Uint8Array(value))
911
+ };
912
+ if (value instanceof Date) return {
913
+ __devflare: "date",
914
+ iso: value.toISOString()
915
+ };
916
+ if (value instanceof URL) return {
917
+ __devflare: "url",
918
+ href: value.href
919
+ };
920
+ if (value instanceof Error) {
921
+ const encoded = {
922
+ __devflare: "error",
923
+ name: value.name,
924
+ message: value.message
925
+ };
926
+ if (value.stack) encoded.stack = value.stack;
927
+ return encoded;
928
+ }
929
+ if (value instanceof Map) {
930
+ const entries = [];
931
+ for (const [k, v] of value.entries()) entries.push([await serializeValueInternal(k, streams, options), await serializeValueInternal(v, streams, options)]);
932
+ return {
933
+ __devflare: "map",
934
+ entries
935
+ };
936
+ }
937
+ if (value instanceof Set) {
938
+ const values = [];
939
+ for (const v of value.values()) values.push(await serializeValueInternal(v, streams, options));
940
+ return {
941
+ __devflare: "set",
942
+ values
943
+ };
944
+ }
945
+ if (Array.isArray(value)) return Promise.all(value.map((v) => serializeValueInternal(v, streams, options)));
946
+ if (typeof value === "object") {
947
+ const result = {};
948
+ for (const [k, v] of Object.entries(value)) result[k] = await serializeValueInternal(v, streams, options);
949
+ return result;
950
+ }
951
+ return value;
952
+ }
953
+ /** Deserialize a value that may contain special types */
954
+ function deserializeValue(value, getStream) {
955
+ if (value === null || value === void 0) return value;
956
+ if (typeof value === "object" && value !== null) {
957
+ const obj = value;
958
+ if (typeof obj.__devflare === "string") switch (obj.__devflare) {
959
+ case "date": return new Date(obj.iso);
960
+ case "url": return new URL(obj.href);
961
+ case "error": {
962
+ const err = new Error(obj.message);
963
+ if (typeof obj.name === "string") err.name = obj.name;
964
+ if (typeof obj.stack === "string") err.stack = obj.stack;
965
+ return err;
966
+ }
967
+ case "map": {
968
+ const entries = obj.entries ?? [];
969
+ const map = /* @__PURE__ */ new Map();
970
+ for (const [k, v] of entries) map.set(deserializeValue(k, getStream), deserializeValue(v, getStream));
971
+ return map;
972
+ }
973
+ case "set": {
974
+ const values = obj.values ?? [];
975
+ const set = /* @__PURE__ */ new Set();
976
+ for (const v of values) set.add(deserializeValue(v, getStream));
977
+ return set;
978
+ }
979
+ }
980
+ if (obj.__type === "Request") return deserializeRequest(obj, getStream);
981
+ if (obj.__type === "Response") return deserializeResponse(obj, getStream);
982
+ if (obj.__type === "ReadableStream") {
983
+ const sid = obj.sid;
984
+ return getStream?.(sid) ?? null;
985
+ }
986
+ if (obj.__type === "Uint8Array") return base64Decode(obj.data);
987
+ if (obj.__type === "ArrayBuffer") return base64Decode(obj.data).buffer;
988
+ if (obj.__type === "R2Object") return deserializeR2Object(obj);
989
+ if (obj.__type === "R2ObjectBody") return deserializeR2ObjectBody(obj);
990
+ if (Array.isArray(value)) return value.map((v) => deserializeValue(v, getStream));
991
+ const result = {};
992
+ for (const [k, v] of Object.entries(obj)) result[k] = deserializeValue(v, getStream);
993
+ return result;
994
+ }
995
+ return value;
996
+ }
997
+ function applySerializedHttpMetadata(headers, httpMetadata) {
998
+ if (httpMetadata?.contentType) headers.set("Content-Type", httpMetadata.contentType);
999
+ if (httpMetadata?.contentLanguage) headers.set("Content-Language", httpMetadata.contentLanguage);
1000
+ if (httpMetadata?.contentDisposition) headers.set("Content-Disposition", httpMetadata.contentDisposition);
1001
+ if (httpMetadata?.contentEncoding) headers.set("Content-Encoding", httpMetadata.contentEncoding);
1002
+ if (httpMetadata?.cacheControl) headers.set("Cache-Control", httpMetadata.cacheControl);
1003
+ if (httpMetadata?.cacheExpiry) headers.set("Expires", new Date(httpMetadata.cacheExpiry).toUTCString());
1004
+ }
1005
+ function createSerializedR2Metadata(serialized) {
1006
+ return {
1007
+ key: serialized.key,
1008
+ version: serialized.version,
1009
+ size: serialized.size,
1010
+ etag: serialized.etag,
1011
+ httpEtag: serialized.httpEtag,
1012
+ checksums: serialized.checksums,
1013
+ uploaded: serialized.uploaded ? new Date(serialized.uploaded) : /* @__PURE__ */ new Date(),
1014
+ httpMetadata: serialized.httpMetadata,
1015
+ customMetadata: serialized.customMetadata,
1016
+ range: serialized.range,
1017
+ storageClass: serialized.storageClass,
1018
+ writeHttpMetadata(headers) {
1019
+ applySerializedHttpMetadata(headers, serialized.httpMetadata);
1020
+ }
1021
+ };
1022
+ }
1023
+ /** Deserialize R2Object (metadata only) */
1024
+ function deserializeR2Object(obj) {
1025
+ return { ...createSerializedR2Metadata(obj) };
1026
+ }
1027
+ /** Deserialize R2ObjectBody (with body data) */
1028
+ function deserializeR2ObjectBody(obj) {
1029
+ const serialized = obj;
1030
+ const bodyBytes = serialized.bodyData ? base64Decode(serialized.bodyData) : new Uint8Array(0);
1031
+ return {
1032
+ ...createSerializedR2Metadata(serialized),
1033
+ body: new ReadableStream({ start(controller) {
1034
+ controller.enqueue(bodyBytes);
1035
+ controller.close();
1036
+ } }),
1037
+ bodyUsed: false,
1038
+ async arrayBuffer() {
1039
+ const copy = new Uint8Array(bodyBytes.byteLength);
1040
+ copy.set(bodyBytes);
1041
+ return copy.buffer;
1042
+ },
1043
+ async text() {
1044
+ return new TextDecoder().decode(bodyBytes);
1045
+ },
1046
+ async json() {
1047
+ const text = new TextDecoder().decode(bodyBytes);
1048
+ return JSON.parse(text);
1049
+ },
1050
+ async blob() {
1051
+ const contentType = serialized.httpMetadata?.contentType || "application/octet-stream";
1052
+ const buffer = bodyBytes.buffer.slice(bodyBytes.byteOffset, bodyBytes.byteOffset + bodyBytes.byteLength);
1053
+ return new Blob([buffer], { type: contentType });
1054
+ }
1055
+ };
1056
+ }
1057
+ /** Encode Uint8Array to base64 string */
1058
+ function base64Encode(bytes) {
1059
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
1060
+ let binary = "";
1061
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
1062
+ return btoa(binary);
1063
+ }
1064
+ /** Decode base64 string to Uint8Array */
1065
+ function base64Decode(str) {
1066
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(str, "base64"));
1067
+ const binary = atob(str);
1068
+ const bytes = new Uint8Array(binary.length);
1069
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1070
+ return bytes;
1071
+ }
1072
+ //#endregion
1073
+ //#region src/bridge/client.ts
1074
+ var BridgeWsAdapter = class {
1075
+ onmessage = null;
1076
+ onclose = null;
1077
+ onerror = null;
1078
+ #ws;
1079
+ constructor(ws) {
1080
+ this.#ws = ws;
1081
+ }
1082
+ send(data) {
1083
+ this.#ws.send(data);
1084
+ }
1085
+ close(code, reason) {
1086
+ this.#ws.close(code, reason);
1087
+ }
1088
+ };
1089
+ const BRIDGE_CLIENT_CAPABILITIES = [
1090
+ "streams",
1091
+ "ws-relay",
1092
+ "http-transfer"
1093
+ ];
1094
+ var BridgeClient = class {
1095
+ ws = null;
1096
+ codec = null;
1097
+ adapter = null;
1098
+ url;
1099
+ autoReconnect;
1100
+ reconnectDelay;
1101
+ connectTimeout;
1102
+ activeStreams = /* @__PURE__ */ new Map();
1103
+ wsProxies = /* @__PURE__ */ new Map();
1104
+ pendingWsOpens = /* @__PURE__ */ new Map();
1105
+ outgoingStreams = /* @__PURE__ */ new Map();
1106
+ eventListeners = /* @__PURE__ */ new Map();
1107
+ connectPromise = null;
1108
+ isConnected = false;
1109
+ constructor(options = {}) {
1110
+ this.url = options.url ?? `ws://localhost:8787`;
1111
+ this.autoReconnect = options.autoReconnect ?? true;
1112
+ this.reconnectDelay = options.reconnectDelay ?? 1e3;
1113
+ this.connectTimeout = options.connectTimeout ?? 5e3;
1114
+ }
1115
+ /** Get the WebSocket URL */
1116
+ getUrl() {
1117
+ return this.url;
1118
+ }
1119
+ /** Get the HTTP URL for transfer endpoint */
1120
+ getHttpUrl() {
1121
+ return this.url.replace(/^ws:\/\//, "http://").replace(/^wss:\/\//, "https://");
1122
+ }
1123
+ /** Connect to the bridge */
1124
+ async connect() {
1125
+ if (this.isConnected) return;
1126
+ if (this.connectPromise) return this.connectPromise;
1127
+ const WebSocketCtor = getRuntimeWebSocketConstructor();
1128
+ const promise = WebSocketCtor ? this.openConnection(WebSocketCtor) : this.openConnectionWithPackageFallback();
1129
+ this.connectPromise = promise;
1130
+ promise.catch(() => {
1131
+ if (this.connectPromise === promise) this.connectPromise = null;
1132
+ });
1133
+ return promise;
1134
+ }
1135
+ async openConnectionWithPackageFallback() {
1136
+ const WebSocketCtor = await importWsPackageConstructor();
1137
+ return this.openConnection(WebSocketCtor);
1138
+ }
1139
+ openConnection(WebSocketCtor) {
1140
+ return new Promise((resolve, reject) => {
1141
+ let socket = null;
1142
+ const isCurrent = () => socket !== null && this.ws === socket;
1143
+ const releaseConnectSlot = () => {
1144
+ if (isCurrent()) this.connectPromise = null;
1145
+ };
1146
+ const timeout = setTimeout(() => {
1147
+ socket?.close();
1148
+ reject(/* @__PURE__ */ new Error(`Connection timeout: ${this.url}`));
1149
+ }, this.connectTimeout);
1150
+ try {
1151
+ socket = new WebSocketCtor(this.url);
1152
+ this.ws = socket;
1153
+ socket.binaryType = "arraybuffer";
1154
+ const adapter = new BridgeWsAdapter(socket);
1155
+ this.adapter = adapter;
1156
+ socket.onopen = () => {
1157
+ clearTimeout(timeout);
1158
+ if (!isCurrent()) {
1159
+ socket?.close();
1160
+ reject(/* @__PURE__ */ new Error(`Bridge connection superseded: ${this.url}`));
1161
+ return;
1162
+ }
1163
+ this.codec = new TransportV2Codec(adapter, {
1164
+ capabilities: [...BRIDGE_CLIENT_CAPABILITIES],
1165
+ onUnknownControl: (data) => this.handleJsonMessage(data),
1166
+ onUnknownBinary: (frame) => this.handleV2BinaryFrame(frame)
1167
+ });
1168
+ this.codec.sendHello();
1169
+ this.codec.handshake.catch(() => {});
1170
+ this.isConnected = true;
1171
+ releaseConnectSlot();
1172
+ resolve();
1173
+ };
1174
+ socket.onerror = (event) => {
1175
+ clearTimeout(timeout);
1176
+ releaseConnectSlot();
1177
+ adapter.onerror?.({ error: event.error });
1178
+ reject(/* @__PURE__ */ new Error("WebSocket connection failed"));
1179
+ };
1180
+ socket.onclose = (event) => {
1181
+ adapter.onclose?.({
1182
+ code: event?.code ?? 1006,
1183
+ reason: event?.reason ?? ""
1184
+ });
1185
+ if (!isCurrent()) return;
1186
+ this.handleDisconnect();
1187
+ };
1188
+ socket.onmessage = (event) => {
1189
+ adapter.onmessage?.({ data: event.data });
1190
+ };
1191
+ } catch (error) {
1192
+ clearTimeout(timeout);
1193
+ reject(error);
1194
+ }
1195
+ });
1196
+ }
1197
+ /** Disconnect from the bridge and tear down all pending state */
1198
+ disconnect() {
1199
+ this.autoReconnect = false;
1200
+ this.codec?.close();
1201
+ this.codec = null;
1202
+ this.adapter = null;
1203
+ this.ws?.close();
1204
+ this.ws = null;
1205
+ this.isConnected = false;
1206
+ this.cleanupPending(/* @__PURE__ */ new Error("Bridge disconnected"));
1207
+ this.eventListeners.clear();
1208
+ }
1209
+ /** Alias for disconnect() */
1210
+ close() {
1211
+ this.disconnect();
1212
+ }
1213
+ /** Check if connected */
1214
+ get connected() {
1215
+ return this.isConnected;
1216
+ }
1217
+ handleDisconnect() {
1218
+ this.isConnected = false;
1219
+ this.codec?.close();
1220
+ this.codec = null;
1221
+ this.adapter = null;
1222
+ this.ws = null;
1223
+ this.cleanupPending(/* @__PURE__ */ new Error("Bridge disconnected"));
1224
+ if (this.autoReconnect) setTimeout(() => {
1225
+ this.connect().catch((error) => {
1226
+ bridgeLog.warn("auto-reconnect attempt failed", error);
1227
+ });
1228
+ }, this.reconnectDelay);
1229
+ }
1230
+ /** Reject/close all pending streams and ws proxies (codec owns RPC pending). */
1231
+ cleanupPending(error) {
1232
+ for (const pending of this.pendingWsOpens.values()) pending.reject(error);
1233
+ this.pendingWsOpens.clear();
1234
+ for (const stream of this.activeStreams.values()) {
1235
+ stream.closed = true;
1236
+ if (stream.pendingPull) {
1237
+ stream.pendingPull.reject(error);
1238
+ stream.pendingPull = null;
1239
+ }
1240
+ try {
1241
+ stream.controller.error(error);
1242
+ } catch {}
1243
+ }
1244
+ this.activeStreams.clear();
1245
+ for (const proxy of this.wsProxies.values()) try {
1246
+ proxy.onClose(1006, error.message);
1247
+ } catch {}
1248
+ this.wsProxies.clear();
1249
+ this.outgoingStreams.clear();
1250
+ }
1251
+ /** Call an RPC method */
1252
+ async call(method, params, timeoutMs = 3e4) {
1253
+ await this.ensureConnected();
1254
+ const codec = this.codec;
1255
+ if (!codec) throw new Error("Bridge disconnected");
1256
+ const { value: serializedParams, streams } = await serializeValue(params);
1257
+ for (const streamRef of streams) this.outgoingStreams.set(streamRef.sid, streamRef);
1258
+ const callPromise = codec.call(method, serializedParams);
1259
+ let timeoutHandle = null;
1260
+ const timeoutPromise = new Promise((_, reject) => {
1261
+ timeoutHandle = setTimeout(() => {
1262
+ reject(/* @__PURE__ */ new Error(`RPC timeout: ${method}`));
1263
+ }, timeoutMs);
1264
+ });
1265
+ try {
1266
+ return deserializeValue(await Promise.race([callPromise, timeoutPromise]), (sid) => this.createReadableStream(sid));
1267
+ } catch (error) {
1268
+ if (!this.isConnected && error instanceof Error && /v2 transport closed|transport/.test(error.message)) throw new Error("Bridge disconnected");
1269
+ throw error;
1270
+ } finally {
1271
+ if (timeoutHandle !== null) clearTimeout(timeoutHandle);
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Subscribe to bridge `event` notifications for a topic.
1276
+ *
1277
+ * Pass `'*'` to receive every event regardless of topic. Returns an
1278
+ * unsubscribe function; calling it removes this listener. Subscriptions
1279
+ * survive auto-reconnect and are only dropped on an explicit disconnect().
1280
+ *
1281
+ * NOTE: no gateway currently emits `event` frames, so listeners will not
1282
+ * fire until an event producer is wired on the gateway side. The subscriber
1283
+ * surface is provided so consumers can register ahead of that work.
1284
+ */
1285
+ on(topic, cb) {
1286
+ let set = this.eventListeners.get(topic);
1287
+ if (!set) {
1288
+ set = /* @__PURE__ */ new Set();
1289
+ this.eventListeners.set(topic, set);
1290
+ }
1291
+ set.add(cb);
1292
+ return () => {
1293
+ const current = this.eventListeners.get(topic);
1294
+ if (!current) return;
1295
+ current.delete(cb);
1296
+ if (current.size === 0) this.eventListeners.delete(topic);
1297
+ };
1298
+ }
1299
+ /**
1300
+ * Create a proxied WebSocket to a Durable Object via the in-process bridge
1301
+ * relay (`ws.open` control frame → gateway `stub.fetch()` pump → `WsData`
1302
+ * frames).
1303
+ *
1304
+ * DEPRECATED for DO connect(): this relay pumps the DO's WebSocket in-process,
1305
+ * which does NOT trigger workerd's hibernation dispatch — so a DO that uses
1306
+ * `ctx.acceptWebSocket()` never sees `webSocketMessage`/`webSocketClose` and
1307
+ * cross-socket `ctx.getWebSockets()` broadcasts never cross. `connect()` now
1308
+ * uses `openDoWebSocket()` (a real pass-through) instead. This method is
1309
+ * retained for the `ws-relay` wire capability and backward compatibility.
1310
+ */
1311
+ async createWsProxy(binding, id, url, headers) {
1312
+ await this.ensureConnected();
1313
+ const wid = nextWsId();
1314
+ const proxy = {
1315
+ clientWs: null,
1316
+ onMessage: () => {},
1317
+ onClose: () => {}
1318
+ };
1319
+ this.wsProxies.set(wid, proxy);
1320
+ const openedPromise = new Promise((resolve, reject) => {
1321
+ this.pendingWsOpens.set(wid, {
1322
+ resolve,
1323
+ reject
1324
+ });
1325
+ });
1326
+ const msg = {
1327
+ t: "ws.open",
1328
+ wid,
1329
+ target: {
1330
+ binding,
1331
+ id,
1332
+ url,
1333
+ headers
1334
+ }
1335
+ };
1336
+ this.send(msg);
1337
+ try {
1338
+ await openedPromise;
1339
+ } catch (error) {
1340
+ this.wsProxies.delete(wid);
1341
+ throw error;
1342
+ }
1343
+ return {
1344
+ wid,
1345
+ send: (data) => {
1346
+ const payload = typeof data === "string" ? new TextEncoder().encode(data) : data;
1347
+ const flags = typeof data === "string" ? BinaryFlags.TEXT : 0;
1348
+ const frame = encodeBinaryFrame(BinaryKind.WsData, wid, 0, flags, payload);
1349
+ this.sendBinary(frame);
1350
+ },
1351
+ close: (code, reason) => {
1352
+ const closeMsg = {
1353
+ t: "ws.close",
1354
+ wid,
1355
+ code,
1356
+ reason
1357
+ };
1358
+ this.send(closeMsg);
1359
+ this.wsProxies.delete(wid);
1360
+ },
1361
+ onMessage: (handler) => {
1362
+ proxy.onMessage = handler;
1363
+ },
1364
+ onClose: (handler) => {
1365
+ proxy.onClose = handler;
1366
+ }
1367
+ };
1368
+ }
1369
+ /**
1370
+ * Open a REAL WebSocket to the gateway's DO pass-through endpoint
1371
+ * (`/_devflare/do-ws`), which forwards the upgrade to the target Durable
1372
+ * Object and passes through its `101` response.
1373
+ *
1374
+ * This is the ONLY way a bridged DO WebSocket triggers the runtime's
1375
+ * hibernation dispatch under miniflare: the gateway returns the DO's client
1376
+ * socket for a genuine inbound connection, so workerd pumps it and invokes
1377
+ * `webSocketMessage`/`webSocketClose` and delivers `ctx.getWebSockets()`
1378
+ * broadcasts. The legacy in-process relay (`createWsProxy` + gateway
1379
+ * `stub.fetch()` pump) never fires hibernation, so two sockets to the same
1380
+ * `getByName(id)` could not see each other's messages. Here they share ONE DO
1381
+ * instance and broadcast across each other, exactly as on real Cloudflare.
1382
+ *
1383
+ * Unlike `createWsProxy`, this does not multiplex over the bridge socket: it
1384
+ * is a standalone connection (see `openDurableObjectWebSocket`) with its own
1385
+ * lifecycle, so it is unaffected by the bridge client's disconnect/reconnect
1386
+ * bookkeeping. It also does not require the bridge socket to be connected.
1387
+ *
1388
+ * @param binding - DO namespace binding name (e.g. `DOC_ROOM`).
1389
+ * @param idHex - Already-resolved Durable Object id, hex form.
1390
+ * @param targetUrl - The DO fetch URL the caller passed to `stub.connect(url)`.
1391
+ * @param headers - Optional upgrade headers (auth/cookies) forwarded to the DO.
1392
+ * @returns A minimal proxy surface (send/close/onMessage/onClose) over the socket.
1393
+ * @throws When the pass-through socket fails to open (bad binding/id, or the
1394
+ * DO rejected the upgrade).
1395
+ */
1396
+ async openDoWebSocket(binding, idHex, targetUrl, headers) {
1397
+ return openDurableObjectWebSocket(this.url, binding, idHex, targetUrl, headers);
1398
+ }
1399
+ /** Create a readable stream that pulls from the bridge */
1400
+ createReadableStream(sid) {
1401
+ return new ReadableStream({
1402
+ start: (controller) => {
1403
+ this.activeStreams.set(sid, {
1404
+ controller,
1405
+ buffer: [],
1406
+ creditRemaining: 0,
1407
+ pendingPull: null,
1408
+ ended: false,
1409
+ closed: false
1410
+ });
1411
+ },
1412
+ pull: async (controller) => {
1413
+ const stream = this.activeStreams.get(sid);
1414
+ if (!stream || stream.closed) return;
1415
+ if (stream.buffer.length > 0) {
1416
+ const chunk = stream.buffer.shift();
1417
+ controller.enqueue(chunk);
1418
+ return;
1419
+ }
1420
+ if (stream.ended) {
1421
+ controller.close();
1422
+ this.activeStreams.delete(sid);
1423
+ return;
1424
+ }
1425
+ const pullMsg = {
1426
+ t: "stream.pull",
1427
+ sid,
1428
+ creditBytes: DEFAULT_CHUNK_SIZE * 4
1429
+ };
1430
+ this.send(pullMsg);
1431
+ await new Promise((resolve, reject) => {
1432
+ stream.pendingPull = {
1433
+ resolve,
1434
+ reject
1435
+ };
1436
+ });
1437
+ stream.pendingPull = null;
1438
+ if (stream.closed) return;
1439
+ if (stream.buffer.length > 0) {
1440
+ const chunk = stream.buffer.shift();
1441
+ controller.enqueue(chunk);
1442
+ return;
1443
+ }
1444
+ if (stream.ended) {
1445
+ controller.close();
1446
+ this.activeStreams.delete(sid);
1447
+ }
1448
+ },
1449
+ cancel: () => {
1450
+ const stream = this.activeStreams.get(sid);
1451
+ if (stream) {
1452
+ stream.closed = true;
1453
+ if (stream.pendingPull) {
1454
+ stream.pendingPull.reject(/* @__PURE__ */ new Error("Stream cancelled"));
1455
+ stream.pendingPull = null;
1456
+ }
1457
+ }
1458
+ this.activeStreams.delete(sid);
1459
+ }
1460
+ });
1461
+ }
1462
+ handleJsonMessage(data) {
1463
+ try {
1464
+ const msg = parseJsonMsg(data);
1465
+ switch (msg.t) {
1466
+ case "event":
1467
+ this.handleEvent(msg);
1468
+ break;
1469
+ case "stream.pull":
1470
+ this.handleStreamPull(msg);
1471
+ break;
1472
+ case "stream.end":
1473
+ this.handleStreamEnd(msg);
1474
+ break;
1475
+ case "stream.abort":
1476
+ this.handleStreamAbort(msg);
1477
+ break;
1478
+ case "ws.opened":
1479
+ this.handleWsOpened(msg);
1480
+ break;
1481
+ case "ws.close":
1482
+ this.handleWsClose(msg);
1483
+ break;
1484
+ }
1485
+ } catch (error) {
1486
+ console.error("[devflare bridge client] parse error:", data, error);
1487
+ }
1488
+ }
1489
+ /**
1490
+ * Receive a v2 binary frame. Frame format is byte-identical to the legacy
1491
+ * v1 frames for kinds 1 (StreamChunk) and 2 (WsData); v2 owns kind 3
1492
+ * (BodyChunk) which the codec handles internally before reaching here.
1493
+ */
1494
+ handleV2BinaryFrame(frame) {
1495
+ switch (frame.kind) {
1496
+ case BinaryKind.StreamChunk:
1497
+ this.handleStreamChunk(frame);
1498
+ break;
1499
+ case BinaryKind.WsData:
1500
+ this.handleWsData(frame);
1501
+ break;
1502
+ }
1503
+ }
1504
+ handleEvent(msg) {
1505
+ this.dispatchEvent(this.eventListeners.get(msg.topic), msg.data, msg.topic);
1506
+ this.dispatchEvent(this.eventListeners.get("*"), msg.data, msg.topic);
1507
+ }
1508
+ dispatchEvent(listeners, data, topic) {
1509
+ if (!listeners) return;
1510
+ for (const cb of [...listeners]) try {
1511
+ cb(data);
1512
+ } catch (error) {
1513
+ bridgeLog.warn(`event listener for topic "${topic}" threw`, error);
1514
+ }
1515
+ }
1516
+ handleStreamPull(msg) {
1517
+ const streamRef = this.outgoingStreams.get(msg.sid);
1518
+ if (!streamRef) return;
1519
+ this.pumpStream(streamRef, msg.creditBytes);
1520
+ }
1521
+ async pumpStream(streamRef, creditBytes) {
1522
+ const reader = streamRef.stream.getReader();
1523
+ let sent = 0;
1524
+ let seq = 0;
1525
+ try {
1526
+ while (sent < creditBytes) {
1527
+ const { done, value } = await reader.read();
1528
+ if (done) {
1529
+ this.send({
1530
+ t: "stream.end",
1531
+ sid: streamRef.sid
1532
+ });
1533
+ this.outgoingStreams.delete(streamRef.sid);
1534
+ break;
1535
+ }
1536
+ if (value) {
1537
+ const frame = encodeBinaryFrame(BinaryKind.StreamChunk, streamRef.sid, seq++, 0, value);
1538
+ this.sendBinary(frame);
1539
+ sent += value.byteLength;
1540
+ }
1541
+ }
1542
+ } catch (error) {
1543
+ this.send({
1544
+ t: "stream.abort",
1545
+ sid: streamRef.sid,
1546
+ error: String(error)
1547
+ });
1548
+ this.outgoingStreams.delete(streamRef.sid);
1549
+ } finally {
1550
+ reader.releaseLock();
1551
+ }
1552
+ }
1553
+ handleStreamChunk(decoded) {
1554
+ const stream = this.activeStreams.get(decoded.id);
1555
+ if (!stream || stream.closed) return;
1556
+ stream.buffer.push(decoded.payload);
1557
+ if (stream.pendingPull) {
1558
+ const pending = stream.pendingPull;
1559
+ stream.pendingPull = null;
1560
+ pending.resolve();
1561
+ }
1562
+ }
1563
+ handleStreamEnd(msg) {
1564
+ const stream = this.activeStreams.get(msg.sid);
1565
+ if (!stream) return;
1566
+ stream.ended = true;
1567
+ if (stream.pendingPull) {
1568
+ const pending = stream.pendingPull;
1569
+ stream.pendingPull = null;
1570
+ pending.resolve();
1571
+ }
1572
+ }
1573
+ handleStreamAbort(msg) {
1574
+ const stream = this.activeStreams.get(msg.sid);
1575
+ if (!stream) return;
1576
+ const err = new Error(msg.error ?? "Stream aborted");
1577
+ stream.closed = true;
1578
+ if (stream.pendingPull) {
1579
+ const pending = stream.pendingPull;
1580
+ stream.pendingPull = null;
1581
+ pending.reject(err);
1582
+ }
1583
+ try {
1584
+ stream.controller.error(err);
1585
+ } catch {}
1586
+ this.activeStreams.delete(msg.sid);
1587
+ }
1588
+ handleWsData(decoded) {
1589
+ const proxy = this.wsProxies.get(decoded.id);
1590
+ if (!proxy) return;
1591
+ const data = (decoded.flags & BinaryFlags.TEXT) !== 0 ? new TextDecoder().decode(decoded.payload) : decoded.payload;
1592
+ proxy.onMessage(data);
1593
+ }
1594
+ handleWsClose(msg) {
1595
+ const proxy = this.wsProxies.get(msg.wid);
1596
+ if (!proxy) return;
1597
+ proxy.onClose(msg.code, msg.reason);
1598
+ this.wsProxies.delete(msg.wid);
1599
+ }
1600
+ handleWsOpened(msg) {
1601
+ const pending = this.pendingWsOpens.get(msg.wid);
1602
+ if (!pending) return;
1603
+ this.pendingWsOpens.delete(msg.wid);
1604
+ pending.resolve();
1605
+ }
1606
+ async ensureConnected() {
1607
+ if (!this.isConnected) await this.connect();
1608
+ }
1609
+ send(msg) {
1610
+ const codec = this.codec;
1611
+ if (!codec || !this.isConnected) throw new Error("Not connected to bridge");
1612
+ codec.sendText(stringifyJsonMsg(msg));
1613
+ }
1614
+ sendBinary(frame) {
1615
+ const codec = this.codec;
1616
+ if (!codec || !this.isConnected) throw new Error("Not connected to bridge");
1617
+ codec.sendBinary(frame);
1618
+ }
1619
+ };
1620
+ let defaultClient = null;
1621
+ /** Get or create the default bridge client */
1622
+ function getClient(options) {
1623
+ if (!defaultClient) defaultClient = new BridgeClient(options);
1624
+ return defaultClient;
1625
+ }
1626
+ //#endregion
1627
+ //#region src/bridge/proxy.ts
1628
+ function createKVProxy(client, bindingName) {
1629
+ return {
1630
+ async get(key, options) {
1631
+ return client.call(`${bindingName}.kv.get`, [key, options]);
1632
+ },
1633
+ async put(key, value, options) {
1634
+ await client.call(`${bindingName}.kv.put`, [
1635
+ key,
1636
+ value,
1637
+ options
1638
+ ]);
1639
+ },
1640
+ async delete(key) {
1641
+ await client.call(`${bindingName}.kv.delete`, [key]);
1642
+ },
1643
+ async list(options) {
1644
+ return client.call(`${bindingName}.kv.list`, [options]);
1645
+ },
1646
+ async getWithMetadata(key, options) {
1647
+ return client.call(`${bindingName}.kv.getWithMetadata`, [key, options]);
1648
+ }
1649
+ };
1650
+ }
1651
+ function createR2Proxy(client, bindingName) {
1652
+ return {
1653
+ async head(key) {
1654
+ return client.call(`${bindingName}.r2.head`, [key]);
1655
+ },
1656
+ async get(key, options) {
1657
+ return client.call(`${bindingName}.r2.get`, [key, options]);
1658
+ },
1659
+ async put(key, value, options) {
1660
+ if (getValueSize(value) > 524288) {
1661
+ const transferId = `${bindingName}:${key}`;
1662
+ const transferUrl = client.getHttpUrl().replace(/\/$/, "") + `/_devflare/transfer/${encodeURIComponent(transferId)}`;
1663
+ const response = await fetch(transferUrl, {
1664
+ method: "PUT",
1665
+ body: value,
1666
+ headers: { ...options?.httpMetadata?.contentType ? { "Content-Type": options.httpMetadata.contentType } : {} }
1667
+ });
1668
+ if (!response.ok) {
1669
+ const error = await response.text();
1670
+ throw new Error(`HTTP transfer failed: ${error}`);
1671
+ }
1672
+ return deserializeValue(await response.json());
1673
+ }
1674
+ return client.call(`${bindingName}.r2.put`, [
1675
+ key,
1676
+ value,
1677
+ options
1678
+ ]);
1679
+ },
1680
+ async delete(keys) {
1681
+ await client.call(`${bindingName}.r2.delete`, [keys]);
1682
+ },
1683
+ async list(options) {
1684
+ return client.call(`${bindingName}.r2.list`, [options]);
1685
+ },
1686
+ async createMultipartUpload(key, options) {
1687
+ return client.call(`${bindingName}.r2.createMultipartUpload`, [key, options]);
1688
+ },
1689
+ async resumeMultipartUpload(key, uploadId) {
1690
+ return client.call(`${bindingName}.r2.resumeMultipartUpload`, [key, uploadId]);
1691
+ }
1692
+ };
1693
+ }
1694
+ function getValueSize(value) {
1695
+ if (value instanceof Blob) return value.size;
1696
+ if (value instanceof ArrayBuffer) return value.byteLength;
1697
+ if (value instanceof Uint8Array) return value.byteLength;
1698
+ if (typeof value === "string") return new TextEncoder().encode(value).byteLength;
1699
+ if (value instanceof ReadableStream) return Number.POSITIVE_INFINITY;
1700
+ return 0;
1701
+ }
1702
+ function createD1Proxy(client, bindingName) {
1703
+ return {
1704
+ prepare(sql) {
1705
+ return createD1StatementProxy(client, bindingName, sql, []);
1706
+ },
1707
+ async batch(statements) {
1708
+ const serialized = statements.map((stmt) => {
1709
+ const s = stmt;
1710
+ return {
1711
+ sql: s._sql,
1712
+ bindings: s._bindings
1713
+ };
1714
+ });
1715
+ return client.call(`${bindingName}.d1.batch`, [serialized]);
1716
+ },
1717
+ async exec(sql) {
1718
+ return client.call(`${bindingName}.d1.exec`, [sql]);
1719
+ },
1720
+ async dump() {
1721
+ return client.call(`${bindingName}.d1.dump`, []);
1722
+ }
1723
+ };
1724
+ }
1725
+ function createD1StatementProxy(client, bindingName, sql, bindings) {
1726
+ return {
1727
+ _sql: sql,
1728
+ _bindings: bindings,
1729
+ bind(...values) {
1730
+ return createD1StatementProxy(client, bindingName, sql, values);
1731
+ },
1732
+ async first(column) {
1733
+ return client.call(`${bindingName}.d1.stmt.first`, [
1734
+ sql,
1735
+ ...bindings,
1736
+ column
1737
+ ]);
1738
+ },
1739
+ async all() {
1740
+ return client.call(`${bindingName}.d1.stmt.all`, [sql, ...bindings]);
1741
+ },
1742
+ async run() {
1743
+ return client.call(`${bindingName}.d1.stmt.run`, [sql, ...bindings]);
1744
+ },
1745
+ async raw(options) {
1746
+ return client.call(`${bindingName}.d1.stmt.raw`, [
1747
+ sql,
1748
+ ...bindings,
1749
+ options
1750
+ ]);
1751
+ }
1752
+ };
1753
+ }
1754
+ function createDOProxy(client, bindingName, proxyOptions = {}) {
1755
+ return {
1756
+ idFromName(name) {
1757
+ return createDOIdProxy(client, bindingName, {
1758
+ type: "name",
1759
+ value: name,
1760
+ jurisdiction: proxyOptions.jurisdiction
1761
+ });
1762
+ },
1763
+ idFromString(hexId) {
1764
+ return createDOIdProxy(client, bindingName, {
1765
+ type: "hex",
1766
+ value: hexId,
1767
+ jurisdiction: proxyOptions.jurisdiction
1768
+ });
1769
+ },
1770
+ newUniqueId(options) {
1771
+ return createDOIdProxy(client, bindingName, {
1772
+ type: "unique",
1773
+ value: crypto.randomUUID().replace(/-/g, ""),
1774
+ options,
1775
+ jurisdiction: proxyOptions.jurisdiction
1776
+ });
1777
+ },
1778
+ get(id) {
1779
+ return createDOStubProxy(client, bindingName, id._idInfo, proxyOptions);
1780
+ },
1781
+ getByName(name) {
1782
+ const id = this.idFromName(name);
1783
+ return this.get(id);
1784
+ },
1785
+ jurisdiction(jurisdiction) {
1786
+ return createDOProxy(client, bindingName, {
1787
+ ...proxyOptions,
1788
+ jurisdiction
1789
+ });
1790
+ }
1791
+ };
1792
+ }
1793
+ function createDOIdProxy(client, bindingName, idInfo) {
1794
+ return {
1795
+ _idInfo: idInfo,
1796
+ toString() {
1797
+ if (idInfo.type === "hex") return idInfo.value;
1798
+ return `${idInfo.type}:${idInfo.value}`;
1799
+ },
1800
+ equals(other) {
1801
+ return this.toString() === other.toString();
1802
+ }
1803
+ };
1804
+ }
1805
+ function createDOStubProxy(client, bindingName, idInfo, proxyOptions = {}) {
1806
+ const { transformResult } = proxyOptions;
1807
+ let resolvedId = null;
1808
+ const resolveId = async () => {
1809
+ if (resolvedId) return resolvedId;
1810
+ switch (idInfo.type) {
1811
+ case "name":
1812
+ resolvedId = await client.call(`${bindingName}.do.idFromName`, [idInfo.value, idInfo.jurisdiction]);
1813
+ break;
1814
+ case "hex":
1815
+ resolvedId = {
1816
+ __type: "DOId",
1817
+ hex: idInfo.value
1818
+ };
1819
+ break;
1820
+ case "unique":
1821
+ resolvedId = await client.call(`${bindingName}.do.newUniqueId`, [idInfo.options, idInfo.jurisdiction]);
1822
+ break;
1823
+ }
1824
+ return resolvedId;
1825
+ };
1826
+ return new Proxy({
1827
+ async fetch(input, init) {
1828
+ const id = await resolveId();
1829
+ const { serialized } = await serializeRequest(input instanceof Request ? input : new Request(input, init));
1830
+ return deserializeResponse(await client.call(`${bindingName}.do.fetch`, [
1831
+ bindingName,
1832
+ id,
1833
+ serialized
1834
+ ]));
1835
+ },
1836
+ async connect(url, options) {
1837
+ const id = await resolveId();
1838
+ const headersList = [];
1839
+ if (options?.headers) new Headers(options.headers).forEach((value, key) => {
1840
+ headersList.push([key, value]);
1841
+ });
1842
+ const wsProxy = await client.openDoWebSocket(bindingName, id.hex, url, headersList);
1843
+ let readController = null;
1844
+ const readable = new ReadableStream({
1845
+ start(controller) {
1846
+ readController = controller;
1847
+ },
1848
+ cancel() {
1849
+ wsProxy.close();
1850
+ }
1851
+ });
1852
+ wsProxy.onMessage((data) => {
1853
+ if (readController) {
1854
+ const chunk = typeof data === "string" ? new TextEncoder().encode(data) : data;
1855
+ readController.enqueue(chunk);
1856
+ }
1857
+ });
1858
+ wsProxy.onClose((code, reason) => {
1859
+ if (readController) readController.close();
1860
+ });
1861
+ return {
1862
+ readable,
1863
+ writable: new WritableStream({
1864
+ write(chunk) {
1865
+ wsProxy.send(chunk);
1866
+ },
1867
+ close() {
1868
+ wsProxy.close(1e3, "Normal closure");
1869
+ },
1870
+ abort(reason) {
1871
+ wsProxy.close(1001, reason?.toString() ?? "Aborted");
1872
+ }
1873
+ }),
1874
+ get opened() {
1875
+ return Promise.resolve({
1876
+ remoteAddress: "127.0.0.1",
1877
+ localAddress: "127.0.0.1"
1878
+ });
1879
+ },
1880
+ get closed() {
1881
+ return new Promise((resolve) => {
1882
+ wsProxy.onClose(() => resolve());
1883
+ });
1884
+ },
1885
+ close() {
1886
+ wsProxy.close(1e3, "Normal closure");
1887
+ return Promise.resolve();
1888
+ },
1889
+ startTls() {
1890
+ throw new Error("startTls() is not supported on a Durable Object WebSocket connection. StartTLS applies to raw TCP sockets (cloudflare:sockets connect()), not WebSocket-tunneled DO connections, whose transport is already secured by the connection itself.");
1891
+ }
1892
+ };
1893
+ },
1894
+ get id() {
1895
+ return createDOIdProxy(client, bindingName, idInfo);
1896
+ },
1897
+ get name() {
1898
+ return idInfo.type === "name" ? idInfo.value : void 0;
1899
+ }
1900
+ }, { get(target, prop) {
1901
+ if (prop in target) return target[prop];
1902
+ if (typeof prop === "symbol") return;
1903
+ if (prop === "then" || prop === "catch" || prop === "finally") return;
1904
+ return async (...args) => {
1905
+ const id = await resolveId();
1906
+ let result = await client.call(`${bindingName}.do.rpc`, [
1907
+ bindingName,
1908
+ id,
1909
+ prop,
1910
+ args
1911
+ ]);
1912
+ if (transformResult) result = transformResult(result);
1913
+ return result;
1914
+ };
1915
+ } });
1916
+ }
1917
+ function isResponseLike(value) {
1918
+ return value instanceof Response;
1919
+ }
1920
+ function createServiceProxy(client, bindingName, proxyOptions = {}) {
1921
+ const { transformResult } = proxyOptions;
1922
+ return new Proxy({ async fetch(input, init) {
1923
+ const { serialized } = await serializeRequest(input instanceof Request ? input : new Request(input, init));
1924
+ const result = await client.call(`${bindingName}.service.fetch`, [serialized]);
1925
+ if (isResponseLike(result)) return result;
1926
+ return deserializeResponse(result);
1927
+ } }, { get(target, prop) {
1928
+ if (typeof prop !== "string") return;
1929
+ if (prop in target) return target[prop];
1930
+ if (prop === "then" || prop === "catch" || prop === "finally") return;
1931
+ if (prop === "toString") return () => `[DevflareServiceBinding ${bindingName}]`;
1932
+ return async (...args) => {
1933
+ let result = await client.call(`${bindingName}.service.rpc`, [prop, args]);
1934
+ if (transformResult) result = transformResult(result);
1935
+ return result;
1936
+ };
1937
+ } });
1938
+ }
1939
+ const EMPTY_QUEUE_METRICS = {
1940
+ backlogCount: 0,
1941
+ backlogBytes: 0
1942
+ };
1943
+ function createQueueResponse() {
1944
+ return { metadata: { metrics: EMPTY_QUEUE_METRICS } };
1945
+ }
1946
+ function createQueueProxy(client, bindingName) {
1947
+ return {
1948
+ async metrics() {
1949
+ return EMPTY_QUEUE_METRICS;
1950
+ },
1951
+ async send(message, options) {
1952
+ await client.call(`${bindingName}.queue.send`, [message, options]);
1953
+ return createQueueResponse();
1954
+ },
1955
+ async sendBatch(messages, options) {
1956
+ await client.call(`${bindingName}.queue.sendBatch`, [messages, options]);
1957
+ return createQueueResponse();
1958
+ }
1959
+ };
1960
+ }
1961
+ function createAIProxy(client, bindingName) {
1962
+ return { async run(model, inputs, options) {
1963
+ return client.call(`${bindingName}.ai.run`, [
1964
+ model,
1965
+ inputs,
1966
+ options
1967
+ ]);
1968
+ } };
1969
+ }
1970
+ function createSendEmailProxy(client, bindingName) {
1971
+ return { async send(message) {
1972
+ return client.call(`${bindingName}.email.send`, [message]);
1973
+ } };
1974
+ }
1975
+ function createWorkflowInstanceProxy(client, bindingName, id) {
1976
+ return {
1977
+ id,
1978
+ async pause() {
1979
+ await client.call(`${bindingName}.workflow.pause`, [id]);
1980
+ },
1981
+ async resume() {
1982
+ await client.call(`${bindingName}.workflow.resume`, [id]);
1983
+ },
1984
+ async terminate() {
1985
+ await client.call(`${bindingName}.workflow.terminate`, [id]);
1986
+ },
1987
+ async restart() {
1988
+ await client.call(`${bindingName}.workflow.restart`, [id]);
1989
+ },
1990
+ async status() {
1991
+ return client.call(`${bindingName}.workflow.status`, [id]);
1992
+ },
1993
+ async sendEvent(event) {
1994
+ await client.call(`${bindingName}.workflow.sendEvent`, [id, event]);
1995
+ }
1996
+ };
1997
+ }
1998
+ function createWorkflowProxy(client, bindingName) {
1999
+ const toInstance = (value) => {
2000
+ const id = value?.id;
2001
+ if (typeof id !== "string") throw new Error(`Workflow ${bindingName} returned an instance without a string id.`);
2002
+ return createWorkflowInstanceProxy(client, bindingName, id);
2003
+ };
2004
+ return {
2005
+ async create(options) {
2006
+ return toInstance(await client.call(`${bindingName}.workflow.create`, [options]));
2007
+ },
2008
+ async get(id) {
2009
+ return toInstance(await client.call(`${bindingName}.workflow.get`, [id]));
2010
+ }
2011
+ };
2012
+ }
2013
+ /** Module-level storage for binding hints */
2014
+ let globalBindingHints = {};
2015
+ /**
2016
+ * Create an env proxy that routes all binding access through the bridge
2017
+ */
2018
+ function createEnvProxy(options = {}) {
2019
+ const client = options.client ?? getClient();
2020
+ const bindingProxies = /* @__PURE__ */ new Map();
2021
+ const doProxyOptions = { transformResult: options.transformResult };
2022
+ const serviceProxyOptions = { transformResult: options.transformResult };
2023
+ const strict = options.strict === true;
2024
+ const hints = {
2025
+ ...globalBindingHints,
2026
+ ...options.hints
2027
+ };
2028
+ return new Proxy({}, {
2029
+ get(target, prop) {
2030
+ if (typeof prop !== "string") return void 0;
2031
+ if (bindingProxies.has(prop)) return bindingProxies.get(prop);
2032
+ const hint = hints[prop];
2033
+ if (!hint && strict) return;
2034
+ let proxy;
2035
+ switch (hint) {
2036
+ case "kv":
2037
+ proxy = createKVProxy(client, prop);
2038
+ break;
2039
+ case "r2":
2040
+ proxy = createR2Proxy(client, prop);
2041
+ break;
2042
+ case "d1":
2043
+ proxy = createD1Proxy(client, prop);
2044
+ break;
2045
+ case "do":
2046
+ proxy = createDOProxy(client, prop, doProxyOptions);
2047
+ break;
2048
+ case "queue":
2049
+ proxy = createQueueProxy(client, prop);
2050
+ break;
2051
+ case "ai":
2052
+ proxy = createAIProxy(client, prop);
2053
+ break;
2054
+ case "service":
2055
+ proxy = createServiceProxy(client, prop, serviceProxyOptions);
2056
+ break;
2057
+ case "sendEmail":
2058
+ proxy = createSendEmailProxy(client, prop);
2059
+ break;
2060
+ case "workflow":
2061
+ proxy = createWorkflowProxy(client, prop);
2062
+ break;
2063
+ case "secret":
2064
+ case "var":
2065
+ proxy = createSimpleBindingProxy(client, prop);
2066
+ break;
2067
+ default: proxy = createGenericBindingProxy(client, prop);
2068
+ }
2069
+ bindingProxies.set(prop, proxy);
2070
+ return proxy;
2071
+ },
2072
+ has(target, prop) {
2073
+ return typeof prop === "string" && (!strict || prop in hints);
2074
+ },
2075
+ ownKeys() {
2076
+ return Object.keys(hints);
2077
+ },
2078
+ getOwnPropertyDescriptor(target, prop) {
2079
+ if (typeof prop === "string" && (!strict || prop in hints)) return {
2080
+ configurable: true,
2081
+ enumerable: true,
2082
+ writable: false
2083
+ };
2084
+ }
2085
+ });
2086
+ }
2087
+ function createGenericBindingProxy(client, bindingName) {
2088
+ return new Proxy({}, { get(target, prop) {
2089
+ if (typeof prop !== "string") return void 0;
2090
+ if ([
2091
+ "get",
2092
+ "put",
2093
+ "delete",
2094
+ "list",
2095
+ "getWithMetadata"
2096
+ ].includes(prop)) return createKVProxy(client, bindingName)[prop];
2097
+ if ([
2098
+ "idFromName",
2099
+ "idFromString",
2100
+ "newUniqueId",
2101
+ "get"
2102
+ ].includes(prop)) return createDOProxy(client, bindingName)[prop];
2103
+ if ([
2104
+ "prepare",
2105
+ "batch",
2106
+ "exec",
2107
+ "dump"
2108
+ ].includes(prop)) return createD1Proxy(client, bindingName)[prop];
2109
+ if (["head"].includes(prop)) return createR2Proxy(client, bindingName)[prop];
2110
+ return async (...args) => {
2111
+ return client.call(`${bindingName}.${prop}`, args);
2112
+ };
2113
+ } });
2114
+ }
2115
+ function createSimpleBindingProxy(client, bindingName) {
2116
+ let cachedValue;
2117
+ let fetched = false;
2118
+ let pendingValue = null;
2119
+ const loadValue = () => {
2120
+ if (fetched) return Promise.resolve(cachedValue);
2121
+ if (!pendingValue) pendingValue = client.call(`${bindingName}.var.value`, []).then((value) => {
2122
+ cachedValue = value;
2123
+ fetched = true;
2124
+ return value;
2125
+ }).catch((error) => {
2126
+ pendingValue = null;
2127
+ throw error;
2128
+ });
2129
+ return pendingValue;
2130
+ };
2131
+ return {
2132
+ then(resolve, reject) {
2133
+ return loadValue().then(resolve ?? void 0, reject ?? void 0);
2134
+ },
2135
+ toString() {
2136
+ if (!fetched) throw new Error(`Binding ${bindingName} not yet fetched. Use await.`);
2137
+ return String(cachedValue);
2138
+ }
2139
+ };
2140
+ }
2141
+ let globalEnvProxy = null;
2142
+ /**
2143
+ * Get the global env proxy for bridge RPC.
2144
+ *
2145
+ * @internal
2146
+ * Internal bridge surface — not part of the documented public API. Prefer
2147
+ * `import { env } from 'devflare'`, which transparently picks the right
2148
+ * source (request context, test context, or bridge) for the current
2149
+ * environment. `bridgeEnv` is retained as an internal escape hatch for the
2150
+ * bridge implementation itself and may change without a major version bump.
2151
+ *
2152
+ * @example
2153
+ * ```ts
2154
+ * await bridgeEnv.MY_KV.get('key')
2155
+ * await bridgeEnv.MY_DO.get(id).fetch(request)
2156
+ * ```
2157
+ */
2158
+ const bridgeEnv = new Proxy({}, { get(target, prop) {
2159
+ if (!globalEnvProxy) globalEnvProxy = createEnvProxy({ lazy: true });
2160
+ return globalEnvProxy[prop];
2161
+ } });
2162
+ /**
2163
+ * Initialize the env proxy with specific options
2164
+ */
2165
+ function initEnv(options = {}) {
2166
+ globalEnvProxy = createEnvProxy(options);
2167
+ return globalEnvProxy;
2168
+ }
2169
+ /**
2170
+ * Set binding hints for better proxy creation
2171
+ * Hints help the bridge create optimized proxies for each binding type
2172
+ */
2173
+ function setBindingHints(hints) {
2174
+ globalBindingHints = {
2175
+ ...globalBindingHints,
2176
+ ...hints
2177
+ };
2178
+ globalEnvProxy = null;
2179
+ }
2180
+ //#endregion
2181
+ //#region src/runtime/context-events.ts
2182
+ function createLocals$1(locals) {
2183
+ return locals ?? {};
2184
+ }
2185
+ /**
2186
+ * Builds the shared scaffold used by every event builder: a wrapped runtime env
2187
+ * (with SendEmail bindings proxied) plus a locals bag. Every event type layers
2188
+ * its specific fields on top of this shell.
2189
+ */
2190
+ function prepareEventShell(env, options = {}) {
2191
+ return {
2192
+ env: wrapEnvSendEmailBindings(env),
2193
+ locals: createLocals$1(options.locals)
2194
+ };
2195
+ }
2196
+ function createAugmentedTarget(target, extra) {
2197
+ return new Proxy(target, {
2198
+ get(target, prop) {
2199
+ if (prop in extra) return extra[prop];
2200
+ const value = Reflect.get(target, prop, target);
2201
+ return typeof value === "function" ? value.bind(target) : value;
2202
+ },
2203
+ has(target, prop) {
2204
+ return prop in extra || prop in target;
2205
+ },
2206
+ ownKeys(target) {
2207
+ return Array.from(new Set([...Reflect.ownKeys(target), ...Reflect.ownKeys(extra)]));
2208
+ },
2209
+ getOwnPropertyDescriptor(target, prop) {
2210
+ if (prop in extra) return {
2211
+ configurable: true,
2212
+ enumerable: true,
2213
+ writable: false,
2214
+ value: extra[prop]
2215
+ };
2216
+ return Reflect.getOwnPropertyDescriptor(target, prop);
2217
+ }
2218
+ });
2219
+ }
2220
+ function createBaseEvent(type, env, ctx, options = {}) {
2221
+ return {
2222
+ type,
2223
+ ctx,
2224
+ ...prepareEventShell(env, { locals: options.locals }),
2225
+ request: options.request ?? null,
2226
+ params: options.params
2227
+ };
2228
+ }
2229
+ function createFetchEvent(request, env, ctx, options = {}) {
2230
+ return createAugmentedTarget(request, {
2231
+ type: "fetch",
2232
+ ctx,
2233
+ ...prepareEventShell(env, { locals: options.locals }),
2234
+ url: new URL(request.url),
2235
+ request,
2236
+ params: options.params ?? {}
2237
+ });
2238
+ }
2239
+ function createQueueEvent(batch, env, ctx, options = {}) {
2240
+ return createAugmentedTarget(batch, {
2241
+ type: "queue",
2242
+ ctx,
2243
+ ...prepareEventShell(env, { locals: options.locals }),
2244
+ batch
2245
+ });
2246
+ }
2247
+ function createScheduledEvent(controller, env, ctx, options = {}) {
2248
+ return createAugmentedTarget(controller, {
2249
+ type: "scheduled",
2250
+ ctx,
2251
+ ...prepareEventShell(env, { locals: options.locals }),
2252
+ controller
2253
+ });
2254
+ }
2255
+ function createEmailEvent(message, env, ctx, options = {}) {
2256
+ return createAugmentedTarget(message, {
2257
+ type: "email",
2258
+ ctx,
2259
+ ...prepareEventShell(env, { locals: options.locals }),
2260
+ message
2261
+ });
2262
+ }
2263
+ function createTailEvent(events, env, ctx, options = {}) {
2264
+ return createAugmentedTarget(events, {
2265
+ type: "tail",
2266
+ ctx,
2267
+ ...prepareEventShell(env, { locals: options.locals }),
2268
+ events
2269
+ });
2270
+ }
2271
+ function createDurableObjectFetchEvent(request, env, state, options = {}) {
2272
+ return createAugmentedTarget(request, {
2273
+ type: "durable-object-fetch",
2274
+ ctx: state,
2275
+ state,
2276
+ ...prepareEventShell(env, { locals: options.locals }),
2277
+ request
2278
+ });
2279
+ }
2280
+ function createDurableObjectAlarmEvent(env, state, options = {}) {
2281
+ return {
2282
+ type: "durable-object-alarm",
2283
+ ctx: state,
2284
+ state,
2285
+ ...prepareEventShell(env, { locals: options.locals })
2286
+ };
2287
+ }
2288
+ function createDurableObjectWebSocketMessageEvent(ws, message, env, state, options = {}) {
2289
+ return createAugmentedTarget(ws, {
2290
+ type: "durable-object-websocket-message",
2291
+ ctx: state,
2292
+ state,
2293
+ ...prepareEventShell(env, { locals: options.locals }),
2294
+ ws,
2295
+ message
2296
+ });
2297
+ }
2298
+ function createDurableObjectWebSocketCloseEvent(ws, code, reason, wasClean, env, state, options = {}) {
2299
+ return createAugmentedTarget(ws, {
2300
+ type: "durable-object-websocket-close",
2301
+ ctx: state,
2302
+ state,
2303
+ ...prepareEventShell(env, { locals: options.locals }),
2304
+ ws,
2305
+ code,
2306
+ reason,
2307
+ wasClean
2308
+ });
2309
+ }
2310
+ function createDurableObjectWebSocketErrorEvent(ws, error, env, state, options = {}) {
2311
+ return createAugmentedTarget(ws, {
2312
+ type: "durable-object-websocket-error",
2313
+ ctx: state,
2314
+ state,
2315
+ ...prepareEventShell(env, { locals: options.locals }),
2316
+ ws,
2317
+ error
2318
+ });
2319
+ }
2320
+ function createDefaultEvent(env, ctx, request, type, locals) {
2321
+ switch (type) {
2322
+ case "fetch":
2323
+ if (request && ctx) return createFetchEvent(request, env, ctx, { locals });
2324
+ return createBaseEvent(type, env, ctx, {
2325
+ locals,
2326
+ request
2327
+ });
2328
+ case "durable-object-fetch":
2329
+ if (request && ctx) return createDurableObjectFetchEvent(request, env, ctx, { locals });
2330
+ return createBaseEvent(type, env, ctx, {
2331
+ locals,
2332
+ request
2333
+ });
2334
+ case "durable-object-alarm":
2335
+ if (ctx) return createDurableObjectAlarmEvent(env, ctx, { locals });
2336
+ return createBaseEvent(type, env, ctx, { locals });
2337
+ case "queue":
2338
+ case "scheduled":
2339
+ case "email":
2340
+ case "tail":
2341
+ case "durable-object-websocket-message":
2342
+ case "durable-object-websocket-close":
2343
+ case "durable-object-websocket-error": return createBaseEvent(type, env, ctx, {
2344
+ locals,
2345
+ request
2346
+ });
2347
+ default: throw new Error(`createDefaultEvent: unknown event type ${String(type)}`);
2348
+ }
2349
+ }
2350
+ //#endregion
2351
+ //#region src/runtime/validation.ts
2352
+ /**
2353
+ * Error thrown when accessing context properties outside an active handler trail
2354
+ */
2355
+ var ContextAccessError = class ContextAccessError extends Error {
2356
+ contextName;
2357
+ propertyName;
2358
+ constructor(contextName, propertyName, message) {
2359
+ super(message ?? `Cannot access ${contextName}.${propertyName} outside of an active Devflare handler trail.\n\nThis typically happens when:\n 1. Accessing ${contextName} at module top-level (during import)\n 2. Accessing ${contextName} in a callback that runs after the handler ends\n 3. Accessing ${contextName} in a setTimeout/setInterval callback\n\nMove the access inside your handler function or middleware.`);
2360
+ this.name = "ContextAccessError";
2361
+ this.contextName = contextName;
2362
+ this.propertyName = propertyName;
2363
+ }
2364
+ /**
2365
+ * Builds a `ContextAccessError` for the "no active handler trail" failure mode
2366
+ * (no AsyncLocalStorage store), with guidance toward the most common causes.
2367
+ * Pass `message` to override the default `nodejs_compat`-mentioning guidance.
2368
+ */
2369
+ static contextUnavailable(message) {
2370
+ return new ContextAccessError("context", "<unavailable>", message ?? "Context not available. Devflare uses AsyncLocalStorage to carry the active event through fetch, queue, scheduled, email, tail, and Durable Object handler call chains.\n\nThis usually means one of:\n\n1. Accessing context at module top-level (runs at cold start, not per-request)\n2. Accessing context in setTimeout/setInterval callbacks\n3. Missing 'nodejs_compat' compatibility flag in your worker config\n\nFix: Move the access inside your handler, middleware, or a helper called from that handler trail.\nLearn more: https://devflare.dev/docs/context-errors");
2371
+ }
2372
+ };
2373
+ function createContextProxy(getter, name, options = {}) {
2374
+ const mutable = options.mutable ?? true;
2375
+ return new Proxy({}, {
2376
+ get(_target, prop) {
2377
+ const ctx = getter();
2378
+ if (ctx === void 0 || ctx === null) throw new ContextAccessError(name, String(prop));
2379
+ return ctx[prop];
2380
+ },
2381
+ set(_target, prop, value) {
2382
+ if (!mutable) throw new TypeError(`Cannot assign to '${String(prop)}' on '${name}' because it is read-only.\nUse 'locals' for mutable request-scoped data.`);
2383
+ const ctx = getter();
2384
+ if (ctx === void 0 || ctx === null) throw new ContextAccessError(name, String(prop));
2385
+ ctx[prop] = value;
2386
+ return true;
2387
+ },
2388
+ deleteProperty(_target, prop) {
2389
+ if (!mutable) throw new TypeError(`Cannot delete property '${String(prop)}' from '${name}' because it is read-only.`);
2390
+ const ctx = getter();
2391
+ if (ctx === void 0 || ctx === null) return true;
2392
+ return Reflect.deleteProperty(ctx, prop);
2393
+ },
2394
+ has(_target, prop) {
2395
+ const ctx = getter();
2396
+ if (ctx === void 0 || ctx === null) return false;
2397
+ return prop in ctx;
2398
+ },
2399
+ ownKeys(_target) {
2400
+ const ctx = getter();
2401
+ if (ctx === void 0 || ctx === null) return [];
2402
+ return Reflect.ownKeys(ctx);
2403
+ },
2404
+ getOwnPropertyDescriptor(_target, prop) {
2405
+ const ctx = getter();
2406
+ if (ctx === void 0 || ctx === null) return;
2407
+ const descriptor = Reflect.getOwnPropertyDescriptor(ctx, prop);
2408
+ if (!descriptor) return;
2409
+ if (!mutable) return {
2410
+ ...descriptor,
2411
+ writable: false
2412
+ };
2413
+ return descriptor;
2414
+ }
2415
+ });
2416
+ }
2417
+ //#endregion
2418
+ //#region src/runtime/context.ts
2419
+ const storage = new AsyncLocalStorage();
2420
+ function createLocals() {
2421
+ return {};
2422
+ }
2423
+ function runWithContext(env, ctx, request, fn, type = "fetch") {
2424
+ return runWithEventContext(createDefaultEvent(env, ctx, request, type, createLocals()), fn);
2425
+ }
2426
+ function runWithEventContext(event, fn) {
2427
+ const context = {
2428
+ env: event.env,
2429
+ ctx: event.ctx,
2430
+ request: event.request ?? null,
2431
+ locals: event.locals,
2432
+ type: event.type,
2433
+ event
2434
+ };
2435
+ return storage.run(context, fn);
2436
+ }
2437
+ function getContext() {
2438
+ const context = storage.getStore();
2439
+ if (!context) throw ContextAccessError.contextUnavailable();
2440
+ return context;
2441
+ }
2442
+ function getContextOrNull() {
2443
+ return storage.getStore() ?? null;
2444
+ }
2445
+ function getEventContext() {
2446
+ return getContext().event;
2447
+ }
2448
+ function getEventContextOrNull() {
2449
+ return getContextOrNull()?.event ?? null;
2450
+ }
2451
+ function hasContext() {
2452
+ return storage.getStore() !== void 0;
2453
+ }
2454
+ function createEventAccessor(name, matcher) {
2455
+ const accessor = (() => {
2456
+ const currentEvent = getEventContextOrNull();
2457
+ if (!currentEvent) throw ContextAccessError.contextUnavailable();
2458
+ if (!matcher(currentEvent)) throw ContextAccessError.contextUnavailable(`${name} is not available in the current '${currentEvent.type}' context.
2459
+
2460
+ Devflare stores event objects in AsyncLocalStorage so helpers called within a handler can reach the active event.
2461
+ Use ${name}.safe() to return null instead of throwing, or call the getter that matches the active surface.`);
2462
+ return currentEvent;
2463
+ });
2464
+ accessor.safe = () => {
2465
+ const currentEvent = getEventContextOrNull();
2466
+ return currentEvent && matcher(currentEvent) ? currentEvent : null;
2467
+ };
2468
+ return accessor;
2469
+ }
2470
+ function isFetchEvent(event) {
2471
+ return event.type === "fetch" && event.request instanceof Request;
2472
+ }
2473
+ function isQueueEvent(event) {
2474
+ return event.type === "queue" && "batch" in event;
2475
+ }
2476
+ function isScheduledEvent(event) {
2477
+ return event.type === "scheduled" && "controller" in event;
2478
+ }
2479
+ function isEmailEvent(event) {
2480
+ return event.type === "email" && "message" in event;
2481
+ }
2482
+ function isTailEvent(event) {
2483
+ return event.type === "tail" && Array.isArray(event) && "events" in event;
2484
+ }
2485
+ function isDurableObjectEvent(event) {
2486
+ return event.type.startsWith("durable-object-") && "state" in event;
2487
+ }
2488
+ function isDurableObjectFetchEvent(event) {
2489
+ return event.type === "durable-object-fetch" && event.request instanceof Request;
2490
+ }
2491
+ function isDurableObjectAlarmEvent(event) {
2492
+ return event.type === "durable-object-alarm" && "state" in event;
2493
+ }
2494
+ function isDurableObjectWebSocketMessageEvent(event) {
2495
+ return event.type === "durable-object-websocket-message" && "ws" in event && "message" in event;
2496
+ }
2497
+ function isDurableObjectWebSocketCloseEvent(event) {
2498
+ return event.type === "durable-object-websocket-close" && "ws" in event && "code" in event;
2499
+ }
2500
+ function isDurableObjectWebSocketErrorEvent(event) {
2501
+ return event.type === "durable-object-websocket-error" && "ws" in event && "error" in event;
2502
+ }
2503
+ const getFetchEvent = createEventAccessor("getFetchEvent()", isFetchEvent);
2504
+ const getQueueEvent = createEventAccessor("getQueueEvent()", isQueueEvent);
2505
+ const getScheduledEvent = createEventAccessor("getScheduledEvent()", isScheduledEvent);
2506
+ const getEmailEvent = createEventAccessor("getEmailEvent()", isEmailEvent);
2507
+ const getTailEvent = createEventAccessor("getTailEvent()", isTailEvent);
2508
+ const getDurableObjectEvent = createEventAccessor("getDurableObjectEvent()", isDurableObjectEvent);
2509
+ const getDurableObjectFetchEvent = createEventAccessor("getDurableObjectFetchEvent()", isDurableObjectFetchEvent);
2510
+ const getDurableObjectAlarmEvent = createEventAccessor("getDurableObjectAlarmEvent()", isDurableObjectAlarmEvent);
2511
+ const getDurableObjectWebSocketMessageEvent = createEventAccessor("getDurableObjectWebSocketMessageEvent()", isDurableObjectWebSocketMessageEvent);
2512
+ const getDurableObjectWebSocketCloseEvent = createEventAccessor("getDurableObjectWebSocketCloseEvent()", isDurableObjectWebSocketCloseEvent);
2513
+ const getDurableObjectWebSocketErrorEvent = createEventAccessor("getDurableObjectWebSocketErrorEvent()", isDurableObjectWebSocketErrorEvent);
2514
+ //#endregion
2515
+ export { createTailEvent as A, createDurableObjectWebSocketCloseEvent as C, createFetchEvent as D, createEmailEvent as E, BridgeClient as F, getClient as I, createEnvProxy as M, initEnv as N, createQueueEvent as O, setBindingHints as P, createDurableObjectFetchEvent as S, createDurableObjectWebSocketMessageEvent as T, runWithContext as _, getDurableObjectFetchEvent as a, createContextProxy as b, getDurableObjectWebSocketMessageEvent as c, getEventContextOrNull as d, getFetchEvent as f, hasContext as g, getTailEvent as h, getDurableObjectEvent as i, bridgeEnv as j, createScheduledEvent as k, getEmailEvent as l, getScheduledEvent as m, getContextOrNull as n, getDurableObjectWebSocketCloseEvent as o, getQueueEvent as p, getDurableObjectAlarmEvent as r, getDurableObjectWebSocketErrorEvent as s, getContext as t, getEventContext as u, runWithEventContext as v, createDurableObjectWebSocketErrorEvent as w, createDurableObjectAlarmEvent as x, ContextAccessError as y };