devflare 1.0.0-next.7 → 1.0.0-next.70

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 (632) hide show
  1. package/LICENSE +21 -0
  2. package/LLM.md +17315 -2144
  3. package/README.md +398 -607
  4. package/bin/devflare.js +30 -14
  5. package/dist/_chunks/account-BHY3fvrA.js +462 -0
  6. package/dist/_chunks/account-resources-BdKj8q1h.js +159 -0
  7. package/dist/_chunks/ai-CN_SREim.js +322 -0
  8. package/dist/_chunks/api-BKClUlUf.js +568 -0
  9. package/dist/_chunks/build-DplSo6Gc.js +24 -0
  10. package/dist/_chunks/build-artifacts-CkwCap5N.js +483 -0
  11. package/dist/_chunks/cli-ZJYtm-lW.js +1214 -0
  12. package/dist/_chunks/cloudflare-Ic5ubQza.js +157 -0
  13. package/dist/_chunks/colors-D0NVzAFN.js +13 -0
  14. package/dist/_chunks/command-utils-DjaaMQX7.js +45 -0
  15. package/dist/_chunks/compiler-UxXQgEPq.js +521 -0
  16. package/dist/_chunks/config-path-CYGlwKDs.js +42 -0
  17. package/dist/_chunks/config-zQd4jmXU.js +78 -0
  18. package/dist/_chunks/context-DGMev2AF.js +2515 -0
  19. package/dist/_chunks/decorators-eXNZ1S0N.js +19 -0
  20. package/dist/_chunks/dependencies-wKqrxKV_.js +57 -0
  21. package/dist/_chunks/deploy-z1_wbNn2.js +1032 -0
  22. package/dist/_chunks/dev-BagtFegV.js +952 -0
  23. package/dist/_chunks/doctor-CAsJ-rSZ.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-BTTpTwUk.js +143 -0
  27. package/dist/_chunks/generated-artifacts-Bb13pGUG.js +32 -0
  28. package/dist/_chunks/glob-DRw9sbfF.js +56 -0
  29. package/dist/_chunks/init-DJ5y3mu5.js +165 -0
  30. package/dist/_chunks/loader-BC0skbnH.js +1330 -0
  31. package/dist/_chunks/local-dev-vars-BFLS-HoI.js +81 -0
  32. package/dist/_chunks/local-hyperdrive-CcORzo76.js +119 -0
  33. package/dist/_chunks/local-media-bindings-ZQe-epuw.js +335 -0
  34. package/dist/_chunks/local-secrets-C0n5oRgI.js +123 -0
  35. package/dist/_chunks/login-CgNcbpEq.js +51 -0
  36. package/dist/_chunks/package-metadata-CLI488gB.js +39 -0
  37. package/dist/_chunks/preferences-CbYERA_m.js +241 -0
  38. package/dist/_chunks/preview-j9Kbx4-G.js +462 -0
  39. package/dist/_chunks/preview-registry-CTXU4mBc.js +1186 -0
  40. package/dist/_chunks/preview-resources-CQIu2-NY.js +359 -0
  41. package/dist/_chunks/previews-BIaw6NVC.js +1133 -0
  42. package/dist/_chunks/productions-CF8oQcX7.js +504 -0
  43. package/dist/_chunks/r2-presign-runtime-C75FkLMd.js +291 -0
  44. package/dist/_chunks/ref-CYJNAAe_.js +178 -0
  45. package/dist/_chunks/remote-8jEHLVGg.js +79 -0
  46. package/dist/_chunks/remote-config-Bw6qIVM4.js +132 -0
  47. package/dist/_chunks/resolve-package-DeJUGxoE.js +152 -0
  48. package/dist/_chunks/rolldown-runtime-CvQ6eiug.js +14 -0
  49. package/dist/_chunks/routes-CRXB3-iw.js +851 -0
  50. package/dist/_chunks/runtime-BlKTWIgD.js +874 -0
  51. package/dist/_chunks/schema-normalization-CTdiY17P.js +667 -0
  52. package/dist/_chunks/secrets-BJuEa9Jz.js +95 -0
  53. package/dist/_chunks/tail-DjGRt8gw.js +239 -0
  54. package/dist/_chunks/token-wmeF8-IQ.js +333 -0
  55. package/dist/_chunks/tokens-KaEr4B8e.js +221 -0
  56. package/dist/_chunks/types-BLGfxIq-.js +484 -0
  57. package/dist/_chunks/ui-BhCdDC2N.js +103 -0
  58. package/dist/_chunks/usage-rRusKejc.js +272 -0
  59. package/dist/_chunks/vite-Bml-Whp8.js +1267 -0
  60. package/dist/_chunks/vite-process-CDa3yQui.js +2929 -0
  61. package/dist/_chunks/vite-utils-D8kPPxUy.js +183 -0
  62. package/dist/_chunks/worker-DgczaXVW.js +410 -0
  63. package/dist/_chunks/worker-bundler-Isj5jiW6.js +458 -0
  64. package/dist/_chunks/worker-entrypoint-C8j23t6d.js +247 -0
  65. package/dist/_chunks/workerName-kEXwmV2m.js +23 -0
  66. package/dist/_chunks/workspace-CrvqPLTX.js +517 -0
  67. package/dist/_chunks/workspace-Ds3xMjOE.js +175 -0
  68. package/dist/bridge/client.d.ts +93 -8
  69. package/dist/bridge/client.d.ts.map +1 -1
  70. package/dist/bridge/do-rpc-dispatch.d.ts +23 -0
  71. package/dist/bridge/do-rpc-dispatch.d.ts.map +1 -0
  72. package/dist/bridge/do-websocket-connect.d.ts +33 -0
  73. package/dist/bridge/do-websocket-connect.d.ts.map +1 -0
  74. package/dist/bridge/gateway-runtime.d.ts +8 -0
  75. package/dist/bridge/gateway-runtime.d.ts.map +1 -0
  76. package/dist/bridge/index.d.ts +6 -6
  77. package/dist/bridge/index.d.ts.map +1 -1
  78. package/dist/bridge/log.d.ts +5 -0
  79. package/dist/bridge/log.d.ts.map +1 -0
  80. package/dist/bridge/miniflare-gateway.d.ts +45 -0
  81. package/dist/bridge/miniflare-gateway.d.ts.map +1 -0
  82. package/dist/bridge/miniflare.d.ts +92 -2
  83. package/dist/bridge/miniflare.d.ts.map +1 -1
  84. package/dist/bridge/proxy.d.ts +12 -11
  85. package/dist/bridge/proxy.d.ts.map +1 -1
  86. package/dist/bridge/r2-presign-runtime.d.ts +9 -0
  87. package/dist/bridge/r2-presign-runtime.d.ts.map +1 -0
  88. package/dist/bridge/server.d.ts +2 -1
  89. package/dist/bridge/server.d.ts.map +1 -1
  90. package/dist/bridge/v2/body-streams.d.ts +53 -0
  91. package/dist/bridge/v2/body-streams.d.ts.map +1 -0
  92. package/dist/bridge/v2/codec.d.ts +106 -0
  93. package/dist/bridge/v2/codec.d.ts.map +1 -0
  94. package/dist/bridge/v2/control-messages.d.ts +46 -0
  95. package/dist/bridge/v2/control-messages.d.ts.map +1 -0
  96. package/dist/bridge/v2/frames.d.ts +109 -0
  97. package/dist/bridge/v2/frames.d.ts.map +1 -0
  98. package/dist/bridge/v2/index.d.ts +11 -0
  99. package/dist/bridge/v2/index.d.ts.map +1 -0
  100. package/dist/bridge/v2/serialization.d.ts +48 -0
  101. package/dist/bridge/v2/serialization.d.ts.map +1 -0
  102. package/dist/bridge/v2/transport.d.ts +31 -0
  103. package/dist/bridge/v2/transport.d.ts.map +1 -0
  104. package/dist/bridge/v2/value-codec.d.ts +61 -0
  105. package/dist/bridge/v2/value-codec.d.ts.map +1 -0
  106. package/dist/bridge/v2/value-serialization.d.ts +139 -0
  107. package/dist/bridge/v2/value-serialization.d.ts.map +1 -0
  108. package/dist/bridge/{protocol.d.ts → v2/wire.d.ts} +32 -8
  109. package/dist/bridge/v2/wire.d.ts.map +1 -0
  110. package/dist/bridge/v2/ws-relay.d.ts +53 -0
  111. package/dist/bridge/v2/ws-relay.d.ts.map +1 -0
  112. package/dist/bridge/websocket-constructor.d.ts +38 -0
  113. package/dist/bridge/websocket-constructor.d.ts.map +1 -0
  114. package/dist/browser-shim/handler.d.ts +2 -2
  115. package/dist/browser-shim/handler.d.ts.map +1 -1
  116. package/dist/browser-shim/index.d.ts +2 -2
  117. package/dist/browser-shim/server.d.ts +63 -0
  118. package/dist/browser-shim/server.d.ts.map +1 -1
  119. package/dist/browser.d.ts +5778 -43
  120. package/dist/browser.d.ts.map +1 -1
  121. package/dist/browser.js +73 -142
  122. package/dist/bundler/defaults.d.ts +23 -0
  123. package/dist/bundler/defaults.d.ts.map +1 -0
  124. package/dist/bundler/do-bundler.d.ts +7 -0
  125. package/dist/bundler/do-bundler.d.ts.map +1 -1
  126. package/dist/bundler/index.d.ts +3 -1
  127. package/dist/bundler/index.d.ts.map +1 -1
  128. package/dist/bundler/rolldown-shared.d.ts +53 -0
  129. package/dist/bundler/rolldown-shared.d.ts.map +1 -0
  130. package/dist/bundler/worker-bundler.d.ts +13 -0
  131. package/dist/bundler/worker-bundler.d.ts.map +1 -0
  132. package/dist/bundler/worker-compat.d.ts +4 -0
  133. package/dist/bundler/worker-compat.d.ts.map +1 -0
  134. package/dist/cli/build-manifest.d.ts +66 -0
  135. package/dist/cli/build-manifest.d.ts.map +1 -0
  136. package/dist/cli/command-utils.d.ts +18 -0
  137. package/dist/cli/command-utils.d.ts.map +1 -0
  138. package/dist/cli/commands/account.d.ts +2 -2
  139. package/dist/cli/commands/account.d.ts.map +1 -1
  140. package/dist/cli/commands/ai.d.ts +1 -1
  141. package/dist/cli/commands/ai.d.ts.map +1 -1
  142. package/dist/cli/commands/build-artifacts.d.ts +40 -0
  143. package/dist/cli/commands/build-artifacts.d.ts.map +1 -0
  144. package/dist/cli/commands/build.d.ts +2 -2
  145. package/dist/cli/commands/build.d.ts.map +1 -1
  146. package/dist/cli/commands/config.d.ts +4 -0
  147. package/dist/cli/commands/config.d.ts.map +1 -0
  148. package/dist/cli/commands/deploy/metadata.d.ts +18 -0
  149. package/dist/cli/commands/deploy/metadata.d.ts.map +1 -0
  150. package/dist/cli/commands/deploy/prepare.d.ts +23 -0
  151. package/dist/cli/commands/deploy/prepare.d.ts.map +1 -0
  152. package/dist/cli/commands/deploy/runtime.d.ts +4 -0
  153. package/dist/cli/commands/deploy/runtime.d.ts.map +1 -0
  154. package/dist/cli/commands/deploy/verification.d.ts +36 -0
  155. package/dist/cli/commands/deploy/verification.d.ts.map +1 -0
  156. package/dist/cli/commands/deploy.d.ts +2 -2
  157. package/dist/cli/commands/deploy.d.ts.map +1 -1
  158. package/dist/cli/commands/dev.d.ts +9 -1
  159. package/dist/cli/commands/dev.d.ts.map +1 -1
  160. package/dist/cli/commands/doctor.d.ts +2 -2
  161. package/dist/cli/commands/doctor.d.ts.map +1 -1
  162. package/dist/cli/commands/init.d.ts +2 -2
  163. package/dist/cli/commands/init.d.ts.map +1 -1
  164. package/dist/cli/commands/login.d.ts +4 -0
  165. package/dist/cli/commands/login.d.ts.map +1 -0
  166. package/dist/cli/commands/previews-support/cleanup.d.ts +9 -0
  167. package/dist/cli/commands/previews-support/cleanup.d.ts.map +1 -0
  168. package/dist/cli/commands/previews-support/family.d.ts +10 -0
  169. package/dist/cli/commands/previews-support/family.d.ts.map +1 -0
  170. package/dist/cli/commands/previews-support/render.d.ts +8 -0
  171. package/dist/cli/commands/previews-support/render.d.ts.map +1 -0
  172. package/dist/cli/commands/previews-support/theme.d.ts +10 -0
  173. package/dist/cli/commands/previews-support/theme.d.ts.map +1 -0
  174. package/dist/cli/commands/previews-support/types.d.ts +70 -0
  175. package/dist/cli/commands/previews-support/types.d.ts.map +1 -0
  176. package/dist/cli/commands/previews.d.ts +4 -0
  177. package/dist/cli/commands/previews.d.ts.map +1 -0
  178. package/dist/cli/commands/productions.d.ts +4 -0
  179. package/dist/cli/commands/productions.d.ts.map +1 -0
  180. package/dist/cli/commands/remote.d.ts +1 -1
  181. package/dist/cli/commands/remote.d.ts.map +1 -1
  182. package/dist/cli/commands/secrets.d.ts +4 -0
  183. package/dist/cli/commands/secrets.d.ts.map +1 -0
  184. package/dist/cli/commands/tail.d.ts +44 -0
  185. package/dist/cli/commands/tail.d.ts.map +1 -0
  186. package/dist/cli/commands/token.d.ts +4 -0
  187. package/dist/cli/commands/token.d.ts.map +1 -0
  188. package/dist/cli/commands/type-generation/discovery.d.ts +7 -0
  189. package/dist/cli/commands/type-generation/discovery.d.ts.map +1 -0
  190. package/dist/cli/commands/type-generation/generator.d.ts +121 -0
  191. package/dist/cli/commands/type-generation/generator.d.ts.map +1 -0
  192. package/dist/cli/commands/type-generation/models.d.ts +27 -0
  193. package/dist/cli/commands/type-generation/models.d.ts.map +1 -0
  194. package/dist/cli/commands/types.d.ts +2 -2
  195. package/dist/cli/commands/types.d.ts.map +1 -1
  196. package/dist/cli/commands/worker.d.ts +4 -0
  197. package/dist/cli/commands/worker.d.ts.map +1 -0
  198. package/dist/cli/commands/workspace.d.ts +8 -0
  199. package/dist/cli/commands/workspace.d.ts.map +1 -0
  200. package/dist/cli/config-path.d.ts +6 -0
  201. package/dist/cli/config-path.d.ts.map +1 -0
  202. package/dist/cli/dependencies.d.ts +2 -1
  203. package/dist/cli/dependencies.d.ts.map +1 -1
  204. package/dist/cli/deploy-strategy.d.ts +17 -0
  205. package/dist/cli/deploy-strategy.d.ts.map +1 -0
  206. package/dist/cli/deploy-target.d.ts +17 -0
  207. package/dist/cli/deploy-target.d.ts.map +1 -0
  208. package/dist/cli/generated-artifacts.d.ts +12 -0
  209. package/dist/cli/generated-artifacts.d.ts.map +1 -0
  210. package/dist/cli/gradual-deploy.d.ts +49 -0
  211. package/dist/cli/gradual-deploy.d.ts.map +1 -0
  212. package/dist/cli/help-pages/pages/account.d.ts +3 -0
  213. package/dist/cli/help-pages/pages/account.d.ts.map +1 -0
  214. package/dist/cli/help-pages/pages/core.d.ts +4 -0
  215. package/dist/cli/help-pages/pages/core.d.ts.map +1 -0
  216. package/dist/cli/help-pages/pages/index.d.ts +3 -0
  217. package/dist/cli/help-pages/pages/index.d.ts.map +1 -0
  218. package/dist/cli/help-pages/pages/misc.d.ts +3 -0
  219. package/dist/cli/help-pages/pages/misc.d.ts.map +1 -0
  220. package/dist/cli/help-pages/pages/previews.d.ts +3 -0
  221. package/dist/cli/help-pages/pages/previews.d.ts.map +1 -0
  222. package/dist/cli/help-pages/pages/productions.d.ts +3 -0
  223. package/dist/cli/help-pages/pages/productions.d.ts.map +1 -0
  224. package/dist/cli/help-pages/render.d.ts +12 -0
  225. package/dist/cli/help-pages/render.d.ts.map +1 -0
  226. package/dist/cli/help-pages/shared.d.ts +15 -0
  227. package/dist/cli/help-pages/shared.d.ts.map +1 -0
  228. package/dist/cli/help-pages/types.d.ts +23 -0
  229. package/dist/cli/help-pages/types.d.ts.map +1 -0
  230. package/dist/cli/help.d.ts +6 -0
  231. package/dist/cli/help.d.ts.map +1 -0
  232. package/dist/cli/index.d.ts +1 -0
  233. package/dist/cli/index.d.ts.map +1 -1
  234. package/dist/cli/index.js +2 -0
  235. package/dist/cli/package-metadata.d.ts +16 -0
  236. package/dist/cli/package-metadata.d.ts.map +1 -0
  237. package/dist/cli/preview-bindings.d.ts +49 -0
  238. package/dist/cli/preview-bindings.d.ts.map +1 -0
  239. package/dist/cli/preview.d.ts +10 -0
  240. package/dist/cli/preview.d.ts.map +1 -0
  241. package/dist/cli/ui.d.ts +37 -0
  242. package/dist/cli/ui.d.ts.map +1 -0
  243. package/dist/cli/workspace-build-guard.d.ts +14 -0
  244. package/dist/cli/workspace-build-guard.d.ts.map +1 -0
  245. package/dist/cli/wrangler-auth.d.ts +1 -1
  246. package/dist/cloudflare/account-core.d.ts +6 -0
  247. package/dist/cloudflare/account-core.d.ts.map +1 -0
  248. package/dist/cloudflare/account-resources.d.ts +40 -0
  249. package/dist/cloudflare/account-resources.d.ts.map +1 -0
  250. package/dist/cloudflare/account-status.d.ts +11 -0
  251. package/dist/cloudflare/account-status.d.ts.map +1 -0
  252. package/dist/cloudflare/account-workers.d.ts +14 -0
  253. package/dist/cloudflare/account-workers.d.ts.map +1 -0
  254. package/dist/cloudflare/account.d.ts +7 -64
  255. package/dist/cloudflare/account.d.ts.map +1 -1
  256. package/dist/cloudflare/api.d.ts +71 -3
  257. package/dist/cloudflare/api.d.ts.map +1 -1
  258. package/dist/cloudflare/auth.d.ts +1 -1
  259. package/dist/cloudflare/auth.d.ts.map +1 -1
  260. package/dist/cloudflare/index.d.ts +61 -6
  261. package/dist/cloudflare/index.d.ts.map +1 -1
  262. package/dist/cloudflare/index.js +4 -13
  263. package/dist/cloudflare/known-permission-group-ids.generated.d.ts +10 -0
  264. package/dist/cloudflare/known-permission-group-ids.generated.d.ts.map +1 -0
  265. package/dist/cloudflare/kv-namespace.d.ts +4 -0
  266. package/dist/cloudflare/kv-namespace.d.ts.map +1 -0
  267. package/dist/cloudflare/preferences.d.ts +7 -0
  268. package/dist/cloudflare/preferences.d.ts.map +1 -1
  269. package/dist/cloudflare/preview-registry-cache.d.ts +6 -0
  270. package/dist/cloudflare/preview-registry-cache.d.ts.map +1 -0
  271. package/dist/cloudflare/preview-registry-inference.d.ts +14 -0
  272. package/dist/cloudflare/preview-registry-inference.d.ts.map +1 -0
  273. package/dist/cloudflare/preview-registry-records.d.ts +4 -0
  274. package/dist/cloudflare/preview-registry-records.d.ts.map +1 -0
  275. package/dist/cloudflare/preview-registry-shape.d.ts +47 -0
  276. package/dist/cloudflare/preview-registry-shape.d.ts.map +1 -0
  277. package/dist/cloudflare/preview-registry-store.d.ts +14 -0
  278. package/dist/cloudflare/preview-registry-store.d.ts.map +1 -0
  279. package/dist/cloudflare/preview-registry-transport.d.ts +4 -0
  280. package/dist/cloudflare/preview-registry-transport.d.ts.map +1 -0
  281. package/dist/cloudflare/preview-registry-types.d.ts +103 -0
  282. package/dist/cloudflare/preview-registry-types.d.ts.map +1 -0
  283. package/dist/cloudflare/preview-registry.d.ts +42 -0
  284. package/dist/cloudflare/preview-registry.d.ts.map +1 -0
  285. package/dist/cloudflare/preview-urls.d.ts +3 -0
  286. package/dist/cloudflare/preview-urls.d.ts.map +1 -0
  287. package/dist/cloudflare/registry-schema.d.ts +253 -0
  288. package/dist/cloudflare/registry-schema.d.ts.map +1 -0
  289. package/dist/cloudflare/remote-config.d.ts.map +1 -1
  290. package/dist/cloudflare/tokens.d.ts +44 -0
  291. package/dist/cloudflare/tokens.d.ts.map +1 -0
  292. package/dist/cloudflare/types.d.ts +124 -7
  293. package/dist/cloudflare/types.d.ts.map +1 -1
  294. package/dist/cloudflare/usage.d.ts +31 -3
  295. package/dist/cloudflare/usage.d.ts.map +1 -1
  296. package/dist/config/binding-resolution-helpers.d.ts +41 -0
  297. package/dist/config/binding-resolution-helpers.d.ts.map +1 -0
  298. package/dist/config/compatibility.d.ts +3 -0
  299. package/dist/config/compatibility.d.ts.map +1 -0
  300. package/dist/config/compiler/bindings.d.ts +14 -0
  301. package/dist/config/compiler/bindings.d.ts.map +1 -0
  302. package/dist/config/compiler/core-helpers.d.ts +6 -0
  303. package/dist/config/compiler/core-helpers.d.ts.map +1 -0
  304. package/dist/config/compiler/do-workers.d.ts +34 -0
  305. package/dist/config/compiler/do-workers.d.ts.map +1 -0
  306. package/dist/config/compiler/paths.d.ts +18 -0
  307. package/dist/config/compiler/paths.d.ts.map +1 -0
  308. package/dist/config/compiler/types.d.ts +308 -0
  309. package/dist/config/compiler/types.d.ts.map +1 -0
  310. package/dist/config/compiler.d.ts +22 -134
  311. package/dist/config/compiler.d.ts.map +1 -1
  312. package/dist/config/cron.d.ts +19 -0
  313. package/dist/config/cron.d.ts.map +1 -0
  314. package/dist/config/define.d.ts +8 -5
  315. package/dist/config/define.d.ts.map +1 -1
  316. package/dist/config/deploy-resources.d.ts +58 -0
  317. package/dist/config/deploy-resources.d.ts.map +1 -0
  318. package/dist/config/env-vars.d.ts +309 -0
  319. package/dist/config/env-vars.d.ts.map +1 -0
  320. package/dist/config/framework-providers.d.ts +9 -0
  321. package/dist/config/framework-providers.d.ts.map +1 -0
  322. package/dist/config/index.d.ts +13 -5
  323. package/dist/config/index.d.ts.map +1 -1
  324. package/dist/config/loader.d.ts +2 -1
  325. package/dist/config/loader.d.ts.map +1 -1
  326. package/dist/config/local-dev-vars.d.ts +15 -0
  327. package/dist/config/local-dev-vars.d.ts.map +1 -0
  328. package/dist/config/preview-resources.d.ts +83 -0
  329. package/dist/config/preview-resources.d.ts.map +1 -0
  330. package/dist/config/preview.d.ts +29 -0
  331. package/dist/config/preview.d.ts.map +1 -0
  332. package/dist/config/ref.d.ts +16 -25
  333. package/dist/config/ref.d.ts.map +1 -1
  334. package/dist/config/resolve-phased.d.ts +72 -0
  335. package/dist/config/resolve-phased.d.ts.map +1 -0
  336. package/dist/config/resolve.d.ts +11 -0
  337. package/dist/config/resolve.d.ts.map +1 -0
  338. package/dist/config/resource-resolution.d.ts +80 -0
  339. package/dist/config/resource-resolution.d.ts.map +1 -0
  340. package/dist/config/schema-bindings.d.ts +2124 -0
  341. package/dist/config/schema-bindings.d.ts.map +1 -0
  342. package/dist/config/schema-build.d.ts +67 -0
  343. package/dist/config/schema-build.d.ts.map +1 -0
  344. package/dist/config/schema-env.d.ts +3821 -0
  345. package/dist/config/schema-env.d.ts.map +1 -0
  346. package/dist/config/schema-normalization.d.ts +272 -0
  347. package/dist/config/schema-normalization.d.ts.map +1 -0
  348. package/dist/config/schema-runtime.d.ts +597 -0
  349. package/dist/config/schema-runtime.d.ts.map +1 -0
  350. package/dist/config/schema-types-bindings-platform.d.ts +520 -0
  351. package/dist/config/schema-types-bindings-platform.d.ts.map +1 -0
  352. package/dist/config/schema-types-bindings-resources.d.ts +802 -0
  353. package/dist/config/schema-types-bindings-resources.d.ts.map +1 -0
  354. package/dist/config/schema-types-bindings.d.ts +293 -0
  355. package/dist/config/schema-types-bindings.d.ts.map +1 -0
  356. package/dist/config/schema-types-build.d.ts +86 -0
  357. package/dist/config/schema-types-build.d.ts.map +1 -0
  358. package/dist/config/schema-types-runtime-server.d.ts +196 -0
  359. package/dist/config/schema-types-runtime-server.d.ts.map +1 -0
  360. package/dist/config/schema-types-runtime.d.ts +913 -0
  361. package/dist/config/schema-types-runtime.d.ts.map +1 -0
  362. package/dist/config/schema-types.d.ts +458 -0
  363. package/dist/config/schema-types.d.ts.map +1 -0
  364. package/dist/config/schema.d.ts +5796 -2023
  365. package/dist/config/schema.d.ts.map +1 -1
  366. package/dist/config/service-bindings-validation.d.ts +36 -0
  367. package/dist/config/service-bindings-validation.d.ts.map +1 -0
  368. package/dist/config/workspace.d.ts +282 -0
  369. package/dist/config/workspace.d.ts.map +1 -0
  370. package/dist/config-entry.d.ts +7 -0
  371. package/dist/config-entry.d.ts.map +1 -0
  372. package/dist/config-entry.js +3 -0
  373. package/dist/decorators/durable-object.d.ts.map +1 -1
  374. package/dist/decorators/index.d.ts +2 -2
  375. package/dist/decorators/index.js +2 -9
  376. package/dist/dev-server/d1-migrations.d.ts +36 -0
  377. package/dist/dev-server/d1-migrations.d.ts.map +1 -0
  378. package/dist/dev-server/dev-server-state.d.ts +59 -0
  379. package/dist/dev-server/dev-server-state.d.ts.map +1 -0
  380. package/dist/dev-server/gateway-script.d.ts +22 -0
  381. package/dist/dev-server/gateway-script.d.ts.map +1 -0
  382. package/dist/dev-server/index.d.ts +1 -1
  383. package/dist/dev-server/miniflare-bindings.d.ts +90 -0
  384. package/dist/dev-server/miniflare-bindings.d.ts.map +1 -0
  385. package/dist/dev-server/miniflare-dev-config.d.ts +57 -0
  386. package/dist/dev-server/miniflare-dev-config.d.ts.map +1 -0
  387. package/dist/dev-server/miniflare-log.d.ts +20 -0
  388. package/dist/dev-server/miniflare-log.d.ts.map +1 -0
  389. package/dist/dev-server/miniflare-worker-config.d.ts +100 -0
  390. package/dist/dev-server/miniflare-worker-config.d.ts.map +1 -0
  391. package/dist/dev-server/reload-queue.d.ts +13 -0
  392. package/dist/dev-server/reload-queue.d.ts.map +1 -0
  393. package/dist/dev-server/runtime-health.d.ts +79 -0
  394. package/dist/dev-server/runtime-health.d.ts.map +1 -0
  395. package/dist/dev-server/runtime-stdio.d.ts +8 -0
  396. package/dist/dev-server/runtime-stdio.d.ts.map +1 -0
  397. package/dist/dev-server/server-startup-helpers.d.ts +84 -0
  398. package/dist/dev-server/server-startup-helpers.d.ts.map +1 -0
  399. package/dist/dev-server/server.d.ts +2 -0
  400. package/dist/dev-server/server.d.ts.map +1 -1
  401. package/dist/dev-server/vite-process.d.ts +24 -0
  402. package/dist/dev-server/vite-process.d.ts.map +1 -0
  403. package/dist/dev-server/vite-utils.d.ts +19 -1
  404. package/dist/dev-server/vite-utils.d.ts.map +1 -1
  405. package/dist/dev-server/worker-source-watcher.d.ts +17 -0
  406. package/dist/dev-server/worker-source-watcher.d.ts.map +1 -0
  407. package/dist/dev-server/worker-surface-paths.d.ts +6 -0
  408. package/dist/dev-server/worker-surface-paths.d.ts.map +1 -0
  409. package/dist/dev-server/workspace/merge-config.d.ts +81 -0
  410. package/dist/dev-server/workspace/merge-config.d.ts.map +1 -0
  411. package/dist/dev-server/workspace/prepare-app.d.ts +84 -0
  412. package/dist/dev-server/workspace/prepare-app.d.ts.map +1 -0
  413. package/dist/dev-server/workspace/server.d.ts +47 -0
  414. package/dist/dev-server/workspace/server.d.ts.map +1 -0
  415. package/dist/env.d.ts +10 -0
  416. package/dist/env.d.ts.map +1 -1
  417. package/dist/index.d.ts +8 -12
  418. package/dist/index.d.ts.map +1 -1
  419. package/dist/index.js +10 -297
  420. package/dist/runtime/context-events.d.ts +13 -0
  421. package/dist/runtime/context-events.d.ts.map +1 -0
  422. package/dist/runtime/context-types.d.ts +82 -0
  423. package/dist/runtime/context-types.d.ts.map +1 -0
  424. package/dist/runtime/context.d.ts +20 -44
  425. package/dist/runtime/context.d.ts.map +1 -1
  426. package/dist/runtime/exports.d.ts +70 -55
  427. package/dist/runtime/exports.d.ts.map +1 -1
  428. package/dist/runtime/index.d.ts +11 -5
  429. package/dist/runtime/index.d.ts.map +1 -1
  430. package/dist/runtime/index.js +5 -184
  431. package/dist/runtime/middleware.d.ts +119 -67
  432. package/dist/runtime/middleware.d.ts.map +1 -1
  433. package/dist/runtime/r2-presign.d.ts +164 -0
  434. package/dist/runtime/r2-presign.d.ts.map +1 -0
  435. package/dist/runtime/router/index.d.ts +7 -0
  436. package/dist/runtime/router/index.d.ts.map +1 -0
  437. package/dist/runtime/router/types.d.ts +24 -0
  438. package/dist/runtime/router/types.d.ts.map +1 -0
  439. package/dist/runtime/validation.d.ts +18 -4
  440. package/dist/runtime/validation.d.ts.map +1 -1
  441. package/dist/secrets/local-secrets.d.ts +46 -0
  442. package/dist/secrets/local-secrets.d.ts.map +1 -0
  443. package/dist/shims/local-hyperdrive.d.ts +12 -0
  444. package/dist/shims/local-hyperdrive.d.ts.map +1 -0
  445. package/dist/shims/local-media-bindings.d.ts +19 -0
  446. package/dist/shims/local-media-bindings.d.ts.map +1 -0
  447. package/dist/shims/local-worker-loader.d.ts +3 -0
  448. package/dist/shims/local-worker-loader.d.ts.map +1 -0
  449. package/dist/sveltekit/index.d.ts +1 -1
  450. package/dist/sveltekit/index.d.ts.map +1 -1
  451. package/dist/sveltekit/index.js +377 -169
  452. package/dist/sveltekit/local-bindings.d.ts +4 -0
  453. package/dist/sveltekit/local-bindings.d.ts.map +1 -0
  454. package/dist/sveltekit/platform.d.ts +42 -2
  455. package/dist/sveltekit/platform.d.ts.map +1 -1
  456. package/dist/test/ai-search.d.ts +39 -0
  457. package/dist/test/ai-search.d.ts.map +1 -0
  458. package/dist/test/alarm.d.ts +55 -0
  459. package/dist/test/alarm.d.ts.map +1 -0
  460. package/dist/test/binding-hints.d.ts +10 -0
  461. package/dist/test/binding-hints.d.ts.map +1 -0
  462. package/dist/test/cf.d.ts +71 -35
  463. package/dist/test/cf.d.ts.map +1 -1
  464. package/dist/test/containers.d.ts +87 -0
  465. package/dist/test/containers.d.ts.map +1 -0
  466. package/dist/test/email.d.ts +16 -7
  467. package/dist/test/email.d.ts.map +1 -1
  468. package/dist/test/index.d.ts +20 -21
  469. package/dist/test/index.d.ts.map +1 -1
  470. package/dist/test/index.js +5115 -75
  471. package/dist/test/offline-bindings.d.ts +124 -0
  472. package/dist/test/offline-bindings.d.ts.map +1 -0
  473. package/dist/test/queue.d.ts.map +1 -1
  474. package/dist/test/remote-ai.d.ts.map +1 -1
  475. package/dist/test/remote-cloudflare.d.ts +13 -0
  476. package/dist/test/remote-cloudflare.d.ts.map +1 -0
  477. package/dist/test/remote-vectorize.d.ts.map +1 -1
  478. package/dist/test/resolve-service-bindings.d.ts +64 -4
  479. package/dist/test/resolve-service-bindings.d.ts.map +1 -1
  480. package/dist/test/scheduled.d.ts.map +1 -1
  481. package/dist/test/should-skip.d.ts +14 -18
  482. package/dist/test/should-skip.d.ts.map +1 -1
  483. package/dist/test/simple-context-bindings.d.ts +13 -0
  484. package/dist/test/simple-context-bindings.d.ts.map +1 -0
  485. package/dist/test/simple-context-durable-objects.d.ts +6 -0
  486. package/dist/test/simple-context-durable-objects.d.ts.map +1 -0
  487. package/dist/test/simple-context-env.d.ts +35 -0
  488. package/dist/test/simple-context-env.d.ts.map +1 -0
  489. package/dist/test/simple-context-gateway-script.d.ts +2 -0
  490. package/dist/test/simple-context-gateway-script.d.ts.map +1 -0
  491. package/dist/test/simple-context-handlers.d.ts +12 -0
  492. package/dist/test/simple-context-handlers.d.ts.map +1 -0
  493. package/dist/test/simple-context-lifecycle.d.ts +32 -0
  494. package/dist/test/simple-context-lifecycle.d.ts.map +1 -0
  495. package/dist/test/simple-context-mfconfig.d.ts +18 -0
  496. package/dist/test/simple-context-mfconfig.d.ts.map +1 -0
  497. package/dist/test/simple-context-multi-worker.d.ts +16 -0
  498. package/dist/test/simple-context-multi-worker.d.ts.map +1 -0
  499. package/dist/test/simple-context-paths.d.ts +40 -0
  500. package/dist/test/simple-context-paths.d.ts.map +1 -0
  501. package/dist/test/simple-context-runtime.d.ts +19 -0
  502. package/dist/test/simple-context-runtime.d.ts.map +1 -0
  503. package/dist/test/simple-context-startup.d.ts +11 -0
  504. package/dist/test/simple-context-startup.d.ts.map +1 -0
  505. package/dist/test/simple-context-transport.d.ts +14 -0
  506. package/dist/test/simple-context-transport.d.ts.map +1 -0
  507. package/dist/test/simple-context.d.ts +8 -27
  508. package/dist/test/simple-context.d.ts.map +1 -1
  509. package/dist/test/tail.d.ts +3 -2
  510. package/dist/test/tail.d.ts.map +1 -1
  511. package/dist/test/utilities/analytics-engine.d.ts +22 -0
  512. package/dist/test/utilities/analytics-engine.d.ts.map +1 -0
  513. package/dist/test/utilities/artifacts.d.ts +11 -0
  514. package/dist/test/utilities/artifacts.d.ts.map +1 -0
  515. package/dist/test/utilities/context.d.ts +39 -0
  516. package/dist/test/utilities/context.d.ts.map +1 -0
  517. package/dist/test/utilities/d1.d.ts +21 -0
  518. package/dist/test/utilities/d1.d.ts.map +1 -0
  519. package/dist/test/utilities/env.d.ts +45 -0
  520. package/dist/test/utilities/env.d.ts.map +1 -0
  521. package/dist/test/utilities/kv.d.ts +11 -0
  522. package/dist/test/utilities/kv.d.ts.map +1 -0
  523. package/dist/test/utilities/media.d.ts +16 -0
  524. package/dist/test/utilities/media.d.ts.map +1 -0
  525. package/dist/test/utilities/platform.d.ts +41 -0
  526. package/dist/test/utilities/platform.d.ts.map +1 -0
  527. package/dist/test/utilities/queue.d.ts +5 -0
  528. package/dist/test/utilities/queue.d.ts.map +1 -0
  529. package/dist/test/utilities/r2.d.ts +2 -0
  530. package/dist/test/utilities/r2.d.ts.map +1 -0
  531. package/dist/test/utilities/send-email.d.ts +27 -0
  532. package/dist/test/utilities/send-email.d.ts.map +1 -0
  533. package/dist/test/utilities/stream-flagship.d.ts +27 -0
  534. package/dist/test/utilities/stream-flagship.d.ts.map +1 -0
  535. package/dist/test/utilities/vectorize.d.ts +38 -0
  536. package/dist/test/utilities/vectorize.d.ts.map +1 -0
  537. package/dist/test/utilities/workflows.d.ts +26 -0
  538. package/dist/test/utilities/workflows.d.ts.map +1 -0
  539. package/dist/test/utilities.d.ts +14 -98
  540. package/dist/test/utilities.d.ts.map +1 -1
  541. package/dist/test/worker.d.ts +6 -0
  542. package/dist/test/worker.d.ts.map +1 -1
  543. package/dist/transform/durable-object.d.ts.map +1 -1
  544. package/dist/transform/index.d.ts +2 -2
  545. package/dist/transform/worker-entrypoint.d.ts +5 -0
  546. package/dist/transform/worker-entrypoint.d.ts.map +1 -1
  547. package/dist/utils/entrypoint-discovery.d.ts +6 -3
  548. package/dist/utils/entrypoint-discovery.d.ts.map +1 -1
  549. package/dist/utils/glob.d.ts.map +1 -1
  550. package/dist/utils/resolve-package.d.ts.map +1 -1
  551. package/dist/utils/send-email.d.ts +15 -0
  552. package/dist/utils/send-email.d.ts.map +1 -0
  553. package/dist/utils/send-email.js +163 -0
  554. package/dist/vite/config-file.d.ts +25 -0
  555. package/dist/vite/config-file.d.ts.map +1 -0
  556. package/dist/vite/index.d.ts +3 -2
  557. package/dist/vite/index.d.ts.map +1 -1
  558. package/dist/vite/index.js +2 -407
  559. package/dist/vite/plugin-config-hook.d.ts +28 -0
  560. package/dist/vite/plugin-config-hook.d.ts.map +1 -0
  561. package/dist/vite/plugin-context.d.ts +27 -0
  562. package/dist/vite/plugin-context.d.ts.map +1 -0
  563. package/dist/vite/plugin-durable-objects.d.ts +18 -0
  564. package/dist/vite/plugin-durable-objects.d.ts.map +1 -0
  565. package/dist/vite/plugin-programmatic.d.ts +44 -0
  566. package/dist/vite/plugin-programmatic.d.ts.map +1 -0
  567. package/dist/vite/plugin-service-bindings.d.ts +13 -0
  568. package/dist/vite/plugin-service-bindings.d.ts.map +1 -0
  569. package/dist/vite/plugin-transform.d.ts +41 -0
  570. package/dist/vite/plugin-transform.d.ts.map +1 -0
  571. package/dist/vite/plugin.d.ts +10 -41
  572. package/dist/vite/plugin.d.ts.map +1 -1
  573. package/dist/worker-entry/composed-worker.d.ts +5 -8
  574. package/dist/worker-entry/composed-worker.d.ts.map +1 -1
  575. package/dist/worker-entry/durable-object-discovery.d.ts +20 -0
  576. package/dist/worker-entry/durable-object-discovery.d.ts.map +1 -0
  577. package/dist/worker-entry/extensions.d.ts +5 -0
  578. package/dist/worker-entry/extensions.d.ts.map +1 -0
  579. package/dist/worker-entry/routes.d.ts +22 -0
  580. package/dist/worker-entry/routes.d.ts.map +1 -0
  581. package/dist/worker-entry/surface-paths.d.ts +26 -0
  582. package/dist/worker-entry/surface-paths.d.ts.map +1 -0
  583. package/dist/worker-entry/validate-fetch-style.d.ts +12 -0
  584. package/dist/worker-entry/validate-fetch-style.d.ts.map +1 -0
  585. package/dist/workflows/local-workflow-entrypoints.d.ts +7 -0
  586. package/dist/workflows/local-workflow-entrypoints.d.ts.map +1 -0
  587. package/package.json +160 -117
  588. package/R2.md +0 -170
  589. package/dist/account-rvrj687w.js +0 -397
  590. package/dist/ai-dx4fr9jh.js +0 -107
  591. package/dist/bridge/protocol.d.ts.map +0 -1
  592. package/dist/bridge/serialization.d.ts +0 -83
  593. package/dist/bridge/serialization.d.ts.map +0 -1
  594. package/dist/browser-shim/worker.d.ts +0 -14
  595. package/dist/browser-shim/worker.d.ts.map +0 -1
  596. package/dist/build-9myaxf07.js +0 -70
  597. package/dist/deploy-h1wz5p7m.js +0 -86
  598. package/dist/dev-rsdssknb.js +0 -2707
  599. package/dist/doctor-v7jy4s3r.js +0 -190
  600. package/dist/durable-object-t4kbb0yt.js +0 -13
  601. package/dist/index-18hvb6gb.js +0 -194
  602. package/dist/index-1xpj0m4r.js +0 -57
  603. package/dist/index-37x76zdn.js +0 -4
  604. package/dist/index-3t6rypgc.js +0 -13
  605. package/dist/index-62b3gt2g.js +0 -12
  606. package/dist/index-67qcae0f.js +0 -183
  607. package/dist/index-9ats0s83.js +0 -70
  608. package/dist/index-a0fjkq68.js +0 -198
  609. package/dist/index-a855bdsx.js +0 -18
  610. package/dist/index-ccrh4w3t.js +0 -1133
  611. package/dist/index-d8bdkx2h.js +0 -109
  612. package/dist/index-f8qh2tyh.js +0 -2152
  613. package/dist/index-gz1gndna.js +0 -307
  614. package/dist/index-hcex3rgh.js +0 -266
  615. package/dist/index-k7r18na8.js +0 -0
  616. package/dist/index-n3np2d6t.js +0 -462
  617. package/dist/index-n7rs26ft.js +0 -77
  618. package/dist/index-npc1c8jx.js +0 -44
  619. package/dist/index-p7g30wd2.js +0 -281
  620. package/dist/index-rbht7m9r.js +0 -36
  621. package/dist/index-tfyxa77h.js +0 -850
  622. package/dist/index-tk6ej9dj.js +0 -94
  623. package/dist/index-v8vvsn9x.js +0 -169
  624. package/dist/index-z14anrqp.js +0 -226
  625. package/dist/init-f9mgmew3.js +0 -186
  626. package/dist/remote-q59qk463.js +0 -97
  627. package/dist/test/bridge-context.d.ts +0 -76
  628. package/dist/test/bridge-context.d.ts.map +0 -1
  629. package/dist/test/multi-worker-context.d.ts +0 -114
  630. package/dist/test/multi-worker-context.d.ts.map +0 -1
  631. package/dist/types-wdcpnfvy.js +0 -487
  632. package/dist/worker-entrypoint-m9th0rg0.js +0 -13
@@ -1,2152 +0,0 @@
1
- import {
2
- getRemoteModeStatus,
3
- isRemoteModeActive
4
- } from "./index-d8bdkx2h.js";
5
- import {
6
- transformWorkerEntrypoint
7
- } from "./index-z14anrqp.js";
8
- import {
9
- discoverEntrypointsSync,
10
- resolvePackageSpecifier
11
- } from "./index-tk6ej9dj.js";
12
- import {
13
- __clearTestContext,
14
- __setTestContext
15
- } from "./index-9ats0s83.js";
16
- import {
17
- runWithContext
18
- } from "./index-npc1c8jx.js";
19
- import {
20
- DEFAULT_DO_PATTERN,
21
- findFiles,
22
- findFilesSync
23
- } from "./index-rbht7m9r.js";
24
- import {
25
- findDurableObjectClasses
26
- } from "./index-gz1gndna.js";
27
- import {
28
- startMiniflare,
29
- startMiniflareFromConfig
30
- } from "./index-p7g30wd2.js";
31
- import {
32
- BridgeClient,
33
- createEnvProxy,
34
- setBindingHints
35
- } from "./index-ccrh4w3t.js";
36
- import {
37
- loadConfig,
38
- normalizeDOBinding,
39
- resolveConfigPath
40
- } from "./index-hcex3rgh.js";
41
- import {
42
- canProceedWithTest,
43
- getApiToken,
44
- getEffectiveAccountId,
45
- getPrimaryAccount,
46
- isAuthenticated
47
- } from "./index-tfyxa77h.js";
48
- import {
49
- __require
50
- } from "./index-37x76zdn.js";
51
-
52
- // src/test/simple-context.ts
53
- import { resolve as resolve2, dirname as dirname2, join as join6 } from "path";
54
- import { existsSync as existsSync2 } from "fs";
55
-
56
- // src/test/remote-ai.ts
57
- function createRemoteAI(accountId) {
58
- let resolvedAccountId = null;
59
- async function getAccountId() {
60
- if (accountId)
61
- return accountId;
62
- if (resolvedAccountId)
63
- return resolvedAccountId;
64
- const primary = await getPrimaryAccount();
65
- if (!primary) {
66
- throw new Error("No Cloudflare account found. Run: bunx wrangler login");
67
- }
68
- const { accountId: effectiveId } = await getEffectiveAccountId(primary.id);
69
- resolvedAccountId = effectiveId;
70
- return effectiveId;
71
- }
72
- async function getToken() {
73
- const token = await getApiToken();
74
- if (!token) {
75
- throw new Error("Not authenticated. Run: bunx wrangler login");
76
- }
77
- return token;
78
- }
79
- const ai = {
80
- async run(model, inputs) {
81
- const [acctId, token] = await Promise.all([getAccountId(), getToken()]);
82
- const url = `https://api.cloudflare.com/client/v4/accounts/${acctId}/ai/run/${model}`;
83
- const response = await fetch(url, {
84
- method: "POST",
85
- headers: {
86
- Authorization: `Bearer ${token}`,
87
- "Content-Type": "application/json"
88
- },
89
- body: JSON.stringify(inputs)
90
- });
91
- if (!response.ok) {
92
- const errorText = await response.text();
93
- throw new Error(`AI API error (${response.status}): ${errorText}`);
94
- }
95
- const result = await response.json();
96
- if (!result.success) {
97
- const message = result.errors?.[0]?.message || "Unknown AI error";
98
- throw new Error(`AI API error: ${message}`);
99
- }
100
- return result.result;
101
- },
102
- gateway(_gatewayId) {
103
- console.warn("AI Gateway is not supported in remote test mode");
104
- return ai;
105
- }
106
- };
107
- return ai;
108
- }
109
-
110
- // src/test/remote-vectorize.ts
111
- function createRemoteVectorize(indexName, accountId) {
112
- let resolvedAccountId = null;
113
- async function getAccountId() {
114
- if (accountId)
115
- return accountId;
116
- if (resolvedAccountId)
117
- return resolvedAccountId;
118
- const primary = await getPrimaryAccount();
119
- if (!primary) {
120
- throw new Error("No Cloudflare account found. Run: bunx wrangler login");
121
- }
122
- const { accountId: effectiveId } = await getEffectiveAccountId(primary.id);
123
- resolvedAccountId = effectiveId;
124
- return effectiveId;
125
- }
126
- async function getToken() {
127
- const token = await getApiToken();
128
- if (!token) {
129
- throw new Error("Not authenticated. Run: bunx wrangler login");
130
- }
131
- return token;
132
- }
133
- async function apiRequest(method, endpoint, body) {
134
- const [acctId, token] = await Promise.all([getAccountId(), getToken()]);
135
- const url = `https://api.cloudflare.com/client/v4/accounts/${acctId}/vectorize/v2/indexes/${indexName}${endpoint}`;
136
- const response = await fetch(url, {
137
- method,
138
- headers: {
139
- Authorization: `Bearer ${token}`,
140
- "Content-Type": "application/json"
141
- },
142
- body: body ? JSON.stringify(body) : undefined
143
- });
144
- if (!response.ok) {
145
- const errorText = await response.text();
146
- throw new Error(`Vectorize API error (${response.status}): ${errorText}`);
147
- }
148
- const result = await response.json();
149
- if (!result.success) {
150
- const message = result.errors?.[0]?.message || "Unknown Vectorize error";
151
- throw new Error(`Vectorize API error: ${message}`);
152
- }
153
- return result.result;
154
- }
155
- async function ndjsonRequest(endpoint, vectors) {
156
- const [acctId, token] = await Promise.all([getAccountId(), getToken()]);
157
- const url = `https://api.cloudflare.com/client/v4/accounts/${acctId}/vectorize/v2/indexes/${indexName}${endpoint}`;
158
- const ndjson = vectors.map((v) => JSON.stringify(v)).join(`
159
- `);
160
- const response = await fetch(url, {
161
- method: "POST",
162
- headers: {
163
- Authorization: `Bearer ${token}`,
164
- "Content-Type": "application/x-ndjson"
165
- },
166
- body: ndjson
167
- });
168
- if (!response.ok) {
169
- const errorText = await response.text();
170
- throw new Error(`Vectorize API error (${response.status}): ${errorText}`);
171
- }
172
- const result = await response.json();
173
- if (!result.success) {
174
- const message = result.errors?.[0]?.message || "Unknown Vectorize error";
175
- throw new Error(`Vectorize API error: ${message}`);
176
- }
177
- return result.result;
178
- }
179
- const vectorize = {
180
- async describe() {
181
- return apiRequest("GET", "");
182
- },
183
- async query(vector, options) {
184
- const vectorArray = Array.isArray(vector) ? vector : Array.from(vector);
185
- return apiRequest("POST", "/query", {
186
- vector: vectorArray,
187
- topK: options?.topK ?? 10,
188
- returnValues: options?.returnValues ?? false,
189
- returnMetadata: options?.returnMetadata ?? "none",
190
- namespace: options?.namespace,
191
- filter: options?.filter
192
- });
193
- },
194
- async insert(vectors) {
195
- const result = await ndjsonRequest("/insert", vectors);
196
- return {
197
- count: result.count,
198
- ids: result.ids || vectors.map((v) => v.id)
199
- };
200
- },
201
- async upsert(vectors) {
202
- const result = await ndjsonRequest("/upsert", vectors);
203
- return {
204
- count: result.count,
205
- ids: result.ids || vectors.map((v) => v.id)
206
- };
207
- },
208
- async deleteByIds(ids) {
209
- const result = await apiRequest("POST", "/delete-by-ids", { ids });
210
- return {
211
- count: result.count,
212
- ids
213
- };
214
- },
215
- async getByIds(ids) {
216
- return apiRequest("POST", "/get-by-ids", { ids });
217
- }
218
- };
219
- return vectorize;
220
- }
221
-
222
- // src/test/resolve-service-bindings.ts
223
- import { dirname, join, resolve } from "path";
224
- import { existsSync, readFileSync } from "fs";
225
- function getBunRuntime() {
226
- const g = globalThis;
227
- if (typeof g.Bun === "object" && g.Bun !== null) {
228
- return g.Bun;
229
- }
230
- return;
231
- }
232
- function discoverDOFilesSync(dir) {
233
- const classToPath = new Map;
234
- try {
235
- const files = findFilesSync(DEFAULT_DO_PATTERN, { cwd: dir });
236
- for (const filePath of files) {
237
- try {
238
- const code = readFileSync(filePath, "utf-8");
239
- const classNames = findDurableObjectClasses(code);
240
- for (const className of classNames) {
241
- if (!classToPath.has(className)) {
242
- classToPath.set(className, filePath);
243
- }
244
- }
245
- } catch {}
246
- }
247
- } catch {}
248
- return classToPath;
249
- }
250
- var bundleCache = new Map;
251
- function clearBundleCache() {
252
- bundleCache.clear();
253
- }
254
- function hasServiceBindings(config) {
255
- const services = config.bindings?.services;
256
- if (!services)
257
- return false;
258
- return Object.keys(services).length > 0;
259
- }
260
- async function resolveServiceBindings(config, configDir) {
261
- const services = config.bindings?.services;
262
- if (!services) {
263
- return { workers: [], primaryServiceBindings: {} };
264
- }
265
- const workersByName = new Map;
266
- const primaryServiceBindings = {};
267
- for (const [bindingName, binding] of Object.entries(services)) {
268
- const workerBinding = binding;
269
- const ref = workerBinding.__ref;
270
- if (ref) {
271
- if ("__import" in ref && typeof ref.__import === "function") {
272
- await ref.resolve();
273
- }
274
- const workerName = ref.name;
275
- const entrypoint = workerBinding.entrypoint;
276
- if (!workersByName.has(workerName)) {
277
- const worker = await resolveRefWorker(ref, entrypoint, configDir);
278
- if (worker) {
279
- workersByName.set(workerName, worker);
280
- }
281
- }
282
- primaryServiceBindings[bindingName] = {
283
- name: workerName,
284
- ...entrypoint && { entrypoint }
285
- };
286
- } else {
287
- primaryServiceBindings[bindingName] = {
288
- name: workerBinding.service,
289
- ...workerBinding.entrypoint && { entrypoint: workerBinding.entrypoint }
290
- };
291
- }
292
- }
293
- return {
294
- workers: [...workersByName.values()],
295
- primaryServiceBindings
296
- };
297
- }
298
- async function resolveRefWorker(ref, _entrypoint, parentConfigDir) {
299
- const config = ref.config;
300
- if (!config)
301
- return null;
302
- const configPath = ref.configPath;
303
- if (!configPath || configPath === "<resolved>") {
304
- console.warn(`[devflare] Cannot resolve worker "${ref.name}" - configPath not available`);
305
- return null;
306
- }
307
- const refConfigDir = resolve(parentConfigDir, dirname(configPath));
308
- const entrypoints = [];
309
- const files = config.files;
310
- const mainPath = files?.fetch ?? "src/worker.ts";
311
- const workerTsPath = resolve(refConfigDir, mainPath);
312
- if (existsSync(workerTsPath)) {
313
- const isWorkerTs = mainPath.endsWith("worker.ts") || mainPath.endsWith("worker.js");
314
- entrypoints.push({
315
- path: workerTsPath,
316
- className: "Worker",
317
- isWorkerTs
318
- });
319
- }
320
- const discoveredEntrypoints = discoverEntrypointsSync(refConfigDir);
321
- for (const ep of discoveredEntrypoints) {
322
- entrypoints.push({
323
- path: ep.filePath,
324
- className: ep.className,
325
- isWorkerTs: false
326
- });
327
- }
328
- if (entrypoints.length === 0) {
329
- console.warn(`[devflare] Worker "${ref.name}" has no entry points`);
330
- return null;
331
- }
332
- const script = await bundleAllEntrypoints(entrypoints, ref.name);
333
- if (!script)
334
- return null;
335
- return {
336
- name: ref.name,
337
- script,
338
- modules: true,
339
- compatibilityDate: config.compatibilityDate ?? "2025-01-01"
340
- };
341
- }
342
- async function bundleAllEntrypoints(entrypoints, workerName) {
343
- const cacheKey = entrypoints.map((ep) => `${ep.path}::${ep.className}`).join("|");
344
- const cached = bundleCache.get(cacheKey);
345
- if (cached) {
346
- return cached;
347
- }
348
- const bun = getBunRuntime();
349
- if (!bun) {
350
- console.warn("[devflare] Bun runtime required for bundling worker scripts");
351
- return null;
352
- }
353
- try {
354
- const { readFileSync: readFileSync2, writeFileSync, mkdirSync, unlinkSync } = await import("fs");
355
- const imports = [];
356
- const exports = [];
357
- let defaultExportClass = null;
358
- for (let i = 0;i < entrypoints.length; i++) {
359
- const ep = entrypoints[i];
360
- const sourceCode = readFileSync2(ep.path, "utf-8");
361
- if (ep.isWorkerTs) {
362
- const result = transformWorkerEntrypoint(sourceCode, ep.path, {
363
- className: ep.className,
364
- injectContext: false
365
- });
366
- if (result) {
367
- const tempDir2 = join(dirname(ep.path), ".devflare");
368
- mkdirSync(tempDir2, { recursive: true });
369
- const tempPath = join(tempDir2, `__${ep.className}_${i}.ts`);
370
- writeFileSync(tempPath, result.code);
371
- imports.push(`import { ${ep.className} } from '${tempPath.replace(/\\/g, "/")}'`);
372
- exports.push(ep.className);
373
- if (!defaultExportClass) {
374
- defaultExportClass = ep.className;
375
- }
376
- }
377
- } else {
378
- imports.push(`import { ${ep.className} } from '${ep.path.replace(/\\/g, "/")}'`);
379
- exports.push(ep.className);
380
- }
381
- }
382
- const defaultExport = defaultExportClass ? `
383
- export default ${defaultExportClass}` : "";
384
- const entryCode = `
385
- ${imports.join(`
386
- `)}
387
- export { ${exports.join(", ")} }${defaultExport}
388
- `;
389
- const tempDir = join(dirname(entrypoints[0].path), ".devflare");
390
- mkdirSync(tempDir, { recursive: true });
391
- const entryPath = join(tempDir, `__entry_${workerName}.ts`);
392
- writeFileSync(entryPath, entryCode);
393
- try {
394
- const result = await bun.build({
395
- entrypoints: [entryPath],
396
- target: "browser",
397
- format: "esm",
398
- minify: false,
399
- external: ["cloudflare:workers", "cloudflare:*"]
400
- });
401
- if (!result.success) {
402
- console.warn(`[devflare] Failed to bundle worker "${workerName}": ${result.logs.join(`
403
- `)}`);
404
- return null;
405
- }
406
- const bundledCode = await result.outputs[0].text();
407
- bundleCache.set(cacheKey, bundledCode);
408
- return bundledCode;
409
- } finally {
410
- try {
411
- unlinkSync(entryPath);
412
- } catch {}
413
- }
414
- } catch (error) {
415
- console.warn(`[devflare] Error bundling worker "${workerName}":`, error);
416
- return null;
417
- }
418
- }
419
- function hasCrossWorkerDOs(config) {
420
- const dos = config.bindings?.durableObjects;
421
- if (!dos)
422
- return false;
423
- for (const doConfig of Object.values(dos)) {
424
- const normalized = normalizeDOBinding(doConfig);
425
- if (normalized.__ref)
426
- return true;
427
- }
428
- return false;
429
- }
430
- async function resolveDOBindings(config, configDir) {
431
- const dos = config.bindings?.durableObjects;
432
- if (!dos) {
433
- return { workers: [], crossWorkerDOBindings: {} };
434
- }
435
- const workersByName = new Map;
436
- const crossWorkerDOBindings = {};
437
- for (const [bindingName, rawDoConfig] of Object.entries(dos)) {
438
- const hasRef = typeof rawDoConfig === "object" && "__ref" in rawDoConfig;
439
- if (!hasRef) {
440
- continue;
441
- }
442
- const ref = rawDoConfig.__ref;
443
- if ("__import" in ref && typeof ref.__import === "function") {
444
- await ref.resolve();
445
- }
446
- const doConfig = normalizeDOBinding(rawDoConfig);
447
- const workerName = ref.name;
448
- if (!workersByName.has(workerName)) {
449
- const worker = await resolveDORefWorker(ref, configDir);
450
- if (worker) {
451
- workersByName.set(workerName, worker);
452
- }
453
- }
454
- crossWorkerDOBindings[bindingName] = {
455
- className: doConfig.className,
456
- scriptName: workerName
457
- };
458
- }
459
- return {
460
- workers: [...workersByName.values()],
461
- crossWorkerDOBindings
462
- };
463
- }
464
- async function resolveDORefWorker(ref, parentConfigDir) {
465
- const config = ref.config;
466
- if (!config)
467
- return null;
468
- const configPath = ref.configPath;
469
- if (!configPath || configPath === "<resolved>") {
470
- console.warn(`[devflare] Cannot resolve DO worker "${ref.name}" - configPath not available`);
471
- return null;
472
- }
473
- const resolvedConfigPath = resolvePackageSpecifier(configPath, parentConfigDir);
474
- const refConfigDir = dirname(resolvedConfigPath);
475
- const dosConfig = config.bindings?.durableObjects;
476
- if (!dosConfig || Object.keys(dosConfig).length === 0) {
477
- console.warn(`[devflare] Referenced worker "${ref.name}" has no Durable Objects`);
478
- return null;
479
- }
480
- const discoveredDOs = discoverDOFilesSync(refConfigDir);
481
- const doClasses = [];
482
- for (const [bindingName, rawDoConfig] of Object.entries(dosConfig)) {
483
- const doConfig = normalizeDOBinding(rawDoConfig);
484
- const className = doConfig.className;
485
- const scriptName = doConfig.scriptName;
486
- if (scriptName) {
487
- const scriptPath = resolve(refConfigDir, "src", scriptName);
488
- if (!existsSync(scriptPath)) {
489
- const altPath = resolve(refConfigDir, scriptName);
490
- if (!existsSync(altPath)) {
491
- console.warn(`[devflare] DO script not found: ${scriptPath} or ${altPath}`);
492
- continue;
493
- }
494
- doClasses.push({ bindingName, className, scriptPath: altPath });
495
- } else {
496
- doClasses.push({ bindingName, className, scriptPath });
497
- }
498
- } else {
499
- const discoveredPath = discoveredDOs.get(className);
500
- if (discoveredPath) {
501
- doClasses.push({ bindingName, className, scriptPath: discoveredPath });
502
- } else {
503
- console.warn(`[devflare] DO "${bindingName}" (class: ${className}) not found in do.*.ts files in "${ref.name}"`);
504
- continue;
505
- }
506
- }
507
- }
508
- if (doClasses.length === 0) {
509
- console.warn(`[devflare] No valid DO classes found in "${ref.name}"`);
510
- return null;
511
- }
512
- const script = await bundleDOClasses(doClasses, ref.name);
513
- if (!script)
514
- return null;
515
- const durableObjects = {};
516
- for (const do_ of doClasses) {
517
- durableObjects[do_.bindingName] = do_.className;
518
- }
519
- return {
520
- name: ref.name,
521
- script,
522
- modules: true,
523
- compatibilityDate: config.compatibilityDate ?? "2025-01-01",
524
- durableObjects
525
- };
526
- }
527
- async function bundleDOClasses(doClasses, workerName) {
528
- const cacheKey = `do:${doClasses.map((d) => `${d.scriptPath}::${d.className}`).join("|")}`;
529
- const cached = bundleCache.get(cacheKey);
530
- if (cached)
531
- return cached;
532
- const bun = getBunRuntime();
533
- if (!bun) {
534
- console.warn("[devflare] Bun runtime required for bundling DO classes");
535
- return null;
536
- }
537
- try {
538
- const { writeFileSync, mkdirSync, unlinkSync } = await import("fs");
539
- const imports = doClasses.map((d) => `import { ${d.className} } from '${d.scriptPath.replace(/\\/g, "/")}'`).join(`
540
- `);
541
- const exports = doClasses.map((d) => d.className).join(", ");
542
- const entryCode = `
543
- ${imports}
544
-
545
- // Re-export DO classes for Miniflare binding
546
- export { ${exports} }
547
-
548
- // Default export with fetch handler
549
- export default {
550
- async fetch(request, env) {
551
- return new Response('DO Worker: ${workerName}')
552
- }
553
- }
554
- `;
555
- const tempDir = join(dirname(doClasses[0].scriptPath), ".devflare");
556
- mkdirSync(tempDir, { recursive: true });
557
- const entryPath = join(tempDir, `__do_entry_${workerName}.ts`);
558
- writeFileSync(entryPath, entryCode);
559
- try {
560
- const result = await bun.build({
561
- entrypoints: [entryPath],
562
- target: "browser",
563
- format: "esm",
564
- minify: false,
565
- external: ["cloudflare:workers", "cloudflare:*"]
566
- });
567
- if (!result.success) {
568
- console.warn(`[devflare] Failed to bundle DO worker "${workerName}": ${result.logs.join(`
569
- `)}`);
570
- return null;
571
- }
572
- const bundledCode = await result.outputs[0].text();
573
- bundleCache.set(cacheKey, bundledCode);
574
- return bundledCode;
575
- } finally {
576
- try {
577
- unlinkSync(entryPath);
578
- } catch {}
579
- }
580
- } catch (error) {
581
- console.warn(`[devflare] Error bundling DO worker "${workerName}":`, error);
582
- return null;
583
- }
584
- }
585
-
586
- // src/test/queue.ts
587
- import { join as join2 } from "path";
588
- var queueHandlerPath = null;
589
- var configDir = null;
590
- var testEnvGetter = null;
591
- function configureQueue(options) {
592
- queueHandlerPath = options.handlerPath;
593
- configDir = options.configDir;
594
- testEnvGetter = options.getEnv;
595
- }
596
- function resetQueueState() {
597
- queueHandlerPath = null;
598
- configDir = null;
599
- testEnvGetter = null;
600
- }
601
- function createMessage(options) {
602
- const id = options.id ?? crypto.randomUUID();
603
- const timestamp = options.timestamp ?? new Date;
604
- const attempts = options.attempts ?? 1;
605
- let state = "pending";
606
- return {
607
- id,
608
- timestamp,
609
- body: options.body,
610
- attempts,
611
- ack() {
612
- state = "acked";
613
- },
614
- retry(opts) {
615
- state = "retried";
616
- },
617
- retryAll() {
618
- state = "retried";
619
- },
620
- get _state() {
621
- return state;
622
- }
623
- };
624
- }
625
- function createMessageBatch(messages) {
626
- return {
627
- queue: "test-queue",
628
- messages,
629
- ackAll() {
630
- for (const msg of messages) {
631
- msg.ack();
632
- }
633
- },
634
- retryAll() {
635
- for (const msg of messages) {
636
- msg.retry();
637
- }
638
- }
639
- };
640
- }
641
- async function trigger(messages) {
642
- if (!queueHandlerPath) {
643
- throw new Error("Queue handler not configured. Make sure your devflare.config.ts has files.queue set, " + "and the file exists at the specified path (default: src/queue.ts)");
644
- }
645
- if (!configDir || !testEnvGetter) {
646
- throw new Error("Queue helper not initialized. Call createTestContext() before using cf.queue.trigger()");
647
- }
648
- const absolutePath = join2(configDir, queueHandlerPath);
649
- const handlerModule = await import(absolutePath);
650
- const queueHandler = handlerModule.default ?? handlerModule.queue;
651
- if (typeof queueHandler !== "function") {
652
- throw new Error(`Queue handler at "${queueHandlerPath}" must export a default function or named "queue" export.
653
- Expected: export default async function queue(batch, env, ctx) { ... }
654
- Or: export async function queue(batch, env, ctx) { ... }`);
655
- }
656
- const normalizedMessages = messages.map((msg) => {
657
- if (typeof msg === "object" && msg !== null && "body" in msg) {
658
- return msg;
659
- }
660
- return { body: msg };
661
- });
662
- const mockMessages = normalizedMessages.map((opts) => createMessage(opts));
663
- const batch = createMessageBatch(mockMessages);
664
- const waitUntilPromises = [];
665
- const ctx = {
666
- waitUntil(promise) {
667
- waitUntilPromises.push(promise);
668
- },
669
- passThroughOnException() {},
670
- props: {}
671
- };
672
- const env = testEnvGetter();
673
- await queueHandler(batch, env, ctx);
674
- await Promise.all(waitUntilPromises);
675
- const acked = [];
676
- const retried = [];
677
- const failed = [];
678
- for (const msg of mockMessages) {
679
- switch (msg._state) {
680
- case "acked":
681
- acked.push(msg.id);
682
- break;
683
- case "retried":
684
- retried.push(msg.id);
685
- break;
686
- case "failed":
687
- failed.push(msg.id);
688
- break;
689
- }
690
- }
691
- return {
692
- acked,
693
- retried,
694
- failed,
695
- total: mockMessages.length
696
- };
697
- }
698
- async function send(message) {
699
- return trigger([message]);
700
- }
701
- var queue = {
702
- trigger,
703
- send
704
- };
705
-
706
- // src/test/scheduled.ts
707
- import { join as join3 } from "path";
708
- var scheduledHandlerPath = null;
709
- var configDir2 = null;
710
- var testEnvGetter2 = null;
711
- function configureScheduled(options) {
712
- scheduledHandlerPath = options.handlerPath;
713
- configDir2 = options.configDir;
714
- testEnvGetter2 = options.getEnv;
715
- }
716
- function resetScheduledState() {
717
- scheduledHandlerPath = null;
718
- configDir2 = null;
719
- testEnvGetter2 = null;
720
- }
721
- async function trigger2(cronOrOptions) {
722
- if (!scheduledHandlerPath) {
723
- throw new Error("Scheduled handler not configured. Make sure your devflare.config.ts has files.scheduled set, " + "and the file exists at the specified path (default: src/scheduled.ts)");
724
- }
725
- if (!configDir2 || !testEnvGetter2) {
726
- throw new Error("Scheduled helper not initialized. Call createTestContext() before using cf.scheduled.trigger()");
727
- }
728
- const options = typeof cronOrOptions === "string" ? { cron: cronOrOptions } : cronOrOptions ?? {};
729
- const cron = options.cron ?? "* * * * *";
730
- const scheduledTime = options.scheduledTime instanceof Date ? options.scheduledTime.getTime() : options.scheduledTime ?? Date.now();
731
- const absolutePath = join3(configDir2, scheduledHandlerPath);
732
- const handlerModule = await import(absolutePath);
733
- const scheduledHandler = handlerModule.default ?? handlerModule.scheduled;
734
- if (typeof scheduledHandler !== "function") {
735
- throw new Error(`Scheduled handler at "${scheduledHandlerPath}" must export a default function or named "scheduled" export.
736
- Expected: export default async function scheduled(controller, env, ctx) { ... }
737
- Or: export async function scheduled(controller, env, ctx) { ... }`);
738
- }
739
- const controller = {
740
- scheduledTime,
741
- cron,
742
- noRetry() {}
743
- };
744
- const waitUntilPromises = [];
745
- const ctx = {
746
- waitUntil(promise) {
747
- waitUntilPromises.push(promise);
748
- },
749
- passThroughOnException() {},
750
- props: {}
751
- };
752
- const env = testEnvGetter2();
753
- try {
754
- await scheduledHandler(controller, env, ctx);
755
- await Promise.all(waitUntilPromises);
756
- return {
757
- success: true,
758
- cron,
759
- scheduledTime
760
- };
761
- } catch (error) {
762
- return {
763
- success: false,
764
- error: error instanceof Error ? error.message : String(error),
765
- cron,
766
- scheduledTime
767
- };
768
- }
769
- }
770
- var scheduled = {
771
- trigger: trigger2
772
- };
773
-
774
- // src/test/worker.ts
775
- import { join as join4 } from "path";
776
- var fetchHandlerPath = null;
777
- var configDir3 = null;
778
- var testEnvGetter3 = null;
779
- function configureWorker(options) {
780
- fetchHandlerPath = options.handlerPath;
781
- configDir3 = options.configDir;
782
- testEnvGetter3 = options.getEnv;
783
- }
784
- function resetWorkerState() {
785
- fetchHandlerPath = null;
786
- configDir3 = null;
787
- testEnvGetter3 = null;
788
- }
789
- async function fetch2(request, options) {
790
- if (!fetchHandlerPath) {
791
- throw new Error("Fetch handler not configured. Make sure your devflare.config.ts has files.fetch set, " + "and the file exists at the specified path (default: src/fetch.ts)");
792
- }
793
- if (!configDir3 || !testEnvGetter3) {
794
- throw new Error("Worker helper not initialized. Call createTestContext() before using cf.worker.fetch()");
795
- }
796
- let req;
797
- if (typeof request === "string") {
798
- const url = request.startsWith("http") ? request : `http://localhost${request.startsWith("/") ? "" : "/"}${request}`;
799
- const headers = new Headers(options?.headers);
800
- let body;
801
- if (options?.body !== undefined) {
802
- if (typeof options.body === "string") {
803
- body = options.body;
804
- } else {
805
- body = JSON.stringify(options.body);
806
- if (!headers.has("Content-Type")) {
807
- headers.set("Content-Type", "application/json");
808
- }
809
- }
810
- }
811
- req = new Request(url, {
812
- method: options?.method ?? "GET",
813
- headers,
814
- body
815
- });
816
- } else {
817
- req = request;
818
- }
819
- const absolutePath = join4(configDir3, fetchHandlerPath);
820
- const handlerModule = await import(absolutePath);
821
- const fetchHandler = handlerModule.default ?? handlerModule.fetch;
822
- if (typeof fetchHandler !== "function") {
823
- throw new Error(`Fetch handler at "${fetchHandlerPath}" must export a default function or named "fetch" export.
824
- Expected: export default async function fetch(request, env, ctx) { ... }
825
- Or: export async function fetch(request, env, ctx) { ... }`);
826
- }
827
- const waitUntilPromises = [];
828
- const ctx = {
829
- waitUntil(promise) {
830
- waitUntilPromises.push(promise);
831
- },
832
- passThroughOnException() {},
833
- props: {}
834
- };
835
- const env = testEnvGetter3();
836
- const response = await fetchHandler(req, env, ctx);
837
- return response;
838
- }
839
- async function get(path, headers) {
840
- return fetch2(path, { method: "GET", headers });
841
- }
842
- async function post(path, body, headers) {
843
- return fetch2(path, { method: "POST", body, headers });
844
- }
845
- async function put(path, body, headers) {
846
- return fetch2(path, { method: "PUT", body, headers });
847
- }
848
- async function del(path, headers) {
849
- return fetch2(path, { method: "DELETE", headers });
850
- }
851
- async function patch(path, body, headers) {
852
- return fetch2(path, { method: "PATCH", body, headers });
853
- }
854
- var worker = {
855
- fetch: fetch2,
856
- get,
857
- post,
858
- put,
859
- delete: del,
860
- patch
861
- };
862
-
863
- // src/test/tail.ts
864
- import { join as join5 } from "path";
865
- var tailHandlerPath = null;
866
- var configDir4 = null;
867
- var testEnvGetter4 = null;
868
- function configureTail(options) {
869
- tailHandlerPath = options.handlerPath;
870
- configDir4 = options.configDir;
871
- testEnvGetter4 = options.getEnv;
872
- }
873
- function resetTailState() {
874
- tailHandlerPath = null;
875
- configDir4 = null;
876
- testEnvGetter4 = null;
877
- }
878
- function createTraceItem(options) {
879
- return {
880
- scriptName: options.scriptName ?? "test-worker",
881
- outcome: options.outcome ?? "ok",
882
- eventTimestamp: options.eventTimestamp ?? Date.now(),
883
- event: options.event ?? {
884
- request: {
885
- url: "https://example.com/",
886
- method: "GET"
887
- }
888
- },
889
- logs: options.logs ?? [],
890
- exceptions: options.exceptions ?? [],
891
- diagnosticsChannelEvents: options.diagnosticsChannelEvents ?? [],
892
- scriptVersion: options.scriptVersion ?? { id: "test-version" },
893
- dispatchNamespace: options.dispatchNamespace,
894
- scriptTags: options.scriptTags ?? []
895
- };
896
- }
897
- async function trigger3(items) {
898
- if (!tailHandlerPath) {
899
- throw new Error("Tail handler not configured. Make sure your devflare.config.ts has files.tail set, " + "or the file exists at src/tail.ts");
900
- }
901
- if (!configDir4 || !testEnvGetter4) {
902
- throw new Error("Tail helper not initialized. Call createTestContext() before using cf.tail.trigger()");
903
- }
904
- const traceItems = items.map((item) => {
905
- if ("eventTimestamp" in item && "outcome" in item && "scriptName" in item) {
906
- return item;
907
- }
908
- return createTraceItem(item);
909
- });
910
- const absolutePath = join5(configDir4, tailHandlerPath);
911
- const handlerModule = await import(absolutePath);
912
- const tailHandler = handlerModule.default ?? handlerModule.tail;
913
- if (typeof tailHandler !== "function") {
914
- throw new Error(`Tail handler at "${tailHandlerPath}" must export a default function or named "tail" export.
915
- Expected: export default async function tail(events, env, ctx) { ... }
916
- Or: export async function tail(events, env, ctx) { ... }`);
917
- }
918
- const waitUntilPromises = [];
919
- const ctx = {
920
- waitUntil(promise) {
921
- waitUntilPromises.push(promise);
922
- },
923
- passThroughOnException() {},
924
- props: {}
925
- };
926
- const env = testEnvGetter4();
927
- try {
928
- await tailHandler(traceItems, env, ctx);
929
- await Promise.all(waitUntilPromises);
930
- return {
931
- success: true,
932
- itemCount: traceItems.length
933
- };
934
- } catch (error) {
935
- return {
936
- success: false,
937
- error: error instanceof Error ? error.message : String(error),
938
- itemCount: traceItems.length
939
- };
940
- }
941
- }
942
- function create(options = {}) {
943
- return createTraceItem(options);
944
- }
945
- var tail = {
946
- trigger: trigger3,
947
- create
948
- };
949
-
950
- // src/test/email.ts
951
- var miniflarePort = 8787;
952
- var emailListeners = [];
953
- var sentEmails = [];
954
- function configureEmail(options = {}) {
955
- if (options.port) {
956
- miniflarePort = options.port;
957
- }
958
- }
959
- function buildRawEmail(options) {
960
- if (options.raw) {
961
- return options.raw;
962
- }
963
- const lines = [];
964
- const messageId = `<${Date.now()}-${Math.random().toString(36).slice(2)}@devflare.dev>`;
965
- const date = new Date().toUTCString();
966
- lines.push(`From: ${options.from}`);
967
- lines.push(`To: ${options.to}`);
968
- lines.push(`Date: ${date}`);
969
- lines.push(`Message-ID: ${messageId}`);
970
- if (options.subject) {
971
- lines.push(`Subject: ${options.subject}`);
972
- }
973
- if (options.headers) {
974
- for (const [key, value] of Object.entries(options.headers)) {
975
- lines.push(`${key}: ${value}`);
976
- }
977
- }
978
- lines.push("MIME-Version: 1.0");
979
- lines.push("Content-Type: text/plain; charset=UTF-8");
980
- lines.push("");
981
- lines.push(options.body ?? "");
982
- return lines.join(`\r
983
- `);
984
- }
985
- async function send2(options) {
986
- const raw = buildRawEmail(options);
987
- const url = new URL(`http://localhost:${miniflarePort}/cdn-cgi/handler/email`);
988
- url.searchParams.set("from", options.from);
989
- url.searchParams.set("to", options.to);
990
- const response = await fetch(url.toString(), {
991
- method: "POST",
992
- headers: {
993
- "Content-Type": "text/plain"
994
- },
995
- body: raw
996
- });
997
- return response;
998
- }
999
- function onReceive(callback) {
1000
- emailListeners.push(callback);
1001
- return () => {
1002
- emailListeners = emailListeners.filter((cb) => cb !== callback);
1003
- };
1004
- }
1005
- function getSentEmails() {
1006
- return [...sentEmails];
1007
- }
1008
- function clearSentEmails() {
1009
- sentEmails = [];
1010
- }
1011
- function resetEmailState() {
1012
- emailListeners = [];
1013
- sentEmails = [];
1014
- }
1015
- var email = {
1016
- send: send2,
1017
- onReceive,
1018
- getSentEmails,
1019
- clearSentEmails
1020
- };
1021
-
1022
- // src/test/simple-context.ts
1023
- function findExportedClasses(code) {
1024
- const classes = [];
1025
- const classPattern = /export\s+class\s+(\w+)/g;
1026
- let match;
1027
- while ((match = classPattern.exec(code)) !== null) {
1028
- classes.push(match[1]);
1029
- }
1030
- return classes;
1031
- }
1032
- function getBunRuntime2() {
1033
- const g = globalThis;
1034
- if (typeof g.Bun === "object" && g.Bun !== null) {
1035
- return g.Bun;
1036
- }
1037
- return;
1038
- }
1039
- var globalClient = null;
1040
- var globalMiniflare = null;
1041
- var globalEnvProxy = null;
1042
- var globalTransportDecode = null;
1043
- var globalRemoteBindings = null;
1044
- var globalMiniflareBindings = null;
1045
- function getCallerDirectory() {
1046
- const bun = getBunRuntime2();
1047
- if (bun?.main) {
1048
- const mainPath = bun.main;
1049
- if (!mainPath.includes("[") && existsSync2(mainPath)) {
1050
- return dirname2(mainPath);
1051
- }
1052
- }
1053
- const originalPrepare = Error.prepareStackTrace;
1054
- Error.prepareStackTrace = (_, stack2) => stack2;
1055
- const err = new Error;
1056
- const stack = err.stack;
1057
- Error.prepareStackTrace = originalPrepare;
1058
- for (const site of stack) {
1059
- const filename = site.getFileName?.();
1060
- if (filename && !filename.includes("simple-context") && !filename.includes("node_modules") && !filename.includes("[") && existsSync2(filename)) {
1061
- return dirname2(filename);
1062
- }
1063
- }
1064
- return process.cwd();
1065
- }
1066
- async function findNearestConfig(startDir) {
1067
- let currentDir = startDir;
1068
- while (true) {
1069
- const configPath = await resolveConfigPath(currentDir);
1070
- if (configPath) {
1071
- return configPath;
1072
- }
1073
- const parentDir = dirname2(currentDir);
1074
- if (parentDir === currentDir) {
1075
- return null;
1076
- }
1077
- currentDir = parentDir;
1078
- }
1079
- }
1080
- async function createTestContext(configPath) {
1081
- const callerDir = getCallerDirectory();
1082
- let absolutePath;
1083
- if (configPath) {
1084
- absolutePath = resolve2(callerDir, configPath);
1085
- } else {
1086
- const found = await findNearestConfig(callerDir);
1087
- if (!found) {
1088
- throw new Error(`Could not find a devflare config file. Searched upward from: ${callerDir}
1089
- ` + `Expected one of: devflare.config.ts, devflare.config.mts, devflare.config.js, devflare.config.mjs
1090
- ` + `Either create a config file or provide an explicit path: createTestContext('./path/to/config.ts')`);
1091
- }
1092
- absolutePath = found;
1093
- }
1094
- const configDir5 = dirname2(absolutePath);
1095
- const config = await loadConfig({
1096
- cwd: configDir5,
1097
- configFile: absolutePath.split(/[/\\]/).pop()
1098
- });
1099
- globalRemoteBindings = {};
1100
- if (isRemoteModeActive()) {
1101
- if (config.bindings?.ai) {
1102
- const aiBindingName = config.bindings.ai.binding || "AI";
1103
- globalRemoteBindings[aiBindingName] = createRemoteAI(config.accountId);
1104
- }
1105
- if (config.bindings?.vectorize) {
1106
- for (const [name, vectorConfig] of Object.entries(config.bindings.vectorize)) {
1107
- globalRemoteBindings[name] = createRemoteVectorize(vectorConfig.indexName, config.accountId);
1108
- }
1109
- }
1110
- }
1111
- if (config.vars) {
1112
- for (const [key, value] of Object.entries(config.vars)) {
1113
- globalRemoteBindings[key] = value;
1114
- }
1115
- }
1116
- const hints = {};
1117
- if (config.bindings?.kv) {
1118
- for (const name of Object.keys(config.bindings.kv))
1119
- hints[name] = "kv";
1120
- }
1121
- if (config.bindings?.r2) {
1122
- for (const name of Object.keys(config.bindings.r2))
1123
- hints[name] = "r2";
1124
- }
1125
- if (config.bindings?.d1) {
1126
- for (const name of Object.keys(config.bindings.d1))
1127
- hints[name] = "d1";
1128
- }
1129
- if (config.bindings?.durableObjects) {
1130
- for (const name of Object.keys(config.bindings.durableObjects))
1131
- hints[name] = "do";
1132
- }
1133
- if (config.bindings?.services) {
1134
- for (const name of Object.keys(config.bindings.services))
1135
- hints[name] = "service";
1136
- }
1137
- const needsMultiWorkerForServices = hasServiceBindings(config);
1138
- const needsMultiWorkerForDOs = hasCrossWorkerDOs(config);
1139
- const needsMultiWorker = needsMultiWorkerForServices || needsMultiWorkerForDOs;
1140
- let serviceBindingResolution = null;
1141
- let doBindingResolution = null;
1142
- if (needsMultiWorkerForServices) {
1143
- serviceBindingResolution = await resolveServiceBindings(config, configDir5);
1144
- }
1145
- if (needsMultiWorkerForDOs) {
1146
- doBindingResolution = await resolveDOBindings(config, configDir5);
1147
- }
1148
- const randomPort = 1e4 + Math.floor(Math.random() * 50000);
1149
- const mfConfig = {
1150
- modules: true,
1151
- port: randomPort
1152
- };
1153
- if (config.bindings?.kv)
1154
- mfConfig.kvNamespaces = Object.keys(config.bindings.kv);
1155
- if (config.bindings?.r2)
1156
- mfConfig.r2Buckets = Object.keys(config.bindings.r2);
1157
- if (config.bindings?.d1)
1158
- mfConfig.d1Databases = Object.keys(config.bindings.d1);
1159
- if (config.bindings?.queues?.producers) {
1160
- const queueProducers = {};
1161
- for (const [bindingName, queueName] of Object.entries(config.bindings.queues.producers)) {
1162
- queueProducers[bindingName] = { queueName };
1163
- }
1164
- mfConfig.queueProducers = queueProducers;
1165
- }
1166
- const transportFile = config.files?.transport;
1167
- if (transportFile) {
1168
- const transportPath = join6(configDir5, transportFile);
1169
- const transportModule = await import(transportPath);
1170
- if (!transportModule.transport) {
1171
- console.warn(`[devflare] Warning: Transport file "${transportFile}" does not export a named "transport" object.
1172
- Expected: export const transport = { ... }
1173
- Transport encoding/decoding will be disabled.`);
1174
- } else {
1175
- globalTransportDecode = new Map;
1176
- for (const [typeName, transporter] of Object.entries(transportModule.transport)) {
1177
- const t = transporter;
1178
- globalTransportDecode.set(typeName, t.decode);
1179
- }
1180
- }
1181
- }
1182
- if (config.bindings?.durableObjects) {
1183
- const doConfig = {};
1184
- const doInfos = [];
1185
- const classToFilePath = new Map;
1186
- const doPatternConfig = config.files?.durableObjects;
1187
- const doPattern = typeof doPatternConfig === "string" ? doPatternConfig : DEFAULT_DO_PATTERN;
1188
- if (doPatternConfig !== false) {
1189
- const fs = await import("fs/promises");
1190
- const doFiles = await findFiles(doPattern, { cwd: configDir5 });
1191
- for (const filePath of doFiles) {
1192
- try {
1193
- const code = await fs.readFile(filePath, "utf-8");
1194
- const classNames = findExportedClasses(code);
1195
- for (const className of classNames) {
1196
- classToFilePath.set(className, filePath);
1197
- }
1198
- } catch {}
1199
- }
1200
- }
1201
- for (const [name, rawDoInfo] of Object.entries(config.bindings.durableObjects)) {
1202
- const doInfo = normalizeDOBinding(rawDoInfo);
1203
- if (doInfo.__ref) {
1204
- continue;
1205
- }
1206
- let scriptPath;
1207
- if (doInfo.scriptName) {
1208
- scriptPath = join6(configDir5, "src", doInfo.scriptName);
1209
- } else {
1210
- const discoveredPath = classToFilePath.get(doInfo.className);
1211
- if (!discoveredPath) {
1212
- throw new Error(`Durable object ${name} (className: '${doInfo.className}') not found.
1213
- Either:
1214
- 1. Set files.durableObjects pattern in config (e.g., 'src/do.*.ts')
1215
- 2. Use explicit scriptName: { className: '${doInfo.className}', scriptName: 'do.file.ts' }`);
1216
- }
1217
- scriptPath = discoveredPath;
1218
- }
1219
- doConfig[name] = doInfo.className;
1220
- doInfos.push({ name, className: doInfo.className, scriptPath });
1221
- }
1222
- const virtualImports = [];
1223
- const virtualExports = [];
1224
- if (transportFile) {
1225
- const transportPath = join6(configDir5, transportFile);
1226
- virtualImports.push(`import { transport } from '${transportPath.replace(/\\/g, "/")}'`);
1227
- virtualExports.push("export { transport }");
1228
- }
1229
- for (const info of doInfos) {
1230
- virtualImports.push(`import { ${info.className} } from '${info.scriptPath.replace(/\\/g, "/")}'`);
1231
- virtualExports.push(`export { ${info.className} }`);
1232
- }
1233
- let bundledCode = "";
1234
- if (virtualImports.length > 0) {
1235
- const virtualEntry = [...virtualImports, "", ...virtualExports].join(`
1236
- `);
1237
- const virtualPath = join6(configDir5, ".devflare", "__test_entry.ts");
1238
- const { writeFileSync, mkdirSync } = await import("fs");
1239
- mkdirSync(dirname2(virtualPath), { recursive: true });
1240
- writeFileSync(virtualPath, virtualEntry);
1241
- const bun = getBunRuntime2();
1242
- if (!bun) {
1243
- throw new Error("Bun runtime is required for createTestContext with Durable Objects");
1244
- }
1245
- const result = await bun.build({
1246
- entrypoints: [virtualPath],
1247
- target: "browser",
1248
- format: "esm",
1249
- minify: false,
1250
- external: ["cloudflare:workers", "cloudflare:*"]
1251
- });
1252
- if (!result.success) {
1253
- throw new Error(`Failed to bundle test entry: ${result.logs.join(`
1254
- `)}`);
1255
- }
1256
- bundledCode = await result.outputs[0].text();
1257
- }
1258
- mfConfig.durableObjects = doConfig;
1259
- mfConfig.script = buildGatewayScript(bundledCode, "");
1260
- } else {
1261
- mfConfig.script = buildGatewayScript("", "");
1262
- }
1263
- const hasMultiWorkerServices = serviceBindingResolution && serviceBindingResolution.workers.length > 0;
1264
- const hasMultiWorkerDOs = doBindingResolution && doBindingResolution.workers.length > 0;
1265
- if (hasMultiWorkerServices || hasMultiWorkerDOs) {
1266
- const primaryDurableObjects = {
1267
- ...mfConfig.durableObjects || {},
1268
- ...doBindingResolution?.crossWorkerDOBindings || {}
1269
- };
1270
- const primaryWorker = {
1271
- name: config.name ?? "primary",
1272
- modules: true,
1273
- script: mfConfig.script,
1274
- compatibilityDate: config.compatibilityDate ?? "2025-01-01",
1275
- ...mfConfig.kvNamespaces && { kvNamespaces: mfConfig.kvNamespaces },
1276
- ...mfConfig.r2Buckets && { r2Buckets: mfConfig.r2Buckets },
1277
- ...mfConfig.d1Databases && { d1Databases: mfConfig.d1Databases },
1278
- ...Object.keys(primaryDurableObjects).length > 0 && { durableObjects: primaryDurableObjects },
1279
- ...serviceBindingResolution?.primaryServiceBindings && { serviceBindings: serviceBindingResolution.primaryServiceBindings }
1280
- };
1281
- const additionalWorkers = [
1282
- ...serviceBindingResolution?.workers || [],
1283
- ...doBindingResolution?.workers || []
1284
- ];
1285
- const workersByName = new Map;
1286
- for (const worker2 of additionalWorkers) {
1287
- if (!workersByName.has(worker2.name)) {
1288
- workersByName.set(worker2.name, worker2);
1289
- } else {
1290
- const existing = workersByName.get(worker2.name);
1291
- if (worker2.durableObjects) {
1292
- existing.durableObjects = {
1293
- ...existing.durableObjects || {},
1294
- ...worker2.durableObjects
1295
- };
1296
- }
1297
- }
1298
- }
1299
- const workers = [primaryWorker, ...workersByName.values()];
1300
- delete mfConfig.script;
1301
- delete mfConfig.modules;
1302
- delete mfConfig.kvNamespaces;
1303
- delete mfConfig.r2Buckets;
1304
- delete mfConfig.d1Databases;
1305
- delete mfConfig.durableObjects;
1306
- mfConfig.workers = workers;
1307
- }
1308
- const { Miniflare } = await import("miniflare");
1309
- globalMiniflare = new Miniflare(mfConfig);
1310
- await globalMiniflare.ready;
1311
- globalMiniflareBindings = await globalMiniflare.getBindings();
1312
- const disposeContext = async () => {
1313
- if (globalClient) {
1314
- await globalClient.disconnect();
1315
- globalClient = null;
1316
- }
1317
- if (globalMiniflare) {
1318
- await globalMiniflare.dispose();
1319
- globalMiniflare = null;
1320
- }
1321
- globalEnvProxy = null;
1322
- globalTransportDecode = null;
1323
- globalRemoteBindings = null;
1324
- globalMiniflareBindings = null;
1325
- resetQueueState();
1326
- resetScheduledState();
1327
- resetWorkerState();
1328
- resetTailState();
1329
- resetEmailState();
1330
- __clearTestContext();
1331
- };
1332
- const getTestEnv = () => {
1333
- if (globalMiniflareBindings)
1334
- return globalMiniflareBindings;
1335
- if (globalRemoteBindings)
1336
- return globalRemoteBindings;
1337
- if (globalEnvProxy)
1338
- return globalEnvProxy;
1339
- return {};
1340
- };
1341
- const queuePath = config.files?.queue;
1342
- const scheduledPath = config.files?.scheduled;
1343
- const fetchPath = config.files?.fetch;
1344
- const DEFAULT_FETCH_PATH = "src/fetch.ts";
1345
- const DEFAULT_QUEUE_PATH = "src/queue.ts";
1346
- const DEFAULT_SCHEDULED_PATH = "src/scheduled.ts";
1347
- const resolvePath = async (configValue, defaultPath) => {
1348
- if (typeof configValue === "string")
1349
- return configValue;
1350
- if (configValue === false)
1351
- return null;
1352
- const defaultAbsolute = join6(configDir5, defaultPath);
1353
- try {
1354
- const fs = await import("fs/promises");
1355
- await fs.access(defaultAbsolute);
1356
- return defaultPath;
1357
- } catch {
1358
- return null;
1359
- }
1360
- };
1361
- const [resolvedFetchPath, resolvedQueuePath, resolvedScheduledPath] = await Promise.all([
1362
- resolvePath(fetchPath, DEFAULT_FETCH_PATH),
1363
- resolvePath(queuePath, DEFAULT_QUEUE_PATH),
1364
- resolvePath(scheduledPath, DEFAULT_SCHEDULED_PATH)
1365
- ]);
1366
- configureQueue({
1367
- handlerPath: resolvedQueuePath,
1368
- configDir: configDir5,
1369
- getEnv: getTestEnv
1370
- });
1371
- configureScheduled({
1372
- handlerPath: resolvedScheduledPath,
1373
- configDir: configDir5,
1374
- getEnv: getTestEnv
1375
- });
1376
- configureWorker({
1377
- handlerPath: resolvedFetchPath,
1378
- configDir: configDir5,
1379
- getEnv: getTestEnv
1380
- });
1381
- configureTail({
1382
- handlerPath: null,
1383
- configDir: configDir5,
1384
- getEnv: getTestEnv
1385
- });
1386
- configureEmail({ port: randomPort });
1387
- if (hasMultiWorkerServices || hasMultiWorkerDOs) {
1388
- setBindingHints(hints);
1389
- const envAccessor2 = new Proxy({}, {
1390
- get(_, prop) {
1391
- if (globalRemoteBindings && prop in globalRemoteBindings) {
1392
- return globalRemoteBindings[prop];
1393
- }
1394
- if (globalMiniflareBindings && prop in globalMiniflareBindings) {
1395
- return globalMiniflareBindings[prop];
1396
- }
1397
- return;
1398
- },
1399
- has(_, prop) {
1400
- return Boolean(globalRemoteBindings && prop in globalRemoteBindings || globalMiniflareBindings && prop in globalMiniflareBindings);
1401
- }
1402
- });
1403
- __setTestContext(envAccessor2, disposeContext);
1404
- return;
1405
- }
1406
- globalClient = new BridgeClient({
1407
- url: `ws://localhost:${randomPort}`
1408
- });
1409
- await globalClient.connect();
1410
- setBindingHints(hints);
1411
- globalEnvProxy = createEnvProxy({
1412
- client: globalClient,
1413
- transformResult: (result) => decodeTransport(result)
1414
- });
1415
- const envAccessor = new Proxy({}, {
1416
- get(_, prop) {
1417
- if (globalRemoteBindings && prop in globalRemoteBindings) {
1418
- return globalRemoteBindings[prop];
1419
- }
1420
- if (globalMiniflareBindings && prop in globalMiniflareBindings) {
1421
- return globalMiniflareBindings[prop];
1422
- }
1423
- if (globalEnvProxy) {
1424
- return globalEnvProxy[prop];
1425
- }
1426
- return;
1427
- },
1428
- has(_, prop) {
1429
- return Boolean(globalRemoteBindings && prop in globalRemoteBindings || globalMiniflareBindings && prop in globalMiniflareBindings || globalEnvProxy !== null);
1430
- }
1431
- });
1432
- __setTestContext(envAccessor, disposeContext);
1433
- }
1434
- function decodeTransport(value) {
1435
- if (!globalTransportDecode || value === null || typeof value !== "object") {
1436
- return value;
1437
- }
1438
- if ("__transport" in value) {
1439
- const encoded = value;
1440
- const decoder = globalTransportDecode.get(encoded.__transport);
1441
- if (decoder) {
1442
- return decoder(encoded.value);
1443
- }
1444
- }
1445
- if (Array.isArray(value)) {
1446
- return value.map(decodeTransport);
1447
- }
1448
- const result = {};
1449
- for (const [k, v] of Object.entries(value)) {
1450
- result[k] = decodeTransport(v);
1451
- }
1452
- return result;
1453
- }
1454
- function buildGatewayScript(bundledCode, wrappers) {
1455
- return `
1456
- // Bundled transport + DO classes
1457
- ${bundledCode}
1458
-
1459
- // DO Wrappers with RPC
1460
- ${wrappers}
1461
-
1462
- // Transport encoding helper
1463
- const __transportEncoders = typeof transport !== 'undefined' ? transport : {}
1464
-
1465
- function __encodeTransport(value) {
1466
- if (value === null || value === undefined) return value
1467
-
1468
- // Try each encoder
1469
- for (const [typeName, transporter] of Object.entries(__transportEncoders)) {
1470
- const encoded = transporter.encode(value)
1471
- if (encoded !== false && encoded !== undefined) {
1472
- return { __transport: typeName, value: encoded }
1473
- }
1474
- }
1475
-
1476
- // Recursively encode arrays and objects
1477
- if (Array.isArray(value)) {
1478
- return value.map(__encodeTransport)
1479
- }
1480
- if (typeof value === 'object') {
1481
- const result = {}
1482
- for (const [k, v] of Object.entries(value)) {
1483
- result[k] = __encodeTransport(v)
1484
- }
1485
- return result
1486
- }
1487
-
1488
- return value
1489
- }
1490
-
1491
- // Gateway with WebSocket RPC
1492
- export default {
1493
- async fetch(request, env) {
1494
- if (request.headers.get('Upgrade') === 'websocket') {
1495
- const { 0: client, 1: server } = new WebSocketPair()
1496
- server.accept()
1497
- server.addEventListener('message', async (e) => {
1498
- try {
1499
- const m = JSON.parse(e.data)
1500
- if (m.t === 'rpc.call') {
1501
- const result = await executeRpc(env, m.method, m.params)
1502
- server.send(JSON.stringify({ t: 'rpc.ok', id: m.id, result }))
1503
- }
1504
- } catch (error) {
1505
- server.send(JSON.stringify({ t: 'rpc.err', id: 'unknown', error: { code: 'RPC_ERROR', message: error.message } }))
1506
- }
1507
- })
1508
- return new Response(null, { status: 101, webSocket: client })
1509
- }
1510
- return new Response('Gateway')
1511
- }
1512
- }
1513
-
1514
- async function executeRpc(env, method, params) {
1515
- const [bindingName, ...rest] = method.split('.')
1516
- const op = rest.join('.')
1517
- const binding = env[bindingName]
1518
- if (!binding) throw new Error('Binding not found: ' + bindingName)
1519
-
1520
- // KV operations
1521
- if (op === 'get') return binding.get(params[0], params[1])
1522
- if (op === 'put') return binding.put(params[0], params[1], params[2])
1523
- if (op === 'delete') return binding.delete(params[0])
1524
- if (op === 'list') return binding.list(params[0])
1525
- if (op === 'getWithMetadata') return binding.getWithMetadata(params[0], params[1])
1526
-
1527
- // R2 operations
1528
- if (op === 'r2.get') return binding.get(params[0], params[1])
1529
- if (op === 'r2.put') return binding.put(params[0], params[1], params[2])
1530
- if (op === 'r2.delete') return binding.delete(params[0])
1531
- if (op === 'r2.list') return binding.list(params[0])
1532
- if (op === 'head') return binding.head(params[0])
1533
-
1534
- // D1 operations
1535
- if (op === 'exec') return binding.exec(params[0])
1536
- if (op === 'dump') return binding.dump()
1537
- if (op === 'batch') {
1538
- const stmts = params[0].map(s => {
1539
- const stmt = binding.prepare(s.sql)
1540
- return s.bindings?.length ? stmt.bind(...s.bindings) : stmt
1541
- })
1542
- return binding.batch(stmts)
1543
- }
1544
- if (op === 'prepare.run') return binding.prepare(params[0]).bind(...(params[1] || [])).run()
1545
- if (op === 'prepare.all') return binding.prepare(params[0]).bind(...(params[1] || [])).all()
1546
- if (op === 'prepare.first') return binding.prepare(params[0]).bind(...(params[1] || [])).first(params[2])
1547
- if (op === 'prepare.raw') return binding.prepare(params[0]).bind(...(params[1] || [])).raw({ columnNames: params[2] })
1548
-
1549
- // DO operations
1550
- if (op === 'idFromName') {
1551
- return { __type: 'DOId', hex: binding.idFromName(params[0]).toString() }
1552
- }
1553
- if (op === 'stub.rpc') {
1554
- const [, idSerialized, rpcMethod, rpcParams] = params
1555
- const stub = binding.get(binding.idFromString(idSerialized.hex))
1556
-
1557
- // Use native RPC: call method directly on stub
1558
- // This works for DOs extending DurableObject from cloudflare:workers
1559
- let result = await stub[rpcMethod](...(rpcParams || []))
1560
- // Apply transport encoding
1561
- result = __encodeTransport(result)
1562
- return result
1563
- }
1564
-
1565
- throw new Error('Unknown operation: ' + method)
1566
- }
1567
- `;
1568
- }
1569
- // src/test/cf.ts
1570
- var cf = {
1571
- email,
1572
- queue,
1573
- scheduled,
1574
- worker,
1575
- tail
1576
- };
1577
- // src/test/multi-worker-context.ts
1578
- async function createMultiWorkerContext(options) {
1579
- const { workers, primary } = options;
1580
- const primaryName = primary ?? workers[0]?.name;
1581
- if (!primaryName) {
1582
- throw new Error("At least one worker must be configured");
1583
- }
1584
- const { Miniflare } = await import("miniflare");
1585
- const mfWorkers = workers.map((worker2) => {
1586
- const serviceBindings = {};
1587
- if (worker2.serviceBindings) {
1588
- for (const [bindingName, target] of Object.entries(worker2.serviceBindings)) {
1589
- if (typeof target === "string") {
1590
- serviceBindings[bindingName] = { name: target };
1591
- } else {
1592
- serviceBindings[bindingName] = target;
1593
- }
1594
- }
1595
- }
1596
- return {
1597
- name: worker2.name,
1598
- modules: worker2.modules ?? true,
1599
- script: worker2.script,
1600
- compatibilityDate: worker2.compatibilityDate ?? "2025-01-01",
1601
- ...Object.keys(serviceBindings).length > 0 ? { serviceBindings } : {}
1602
- };
1603
- });
1604
- const mf = new Miniflare({
1605
- workers: mfWorkers
1606
- });
1607
- const env2 = await mf.getBindings();
1608
- const fetch3 = async (input, init) => {
1609
- const response = await mf.dispatchFetch(input, init);
1610
- return response;
1611
- };
1612
- const dispose = async () => {
1613
- await new Promise((r) => setTimeout(r, 50));
1614
- await mf.dispose();
1615
- };
1616
- return {
1617
- mf,
1618
- env: env2,
1619
- fetch: fetch3,
1620
- dispose
1621
- };
1622
- }
1623
- function createEntrypointScript(className, methods) {
1624
- const methodDefs = Object.entries(methods).map(([name, body]) => ` ${name}${body}`).join(`
1625
-
1626
- `);
1627
- return `import { WorkerEntrypoint } from 'cloudflare:workers'
1628
-
1629
- export class ${className} extends WorkerEntrypoint {
1630
- ${methodDefs}
1631
- }
1632
- `;
1633
- }
1634
- // src/test/should-skip.ts
1635
- var REMOTE_ONLY_SERVICES = new Set([
1636
- "ai",
1637
- "vectorize"
1638
- ]);
1639
- function isRemoteModeEnabled() {
1640
- return isRemoteModeActive();
1641
- }
1642
- var skipResults = new Map;
1643
- var EXPECTED_ERROR_PATTERNS = [
1644
- "ECONNREFUSED",
1645
- "ETIMEDOUT",
1646
- "ENOTFOUND",
1647
- "fetch failed",
1648
- "network",
1649
- "401",
1650
- "403",
1651
- "429",
1652
- "500",
1653
- "502",
1654
- "503",
1655
- "504",
1656
- "rate limit",
1657
- "unauthorized",
1658
- "forbidden",
1659
- "timeout"
1660
- ];
1661
- function isExpectedError(error) {
1662
- if (!(error instanceof Error))
1663
- return false;
1664
- const msg = error.message.toLowerCase();
1665
- return EXPECTED_ERROR_PATTERNS.some((pattern) => msg.includes(pattern.toLowerCase()));
1666
- }
1667
- async function computeSkip(service) {
1668
- try {
1669
- if (REMOTE_ONLY_SERVICES.has(service) && !isRemoteModeActive()) {
1670
- const status = getRemoteModeStatus();
1671
- console.log(`⏭️ ${service.toUpperCase()} tests skipped: Remote-only service.
1672
- ` + ` Enable with: ${status.isEnabled ? "" : "devflare remote enable"}
1673
- ` + ` Or set: DEVFLARE_REMOTE=1
1674
- ` + ` See: https://github.com/ArthurvdVenne/devflare#remote-testing`);
1675
- return true;
1676
- }
1677
- const isAuth = await isAuthenticated();
1678
- if (!isAuth) {
1679
- console.log(`⏭️ ${service.toUpperCase()} tests skipped: Not authenticated. Run: bunx wrangler login
1680
- ` + ` See: https://github.com/ArthurvdVenne/devflare#authentication`);
1681
- return true;
1682
- }
1683
- const primary = await getPrimaryAccount();
1684
- if (!primary) {
1685
- console.log(`⏭️ ${service.toUpperCase()} tests skipped: No Cloudflare account found
1686
- ` + ` See: https://github.com/ArthurvdVenne/devflare#authentication`);
1687
- return true;
1688
- }
1689
- const { accountId } = await getEffectiveAccountId(primary.id);
1690
- try {
1691
- const { allowed, reason } = await canProceedWithTest(accountId, service);
1692
- if (!allowed) {
1693
- console.log(`⏭️ ${service.toUpperCase()} tests skipped: ${reason}`);
1694
- return true;
1695
- }
1696
- } catch {}
1697
- return false;
1698
- } catch (error) {
1699
- if (isExpectedError(error)) {
1700
- const message = error instanceof Error ? error.message : "Unknown error";
1701
- console.log(`⏭️ ${service.toUpperCase()} tests skipped: ${message}`);
1702
- return true;
1703
- }
1704
- throw error;
1705
- }
1706
- }
1707
- function getSkipResult(service) {
1708
- let result = skipResults.get(service);
1709
- if (!result) {
1710
- result = computeSkip(service);
1711
- skipResults.set(service, result);
1712
- }
1713
- return result;
1714
- }
1715
- var shouldSkip = {
1716
- get ai() {
1717
- return getSkipResult("ai");
1718
- },
1719
- get vectorize() {
1720
- return getSkipResult("vectorize");
1721
- },
1722
- get workers() {
1723
- return getSkipResult("workers");
1724
- },
1725
- get kv() {
1726
- return getSkipResult("kv");
1727
- },
1728
- get d1() {
1729
- return getSkipResult("d1");
1730
- },
1731
- get r2() {
1732
- return getSkipResult("r2");
1733
- },
1734
- get queues() {
1735
- return getSkipResult("queues");
1736
- },
1737
- get durableObjects() {
1738
- return getSkipResult("durable_objects");
1739
- }
1740
- };
1741
- // src/test/utilities.ts
1742
- function createMockTestContext(options = {}) {
1743
- const waitUntilPromises = [];
1744
- const ctx = {
1745
- waitUntil(promise) {
1746
- waitUntilPromises.push(promise);
1747
- },
1748
- passThroughOnException() {},
1749
- props: {}
1750
- };
1751
- return {
1752
- env: options.env ?? {},
1753
- ctx,
1754
- request: options.request ?? null,
1755
- waitUntilPromises
1756
- };
1757
- }
1758
- async function withTestContext(options, handler) {
1759
- const testCtx = createMockTestContext(options);
1760
- return runWithContext(testCtx.env, testCtx.ctx, options.request ?? null, handler, options.type ?? "fetch");
1761
- }
1762
- function createMockKV(initialData = {}) {
1763
- const store = new Map(Object.entries(initialData));
1764
- const metadata = new Map;
1765
- return {
1766
- async get(key, options) {
1767
- const value = store.get(key);
1768
- if (value === null || value === undefined)
1769
- return null;
1770
- const type = typeof options === "string" ? options : options?.type ?? "text";
1771
- switch (type) {
1772
- case "json":
1773
- return JSON.parse(value);
1774
- case "arrayBuffer":
1775
- return new TextEncoder().encode(value).buffer;
1776
- case "stream":
1777
- return new ReadableStream({
1778
- start(controller) {
1779
- controller.enqueue(new TextEncoder().encode(value));
1780
- controller.close();
1781
- }
1782
- });
1783
- default:
1784
- return value;
1785
- }
1786
- },
1787
- async put(key, value, options) {
1788
- if (typeof value === "string") {
1789
- store.set(key, value);
1790
- } else if (value instanceof ArrayBuffer) {
1791
- store.set(key, new TextDecoder().decode(value));
1792
- } else {
1793
- const reader = value.getReader();
1794
- const chunks = [];
1795
- let done = false;
1796
- while (!done) {
1797
- const result = await reader.read();
1798
- done = result.done;
1799
- if (result.value)
1800
- chunks.push(result.value);
1801
- }
1802
- const combined = new Uint8Array(chunks.reduce((acc, c) => acc + c.length, 0));
1803
- let offset = 0;
1804
- for (const chunk of chunks) {
1805
- combined.set(chunk, offset);
1806
- offset += chunk.length;
1807
- }
1808
- store.set(key, new TextDecoder().decode(combined));
1809
- }
1810
- },
1811
- async delete(key) {
1812
- store.delete(key);
1813
- },
1814
- async list(options) {
1815
- const prefix = options?.prefix ?? "";
1816
- const limit = options?.limit ?? 1000;
1817
- const keys = Array.from(store.keys()).filter((key) => key.startsWith(prefix)).slice(0, limit).map((name) => ({ name }));
1818
- return {
1819
- keys,
1820
- list_complete: keys.length < limit,
1821
- cursor: undefined
1822
- };
1823
- },
1824
- async getWithMetadata(key, options) {
1825
- return {
1826
- value: store.get(key) ?? null,
1827
- metadata: metadata.get(key) ?? null
1828
- };
1829
- }
1830
- };
1831
- }
1832
- function createMockD1(mockResults = []) {
1833
- let boundValues = [];
1834
- let currentResults = [...mockResults];
1835
- const createStatement = () => ({
1836
- bind(...values) {
1837
- boundValues = values;
1838
- return this;
1839
- },
1840
- async first(column) {
1841
- const row = currentResults[0];
1842
- if (!row)
1843
- return null;
1844
- if (column)
1845
- return row[column];
1846
- return row;
1847
- },
1848
- async all() {
1849
- return {
1850
- results: currentResults,
1851
- success: true,
1852
- meta: { duration: 0, changes: 0, last_row_id: 0 }
1853
- };
1854
- },
1855
- async run() {
1856
- return {
1857
- results: [],
1858
- success: true,
1859
- meta: { duration: 0, changes: 1, last_row_id: 1 }
1860
- };
1861
- },
1862
- async raw(options) {
1863
- return currentResults.map((row) => Object.values(row));
1864
- }
1865
- });
1866
- return {
1867
- prepare(query) {
1868
- return createStatement();
1869
- },
1870
- async exec(query) {
1871
- return {
1872
- results: [],
1873
- success: true,
1874
- meta: { duration: 0, changes: 0, last_row_id: 0 }
1875
- };
1876
- },
1877
- async batch(statements) {
1878
- return statements.map(() => ({
1879
- results: [],
1880
- success: true,
1881
- meta: { duration: 0, changes: 0, last_row_id: 0 }
1882
- }));
1883
- },
1884
- async dump() {
1885
- return new ArrayBuffer(0);
1886
- },
1887
- withSession(constraintOrBookmark) {
1888
- return this;
1889
- }
1890
- };
1891
- }
1892
- function createMockR2() {
1893
- const store = new Map;
1894
- const createR2Object = (key, content, metadata) => {
1895
- const encoder = new TextEncoder;
1896
- const data = encoder.encode(content);
1897
- return {
1898
- key,
1899
- version: "1",
1900
- size: data.length,
1901
- etag: `"${key}-etag"`,
1902
- httpEtag: `"${key}-etag"`,
1903
- uploaded: new Date,
1904
- httpMetadata: metadata ?? {},
1905
- customMetadata: {},
1906
- checksums: {},
1907
- storageClass: "Standard",
1908
- body: new ReadableStream({
1909
- start(controller) {
1910
- controller.enqueue(data);
1911
- controller.close();
1912
- }
1913
- }),
1914
- bodyUsed: false,
1915
- async arrayBuffer() {
1916
- return new Uint8Array(data).buffer;
1917
- },
1918
- async text() {
1919
- return content;
1920
- },
1921
- async json() {
1922
- return JSON.parse(content);
1923
- },
1924
- async blob() {
1925
- return new Blob([data]);
1926
- },
1927
- writeHttpMetadata(headers) {}
1928
- };
1929
- };
1930
- return {
1931
- async put(key, value, options) {
1932
- let content;
1933
- if (typeof value === "string") {
1934
- content = value;
1935
- } else if (value instanceof ArrayBuffer) {
1936
- content = new TextDecoder().decode(value);
1937
- } else if (value instanceof Blob) {
1938
- content = await value.text();
1939
- } else if (value === null) {
1940
- content = "";
1941
- } else {
1942
- const reader = value.getReader();
1943
- const chunks = [];
1944
- let done = false;
1945
- while (!done) {
1946
- const result = await reader.read();
1947
- done = result.done;
1948
- if (result.value) {
1949
- chunks.push(new TextDecoder().decode(result.value));
1950
- }
1951
- }
1952
- content = chunks.join("");
1953
- }
1954
- store.set(key, { content });
1955
- return createR2Object(key, content);
1956
- },
1957
- async get(key, options) {
1958
- const item = store.get(key);
1959
- if (!item)
1960
- return null;
1961
- return createR2Object(key, item.content, item.metadata);
1962
- },
1963
- async head(key) {
1964
- const item = store.get(key);
1965
- if (!item)
1966
- return null;
1967
- return {
1968
- key,
1969
- version: "1",
1970
- size: new TextEncoder().encode(item.content).length,
1971
- etag: `"${key}-etag"`,
1972
- httpEtag: `"${key}-etag"`,
1973
- uploaded: new Date,
1974
- httpMetadata: item.metadata ?? {},
1975
- customMetadata: {},
1976
- checksums: {},
1977
- storageClass: "Standard",
1978
- writeHttpMetadata(headers) {}
1979
- };
1980
- },
1981
- async delete(keys) {
1982
- const keyArray = Array.isArray(keys) ? keys : [keys];
1983
- for (const key of keyArray) {
1984
- store.delete(key);
1985
- }
1986
- },
1987
- async list(options) {
1988
- const objects = Array.from(store.entries()).map(([key, { content, metadata }]) => createR2Object(key, content, metadata));
1989
- return {
1990
- objects,
1991
- truncated: false,
1992
- delimitedPrefixes: []
1993
- };
1994
- },
1995
- async createMultipartUpload(key, options) {
1996
- throw new Error("Multipart upload not implemented in mock");
1997
- },
1998
- async resumeMultipartUpload(key, uploadId) {
1999
- throw new Error("Multipart upload not implemented in mock");
2000
- }
2001
- };
2002
- }
2003
- function createMockQueue() {
2004
- const messages = [];
2005
- return {
2006
- async send(message, options) {
2007
- messages.push({ body: message, options });
2008
- },
2009
- async sendBatch(batch) {
2010
- messages.push(...batch);
2011
- },
2012
- _getMessages() {
2013
- return messages;
2014
- }
2015
- };
2016
- }
2017
- function createMockEnv(options = {}) {
2018
- const env2 = {};
2019
- if (options.kv) {
2020
- for (const name of options.kv) {
2021
- env2[name] = createMockKV();
2022
- }
2023
- }
2024
- if (options.d1) {
2025
- for (const name of options.d1) {
2026
- env2[name] = createMockD1();
2027
- }
2028
- }
2029
- if (options.r2) {
2030
- for (const name of options.r2) {
2031
- env2[name] = createMockR2();
2032
- }
2033
- }
2034
- if (options.queues) {
2035
- for (const name of options.queues) {
2036
- env2[name] = createMockQueue();
2037
- }
2038
- }
2039
- if (options.vars) {
2040
- Object.assign(env2, options.vars);
2041
- }
2042
- if (options.secrets) {
2043
- Object.assign(env2, options.secrets);
2044
- }
2045
- if (options.custom) {
2046
- Object.assign(env2, options.custom);
2047
- }
2048
- return env2;
2049
- }
2050
- // src/test/bridge-context.ts
2051
- var globalTestContext = null;
2052
- async function createBridgeTestContext(options = {}) {
2053
- if (globalTestContext) {
2054
- await globalTestContext.stop();
2055
- }
2056
- let config = options.config;
2057
- if (options.configPath && !config) {
2058
- config = await loadConfig({ cwd: options.configPath.replace(/[/\\][^/\\]+$/, ""), configFile: options.configPath.split(/[/\\]/).pop() });
2059
- }
2060
- let miniflare;
2061
- if (config) {
2062
- miniflare = await startMiniflareFromConfig(config, {
2063
- ...options.miniflare,
2064
- port: options.port ?? 8787,
2065
- persist: options.persist ?? false,
2066
- verbose: options.verbose ?? false
2067
- });
2068
- } else {
2069
- miniflare = await startMiniflare({
2070
- ...options.miniflare,
2071
- port: options.port ?? 8787,
2072
- persist: options.persist ?? false,
2073
- verbose: options.verbose ?? false
2074
- });
2075
- }
2076
- const bindings = await miniflare.getBindings();
2077
- if (config?.bindings) {
2078
- const hints = {};
2079
- if (config.bindings.kv) {
2080
- Object.keys(config.bindings.kv).forEach((name) => {
2081
- hints[name] = "kv";
2082
- });
2083
- }
2084
- if (config.bindings.r2) {
2085
- Object.keys(config.bindings.r2).forEach((name) => {
2086
- hints[name] = "r2";
2087
- });
2088
- }
2089
- if (config.bindings.d1) {
2090
- Object.keys(config.bindings.d1).forEach((name) => {
2091
- hints[name] = "d1";
2092
- });
2093
- }
2094
- if (config.bindings.durableObjects) {
2095
- Object.keys(config.bindings.durableObjects).forEach((name) => {
2096
- hints[name] = "do";
2097
- });
2098
- }
2099
- if (config.bindings.queues?.consumers) {
2100
- config.bindings.queues.consumers.forEach((c) => {
2101
- hints[c.queue] = "queue";
2102
- });
2103
- }
2104
- if (config.bindings.ai)
2105
- hints[config.bindings.ai.binding] = "ai";
2106
- setBindingHints(hints);
2107
- }
2108
- const ctx = {
2109
- env: bindings,
2110
- miniflare,
2111
- async stop() {
2112
- await miniflare.dispose();
2113
- globalTestContext = null;
2114
- },
2115
- async reset() {
2116
- for (const [name, binding] of Object.entries(bindings)) {
2117
- if (isKVNamespace(binding)) {
2118
- const kv = binding;
2119
- const { keys } = await kv.list();
2120
- for (const key of keys) {
2121
- await kv.delete(key.name);
2122
- }
2123
- }
2124
- }
2125
- }
2126
- };
2127
- globalTestContext = ctx;
2128
- return ctx;
2129
- }
2130
- async function stopBridgeTestContext() {
2131
- if (globalTestContext) {
2132
- await globalTestContext.stop();
2133
- }
2134
- }
2135
- function getBridgeTestContext() {
2136
- if (!globalTestContext) {
2137
- throw new Error("Bridge test context not initialized. Call createBridgeTestContext() in beforeAll().");
2138
- }
2139
- return globalTestContext;
2140
- }
2141
- var testEnv = new Proxy({}, {
2142
- get(target, prop) {
2143
- if (typeof prop !== "string")
2144
- return;
2145
- const ctx = getBridgeTestContext();
2146
- return ctx.env[prop];
2147
- }
2148
- });
2149
- function isKVNamespace(binding) {
2150
- return typeof binding === "object" && binding !== null && "get" in binding && "put" in binding && "delete" in binding && "list" in binding;
2151
- }
2152
- export { clearBundleCache, hasServiceBindings, resolveServiceBindings, hasCrossWorkerDOs, resolveDOBindings, queue, scheduled, worker, tail, email, createTestContext, cf, createMultiWorkerContext, createEntrypointScript, isRemoteModeEnabled, shouldSkip, createMockTestContext, withTestContext, createMockKV, createMockD1, createMockR2, createMockQueue, createMockEnv, createBridgeTestContext, stopBridgeTestContext, getBridgeTestContext, testEnv };