void 1.12.2 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/README.md +1 -0
  2. package/dist/{account-cmd-CdJQba_Q.mjs → account-cmd-4fQiXYX7.mjs} +6 -6
  3. package/dist/{application-analysis-DVeN8yoi.mjs → application-analysis-BjEwHTV2.mjs} +19 -13
  4. package/dist/{application-routing-KKw4Y84h.mjs → application-routing-COCfD2yc.mjs} +1 -1
  5. package/dist/args-DrnTI35r.mjs +88 -0
  6. package/dist/args-MnQnqypt.mjs +1 -0
  7. package/dist/{auth-CqwJwItO.mjs → auth-CeBmolb-.mjs} +3 -3
  8. package/dist/{auth-A7cZ8aXA.mjs → auth-CvaDxOMi.mjs} +1 -1
  9. package/dist/{auth-link-D9MWA_dj.mjs → auth-link-I4omV0pL.mjs} +6 -6
  10. package/dist/{auth-router-FskgTU3B.mjs → auth-router-CXq4q7bb.mjs} +6 -5
  11. package/dist/{better-auth-shared-BS3pDQbT.d.mts → better-auth-shared-CrIkcN8I.d.mts} +2 -1
  12. package/dist/bindings-C7zOgxT3.d.mts +28 -0
  13. package/dist/browser-run-BKgZVwLk.mjs +124 -0
  14. package/dist/{build-cmd-B7OJ0U5R.mjs → build-cmd-Biz6u4rn.mjs} +6 -6
  15. package/dist/{cache-wSpi3aeM.mjs → cache-WkLMUrjQ.mjs} +6 -6
  16. package/dist/{cancel-deploy-DMWzkAlb.mjs → cancel-deploy-BRsrmyTk.mjs} +6 -5
  17. package/dist/{cf-access-DHklo7Rg.mjs → cf-access-B21j-nd6.mjs} +1 -1
  18. package/dist/{cf-build-output-Cso7Vh-t.mjs → cf-build-output-G-7Tdd8b.mjs} +6 -5
  19. package/dist/cf-build-output-Qc43LWzE.mjs +1 -0
  20. package/dist/{cf-command-values-5BPBRc9Z.mjs → cf-command-values-cUnJwCyG.mjs} +24 -1
  21. package/dist/{cf-config-migrate-D271BTiw.mjs → cf-config-migrate-CsbQGzMf.mjs} +200 -94
  22. package/dist/cf-user-agent-HHTRzfud.mjs +15 -0
  23. package/dist/cf-version-api-BWHMVtzw.mjs +1 -0
  24. package/dist/cf-version-api-XEEK2B9A.mjs +856 -0
  25. package/dist/cf-worker-settings-DJKdy97k.mjs +127 -0
  26. package/dist/cli/cli.mjs +1 -1
  27. package/dist/cli/cloudflare-operation-process.mjs +111 -47
  28. package/dist/cli/env-schema-probe.mjs +3 -3
  29. package/dist/cli/json-command-process.d.mts +6 -0
  30. package/dist/cli/json-command-process.mjs +91 -0
  31. package/dist/{cli-main-DaLrQfPS.mjs → cli-main-CJTGhcYN.mjs} +84 -113
  32. package/dist/{client-eLZwqkPH.mjs → client-0um7Lzze.mjs} +1 -1
  33. package/dist/{client-DE2m2ldh.mjs → client-BEHI4UWn.mjs} +14 -8
  34. package/dist/{cloudflare-auth-eWfhdZCk.mjs → cloudflare-auth-iOgRurWm.mjs} +1 -1
  35. package/dist/{cloudflare-cmd-SsFlJe2B.mjs → cloudflare-cmd-DsSlXbNy.mjs} +5 -5
  36. package/dist/{cloudflare-config-D9UFH_A5.mjs → cloudflare-config-KPHKf57C.mjs} +2 -2
  37. package/dist/{cloudflare-connect-BgpHcSg3.mjs → cloudflare-connect-bEtneBjT.mjs} +5 -4
  38. package/dist/{cloudflare-operations-ByjFGats.mjs → cloudflare-operations-BmICrRnm.mjs} +1 -1
  39. package/dist/{cloudflare-operations-BIRQkYwL.mjs → cloudflare-operations-D-9psgPQ.mjs} +19 -11
  40. package/dist/cloudflare-preview-8eLSQPdO.mjs +1 -0
  41. package/dist/cloudflare-preview-BaeU-m74.mjs +112 -0
  42. package/dist/{cloudflare-process-60r4Z2Zf.mjs → cloudflare-process-DFNpqV_m.mjs} +57 -29
  43. package/dist/cloudflare-user-output-DFbD0l4l.mjs +36 -0
  44. package/dist/collect-Aam0GwAU.mjs +1 -0
  45. package/dist/{collect-rNLybAnF.mjs → collect-KC4cizWM.mjs} +6 -1
  46. package/dist/{config-DA6ZbLXO.d.mts → config-BdmM5ZzP.d.mts} +12 -2
  47. package/dist/{config-BFX5ZB1J.mjs → config-CUYGZqdN.mjs} +2 -2
  48. package/dist/{config-BSoW3QCB.mjs → config-C_UjzkVS.mjs} +3 -3
  49. package/dist/{config-DtjrUtPo.mjs → config-Ge-MytMU.mjs} +1 -1
  50. package/dist/{config-Dv5jri1-.mjs → config-KZAiI3gG.mjs} +32 -6
  51. package/dist/config-entry.d.mts +1 -1
  52. package/dist/config-write-dKLINlm2.mjs +80 -0
  53. package/dist/{connect-WG4TcR_d.mjs → connect-Bqq3b9sX.mjs} +10 -9
  54. package/dist/{create-project-CbuDH5Hv.mjs → create-project-MXoP_rte.mjs} +1 -1
  55. package/dist/{create-project-8FdN6D2i.mjs → create-project-T-9AIQDe.mjs} +7 -6
  56. package/dist/{db-BSuWV1PI.mjs → db-B3eoVDNA.mjs} +50 -47
  57. package/dist/{db-args-CiQVg8SJ.mjs → db-args-BcvTZ8KE.mjs} +1 -1
  58. package/dist/db-args-Cx1y4vZn.mjs +1 -0
  59. package/dist/{db-types-B4Cf9dzR.mjs → db-types-BpgXVtQZ.mjs} +1 -1
  60. package/dist/{delete-WtLEfap2.mjs → delete-Cf6SroAw.mjs} +7 -6
  61. package/dist/deploy-DZ9j7MC4.mjs +2 -0
  62. package/dist/{deploy-DtJeunLF.mjs → deploy-UojYUEWr.mjs} +803 -1415
  63. package/dist/{deploy-managed-static-BWBsxOww.mjs → deploy-managed-static-DV_OmTWf.mjs} +54 -393
  64. package/dist/{deploy-security-notice-IRGy6Edf.mjs → deploy-security-notice-3jX71IeP.mjs} +6 -4
  65. package/dist/deploy-summary-Dkl0zvQy.mjs +377 -0
  66. package/dist/{deploy-transport-BKP_oV9q.mjs → deploy-transport-4ISWxx8n.mjs} +4 -3
  67. package/dist/deploy.mjs +14 -10
  68. package/dist/discover-BZWVWeQs.mjs +1 -0
  69. package/dist/{discover-IcspacCg.mjs → discover-BeFs7OPS.mjs} +1 -1
  70. package/dist/{dispatch-DIhDA3NI.mjs → dispatch-BUKbPdqb.mjs} +7 -7
  71. package/dist/{dist-Cr_xGE_K.mjs → dist-BngS28id.mjs} +6 -6
  72. package/dist/{dist-C47zy_kJ.mjs → dist-x99fIj4n.mjs} +1 -1
  73. package/dist/{domain-mweyYXSw.mjs → domain-BK6NWkWK.mjs} +7 -7
  74. package/dist/{drizzle-BJDMPrj7.mjs → drizzle-CnSbVeiZ.mjs} +12 -13
  75. package/dist/{drizzle-CQ5jWuDL.mjs → drizzle-CrkwVwK8.mjs} +1 -1
  76. package/dist/{email-DoDqRH6i.mjs → email-BBSDV0J5.mjs} +13 -12
  77. package/dist/{email-cloudflare-DeYH3Ke7.mjs → email-cloudflare-C-guKEbz.mjs} +10 -8
  78. package/dist/{env-DaAoYR2-.mjs → env-BVnKiGYJ.mjs} +8 -8
  79. package/dist/{env-EjHqc7m9.mjs → env-CU2tMDdO.mjs} +6 -1
  80. package/dist/{env-types-D2hBodXP.mjs → env-types-B33fEHRH.mjs} +1 -1
  81. package/dist/{env-validation-j9pjCDfA.mjs → env-validation-BnAsx6gz.mjs} +1 -1
  82. package/dist/{env-validation-D-v5_CWL.mjs → env-validation-SXsjd6-Z.mjs} +4 -4
  83. package/dist/{fetch-CiEsvjpP.mjs → fetch-DL7OCgwB.mjs} +1 -1
  84. package/dist/{fetch-stream-BIG5lHW6.mjs → fetch-stream-DEilLTCc.mjs} +2 -2
  85. package/dist/{gen-aOtHhZLD.mjs → gen-BxuIN1bz.mjs} +10 -9
  86. package/dist/gen-DaayFP9v.mjs +1 -0
  87. package/dist/{generate-Dq2Bgw75.mjs → generate-Ck-L3e0e.mjs} +1 -1
  88. package/dist/{generate-C3ZAqCy-.mjs → generate-t1dDUYZZ.mjs} +1 -1
  89. package/dist/{github-cmd-BR19Ffdz.mjs → github-cmd-B7U9Hjmi.mjs} +7 -6
  90. package/dist/{handler-DCrDLzw2.mjs → handler-2wAywJgj.mjs} +11 -9
  91. package/dist/{headers-DqBsjDxg.mjs → headers-DPI4MDGC.mjs} +1 -1
  92. package/dist/{help-DvClCzqL.mjs → help-Bgiu5PMX.mjs} +36 -4
  93. package/dist/help-DWGHmt_n.mjs +1 -0
  94. package/dist/html-5sfGLjiI.d.mts +3 -0
  95. package/dist/html-DPSOBDCh.mjs +1 -0
  96. package/dist/{index-Dn2mkPr2.d.mts → index-CqF8_p9C.d.mts} +5 -105
  97. package/dist/index-Cvqotnhc.d.mts +91 -0
  98. package/dist/{index-BQ5qYiAw.d.mts → index-DAinHkj8.d.mts} +1 -1
  99. package/dist/{index-8cAgNdb6.d.mts → index-lnEWwVAS.d.mts} +1 -1
  100. package/dist/index.d.mts +3 -2
  101. package/dist/index.mjs +536 -170
  102. package/dist/{info-P6MBiVJi.mjs → info-7COlpAfY.mjs} +32 -20
  103. package/dist/{init-B2VZ2Hut.mjs → init-DftAx3L4.mjs} +237 -88
  104. package/dist/input-jcps6lAn.mjs +64 -0
  105. package/dist/interactive-prompts-EK0dilFu.mjs +43 -0
  106. package/dist/{limits-BCoQLpn3.mjs → limits-3I3VdX2E.mjs} +4 -1
  107. package/dist/{link-Dyz9IGcM.mjs → link-C3WMNFTG.mjs} +7 -7
  108. package/dist/{list-VGYBMjmx.mjs → list-K4EGVUZN.mjs} +9 -9
  109. package/dist/{load-user-env-B8qC0Q2Y.mjs → load-user-env-uMmQJ-Th.mjs} +1 -1
  110. package/dist/{local-d1-CYOYkVwO.mjs → local-d1-BtLCVC1p.mjs} +2 -2
  111. package/dist/login-BJwPhV_S.mjs +1 -0
  112. package/dist/{login-jUBgfvzk.mjs → login-DaugBfBG.mjs} +6 -5
  113. package/dist/{logs-kS1wuR4b.mjs → logs-BR2szdN5.mjs} +6 -6
  114. package/dist/migrate-BHD46A31.mjs +1 -0
  115. package/dist/{migrate-BNZL1hee.mjs → migrate-Dtlg8fC6.mjs} +7 -7
  116. package/dist/nitro.mjs +3 -3
  117. package/dist/{node-DVJWfV6s.mjs → node-BbKlLpHa.mjs} +5 -5
  118. package/dist/{operator-ai-logging-DD0n6zc2.mjs → operator-ai-logging-4Nvs6Ut3.mjs} +5 -5
  119. package/dist/{operator-args-nvetCWuz.mjs → operator-args-DWvqq3Ws.mjs} +31 -15
  120. package/dist/{operator-auth-DMvn-y9X.mjs → operator-auth-DtRMGXYY.mjs} +2 -2
  121. package/dist/{operator-client-dFNnXfyB.mjs → operator-client-BG0VIMMM.mjs} +2 -2
  122. package/dist/operator-cmd-CR3Q9k4c.mjs +1 -0
  123. package/dist/{operator-cmd-wML5HNfS.mjs → operator-cmd-D4YcMKO-.mjs} +9 -9
  124. package/dist/{operator-security-D5MToU0p.mjs → operator-security-nVLo8vDt.mjs} +11 -5
  125. package/dist/{output-BZLnu0z8.mjs → output-DhJgS6Ve.mjs} +1 -1
  126. package/dist/output-OYwcEwok.mjs +1 -0
  127. package/dist/pages/client.d.mts +34 -20
  128. package/dist/pages/client.mjs +172 -74
  129. package/dist/pages/index.d.mts +11 -4
  130. package/dist/pages/index.mjs +5 -5
  131. package/dist/pages/islands-plugin.d.mts +2 -2
  132. package/dist/pages/islands-plugin.mjs +5 -3
  133. package/dist/pages/protocol.d.mts +3 -3
  134. package/dist/pages/protocol.mjs +3 -3
  135. package/dist/pages/serialize.d.mts +2 -2
  136. package/dist/pages/serialize.mjs +1 -1
  137. package/dist/parse-filename-DIPUjoCh.d.mts +2 -0
  138. package/dist/platform-C3Q44RJ8.mjs +250 -0
  139. package/dist/platform-args-BSyVZESg.mjs +1 -0
  140. package/dist/{platform-args-CvZSuhYS.mjs → platform-args-BnocJDC_.mjs} +1 -1
  141. package/dist/{platform-auth-config-Bv3oQ2gE.mjs → platform-auth-config-BbfNhjBc.mjs} +9 -9
  142. package/dist/{platform-auth-protection-OqzfhXwx.mjs → platform-auth-protection-BHPV4MUf.mjs} +9 -8
  143. package/dist/{platform-auth-recovery-rmIYjXST.mjs → platform-auth-recovery-DE0nArYy.mjs} +8 -7
  144. package/dist/{platform-cmd-D_4z2Ijv.mjs → platform-cmd-CLRU3BRb.mjs} +11 -10
  145. package/dist/{platform-cmd-B3rO4RhU.mjs → platform-cmd-Cs2LkT5L.mjs} +1 -1
  146. package/dist/{platform-discovery-CLxtixHJ.mjs → platform-discovery-CKeeeD82.mjs} +1 -1
  147. package/dist/{platform-domain-CUq9odbd.mjs → platform-domain-kn3WuKPG.mjs} +6 -5
  148. package/dist/{platform-lifecycle-DOSYo0UI.mjs → platform-lifecycle-BoCEYy2w.mjs} +1 -1
  149. package/dist/{platform-lifecycle-DuoVruij.mjs → platform-lifecycle-CKwOg8wz.mjs} +164 -72
  150. package/dist/{platform-management-D_gt3qLb.mjs → platform-management-CaSdFthX.mjs} +1 -1
  151. package/dist/{platform-management-MmO9IubR.mjs → platform-management-fyrsq2Ra.mjs} +27 -14
  152. package/dist/{platform-plans-config-DiydtNKY.mjs → platform-plans-config-BSI-6Inu.mjs} +11 -5
  153. package/dist/{platform-recovery-P_FVslfd.mjs → platform-recovery-PwJ54AIZ.mjs} +3 -3
  154. package/dist/{platform-registry-DHH6fivm.mjs → platform-registry-zHH3RiIm.mjs} +2 -1
  155. package/dist/{platform-setup-Lph9i-rh.mjs → platform-setup-DwYITHfY.mjs} +3 -3
  156. package/dist/{plugin-inference-COlq96WJ.mjs → plugin-inference-D5MjBVMB.mjs} +60 -142
  157. package/dist/prepare-CLl_TA_r.mjs +1 -0
  158. package/dist/{prepare-WvijE289.mjs → prepare-DZEs5AGr.mjs} +3 -3
  159. package/dist/{prepare-co1o1FFd.mjs → prepare-DhVzN7CB.mjs} +14 -12
  160. package/dist/{project-uXKua1it.mjs → project-BXpm-vgG.mjs} +1 -1
  161. package/dist/{project-dh9431bN.mjs → project-DC-BqHef.mjs} +1 -1
  162. package/dist/{project-cmd-BWJTplpc.mjs → project-cmd-BKN3qT4R.mjs} +31 -21
  163. package/dist/{project-paths-2ENfCCih.mjs → project-paths-BeAxxqGh.mjs} +1 -1
  164. package/dist/{project-security-BV1xfj1K.mjs → project-security-B-SHxprt.mjs} +1 -1
  165. package/dist/{project-security-CY_aahvW.mjs → project-security-BWTd6cTU.mjs} +87 -46
  166. package/dist/{project-team-BlIFXlmT.mjs → project-team-jcn9reIB.mjs} +6 -6
  167. package/dist/{project-token-CMsB7I1-.mjs → project-token-BHkBKtzt.mjs} +6 -6
  168. package/dist/{project-tsconfig-BOA4ym99.mjs → project-tsconfig-LjgxDdj_.mjs} +1 -1
  169. package/dist/{project-zero-trust-BI6pdpx4.mjs → project-zero-trust-2t_qI6xa.mjs} +4 -4
  170. package/dist/{protocol-4rEnumif.mjs → protocol-DhMbnxzy.mjs} +120 -35
  171. package/dist/{protocol-ERy-n3jf.d.mts → protocol-wG7JP5Mm.d.mts} +27 -4
  172. package/dist/{provision-DFv7SJDn.mjs → provision-C04aXE3a.mjs} +1 -1
  173. package/dist/{provision-Bh44omGA.mjs → provision-CQykn8gu.mjs} +8 -4
  174. package/dist/{redirect-Dyvuil0Q.mjs → redirect-DjyA_hx_.mjs} +1 -1
  175. package/dist/{requests-CfmJxNYg.mjs → requests-BznxnxTT.mjs} +5 -5
  176. package/dist/resolve-project-Bob_rEi2.mjs +1 -0
  177. package/dist/{resolve-project-8WZ3iVmr.mjs → resolve-project-s_FGWyr-.mjs} +2 -2
  178. package/dist/resource-binding-5nI30acw.mjs +20 -0
  179. package/dist/{resource-name-DlJ9QXzg.mjs → resource-name-D_gw36kh.mjs} +5 -1
  180. package/dist/{rollback-DL5HuAsM.mjs → rollback-CLiINtpt.mjs} +25 -14
  181. package/dist/{route-types-CSed9-Dp.mjs → route-types-DxvqN5bL.mjs} +59 -9
  182. package/dist/{route-url-B41eQ8QI.mjs → route-url-CRC8yR_2.mjs} +2 -3
  183. package/dist/{route-url-Bd6IX-JZ.d.mts → route-url-zDfC-7DD.d.mts} +33 -5
  184. package/dist/routes-stub.d.mts +18 -2
  185. package/dist/routes-stub.mjs +1 -1
  186. package/dist/{runner-CeguHWJx.mjs → runner-CnUrhc8H.mjs} +1 -1
  187. package/dist/{runner-mysql-DOjbj-N1.mjs → runner-mysql-CW6bFa67.mjs} +1 -1
  188. package/dist/{runner-mysql-D549vGGm.mjs → runner-mysql-DSLGFOlC.mjs} +1 -1
  189. package/dist/{runner-pg-Buzw17hl.mjs → runner-pg-BcGF7iBR.mjs} +1 -1
  190. package/dist/{runner-pg-DMJquR3d.mjs → runner-pg-OeP0JpEo.mjs} +1 -1
  191. package/dist/{runner-Bf94YVJK.mjs → runner-rnXCGa20.mjs} +1 -1
  192. package/dist/runtime/ai/index.mjs +1 -1
  193. package/dist/runtime/auth/better-auth-d1.d.mts +1 -1
  194. package/dist/runtime/auth/better-auth-mysql.d.mts +1 -1
  195. package/dist/runtime/auth/better-auth-postgres.d.mts +1 -1
  196. package/dist/runtime/client/fetch-server.mjs +1 -1
  197. package/dist/runtime/client/fetch-stream.mjs +1 -1
  198. package/dist/runtime/client/fetch.mjs +1 -1
  199. package/dist/runtime/client/index.mjs +2 -2
  200. package/dist/runtime/client/react.mjs +2 -2
  201. package/dist/runtime/client/solid.mjs +2 -2
  202. package/dist/runtime/client/svelte.mjs +2 -2
  203. package/dist/runtime/client/vue.mjs +2 -2
  204. package/dist/runtime/durable/index.mjs +11 -26
  205. package/dist/runtime/env/runtime.d.mts +2 -10
  206. package/dist/runtime/handler/index.d.mts +3 -2
  207. package/dist/runtime/handler/index.mjs +2 -2
  208. package/dist/runtime/handler/validator.d.mts +1 -1
  209. package/dist/runtime/handler/validator.mjs +1 -1
  210. package/dist/runtime/html.d.mts +2 -0
  211. package/dist/runtime/html.mjs +1 -0
  212. package/dist/runtime/image/index.d.mts +103 -0
  213. package/dist/runtime/image/index.mjs +89 -0
  214. package/dist/runtime/jsx/index.d.mts +3 -0
  215. package/dist/runtime/jsx/index.mjs +2 -0
  216. package/dist/runtime/jsx/jsx-dev-runtime.d.mts +1 -0
  217. package/dist/runtime/jsx/jsx-dev-runtime.mjs +2 -0
  218. package/dist/runtime/jsx/jsx-runtime.d.mts +1 -0
  219. package/dist/runtime/jsx/jsx-runtime.mjs +2 -0
  220. package/dist/runtime/limits/index.mjs +1 -1
  221. package/dist/runtime/live/client.d.mts +2 -2
  222. package/dist/runtime/live/index.d.mts +1 -1
  223. package/dist/runtime/routing/index.d.mts +87 -4
  224. package/dist/runtime/routing/index.mjs +59 -20
  225. package/dist/runtime/routing/route-url.d.mts +2 -2
  226. package/dist/runtime/routing/route-url.mjs +1 -1
  227. package/dist/runtime/sandbox/index.mjs +1 -1
  228. package/dist/runtime/sse/client.d.mts +1 -1
  229. package/dist/runtime/workflows/entry.d.mts +8 -0
  230. package/dist/runtime/workflows/entry.mjs +49 -0
  231. package/dist/runtime/workflows/index.d.mts +3 -0
  232. package/dist/runtime/workflows/index.mjs +77 -0
  233. package/dist/runtime/ws/index.d.mts +1 -1
  234. package/dist/runtime/ws/index.mjs +2 -2
  235. package/dist/runtime/ws/room.d.mts +1 -1
  236. package/dist/runtime/ws/server.d.mts +2 -2
  237. package/dist/runtime-Db72hLY-.d.mts +11 -0
  238. package/dist/scan-BxhB4BA-.mjs +946 -0
  239. package/dist/scan-D2ISAobj.mjs +308 -0
  240. package/dist/{secret-C-WBaUSS.mjs → secret-Ck9N5xbU.mjs} +9 -8
  241. package/dist/{security-sarif-ClyYwtAW.mjs → security-sarif-DzTIqNwZ.mjs} +1 -1
  242. package/dist/{serialize-DN-envGQ.d.mts → serialize-Dr9B-0yV.d.mts} +10 -1
  243. package/dist/{serialize-BmB4BfKu.mjs → serialize-nW4IeEBI.mjs} +23 -2
  244. package/dist/{skills-C-csz78e.mjs → skills-BR7YHAF7.mjs} +1 -1
  245. package/dist/{scan-Ct_SEzH4.mjs → source-analysis-cache-Ccm_JSOl.mjs} +340 -902
  246. package/dist/standard-schema-DvMcZGMK.mjs +8 -0
  247. package/dist/{subcommand-prompt-B4LOLosl.mjs → subcommand-prompt-AFf2LcrC.mjs} +2 -2
  248. package/dist/{types-FDH6NuY1.d.mts → types-RYVujNS6.d.mts} +4 -2
  249. package/dist/{version-metadata-DqgLa6gc.mjs → untrusted-env-4oW0TdBP.mjs} +1 -23
  250. package/dist/{url-DBQluotE.mjs → url-DAQ1c3lh.mjs} +45 -1
  251. package/dist/{validate-CtBWCzez.mjs → validate-B1PsQ_mt.mjs} +1 -1
  252. package/dist/validate-p9b3r1k4.mjs +1 -0
  253. package/dist/{validation-error-CtcAvyI7.mjs → validation-error-EKI0wMWX.mjs} +2 -2
  254. package/dist/{validator-Dfh9kCDm.mjs → validator-JJcf9E48.mjs} +5 -8
  255. package/dist/version-metadata-CEla0kgi.mjs +23 -0
  256. package/dist/{wrangler-DVe5KV5G.mjs → wrangler-AyMfdVJK.mjs} +34 -69
  257. package/dist/wrangler-BT7qrzWc.mjs +1 -0
  258. package/dist/{wrapper-CcMYpOS8.mjs → wrapper-DPlTBVOx.mjs} +5 -5
  259. package/docs/guide/ai.md +1 -1
  260. package/docs/guide/app-types.md +6 -23
  261. package/docs/guide/auth.md +2 -4
  262. package/docs/guide/database/d1.md +21 -67
  263. package/docs/guide/database/mysql.md +8 -0
  264. package/docs/guide/database/postgresql.md +2 -2
  265. package/docs/guide/database.md +1 -1
  266. package/docs/guide/deployment.md +18 -0
  267. package/docs/guide/edge/prerendering.md +3 -7
  268. package/docs/guide/edge/redirects.md +1 -1
  269. package/docs/guide/edge/revalidation.md +8 -17
  270. package/docs/guide/edge/rewrites.md +1 -1
  271. package/docs/guide/edge/static-assets.md +10 -22
  272. package/docs/guide/email/domains.md +3 -1
  273. package/docs/guide/email/receiving.md +2 -2
  274. package/docs/guide/email/sending.md +3 -1
  275. package/docs/guide/env-vars.md +2 -0
  276. package/docs/guide/image-generation.md +142 -0
  277. package/docs/guide/index.md +17 -15
  278. package/docs/guide/jobs.md +2 -4
  279. package/docs/guide/kv.md +1 -1
  280. package/docs/guide/og-images.md +83 -0
  281. package/docs/guide/pages-routing/actions-and-forms.md +6 -4
  282. package/docs/guide/pages-routing/errors.md +20 -4
  283. package/docs/guide/pages-routing/head.md +5 -5
  284. package/docs/guide/pages-routing/islands.md +4 -14
  285. package/docs/guide/pages-routing/markdown.md +2 -2
  286. package/docs/guide/pages-routing/overview.md +129 -15
  287. package/docs/guide/platform/administration/plans.md +47 -16
  288. package/docs/guide/platform/administration/projects.md +10 -0
  289. package/docs/guide/platform/administration/security-audits.md +76 -30
  290. package/docs/guide/platform/administration/zero-trust.md +1 -1
  291. package/docs/guide/platform/installation/ci.md +0 -4
  292. package/docs/guide/platform/installation/credentials.md +1 -1
  293. package/docs/guide/platform/installation/maintenance.md +10 -10
  294. package/docs/guide/platform/installation/prerequisites.md +3 -1
  295. package/docs/guide/platform/installation/setup.md +7 -15
  296. package/docs/guide/platform/installation/uninstall.md +6 -12
  297. package/docs/guide/project-collaboration.md +1 -4
  298. package/docs/guide/queues.md +6 -8
  299. package/docs/guide/quickstart.md +6 -8
  300. package/docs/guide/sandboxes.md +1 -1
  301. package/docs/guide/self-hosted-platform.md +4 -7
  302. package/docs/guide/server-routing.md +5 -3
  303. package/docs/guide/ssg.md +1 -1
  304. package/docs/guide/type-safety.md +74 -10
  305. package/docs/guide/websockets.md +5 -7
  306. package/docs/guide/workflows.md +122 -0
  307. package/docs/index.md +2 -3
  308. package/docs/integrations/agents.md +3 -16
  309. package/docs/integrations/cloudflare.md +98 -2
  310. package/docs/integrations/frameworks/analog.md +9 -11
  311. package/docs/integrations/frameworks/astro.md +16 -17
  312. package/docs/integrations/frameworks/nuxt.md +11 -13
  313. package/docs/integrations/frameworks/overview.md +18 -20
  314. package/docs/integrations/frameworks/react-router.md +55 -6
  315. package/docs/integrations/frameworks/sveltekit.md +8 -6
  316. package/docs/integrations/frameworks/tanstack-start.md +10 -6
  317. package/docs/integrations/hono.md +27 -12
  318. package/docs/integrations/nodejs-bun-deno.md +10 -2
  319. package/docs/reference/api/database.md +8 -10
  320. package/docs/reference/api/env.md +2 -2
  321. package/docs/reference/api/handlers.md +1 -1
  322. package/docs/reference/api/html.md +45 -0
  323. package/docs/reference/api/pages.md +118 -167
  324. package/docs/reference/api/rewrites.md +5 -5
  325. package/docs/reference/api/types.md +13 -6
  326. package/docs/reference/api/workflows.md +48 -0
  327. package/docs/reference/api.md +7 -1
  328. package/docs/reference/cli/database.md +22 -10
  329. package/docs/reference/cli/deploy.md +49 -4
  330. package/docs/reference/cli/domains.md +7 -3
  331. package/docs/reference/cli/email.md +3 -1
  332. package/docs/reference/cli/platform-installation.md +9 -53
  333. package/docs/reference/cli/platform-security.md +36 -8
  334. package/docs/reference/cli/platform-users.md +11 -1
  335. package/docs/reference/cli/platform-zero-trust.md +1 -1
  336. package/docs/reference/cli/project.md +52 -11
  337. package/docs/reference/cli/setup.md +8 -10
  338. package/docs/reference/cli.md +49 -47
  339. package/docs/reference/config.md +22 -8
  340. package/docs/reference/resource-inference.md +8 -1
  341. package/docs/reference/structure.md +5 -0
  342. package/package.json +52 -25
  343. package/schema.json +20 -1
  344. package/skills/void/SKILL.md +60 -54
  345. package/dist/cf-build-output-Wpk_e5CI.mjs +0 -1
  346. package/dist/cf-worker-settings-BBdlhm9U.mjs +0 -41
  347. package/dist/cli/db-execute-process.d.mts +0 -2
  348. package/dist/cli/db-execute-process.mjs +0 -57
  349. package/dist/cloudflare-user-output-CCR99eQY.mjs +0 -19
  350. package/dist/collect-B6nlSnsb.mjs +0 -1
  351. package/dist/db-args-BvMwAber.mjs +0 -1
  352. package/dist/deploy-GT4CW5fs.mjs +0 -2
  353. package/dist/discover-D2KGP3cR.mjs +0 -1
  354. package/dist/entry-Bwb9ev8K.mjs +0 -113
  355. package/dist/gen-vhBDHs3q.mjs +0 -1
  356. package/dist/help-fKPzcTJv.mjs +0 -1
  357. package/dist/isr-config-DiTnL9Tb.mjs +0 -115
  358. package/dist/login-BbSQTZ6d.mjs +0 -1
  359. package/dist/migrate-C9aoWLvY.mjs +0 -1
  360. package/dist/operator-cmd-jnjzuJKX.mjs +0 -1
  361. package/dist/output-D7K9TWIA.mjs +0 -1
  362. package/dist/platform-args-CMwMoiLp.mjs +0 -1
  363. package/dist/prepare-DcwigRUS.mjs +0 -1
  364. package/dist/providers-D5P8j_8D.d.mts +0 -5
  365. package/dist/resolve-project-YsTH-U9I.mjs +0 -1
  366. package/dist/static-exports-s7P86Ngp.mjs +0 -354
  367. package/dist/validate-CZYUIfR-.mjs +0 -1
  368. package/dist/wrangler-Dq269bjx.mjs +0 -1
  369. package/docs/guide/platform/development/local.md +0 -120
  370. package/docs/guide/platform/development/runtime.md +0 -115
  371. package/docs/guide/platform/development/schema-ci.md +0 -44
  372. package/docs/guide/platform-development.md +0 -16
@@ -1,59 +1,66 @@
1
1
  import { n as __toESM } from "./rolldown-runtime-uD8oG6U2.mjs";
2
- import { A as confirm, K as select, L as log, tt as isCancel } from "./dist-Cr_xGE_K.mjs";
3
- import { a as join, c as resolve, n as dirname, o as normalize, r as extname, s as relative, t as basename } from "./dist-DMYe8CZJ.mjs";
4
- import { a as persistCloudflareConfig, c as stashCloudflareDeployPointer, i as materializeCloudflareConfig } from "./cloudflare-config-D9UFH_A5.mjs";
5
- import { m as resolveBindingNames, p as readConfig, r as convertHeadersConfig, u as isNodeTarget } from "./config-Dv5jri1-.mjs";
6
- import { r as detectFramework } from "./plugin-inference-COlq96WJ.mjs";
2
+ import { a as join, c as resolve, n as dirname, o as normalize, s as relative, t as basename } from "./dist-DMYe8CZJ.mjs";
3
+ import { a as persistCloudflareConfig, c as stashCloudflareDeployPointer, i as materializeCloudflareConfig, n as VOID_LOCK_FILE, r as ignoreMaterializedCloudflareConfig, t as MATERIALIZED_CLOUDFLARE_FILE } from "./cloudflare-config-KPHKf57C.mjs";
4
+ import { d as isNodeTarget, g as resolveBindingNames, h as readConfig, r as convertHeadersConfig } from "./config-KZAiI3gG.mjs";
5
+ import { r as detectFramework } from "./plugin-inference-D5MjBVMB.mjs";
7
6
  import { t as hasOwnKey } from "./has-own-key-D9QEnAkF.mjs";
8
- import { a as buildEnv, i as WRANGLER_AUTH_CREDENTIAL_ENV_VARS, n as readVersionMetadataBinding, r as selectNativeVersionMetadataBinding, t as CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from "./version-metadata-DqgLa6gc.mjs";
9
- import { a as getApiUrl, c as getToken, l as getTokenSource } from "./auth-CqwJwItO.mjs";
10
- import { a as isExpiredTokenError, r as PlatformClient } from "./client-DE2m2ldh.mjs";
7
+ import { n as buildEnv, t as WRANGLER_AUTH_CREDENTIAL_ENV_VARS } from "./untrusted-env-4oW0TdBP.mjs";
8
+ import { a as collectRevalidate, c as resolveDistDir, l as resolveWorkerDirName, n as managedWorkflowDefinitions, o as hasRevalidate, r as planWorkflows, t as FRAMEWORK_WORKFLOWS_ERROR } from "./platform-C3Q44RJ8.mjs";
9
+ import { c as validateSsrEntry, r as scanWorkflowModules } from "./scan-D2ISAobj.mjs";
10
+ import { a as getApiUrl, c as getToken, l as getTokenSource } from "./auth-CeBmolb-.mjs";
11
+ import { a as isExpiredTokenError, r as PlatformClient } from "./client-BEHI4UWn.mjs";
12
+ import { i as renderDeploySeedConfig, o as writeVoidProjectConfig, r as isUnchangedDeploySeed } from "./config-write-dKLINlm2.mjs";
11
13
  import { t as writeFileAtomic } from "./atomic-write-DA6eD1Kp.mjs";
12
- import { r as discoverFrameworkWranglerFiles, t as migrateLegacyVoidConfig } from "./migrate-BNZL1hee.mjs";
13
- import { c as writeDeploymentPlatform, n as readDeploymentPlatform, r as readProjectConfig } from "./project-dh9431bN.mjs";
14
- import { a as FRAMEWORK_PRESETS, c as hasBackendFiles, i as isCleanCloudflareExit, l as resolveCloudflareOperationArgv, o as detectPreset, s as formatProjectCommand, t as createCloudflareProcessRunner, u as resolveProjectCommand } from "./cloudflare-process-60r4Z2Zf.mjs";
14
+ import { r as discoverFrameworkWranglerFiles, t as migrateLegacyVoidConfig } from "./migrate-Dtlg8fC6.mjs";
15
+ import { a as select, n as confirm } from "./interactive-prompts-EK0dilFu.mjs";
16
+ import { c as writeDeploymentPlatform, n as readDeploymentPlatform, r as readProjectConfig } from "./project-DC-BqHef.mjs";
17
+ import { a as FRAMEWORK_PRESETS, c as formatProjectCommand, d as resolveCloudflareOperationArgv, f as resolveProjectCommand, i as isCleanCloudflareExit, l as hasBackendFiles, s as detectPreset, t as createCloudflareProcessRunner, u as isStaticAppType } from "./cloudflare-process-DFNpqV_m.mjs";
15
18
  import { n as redactMessage } from "./env-mask-D31Qztl9.mjs";
16
- import { a as assertSandboxNamespaceConfig, c as resolveSandboxConfig, d as hasEmailHandlers, i as SANDBOX_MIGRATION_TAG, l as sandboxContainerConfig, o as hasSandboxSqliteMigration, s as requiresSandboxPlatformImage, t as analyzeApplicationSync } from "./application-analysis-DVeN8yoi.mjs";
17
- import { A as syncWranglerWebSockets, C as readWranglerManagedQueueCleanupCandidates, D as sameMigrationsDir, E as resolveLiveBindingConfig, L as writeVoidProjectConfig, M as writeProvisionedWranglerConfig, N as writeWranglerPublishedTrafficSnapshot, a as LIVE_MIGRATION_TAG, c as bindingEntriesForField, h as nextDurableObjectMigrationTag, k as syncWranglerDurableObjects, m as hasDurableObjectSqliteMigration, o as acknowledgeWranglerManagedQueueRemovals, r as FRIENDLY_BINDING_NAMES, v as readExistingLiveBindingConfig, w as readWranglerPublishedTrafficSnapshot } from "./wrangler-DVe5KV5G.mjs";
18
- import { A as promptDeployProjectConfig, C as ensureManagedHyperdrive, D as hasNonPageBackend, E as getGitCommit, F as resolveStaticBuildCommand, I as resolveStaticDeployPreset, L as toManifestSchedulesAndQueues, M as resolveDeployWorkerMain, N as resolveDeployWranglerCompat, O as hasPrerenderSources, P as resolveFullDeployBuildCommand, R as validateDeployMigrations, S as createProjectFromSlug, T as getExitCode, _ as getDeploySchemaDriftMessage, a as collectAndHashAssets, b as assertProjectDeployAccess, c as readWranglerHtmlHandling, d as printDeploySuccess, f as mergeAndLintRoutingRules, g as assertDeploySchemaDriftFree, h as warnUnpublishedRouting, i as buildStaticManifest, j as resolveDeployLiveBindingConfig, k as log$1, l as formatDeploySummary, m as warnIgnoredNotFoundForFramework, n as runStaticDeploy, o as collectWorkerFiles, p as streamDirectR2Deploy, r as buildFrameworkManifest, s as detectNonSpaFallbackWarning, t as assembleVoidManifest, u as printDeployContext, v as hasDeploySchemaDrift, w as generateDeployWrapperIfNeeded, x as assertWorkerMainUploaded, y as assertEnvSchemaValid } from "./deploy-managed-static-BWBsxOww.mjs";
19
- import { n as completeApplicationAnalysis, t as analyzeApplication } from "./application-routing-KKw4Y84h.mjs";
20
- import { a as resolveDistDir, n as collectRevalidate, o as resolveWorkerDirName, r as hasRevalidate } from "./isr-config-DiTnL9Tb.mjs";
21
- import { i as otherQueueConsumers, n as chooseCloudflareQueueName, o as scopedCloudflareQueueName, r as cloudflareQueueName } from "./dispatch-DIhDA3NI.mjs";
22
- import { a as checkCloudflareProvisionDrift, d as isRealD1Id, h as provisionCloudflareResources, i as assertValidResourceName, p as isRealKvId, s as deleteEnvVarCaseAware, u as isQueueConfirmedAbsent, y as resolveWorkersDevComplianceRegion } from "./provision-Bh44omGA.mjs";
23
- import { c as scrubWranglerAuthCredentials, n as buildSchemaProbeEnv, o as resolveDeployTransport, r as deployChildEnv, s as scrubManagedDeployBuildMarkers, t as MANAGED_DEPLOY_BUILD_ENV } from "./deploy-transport-BKP_oV9q.mjs";
24
- import { f as listSelfHostSecretNames, h as selfHostSchemaFailureMessage, i as SelfHostSecretListError, l as dischargeSelfHostEnvContext, n as SelfHostFirstDeployError, p as readEmittedWorkerVars, r as SelfHostSchemaError, s as deriveSelfHostEnvContextFromVars, t as SelfHostEnvValidationError } from "./env-validation-D-v5_CWL.mjs";
19
+ import { n as readProjectPaths, o as LEGACY_CONFIG_FILE, s as TYPED_CONFIG_FILE, t as assertNoRootSourceConventionConflicts } from "./project-paths-BeAxxqGh.mjs";
20
+ import { C as toManifestSchedulesAndQueues, S as resolveStaticDeployPreset, _ as resolveDeployLiveBindingConfig, a as assertEnvSchemaValid, b as resolveFullDeployBuildCommand, c as createProjectFromSlug, d as getExitCode, f as getGitCommit, g as promptDeployProjectConfig, h as log, l as ensureManagedHyperdrive, m as hasPrerenderSources, n as printDeployContext, o as assertProjectDeployAccess, p as hasNonPageBackend, r as printDeploySuccess, s as assertWorkerMainUploaded, t as formatDeploySummary, u as generateDeployWrapperIfNeeded, v as resolveDeployWorkerMain, w as validateDeployMigrations, x as resolveStaticBuildCommand, y as resolveDeployWranglerCompat } from "./deploy-summary-Dkl0zvQy.mjs";
21
+ import { n as completeApplicationAnalysis, t as analyzeApplication } from "./application-routing-COCfD2yc.mjs";
22
+ import { i as otherQueueConsumers, n as chooseCloudflareQueueName, o as scopedCloudflareQueueName, r as cloudflareQueueName } from "./dispatch-BUKbPdqb.mjs";
23
+ import { a as assertSandboxNamespaceConfig, c as resolveSandboxConfig, d as hasEmailHandlers, i as SANDBOX_MIGRATION_TAG, l as sandboxContainerConfig, o as hasSandboxSqliteMigration, s as requiresSandboxPlatformImage, t as analyzeApplicationSync } from "./application-analysis-BjEwHTV2.mjs";
24
+ import { C as readWranglerPublishedTrafficSnapshot, E as sameMigrationsDir, M as writeWranglerPublishedTrafficSnapshot, N as DEFAULT_WORKER_COMPAT_DATE, O as syncWranglerDurableObjects, P as assertBrowserCompatibility, S as readWranglerManagedQueueCleanupCandidates, T as resolveLiveBindingConfig, _ as readExistingLiveBindingConfig, a as acknowledgeWranglerManagedQueueRemovals, i as LIVE_MIGRATION_TAG, j as writeProvisionedWranglerConfig, k as syncWranglerWebSockets, m as nextDurableObjectMigrationTag, p as hasDurableObjectSqliteMigration, r as FRIENDLY_BINDING_NAMES, s as bindingEntriesForField } from "./wrangler-AyMfdVJK.mjs";
25
+ import { a as checkCloudflareProvisionDrift, d as isRealD1Id, h as provisionCloudflareResources, i as assertValidResourceName, p as isRealKvId, s as deleteEnvVarCaseAware, u as isQueueConfirmedAbsent, y as resolveWorkersDevComplianceRegion } from "./provision-CQykn8gu.mjs";
26
+ import { a as createSpinner, c as formatCount, g as note, p as getErrorMessage } from "./output-DhJgS6Ve.mjs";
27
+ import { c as scrubWranglerAuthCredentials, n as buildSchemaProbeEnv, o as resolveDeployTransport, r as deployChildEnv, s as scrubManagedDeployBuildMarkers, t as MANAGED_DEPLOY_BUILD_ENV } from "./deploy-transport-4ISWxx8n.mjs";
28
+ import { f as listSelfHostSecretNames, h as selfHostSchemaFailureMessage, i as SelfHostSecretListError, l as dischargeSelfHostEnvContext, n as SelfHostFirstDeployError, p as readEmittedWorkerVars, r as SelfHostSchemaError, s as deriveSelfHostEnvContextFromVars, t as SelfHostEnvValidationError } from "./env-validation-SXsjd6-Z.mjs";
25
29
  import { n as readGeneratedWranglerConfigFile } from "./generated-wrangler-config-CoDaaFsA.mjs";
26
- import { a as createSpinner, c as formatCount, g as note, p as getErrorMessage } from "./output-BZLnu0z8.mjs";
27
- import { t as collectMigrations } from "./collect-rNLybAnF.mjs";
30
+ import { n as collectMigrations } from "./collect-KC4cizWM.mjs";
28
31
  import { n as openMigrationValidationDatabase, t as SqliteMigrationError } from "./sqlite-validation-CLJXXN93.mjs";
29
- import { n as CLOUDFLARE_QUEUE_NAMES_BUILD_ENV, t as CLOUDFLARE_DEPLOY_BUILD_ENV, u as resolveRemoteMode } from "./env-EjHqc7m9.mjs";
30
- import { n as prepareCfFrameworkBuildOutput, r as prepareCfStaticBuildOutput, t as prepareCfBuildOutput } from "./cf-build-output-Cso7Vh-t.mjs";
31
- import { c as VOID_INTERNAL_WORKER_FIRST, d as hasDocumentRoutes, f as resolveAssetConfig, i as readGeneratedAssetHeadersFile, l as edgeRulesNeedWorker, u as hasApiRoutes } from "./headers-DqBsjDxg.mjs";
32
- import { o as validateSsrEntry } from "./entry-Bwb9ev8K.mjs";
33
- import { v as require_ci_info } from "./project-security-CY_aahvW.mjs";
34
- import { a as parseCloudflareAuthSession, i as ensureCloudflareAuthentication, n as cloudflareCredentialOverrides, t as CloudflareAuthenticationError } from "./cloudflare-auth-eWfhdZCk.mjs";
32
+ import { d as resolveRemoteMode, n as CLOUDFLARE_QUEUE_NAMES_BUILD_ENV, r as CLOUDFLARE_WORKER_NAME_BUILD_ENV, t as CLOUDFLARE_DEPLOY_BUILD_ENV } from "./env-CU2tMDdO.mjs";
33
+ import { n as readVersionMetadataBinding, r as selectNativeVersionMetadataBinding, t as CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from "./version-metadata-CEla0kgi.mjs";
34
+ import { L as log$1, tt as isCancel } from "./dist-BngS28id.mjs";
35
+ import { n as prepareCfFrameworkBuildOutput, r as prepareCfStaticBuildOutput, t as prepareCfBuildOutput } from "./cf-build-output-G-7Tdd8b.mjs";
35
36
  import { r as trustedCloudflareWorkerAccessHeaders, t as cfAccessHeaders } from "./cf-access-DmkKPcAI.mjs";
36
- import { i as safePositional, r as readCfUploadOutput, t as CF_VERSION_SOURCE_MAX_OUTPUT_BYTES } from "./cf-command-values-5BPBRc9Z.mjs";
37
- import { n as record, t as migrateBuiltWranglerConfig } from "./cf-config-migrate-D271BTiw.mjs";
38
- import { n as getCfCliVersion, r as getVoidUserAgent, t as publishCloudflareWorkerSettings } from "./cf-worker-settings-BBdlhm9U.mjs";
37
+ import { a as safePositional, i as readCfUploadOutput, r as readCfPreviewDeployOutput, t as CF_VERSION_SOURCE_MAX_OUTPUT_BYTES } from "./cf-command-values-cUnJwCyG.mjs";
38
+ import { t as migrateBuiltWranglerConfig } from "./cf-config-migrate-CsbQGzMf.mjs";
39
+ import { t as getCfCliVersion } from "./cf-user-agent-HHTRzfud.mjs";
40
+ import { n as isSecretBindingType, r as uploadPinnedCloudflareVersion } from "./cf-version-api-XEEK2B9A.mjs";
41
+ import { i as workflowSettingsFit, n as withCloudflareVersionMessage, r as requestedWorkflowLimits, t as publishCloudflareWorkerSettings } from "./cf-worker-settings-DJKdy97k.mjs";
39
42
  import { t as Buffer } from "./node-buffer-D7kgjaDs.mjs";
40
- import { a as createCloudflareEmptyDomainPublisher, i as createCloudflareEmptyCronPublisher } from "./cloudflare-operations-BIRQkYwL.mjs";
41
- import { i as validateMigrations, t as assertJournalCoherence } from "./validate-CtBWCzez.mjs";
42
- import { n as readProjectPaths, t as assertNoRootSourceConventionConflicts } from "./project-paths-2ENfCCih.mjs";
43
+ import { a as parseCloudflareAuthSession, i as ensureCloudflareAuthentication, n as cloudflareCredentialOverrides, t as CloudflareAuthenticationError } from "./cloudflare-auth-iOgRurWm.mjs";
44
+ import { a as createCloudflareEmptyDomainPublisher, i as createCloudflareEmptyCronPublisher } from "./cloudflare-operations-D-9psgPQ.mjs";
45
+ import { v as require_ci_info } from "./project-security-BWTd6cTU.mjs";
46
+ import { c as VOID_INTERNAL_WORKER_FIRST, d as hasDocumentRoutes, f as resolveAssetConfig, i as readGeneratedAssetHeadersFile, l as edgeRulesNeedWorker, u as hasApiRoutes } from "./headers-DPI4MDGC.mjs";
47
+ import { i as runCloudflareStaticPreview, t as checkCloudflarePreviewRequest } from "./cloudflare-preview-BaeU-m74.mjs";
48
+ import { a as collectAndHashAssets, c as readWranglerHtmlHandling, d as streamDirectR2Deploy, f as warnIgnoredNotFoundForFramework, g as hasDeploySchemaDrift, h as getDeploySchemaDriftMessage, i as buildStaticManifest, l as resolveBrowserBinding, m as assertDeploySchemaDriftFree, n as runStaticDeploy, o as collectWorkerFiles, p as warnUnpublishedRouting, r as buildFrameworkManifest, s as detectNonSpaFallbackWarning, t as assembleVoidManifest, u as mergeAndLintRoutingRules } from "./deploy-managed-static-DV_OmTWf.mjs";
49
+ import { i as validateMigrations, t as assertJournalCoherence } from "./validate-B1PsQ_mt.mjs";
43
50
  import { t as sanitizeTerminalLogText } from "./terminal-log-text-CfS2JKM6.mjs";
44
- import { a as runMySqlMigrations } from "./runner-mysql-D549vGGm.mjs";
45
- import { i as runPgMigrations } from "./runner-pg-Buzw17hl.mjs";
46
- import { a as emailConfigInputs, c as preflightEmail, d as renderEmailChecklist, f as collectPrerenderPaths, h as prerenderPagesNode, i as createNodeEmailDns, m as prerenderPages, n as SEND_EMAIL_BINDING, o as formatSendingOnlyPaidHint, p as collectPrerenderPathsNode, r as applyEmailSetup, s as isAwaitingSendingOnboarding, t as EMAIL_FROM_VAR, u as renderAddressMap } from "./email-cloudflare-DeYH3Ke7.mjs";
47
- import { n as printDeploySecurityNotice } from "./deploy-security-notice-IRGy6Edf.mjs";
48
- import { a as needsWrapper, r as cleanupWrapper, t as bundleEntry } from "./wrapper-CcMYpOS8.mjs";
51
+ import { a as runMySqlMigrations } from "./runner-mysql-DSLGFOlC.mjs";
52
+ import { i as runPgMigrations } from "./runner-pg-BcGF7iBR.mjs";
53
+ import { a as emailConfigInputs, c as preflightEmail, d as renderEmailChecklist, f as collectPrerenderPaths, h as prerenderPagesNode, i as createNodeEmailDns, m as prerenderPages, n as SEND_EMAIL_BINDING, o as formatSendingOnlyPaidHint, p as collectPrerenderPathsNode, r as applyEmailSetup, s as isAwaitingSendingOnboarding, t as EMAIL_FROM_VAR, u as renderAddressMap } from "./email-cloudflare-C-guKEbz.mjs";
54
+ import { n as printDeploySecurityNotice } from "./deploy-security-notice-3jX71IeP.mjs";
55
+ import { a as needsWrapper, r as cleanupWrapper, t as bundleEntry } from "./wrapper-DPlTBVOx.mjs";
49
56
  import { t as assertNoPrerenderFailures } from "./prerender-render-BAdYhivW.mjs";
50
57
  import { t as collectGitDeployMetadata } from "./git-metadata-BEokJ6US.mjs";
51
- import { t as ensurePlatformAccessToken } from "./cf-access-DHklo7Rg.mjs";
58
+ import { t as ensurePlatformAccessToken } from "./cf-access-B21j-nd6.mjs";
52
59
  import { r as getPackageDir } from "./agents-64FnLwxP.mjs";
53
60
  import { t as require_picocolors } from "./picocolors-D1NxSLw-.mjs";
54
- import { t as promptForLoginToken } from "./login-jUBgfvzk.mjs";
55
- import { s as listPlatformConnections } from "./platform-registry-DHH6fivm.mjs";
56
- import { t as getRequestedProjectSlug } from "./resolve-project-8WZ3iVmr.mjs";
61
+ import { t as promptForLoginToken } from "./login-DaugBfBG.mjs";
62
+ import { s as listPlatformConnections } from "./platform-registry-zHH3RiIm.mjs";
63
+ import { t as getRequestedProjectSlug } from "./resolve-project-s_FGWyr-.mjs";
57
64
  import { createRequire } from "node:module";
58
65
  import { closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
59
66
  import { fileURLToPath } from "node:url";
@@ -63,13 +70,9 @@ import { homedir, tmpdir } from "node:os";
63
70
  import { isDeepStrictEqual } from "node:util";
64
71
  import { applyEdits, modify, parse } from "jsonc-parser";
65
72
  import { execFile, execSync, spawn } from "node:child_process";
66
- import { getWorkerAssetsDir, getWorkerBundleDir, getWorkerConfigPath, readBuildOutput } from "@cloudflare/build-output-utils";
67
- import { convertToWranglerConfig } from "@cloudflare/config";
68
- import mime from "mime";
69
- import ignore from "ignore";
70
- import { CloudflareWorkerInspectionError, activateCloudflareVersion, assertCloudflareBindingsPreserved, assertCloudflareDurableObjectLifecycleSupported, assertExistingCloudflareConfig, cloudflareCommandDiagnostic, encodeCloudflareVersionMessage, extractWorkersDevSubdomain, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, parseCloudflareVersionMessage, parseRootWranglerConfig, parseRootWranglerConfig as parseRootWranglerConfig$1, readBindingFieldPresence, readCloudflareTriggerConfig, readConfigEntryString, readExistingCloudflareWorker, readStoredResourceName, readWranglerTopLevelString, renderCloudflareStaticEntry, resolveD1MigrateTarget, stageCloudflareStaticAssets, writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig } from "@void/deploy-cloudflare";
73
+ import { getWorkerConfigPath, readBuildOutput } from "@cloudflare/build-output-utils";
74
+ import { CloudflareWorkerInspectionError, activateCloudflareVersion, assertCloudflareBindingsPreserved, assertCloudflareDurableObjectLifecycleSupported, assertExistingCloudflareConfig, cloudflareCommandDiagnostic, cloudflareVersionMessageReference, encodeCloudflareVersionMessage, extractWorkersDevSubdomain, inspectWorkflowSchedule, isLocalWorkflow, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, parseCloudflareVersionMessage, parseRootWranglerConfig, parseRootWranglerConfig as parseRootWranglerConfig$1, previewStaticWorkerConfig, readBindingFieldPresence, readCloudflareTriggerConfig, readConfigEntryString, readExistingCloudflareWorker, readStoredResourceName, readWorkflowDeclarations, readWranglerTopLevelString, renderCloudflareStaticEntry, resolveCloudflareVersionMessage, resolveD1MigrateTarget, stageCloudflareStaticAssets, workflowExports, writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig } from "@void/deploy-cloudflare";
71
75
  import { Minimatch } from "minimatch";
72
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
73
76
  // src/cli/cloudflare-candidate.ts
74
77
  const CANDIDATE_FILE = ".void/cloudflare-candidate.json";
75
78
  const INVALID_CANDIDATE_MESSAGE = "The saved Cloudflare candidate receipt is invalid. Restore or remove .void/cloudflare-candidate.json before retrying.";
@@ -171,7 +174,8 @@ async function prepareExistingCloudflareDeploy(options) {
171
174
  const existing = await (options.readExistingWorker ?? readExistingCloudflareWorker)({
172
175
  runWrangler: options.runWrangler,
173
176
  configPath: options.configPath,
174
- workerName: config.name
177
+ workerName: config.name,
178
+ accountId: options.accountId
175
179
  });
176
180
  const patch = {
177
181
  account_id: options.accountId,
@@ -213,7 +217,8 @@ async function maybeLinkCloudflareDeploy(root, options = {}, deps = {}) {
213
217
  "wrangler.json",
214
218
  "wrangler.toml"
215
219
  ].filter((name) => existsSync(join(root, name))), ...discoverFrameworkWranglerFiles(root)])];
216
- if (!files.length && !existsSync(join(root, "void.config.ts"))) return null;
220
+ const typedPath = join(root, "void.config.ts");
221
+ if (!files.length && (!existsSync(typedPath) || !existsSync(join(root, "void.lock.json")) && isUnchangedDeploySeed(readFileSync(typedPath, "utf8")))) return null;
217
222
  if (files.length > 1) throw new Error("Multiple Wrangler config files were found. Keep one root configuration before linking to Cloudflare.");
218
223
  const name = files[0] ?? ".void-wrangler.jsonc";
219
224
  if (name.endsWith(".toml")) throw new Error("Found wrangler.toml. Direct Cloudflare deployment currently needs a root wrangler.jsonc or wrangler.json with the same settings. Convert the config before linking.");
@@ -223,7 +228,7 @@ async function maybeLinkCloudflareDeploy(root, options = {}, deps = {}) {
223
228
  if (!files.length && (!config || typeof config.name !== "string" || !config.name.trim())) return null;
224
229
  if (errors.length || !config || typeof config !== "object" || Array.isArray(config) || typeof config.name !== "string" || !config.name.trim()) throw new Error(`Set the existing Worker's name in a valid ${name} before linking to Cloudflare.`);
225
230
  if (!(deps.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY))) throw new Error(`Found ${name} without a deployment destination. Run void deploy interactively to link the existing Worker, or use void deploy --platform cloudflare with Cloudflare credentials in CI.`);
226
- log.info(`Found ${basename(name)} for Worker "${config.name}".`);
231
+ log$1.info(`Found ${basename(name)} for Worker "${config.name}".`);
227
232
  const accepted = await (deps.confirm ?? confirm)({
228
233
  message: "Link this project and deploy to Cloudflare using the existing Worker and resources?",
229
234
  initialValue: true
@@ -620,6 +625,7 @@ const DEPLOY_WHOLE_OBJECT_PINNED_FIELDS = [
620
625
  */
621
626
  const DEPLOY_RAW_SNAPSHOT_FIELDS = [
622
627
  ...DEPLOY_WHOLE_OBJECT_PINNED_FIELDS,
628
+ "exports",
623
629
  "durable_objects",
624
630
  "ai",
625
631
  "migrations"
@@ -1023,6 +1029,7 @@ async function computeDesiredCloudflareResources(root, voidConfig, configPath, a
1023
1029
  });
1024
1030
  const { paths, bindings, authEnabled, dialect, bindingNames, migrations, needsDatabase } = analysis;
1025
1031
  const config = parseRootWranglerConfig(configPath);
1032
+ if (bindings.needsBrowser) assertBrowserCompatibility(voidConfig.worker?.compatibility_date ?? readWranglerTopLevelString(config, "compatibility_date") ?? "2026-03-24");
1026
1033
  const workerName = readWranglerTopLevelString(config, "name") ?? deriveWorkerName(root);
1027
1034
  const migrationsDirRelative = paths.sourceDir ? `./${paths.sourceDir}/db/migrations` : "./db/migrations";
1028
1035
  const desired = {
@@ -1098,6 +1105,7 @@ async function computeDesiredCloudflareResources(root, voidConfig, configPath, a
1098
1105
  migrations,
1099
1106
  needsAI: bindings.needsAI,
1100
1107
  aiBindingName: bindingNames?.ai ?? "AI",
1108
+ inferredBrowserBinding: bindings.needsBrowser && config.browser === void 0 ? bindingNames?.browser ?? "BROWSER" : void 0,
1101
1109
  expectedCrons,
1102
1110
  needsEmail: bindings.needsEmail === true || hasEmailHandlers(emailHandlers),
1103
1111
  emailHandlers,
@@ -1105,6 +1113,85 @@ async function computeDesiredCloudflareResources(root, voidConfig, configPath, a
1105
1113
  needsLive: bindings.needsLive === true
1106
1114
  };
1107
1115
  }
1116
+ // src/cli/cloudflare-deploy/classify.ts
1117
+ const configSources = [
1118
+ TYPED_CONFIG_FILE,
1119
+ LEGACY_CONFIG_FILE,
1120
+ ...[
1121
+ "wrangler.jsonc",
1122
+ "wrangler.json",
1123
+ "wrangler.toml",
1124
+ "cloudflare.config.ts"
1125
+ ]
1126
+ ];
1127
+ const savedFiles = [
1128
+ VOID_LOCK_FILE,
1129
+ MATERIALIZED_CLOUDFLARE_FILE,
1130
+ CANDIDATE_FILE
1131
+ ];
1132
+ const configChanged = "deploy: Configuration changed during setup. Rerun `void deploy`.";
1133
+ function hasDeployConfigSource(root) {
1134
+ return configSources.some((name) => existsSync(join(root, name)));
1135
+ }
1136
+ /**
1137
+ * Narrow native Cloudflare deploys to app shapes whose emitted Worker artifact
1138
+ * the current verifier understands. This runs before any account operation;
1139
+ * `runCloudflareDeploy` has already rejected node/bun/deno targets.
1140
+ */
1141
+ function classifyCloudflareDeployApp(root, voidConfig, options, application) {
1142
+ const framework = application.framework;
1143
+ const configuredAppType = voidConfig.inference?.appType;
1144
+ const staticPreset = framework || configuredAppType ? null : detectPreset(root, {
1145
+ dir: options.dir,
1146
+ spa: options.spa
1147
+ });
1148
+ if (staticPreset || isStaticAppType(configuredAppType) || options.dir || options.spa) return unsupported([
1149
+ `deploy: --platform cloudflare could not resolve the ${staticPreset?.appType ?? (options.spa ? "spa" : "static")} output to deploy.`,
1150
+ "Set inference.outputDir in void.config.ts, pass --dir with an existing build directory,",
1151
+ "or add a supported build tool so Void can locate the generated static assets."
1152
+ ].join("\n"));
1153
+ if (framework && application.workflows.length > 0) return unsupported(FRAMEWORK_WORKFLOWS_ERROR);
1154
+ if (!framework && !hasBackendFiles(root)) return unsupported([
1155
+ "deploy: --platform cloudflare found no Void backend to deploy.",
1156
+ "A full Void app has at least one of: routes/, pages/, middleware, crons/, queues/,",
1157
+ "email/, workflows/, or an SSR entry. Add your server code, or use `void deploy` for a static site."
1158
+ ].join("\n"));
1159
+ try {
1160
+ const paths = application.paths;
1161
+ assertNoRootSourceConventionConflicts(paths);
1162
+ validateSsrEntry(root, paths);
1163
+ if (options.seedConfig && (!framework || framework.class === "a")) {
1164
+ const hasSavedState = () => savedFiles.some((name) => existsSync(join(root, name)));
1165
+ if (hasSavedState()) return unsupported("deploy: Restore void.config.ts from version control or a backup.");
1166
+ ignoreMaterializedCloudflareConfig(root);
1167
+ if (hasDeployConfigSource(root) || hasSavedState()) return unsupported(configChanged);
1168
+ const worker = { compatibility_date: DEFAULT_WORKER_COMPAT_DATE };
1169
+ const config = {
1170
+ cloudflare: { name: deriveWorkerName(root) },
1171
+ worker
1172
+ };
1173
+ const contents = renderDeploySeedConfig(config);
1174
+ try {
1175
+ writeFileSync(join(root, TYPED_CONFIG_FILE), contents, { flag: "wx" });
1176
+ } catch (error) {
1177
+ if (error?.code === "EEXIST") return unsupported(configChanged);
1178
+ throw error;
1179
+ }
1180
+ log.step("Created void.config.ts. Commit it, the .gitignore change, and void.lock.json when present.");
1181
+ }
1182
+ syncWranglerDurableObjects(root, application.durableObjects);
1183
+ syncWranglerWebSockets(root, application.websockets);
1184
+ } catch (error) {
1185
+ return unsupported(`deploy: ${getErrorMessage(error)}`);
1186
+ }
1187
+ return { supported: true };
1188
+ }
1189
+ function unsupported(reason) {
1190
+ return {
1191
+ supported: false,
1192
+ reason
1193
+ };
1194
+ }
1108
1195
  // src/cli/deploy-artifact-validation.ts
1109
1196
  /**
1110
1197
  * Derive the env schema's server and required key names in an isolated subprocess, so project
@@ -1278,8 +1365,12 @@ function verifyGeneratedDeployConfig(root, expected) {
1278
1365
  };
1279
1366
  }
1280
1367
  const pinned = passthrough.get(field) ?? /* @__PURE__ */ new Map();
1368
+ if (field === "workflows" && emittedEntries.length !== pinned.size) return {
1369
+ ok: false,
1370
+ reason: "generated config workflows differ from the pre-build Workflow set."
1371
+ };
1281
1372
  for (const { name, entry } of emittedEntries) {
1282
- const pinnedEntry = pinned.get(name);
1373
+ const pinnedEntry = pinned.get(name) ?? (field === "browser" && pinned.size === 0 && name === expected.inferredBrowserBinding ? { binding: name } : void 0);
1283
1374
  if (pinnedEntry === void 0) return {
1284
1375
  ok: false,
1285
1376
  reason: `generated config declares a ${field} binding ${JSON.stringify(name)} that was not present before the build — refusing to deploy a ${field} binding the build injected.`
@@ -1304,6 +1395,10 @@ function verifyGeneratedDeployConfig(root, expected) {
1304
1395
  }
1305
1396
  if (expected.passthroughRawFields) {
1306
1397
  const raw = expected.passthroughRawFields;
1398
+ if (!isDeepStrictEqual(workflowExports(generated.exports), workflowExports(raw.get("exports")))) return {
1399
+ ok: false,
1400
+ reason: "generated Workflow exports differ from the pre-build configuration."
1401
+ };
1307
1402
  for (const field of DEPLOY_WHOLE_OBJECT_PINNED_FIELDS) {
1308
1403
  const emitted = generated[field];
1309
1404
  const rootValue = raw.get(field);
@@ -1442,7 +1537,7 @@ function verifyGeneratedDeployConfig(root, expected) {
1442
1537
  function verifyCloudflareDeployArtifact(root, deps, options) {
1443
1538
  const verification = (deps.verifyDeployConfig ?? verifyGeneratedDeployConfig)(root, options);
1444
1539
  if (!verification.ok) {
1445
- log$1.error([
1540
+ log.error([
1446
1541
  "deploy: the generated deploy config does not match the pinned target — refusing to deploy.",
1447
1542
  verification.reason,
1448
1543
  "This typically means CLOUDFLARE_ENV / CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH (in the",
@@ -1463,7 +1558,7 @@ async function validateCloudflarePostBuildEnv(options) {
1463
1558
  assertExistingCloudflareConfig(existingWorker, generated.config, true, approvedHandoffKv);
1464
1559
  }
1465
1560
  if (!emitted.ok) {
1466
- log$1.error([
1561
+ log.error([
1467
1562
  "deploy: could not read the worker vars the build emitted — refusing to validate secrets.",
1468
1563
  ` ${emitted.reason}`,
1469
1564
  "The build must emit dist/ssr/wrangler.json for this backend. Rerun the build, or deploy",
@@ -1473,7 +1568,7 @@ async function validateCloudflarePostBuildEnv(options) {
1473
1568
  }
1474
1569
  const emittedVars = emitted.vars;
1475
1570
  if (authEnabled && Object.hasOwn(emittedVars, "BETTER_AUTH_SECRET")) {
1476
- log$1.error([
1571
+ log.error([
1477
1572
  `deploy: ${BETTER_AUTH_SECRET_NAME} must be stored as a Cloudflare Worker secret, not a plaintext worker var.`,
1478
1573
  "Remove it from Worker vars and rerun. This deploy command preserves an",
1479
1574
  "existing remote value or creates a persistent one automatically when it is missing."
@@ -1482,7 +1577,7 @@ async function validateCloudflarePostBuildEnv(options) {
1482
1577
  }
1483
1578
  const plaintextServerKeys = schemaFacts.serverKeys.filter((key) => key in emittedVars);
1484
1579
  if (plaintextServerKeys.length > 0) {
1485
- log$1.error([
1580
+ log.error([
1486
1581
  "deploy: server env keys cannot ship as plaintext Worker vars:",
1487
1582
  ...plaintextServerKeys.map((key) => ` • ${key}`),
1488
1583
  "Remove them from Worker vars and set them with `void secret put <NAME>`."
@@ -1495,11 +1590,11 @@ async function validateCloudflarePostBuildEnv(options) {
1495
1590
  try {
1496
1591
  validateResult = await (deps.validateEmittedVars ?? validateEmittedVarsDefault)({ root }, buildSchemaProbeEnv(accountId, apiBaseUrl));
1497
1592
  } catch (err) {
1498
- log$1.error(`deploy: could not validate the emitted worker vars against the env schema — ${getErrorMessage(err)}`);
1593
+ log.error(`deploy: could not validate the emitted worker vars against the env schema — ${getErrorMessage(err)}`);
1499
1594
  return false;
1500
1595
  }
1501
1596
  if (validateResult.kind === "schema-error") {
1502
- log$1.error(`deploy: ${selfHostSchemaFailureMessage(validateResult.reason)}`);
1597
+ log.error(`deploy: ${selfHostSchemaFailureMessage(validateResult.reason)}`);
1503
1598
  return false;
1504
1599
  }
1505
1600
  envContext.invalidKeys = validateResult.invalidKeys;
@@ -1518,1028 +1613,13 @@ async function validateCloudflarePostBuildEnv(options) {
1518
1613
  });
1519
1614
  } catch (err) {
1520
1615
  if (err instanceof SelfHostFirstDeployError || err instanceof SelfHostSecretListError || err instanceof SelfHostEnvValidationError || err instanceof SelfHostSchemaError) {
1521
- log$1.error(err.message);
1616
+ log.error(err.message);
1522
1617
  return false;
1523
1618
  }
1524
1619
  throw err;
1525
1620
  }
1526
1621
  return true;
1527
1622
  }
1528
- // src/cli/deploy-cloudflare-auth.ts
1529
- var import_ci_info = require_ci_info();
1530
- /** Run typed provider operations in the pinned account and API context. */
1531
- function createDeployWranglerRunner(root, accountId, apiBaseUrl) {
1532
- const runner = createCloudflareProcessRunner({
1533
- root,
1534
- accountId,
1535
- apiBaseUrl,
1536
- env: () => deployChildEnv(accountId, apiBaseUrl)
1537
- });
1538
- return (operation, opts) => runner(operation, opts);
1539
- }
1540
- /** Retry an existing-Worker read only when a fresh identity check proves the session is gone. */
1541
- async function prepareExistingCloudflareDeployWithAuth(options, beforeRun) {
1542
- try {
1543
- return await prepareExistingCloudflareDeploy(options);
1544
- } catch (error) {
1545
- if (!(error instanceof CloudflareWorkerInspectionError)) throw error;
1546
- if (!beforeRun()) throw new CloudflareAuthenticationError("The Cloudflare uploader changed during Worker verification.", "uploader-changed");
1547
- const configPath = existsSync(options.configPath) ? options.configPath : void 0;
1548
- const identity = await options.runWrangler({
1549
- type: "auth.whoami",
1550
- configPath
1551
- }, { capture: true });
1552
- const session = isCleanCloudflareExit(identity) ? parseCloudflareAuthSession(identity.data) : null;
1553
- const wrongAccount = session !== null && session.accounts.length > 0 && !session.accounts.some((account) => account.id === options.accountId);
1554
- if (session && !wrongAccount) throw error;
1555
- if (!(identity.data?.loggedIn === false || wrongAccount || /authentication is required|not authenticated|no api token|invalid.*token|expired.*token|unauthorized/i.test(identity.stderr)) || identity.signal || identity.error) throw new Error("Could not verify the Cloudflare session after the Worker check failed. Run `void cloudflare status` and retry.");
1556
- const overrides = cloudflareCredentialOverrides();
1557
- if (overrides.length > 0) throw new Error(`Cloudflare credentials from ${overrides.join(", ")} were rejected or cannot access account ${options.accountId}. Correct or unset them, then retry the deploy.`);
1558
- if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error(wrongAccount ? `The Cloudflare session cannot access account ${options.accountId}. Run \`void cloudflare login\` with the correct user, or set a token for that account in CI, then retry.` : "Cloudflare authentication expired or is unavailable. Run `void cloudflare login` in a terminal, or set CLOUDFLARE_API_TOKEN in CI, then retry.");
1559
- log$1.warn(wrongAccount ? "The current Cloudflare session cannot access the deployment account. Signing in before retrying the Worker check." : "Cloudflare session is unavailable. Signing in before retrying the Worker check.");
1560
- if (!(await ensureCloudflareAuthentication({
1561
- forceLogin: true,
1562
- requireAccounts: true,
1563
- beforeRun,
1564
- runWrangler: (operation, capture) => options.runWrangler(operation, { capture }),
1565
- configPath
1566
- })).accounts.some((account) => account.id === options.accountId)) throw new Error(`The signed-in Cloudflare user cannot access account ${options.accountId}. Sign in with a user who can access it, then retry.`);
1567
- if (!beforeRun()) throw new CloudflareAuthenticationError("The Cloudflare uploader changed during sign-in.", "uploader-changed");
1568
- return await prepareExistingCloudflareDeploy(options);
1569
- }
1570
- }
1571
- async function chooseCloudflareDeployAccount(options) {
1572
- const accounts = (await ensureCloudflareAuthentication({
1573
- beforeRun: options.beforeWranglerRun,
1574
- requireAccounts: true,
1575
- runWrangler: (operation, capture) => options.runWrangler(operation, { capture }),
1576
- configPath: existsSync(options.configPath) ? options.configPath : void 0
1577
- })).accounts;
1578
- let account = accounts[0];
1579
- if (accounts.length > 1) {
1580
- if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Multiple Cloudflare accounts are available. Set CLOUDFLARE_ACCOUNT_ID in CI, or run `void init` interactively to choose one.");
1581
- const accountId = await select({
1582
- message: "Choose a Cloudflare account:",
1583
- initialValue: account.id,
1584
- options: accounts.map((candidate) => ({
1585
- value: candidate.id,
1586
- label: candidate.name,
1587
- hint: candidate.id
1588
- }))
1589
- });
1590
- if (isCancel(accountId) || typeof accountId === "symbol") throw new Error("Cloudflare account selection was cancelled.");
1591
- account = accounts.find((candidate) => candidate.id === accountId) ?? account;
1592
- }
1593
- if (options.persist !== false) writeProvisionedWranglerConfig(options.root, { accountId: account.id }, { configPath: options.configPath });
1594
- log$1.step(`Configured Cloudflare account: ${account.name}`);
1595
- return account.id;
1596
- }
1597
- /** Non-interactive when CI is detected or stdin/stdout is not a TTY. */
1598
- function isWranglerNonInteractiveOrCI() {
1599
- return import_ci_info.isCI || !(process.stdin.isTTY && process.stdout.isTTY);
1600
- }
1601
- const GLOBAL_API_KEY_SESSION = "the session uses a Global API Key (CLOUDFLARE_API_KEY), which this step cannot use. Set CLOUDFLARE_API_TOKEN, or unset CLOUDFLARE_API_KEY and run `void cloudflare login`, then retry.";
1602
- const fail = (status, signal, stderr) => ({
1603
- ok: false,
1604
- failure: {
1605
- status: status === 0 ? 1 : status,
1606
- ...signal ? { signal } : {},
1607
- stdout: "",
1608
- stderr
1609
- }
1610
- });
1611
- /**
1612
- * Read the current Cloudflare session bearer through the pinned deploy runner, for API calls
1613
- * Void makes itself. The token goes only to the caller. A failure is built fresh from the
1614
- * child's status, signal and stderr: it never carries the child's errorCode, failure, errors
1615
- * or data, so an auth failure can never be read as a Cloudflare upload error.
1616
- */
1617
- async function readWranglerAuthToken(runWrangler, configPath) {
1618
- let result;
1619
- try {
1620
- result = await Promise.resolve(runWrangler({
1621
- type: "auth.token",
1622
- configPath
1623
- }, { capture: true }));
1624
- } catch (error) {
1625
- return fail(1, null, `${describeCloudflareChildFailure({
1626
- status: 1,
1627
- error: getErrorMessage(error)
1628
- })}.`);
1629
- }
1630
- const parsed = result.data;
1631
- if (!isCleanCloudflareExit(result)) {
1632
- if (parsed?.type === "api_key" && !result.error && !result.signal) return fail(result.status, null, GLOBAL_API_KEY_SESSION);
1633
- return fail(result.status, result.signal, formatCloudflareChildFailure(result));
1634
- }
1635
- const type = parsed?.type;
1636
- const token = parsed?.token;
1637
- return (type === "oauth" || type === "api_token") && typeof token === "string" && token.length > 0 ? {
1638
- ok: true,
1639
- token
1640
- } : fail(1, null, "the Void CLI helper process returned no session credential.");
1641
- }
1642
- /** {@link readWranglerAuthToken} for callers that only need the token; every failure is `null`. */
1643
- async function runWranglerAuthToken(runWrangler, configPath) {
1644
- const read = await readWranglerAuthToken(runWrangler, configPath);
1645
- return read.ok ? read.token : null;
1646
- }
1647
- /**
1648
- * Ensure an auth-enabled worker has one persistent Better Auth secret.
1649
- *
1650
- * Existing remote secrets are adopted unchanged. A missing secret is generated
1651
- * once, streamed to `wrangler secret put` over stdin (never argv), then verified
1652
- * by listing names again. A not-yet-deployed Worker is the one safe list failure
1653
- * treated as absence because Wrangler can attach a secret to its draft Worker.
1654
- */
1655
- async function ensureCloudflareAuthSecret(options) {
1656
- let workerWasMissing = false;
1657
- const beforeRun = () => {
1658
- if (options.beforeWranglerRun && !options.beforeWranglerRun()) throw new CloudflareAuthSecretError("", "uploader-changed");
1659
- };
1660
- const list = async (allowMissingWorker) => {
1661
- beforeRun();
1662
- try {
1663
- return await listSelfHostSecretNames({
1664
- root: options.root,
1665
- configPath: options.configPath,
1666
- accountId: options.accountId,
1667
- workerName: options.workerName,
1668
- runWrangler: (args) => options.runWrangler(args, { capture: true })
1669
- }, [BETTER_AUTH_SECRET_NAME]);
1670
- } catch (error) {
1671
- if (allowMissingWorker && error instanceof SelfHostFirstDeployError) {
1672
- workerWasMissing = true;
1673
- return [];
1674
- }
1675
- if (error instanceof SelfHostSecretListError) throw new CloudflareAuthSecretError(`deploy: could not confirm the remote ${BETTER_AUTH_SECRET_NAME}. No worker was uploaded. Run \`void secret list\` to diagnose the Cloudflare response, then retry.`, allowMissingWorker ? "list-failed" : "verification-failed");
1676
- throw error;
1677
- }
1678
- };
1679
- if ((await list(true)).includes("BETTER_AUTH_SECRET")) return { created: false };
1680
- const secret = randomBytes(32).toString("hex");
1681
- if (workerWasMissing) return {
1682
- created: true,
1683
- workerWasMissing: true,
1684
- candidateSecret: secret
1685
- };
1686
- beforeRun();
1687
- let put;
1688
- try {
1689
- put = await Promise.resolve(options.runWrangler({
1690
- type: "secret.put",
1691
- name: BETTER_AUTH_SECRET_NAME,
1692
- configPath: options.configPath,
1693
- workerName: options.workerName
1694
- }, {
1695
- capture: true,
1696
- input: `${secret}\n`
1697
- }));
1698
- } catch {
1699
- throw new CloudflareAuthSecretError(`deploy: could not create the remote ${BETTER_AUTH_SECRET_NAME}. No worker was uploaded. Run \`void secret put ${BETTER_AUTH_SECRET_NAME}\` and retry.`, "put-failed");
1700
- }
1701
- if (!isCleanCloudflareExit(put)) throw new CloudflareAuthSecretError(`deploy: could not create the remote ${BETTER_AUTH_SECRET_NAME} (Cloudflare command exit ${String(put.status)}). No worker was uploaded. Run \`void secret put ${BETTER_AUTH_SECRET_NAME}\` and retry.`, "put-failed");
1702
- if (!(await list(false)).includes("BETTER_AUTH_SECRET")) throw new CloudflareAuthSecretError(`deploy: Cloudflare reported success but ${BETTER_AUTH_SECRET_NAME} was not present afterward. No worker was uploaded; retry once Cloudflare secret storage is available.`, "verification-failed");
1703
- return { created: true };
1704
- }
1705
- // src/cli/cf-version-api.ts
1706
- var CloudflareApiError = class extends Error {
1707
- status;
1708
- code;
1709
- constructor(message, status, code) {
1710
- super(message);
1711
- this.status = status;
1712
- this.code = code;
1713
- }
1714
- };
1715
- /** Worker binding types whose value comes from a secret rather than the build output. */
1716
- function isSecretBindingType(type) {
1717
- return type === "secret" || type === "inherit" || type === "unsafe:inherit";
1718
- }
1719
- function assertUploaderUnchanged(verifyUploader) {
1720
- if (!verifyUploader()) throw new Error("The Cloudflare uploader changed during deployment.");
1721
- }
1722
- function requiredString(value, label) {
1723
- if (typeof value !== "string" || !value) throw new Error(`The Cloudflare ${label} is missing from the verified Worker output.`);
1724
- return value;
1725
- }
1726
- function textValue(value, label) {
1727
- if (typeof value !== "string") throw new Error(`The Cloudflare ${label} is missing from the verified Worker output.`);
1728
- return value;
1729
- }
1730
- /** Match cf's package collection for uploads that preserve secrets through the JSON API. */
1731
- async function readPackageDependencies(directory) {
1732
- try {
1733
- const pkg = record(JSON.parse(readFileSync(join(directory, "package.json"), "utf8")));
1734
- const declared = {
1735
- ...record(pkg?.dependencies),
1736
- ...record(pkg?.devDependencies)
1737
- };
1738
- const { getInstalledPackageVersion } = await import("@cloudflare/workers-utils");
1739
- const dependencies = [];
1740
- for (const [name, packageJsonVersion] of Object.entries(declared)) {
1741
- if (dependencies.length >= 200) break;
1742
- if (typeof packageJsonVersion !== "string" || /^(workspace|catalog|file|link):/.test(packageJsonVersion)) continue;
1743
- const installedVersion = getInstalledPackageVersion(name, directory);
1744
- if (installedVersion) dependencies.push({
1745
- name,
1746
- packageJsonVersion,
1747
- installedVersion
1748
- });
1749
- }
1750
- return dependencies.length ? dependencies : void 0;
1751
- } catch {
1752
- return;
1753
- }
1754
- }
1755
- const moduleContentTypes = /* @__PURE__ */ new Map([
1756
- ["esm", "application/javascript+module"],
1757
- ["cjs", "application/javascript"],
1758
- ["wasm", "application/wasm"],
1759
- ["text", "text/plain"],
1760
- ["data", "application/octet-stream"],
1761
- ["json", "text/plain"],
1762
- ["sourcemap", "application/source-map"]
1763
- ]);
1764
- function bindingsFromOutput(env, workerName, activeSecrets, explicitSecrets) {
1765
- const inherited = new Map(activeSecrets.bindings.map((binding) => [binding.name, binding.type]));
1766
- const names = /* @__PURE__ */ new Set([
1767
- ...Object.keys(env),
1768
- ...inherited.keys(),
1769
- ...Object.keys(explicitSecrets)
1770
- ]);
1771
- const bindings = [];
1772
- for (const name of names) {
1773
- const value = record(env[name]);
1774
- const explicit = explicitSecrets[name];
1775
- if (explicit !== void 0) {
1776
- if (typeof explicit !== "string" || inherited.get(name) === "secret_key" || value && value.type !== "secret") throw new Error(`Cloudflare secret ${name} has an invalid explicit value or binding.`);
1777
- bindings.push({
1778
- name,
1779
- type: "secret_text",
1780
- text: explicit
1781
- });
1782
- continue;
1783
- }
1784
- if (inherited.has(name)) {
1785
- if (value && !isSecretBindingType(value.type)) throw new Error(`Cloudflare secret ${name} conflicts with a Worker binding.`);
1786
- bindings.push({
1787
- name,
1788
- type: "inherit",
1789
- version_id: activeSecrets.versionId
1790
- });
1791
- continue;
1792
- }
1793
- if (!value) throw new Error(`Cloudflare binding ${name} is missing from the Worker output.`);
1794
- switch (value.type) {
1795
- case "text":
1796
- bindings.push({
1797
- name,
1798
- type: "plain_text",
1799
- text: textValue(value.value, name)
1800
- });
1801
- break;
1802
- case "json":
1803
- bindings.push({
1804
- name,
1805
- type: "json",
1806
- json: value.value
1807
- });
1808
- break;
1809
- case "kv":
1810
- bindings.push({
1811
- name,
1812
- type: "kv_namespace",
1813
- namespace_id: requiredString(value.id, name)
1814
- });
1815
- break;
1816
- case "d1":
1817
- bindings.push({
1818
- name,
1819
- type: "d1",
1820
- database_id: requiredString(value.id, name)
1821
- });
1822
- break;
1823
- case "r2":
1824
- bindings.push({
1825
- name,
1826
- type: "r2_bucket",
1827
- bucket_name: requiredString(value.name, name),
1828
- ...value.jurisdiction ? { jurisdiction: value.jurisdiction } : {}
1829
- });
1830
- break;
1831
- case "durable-object":
1832
- bindings.push({
1833
- name,
1834
- type: "durable_object_namespace",
1835
- class_name: requiredString(value.exportName, name),
1836
- ...value.worker !== workerName ? { script_name: requiredString(value.worker, name) } : {}
1837
- });
1838
- break;
1839
- case "unsafe:durable_object_namespace":
1840
- if (Object.keys(value).some((key) => ![
1841
- "type",
1842
- "class_name",
1843
- "dev"
1844
- ].includes(key))) throw new Error(`Cloudflare binding ${name} is not a verified local Durable Object.`);
1845
- bindings.push({
1846
- name,
1847
- type: "durable_object_namespace",
1848
- class_name: requiredString(value.class_name, name)
1849
- });
1850
- break;
1851
- case "queue":
1852
- bindings.push({
1853
- name,
1854
- type: "queue",
1855
- queue_name: requiredString(value.name, name),
1856
- ...value.deliveryDelay === void 0 ? {} : { delivery_delay: value.deliveryDelay }
1857
- });
1858
- break;
1859
- case "rate-limit":
1860
- bindings.push({
1861
- name,
1862
- type: "ratelimit",
1863
- namespace_id: requiredString(value.namespace, name),
1864
- simple: value.simple
1865
- });
1866
- break;
1867
- case "ai":
1868
- case "browser":
1869
- case "images":
1870
- bindings.push({
1871
- name,
1872
- type: value.type
1873
- });
1874
- break;
1875
- case "hyperdrive":
1876
- bindings.push({
1877
- name,
1878
- type: "hyperdrive",
1879
- id: requiredString(value.id, name)
1880
- });
1881
- break;
1882
- case "worker":
1883
- bindings.push({
1884
- name,
1885
- type: "service",
1886
- service: requiredString(value.worker, name),
1887
- ...value.exportName === void 0 ? {} : { entrypoint: value.exportName },
1888
- ...value.props === void 0 ? {} : { props: value.props }
1889
- });
1890
- break;
1891
- case "workflow":
1892
- bindings.push({
1893
- name,
1894
- type: "workflow",
1895
- workflow_name: requiredString(value.name, name),
1896
- ...value.worker === workerName ? { class_name: requiredString(value.exportName, name) } : { script_name: requiredString(value.worker, name) }
1897
- });
1898
- break;
1899
- case "send-email":
1900
- bindings.push({
1901
- name,
1902
- type: "send_email",
1903
- ...value.destinationAddress === void 0 ? {} : { destination_address: value.destinationAddress },
1904
- ...value.allowedDestinationAddresses === void 0 ? {} : { allowed_destination_addresses: value.allowedDestinationAddresses },
1905
- ...value.allowedSenderAddresses === void 0 ? {} : { allowed_sender_addresses: value.allowedSenderAddresses }
1906
- });
1907
- break;
1908
- case "analytics-engine-dataset":
1909
- bindings.push({
1910
- name,
1911
- type: "analytics_engine",
1912
- ...value.name === void 0 ? {} : { dataset: value.name }
1913
- });
1914
- break;
1915
- case "vectorize":
1916
- bindings.push({
1917
- name,
1918
- type: "vectorize",
1919
- index_name: requiredString(value.name, name)
1920
- });
1921
- break;
1922
- case "dispatch-namespace": {
1923
- const outbound = record(value.outbound);
1924
- bindings.push({
1925
- name,
1926
- type: "dispatch_namespace",
1927
- namespace: requiredString(value.namespace, name),
1928
- ...outbound ? { outbound: {
1929
- worker: { service: requiredString(outbound.worker, name) },
1930
- ...Array.isArray(outbound.parameters) ? { params: outbound.parameters.map((parameter) => ({ name: parameter })) } : {}
1931
- } } : {}
1932
- });
1933
- break;
1934
- }
1935
- case "assets":
1936
- bindings.push({
1937
- name,
1938
- type: "assets"
1939
- });
1940
- break;
1941
- case "version-metadata":
1942
- bindings.push({
1943
- name,
1944
- type: "version_metadata"
1945
- });
1946
- break;
1947
- case "worker-loader":
1948
- bindings.push({
1949
- name,
1950
- type: "worker_loader"
1951
- });
1952
- break;
1953
- default: throw new Error(`Cloudflare binding ${name} cannot be uploaded with pinned secrets.`);
1954
- }
1955
- }
1956
- return bindings;
1957
- }
1958
- const durableObjectStates = /* @__PURE__ */ new Set([
1959
- "created",
1960
- "deleted",
1961
- "renamed",
1962
- "transferred",
1963
- "expecting-transfer"
1964
- ]);
1965
- /**
1966
- * The `exports` that cf uploads for the same Build Output. cf converts them with
1967
- * `@cloudflare/config`'s `convertToWranglerConfig` (cf `build-*.mjs`), and its
1968
- * `resolveExportsUploadPayload` (cf `containers-*.mjs`) sends Worker entrypoints,
1969
- * then Durable Objects, then Workflows reduced to their identity. Cloudflare
1970
- * stages a version at 0% only when its exports are identical to the live
1971
- * version's, and that version may have been uploaded by cf.
1972
- */
1973
- function exportsFromOutput(exports, bindings) {
1974
- if (exports === void 0) return;
1975
- const entries = record(exports);
1976
- if (!entries) throw new Error("Cloudflare Durable Object exports were not readable.");
1977
- const workflows = /* @__PURE__ */ new Map();
1978
- for (const [name, raw] of Object.entries(entries)) {
1979
- const value = record(raw);
1980
- if (value?.type === "workflow") {
1981
- const workflowName = requiredString(value.name, `Workflow export ${name} name`);
1982
- if (workflows.has(workflowName)) throw new Error(`Cloudflare Workflow ${workflowName} has multiple local exports.`);
1983
- workflows.set(workflowName, name);
1984
- continue;
1985
- }
1986
- if (value?.type === "worker") continue;
1987
- if (!value || value.type !== "durable-object") throw new Error(`Cloudflare export ${name} cannot be uploaded with pinned secrets.`);
1988
- const state = value.state ?? "created";
1989
- if (!durableObjectStates.has(String(state))) throw new Error(`Cloudflare Durable Object export ${name} has an unsupported state.`);
1990
- if (state === "renamed" || state === "transferred") requiredString(value[state === "renamed" ? "renamedTo" : "transferredTo"], name);
1991
- else if (state !== "deleted") {
1992
- if (value.storage !== "sqlite" && value.storage !== "legacy-kv") throw new Error(`Cloudflare Durable Object export ${name} has no storage type.`);
1993
- if (value.container !== void 0) requiredString(value.container, name);
1994
- if (state === "expecting-transfer") requiredString(value.transferFrom, name);
1995
- }
1996
- }
1997
- for (const binding of bindings) {
1998
- if (binding.type !== "workflow") continue;
1999
- const localExport = workflows.get(String(binding.workflow_name));
2000
- if (localExport !== void 0 && (binding.script_name !== void 0 || binding.class_name !== localExport)) throw new Error(`Cloudflare Workflow binding ${binding.name} conflicts with its local export.`);
2001
- }
2002
- const converted = record(convertToWranglerConfig({
2003
- worker: { exports: entries },
2004
- containers: []
2005
- }).exports) ?? {};
2006
- const result = {};
2007
- for (const type of [
2008
- "worker",
2009
- "durable-object",
2010
- "workflow"
2011
- ]) for (const [name, value] of Object.entries(converted)) {
2012
- const entry = record(value);
2013
- if (entry?.type !== type) continue;
2014
- result[name] = entry;
2015
- }
2016
- return Object.keys(result).length > 0 ? result : void 0;
2017
- }
2018
- async function preflightWorkflowExports(options) {
2019
- for (const raw of Object.values(options.exports ?? {})) {
2020
- const entry = record(raw);
2021
- if (entry?.type !== "workflow") continue;
2022
- const name = requiredString(entry.name, "Workflow name");
2023
- let workflow;
2024
- try {
2025
- workflow = await apiResult(`${options.accountUrl}/workflows/${encodeURIComponent(name)}`, options.token, "GET", void 0, options.verifyUploader);
2026
- } catch (cause) {
2027
- if (cause instanceof CloudflareApiError && cause.status === 404 && cause.code === 10200) continue;
2028
- throw cause;
2029
- }
2030
- if (workflow.name !== name || workflow.script_name !== options.workerName || typeof workflow.class_name !== "string" || !workflow.class_name) throw new Error(`Cloudflare Workflow ${name} is not owned by this Worker.`);
2031
- }
2032
- }
2033
- function assetConfigFromOutput(value) {
2034
- if (value === void 0) return;
2035
- const config = record(value);
2036
- if (!config) throw new Error("Cloudflare asset configuration was not readable.");
2037
- const supported = /* @__PURE__ */ new Set([
2038
- "basePath",
2039
- "htmlHandling",
2040
- "notFoundHandling",
2041
- "runWorkerFirst"
2042
- ]);
2043
- if (Object.keys(config).some((key) => !supported.has(key))) throw new Error("Cloudflare asset configuration has an unsupported setting.");
2044
- return {
2045
- ...config.basePath === void 0 ? {} : { base_path: config.basePath },
2046
- ...config.htmlHandling === void 0 ? {} : { html_handling: config.htmlHandling },
2047
- ...config.notFoundHandling === void 0 ? {} : { not_found_handling: config.notFoundHandling },
2048
- ...config.runWorkerFirst === void 0 ? {} : { run_worker_first: config.runWorkerFirst }
2049
- };
2050
- }
2051
- /** The region, host or hostname of a targeted placement. */
2052
- function placementTarget(placement) {
2053
- if (!placement) return;
2054
- for (const kind of [
2055
- "region",
2056
- "host",
2057
- "hostname"
2058
- ]) {
2059
- const value = placement[kind];
2060
- if (typeof value === "string" && value) return {
2061
- kind,
2062
- value
2063
- };
2064
- }
2065
- }
2066
- /** The version API placement, in the shape cf's own version uploads send. */
2067
- function placementFromOutput(placement) {
2068
- if (!placement) return;
2069
- const hint = "hint" in placement ? placement.hint : void 0;
2070
- if (hint || placement.mode === "smart") return {
2071
- mode: "smart",
2072
- ...hint ? { hint } : {}
2073
- };
2074
- const target = placementTarget(placement);
2075
- return target ? {
2076
- mode: "targeted",
2077
- [target.kind]: target.value
2078
- } : void 0;
2079
- }
2080
- /**
2081
- * Whether the upload reply still names the requested target. The Workers beta version
2082
- * endpoint has replied `placement: {}` after dropping one (terraform-provider-cloudflare#7273).
2083
- * It now replies with the target alone, e.g. `{ region }`.
2084
- */
2085
- function keepsPlacementTarget(placement, target) {
2086
- const reply = record(placement);
2087
- if (!reply) return false;
2088
- const targets = reply.target === void 0 ? [reply] : reply.target;
2089
- return Array.isArray(targets) && targets.length === 1 && record(targets[0])?.[target.kind] === target.value;
2090
- }
2091
- async function apiResult(url, token, method, body, verifyUploader, timeout = 12e4, headers) {
2092
- assertUploaderUnchanged(verifyUploader);
2093
- const form = body instanceof FormData;
2094
- const response = await fetch(url, {
2095
- method,
2096
- headers: {
2097
- "User-Agent": getVoidUserAgent(),
2098
- Authorization: `Bearer ${token}`,
2099
- ...body && !form ? { "Content-Type": "application/json" } : {},
2100
- ...headers
2101
- },
2102
- ...body ? { body: form ? body : JSON.stringify(body) } : {},
2103
- redirect: "manual",
2104
- signal: AbortSignal.timeout(timeout)
2105
- });
2106
- const parsed = record(await response.json());
2107
- const result = record(parsed?.result);
2108
- if (!response.ok || parsed?.success !== true || !result) {
2109
- const error = Array.isArray(parsed?.errors) ? record(parsed.errors[0]) : null;
2110
- const code = error && Number.isSafeInteger(error.code) ? ` [code: ${error.code}]` : "";
2111
- throw new CloudflareApiError(`Cloudflare version upload failed (${response.status})${code}.`, response.status, typeof error?.code === "number" ? error.code : void 0);
2112
- }
2113
- return result;
2114
- }
2115
- /** Durable Object namespace bindings that point at this Worker's own class. */
2116
- function localNamespaceBindings(bindings, className, workerName) {
2117
- return bindings.flatMap((item) => {
2118
- const binding = record(item);
2119
- return binding?.type === "durable_object_namespace" && binding.class_name === className && (binding.script_name === void 0 || binding.script_name === workerName) && binding.environment === void 0 && binding.dispatch_namespace === void 0 ? [binding] : [];
2120
- });
2121
- }
2122
- function assertContainerApplicationIdentity(application, plan, namespace) {
2123
- if (application.id !== namespace || application.name !== plan.name || application.scheduling_policy !== "durable_object" || record(application.durable_objects)?.namespace_id !== namespace) throw new Error(`Cloudflare Container ${plan.name} application identity does not match the uploaded namespace.`);
2124
- }
2125
- function compareFlagValues(left, right) {
2126
- const a = String(left);
2127
- const b = String(right);
2128
- return a < b ? -1 : a > b ? 1 : 0;
2129
- }
2130
- function assertContainerApplicationSettings(application, plan) {
2131
- const desired = record(plan.settings.configuration) ?? {};
2132
- const current = record(application.configuration) ?? {};
2133
- const changedConfiguration = Object.entries(desired).some(([key, value]) => {
2134
- if (key === "wrangler_ssh") {
2135
- const ssh = record(current.wrangler_ssh) ?? {};
2136
- const expected = record(value) ?? {};
2137
- return !isDeepStrictEqual(ssh.enabled ?? false, expected.enabled) || expected.enabled === true && expected.port !== void 0 && !isDeepStrictEqual(ssh.port, expected.port);
2138
- }
2139
- if (key === "experimental_flags" && Array.isArray(value)) {
2140
- const flags = current.experimental_flags ?? [];
2141
- return !Array.isArray(flags) || !isDeepStrictEqual([...flags].sort(compareFlagValues), [...value].sort(compareFlagValues));
2142
- }
2143
- return !isDeepStrictEqual(current[key] ?? [], value);
2144
- });
2145
- const logs = record(record(plan.settings.observability)?.logs);
2146
- const currentLogs = record(record(application.observability)?.logs);
2147
- if (changedConfiguration || logs !== null && !isDeepStrictEqual(currentLogs?.enabled ?? false, logs.enabled)) throw new Error(`Cloudflare Container ${plan.name} settings differ from the live application. Version-aware deployment cannot safely change these shared settings. Keep the existing Container settings in your configuration, or update this Container explicitly in the Cloudflare dashboard before retrying.`);
2148
- }
2149
- async function preflightContainerApplications(plans, bindings, accountUrl, workerName, token, verifyUploader) {
2150
- for (const plan of plans) {
2151
- const matches = localNamespaceBindings(bindings, plan.className, workerName).filter((binding) => binding.namespace_id !== void 0);
2152
- const namespaces = new Set(matches.map((binding) => binding.namespace_id));
2153
- if (namespaces.size > 1) throw new Error(`Cloudflare Container ${plan.name} active namespace was ambiguous.`);
2154
- const namespace = [...namespaces][0];
2155
- if (namespace === void 0) {
2156
- if (Object.keys(plan.images).length === 0) throw new Error(`Cloudflare Container ${plan.name} has no images and no verified existing namespace application.`);
2157
- continue;
2158
- }
2159
- if (typeof namespace !== "string" || !/^[a-f0-9]{32}$/.test(namespace)) throw new Error("The active Container namespace ID was invalid.");
2160
- try {
2161
- const application = await apiResult(`${accountUrl}/containers/applications/${encodeURIComponent(namespace)}`, token, "GET", void 0, verifyUploader);
2162
- assertContainerApplicationIdentity(application, plan, namespace);
2163
- assertContainerApplicationSettings(application, plan);
2164
- } catch (cause) {
2165
- if (!(cause instanceof CloudflareApiError) || cause.status !== 404 || Object.keys(plan.images).length === 0) throw cause;
2166
- }
2167
- }
2168
- }
2169
- function containerPlansFromOutput(containers, exports, bindings) {
2170
- const plans = [];
2171
- for (const { config } of containers) {
2172
- if (config.schedulingPolicy !== "durable-object") throw new Error("Scheduler-managed Cloudflare Containers cannot be uploaded with pinned secrets.");
2173
- const classes = Object.entries(exports ?? {}).filter(([, value]) => record(value)?.container === config.name);
2174
- if (classes.length !== 1) throw new Error(`Cloudflare Container ${config.name} needs exactly one local SQLite export.`);
2175
- const [className, raw] = classes[0];
2176
- const declaration = record(raw);
2177
- const localBindings = bindings.filter((binding) => binding.type === "durable_object_namespace" && binding.class_name === className && binding.script_name === void 0);
2178
- if (declaration?.storage !== "sqlite" || localBindings.length === 0) throw new Error(`Cloudflare Container ${config.name} needs a local SQLite Durable Object binding.`);
2179
- const unsafe = record(config.unsafe);
2180
- const configuration = record(unsafe?.configuration);
2181
- if (unsafe && Object.keys(unsafe).some((key) => key !== "configuration") || configuration && Object.keys(configuration).some((key) => key !== "experimental_flags")) throw new Error(`Cloudflare Container ${config.name} has an unsupported setting.`);
2182
- const settings = {
2183
- ...configuration || config.ssh || config.authorizedKeys ? { configuration: {
2184
- ...configuration ?? {},
2185
- ...config.ssh ? { wrangler_ssh: config.ssh } : {},
2186
- ...config.authorizedKeys ? { authorized_keys: config.authorizedKeys.map(({ name, publicKey }) => ({
2187
- name,
2188
- public_key: publicKey
2189
- })) } : {}
2190
- } } : {},
2191
- ...config.observability ? { observability: { logs: { enabled: config.observability.enabled === true || config.observability.logs?.enabled === true } } } : {}
2192
- };
2193
- plans.push({
2194
- name: config.name,
2195
- className,
2196
- images: config.images ?? {},
2197
- settings
2198
- });
2199
- }
2200
- for (const [name, raw] of Object.entries(exports ?? {})) {
2201
- const container = record(raw)?.container;
2202
- if (container !== void 0 && !plans.some((plan) => plan.name === container && plan.className === name)) throw new Error(`Cloudflare export ${name} references a Container outside the verified output.`);
2203
- }
2204
- return plans;
2205
- }
2206
- async function dockerImageDigest(image, timeout, verifyUploader) {
2207
- assertUploaderUnchanged(verifyUploader);
2208
- const stdout = await new Promise((resolve, reject) => {
2209
- execFile(process.env.WRANGLER_DOCKER_BIN ?? "docker", [
2210
- "image",
2211
- "inspect",
2212
- "--format",
2213
- "{{json .RepoDigests}}",
2214
- image
2215
- ], {
2216
- encoding: "utf8",
2217
- timeout,
2218
- maxBuffer: 1048576,
2219
- windowsHide: true
2220
- }, (error, stdout) => error ? reject(/* @__PURE__ */ new Error("Cloudflare Container image digest could not be verified after push.")) : resolve(stdout));
2221
- });
2222
- const digests = JSON.parse(stdout);
2223
- const repository = image.replace(/:[^/:]+$/, "");
2224
- const matching = Array.isArray(digests) ? digests.filter((digest) => typeof digest === "string" && digest.startsWith(`${repository}@sha256:`) && /^[a-f0-9]{64}$/.test(digest.slice(digest.lastIndexOf(":") + 1))) : [];
2225
- if (matching.length !== 1) throw new Error("Cloudflare Container image digest could not be verified after push.");
2226
- return matching[0];
2227
- }
2228
- async function prepareContainerMetadata(options) {
2229
- if (options.plans.length === 0) return [];
2230
- const deadline = Date.now() + 9e5;
2231
- const remaining = () => {
2232
- const duration = deadline - Date.now();
2233
- if (duration <= 0) throw new Error("Cloudflare Container image preparation timed out.");
2234
- return duration;
2235
- };
2236
- const prepared = /* @__PURE__ */ new Map();
2237
- const result = [];
2238
- for (const plan of options.plans) {
2239
- const images = {};
2240
- for (const [name, raw] of Object.entries(plan.images)) {
2241
- const source = record(raw);
2242
- const reference = requiredString(source?.localReference ?? source?.reference, `Container ${plan.name} image`);
2243
- let image = prepared.get(reference);
2244
- if (!image) {
2245
- image = reference;
2246
- if (source?.localReference !== void 0) {
2247
- if (!options.runCf || !options.verifyUploader()) throw new Error("The verified Cloudflare Container image uploader is unavailable.");
2248
- const pushed = await options.runCf([
2249
- "containers",
2250
- "push",
2251
- "--tag",
2252
- reference
2253
- ], {
2254
- cwd: options.directory,
2255
- capture: true,
2256
- timeoutMs: remaining(),
2257
- maxOutputBytes: 16777216
2258
- });
2259
- if (pushed.status !== 0 || pushed.signal || pushed.error) throw new Error("Cloudflare Container image push failed.");
2260
- const matches = [...`${pushed.stdout}\n${pushed.stderr}`.matchAll(/Pushed image:\s*(\S+)/g)];
2261
- const remote = matches.length === 1 ? matches[0][1] : "";
2262
- if (!remote.startsWith(`registry.cloudflare.com/${options.accountId}/`) || Array.from(remote).some((character) => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127)) throw new Error("Cloudflare Container image push did not return the verified account registry.");
2263
- image = await dockerImageDigest(remote, Math.min(12e4, remaining()), options.verifyUploader);
2264
- }
2265
- for (;;) {
2266
- const ready = await apiResult(`${options.accountUrl}/containers/image-preparations`, options.token, "POST", { image }, options.verifyUploader, Math.min(12e4, remaining()));
2267
- if (ready.image !== image) throw new Error("Cloudflare Container image preparation returned another image.");
2268
- if (ready.status === "ready") break;
2269
- if (ready.status !== "pending") throw new Error("Cloudflare Container image preparation failed or returned an unsupported state.");
2270
- await setTimeout$1(Math.min(2e3, remaining()));
2271
- }
2272
- prepared.set(reference, image);
2273
- }
2274
- images[name] = image;
2275
- }
2276
- result.push({
2277
- name: plan.name,
2278
- class_name: plan.className,
2279
- ...Object.keys(images).length ? { images } : {}
2280
- });
2281
- }
2282
- return result;
2283
- }
2284
- async function ensureContainerApplications(options) {
2285
- if (options.plans.length === 0) return;
2286
- const deadline = Date.now() + 6e4;
2287
- let version;
2288
- for (;;) try {
2289
- version = await apiResult(`${options.accountUrl}/workers/scripts/${encodeURIComponent(options.workerName)}/versions/${encodeURIComponent(options.versionId)}`, options.token, "GET", void 0, options.verifyUploader, Math.max(1, Math.min(3e4, deadline - Date.now())));
2290
- break;
2291
- } catch (cause) {
2292
- if (!(cause instanceof CloudflareApiError) || cause.code !== 100146 || Date.now() >= deadline) throw cause;
2293
- await setTimeout$1(Math.min(2e3, deadline - Date.now()));
2294
- }
2295
- const versionBindings = record(version.resources)?.bindings;
2296
- if (version.id !== options.versionId || !Array.isArray(versionBindings)) throw new Error("The uploaded Container namespace could not be verified.");
2297
- const metadata = record(record(version.resources)?.script_runtime)?.containers;
2298
- if (!Array.isArray(metadata) || metadata.length !== options.containers.length || options.containers.some((expected) => {
2299
- const matching = metadata.map(record).filter((entry) => entry !== null && entry.name === expected.name && entry.class_name === expected.class_name);
2300
- const actual = matching[0];
2301
- return matching.length !== 1 || !actual || !isDeepStrictEqual(actual.images ?? {}, expected.images ?? {});
2302
- })) throw new Error("The uploaded Worker version did not retain the verified Container image metadata.");
2303
- for (const plan of options.plans) {
2304
- const matches = localNamespaceBindings(versionBindings, plan.className, options.workerName);
2305
- const namespaces = new Set(matches.map((binding) => binding.namespace_id));
2306
- if (matches.length === 0 || namespaces.size !== 1) throw new Error(`Cloudflare Container ${plan.name} has no unambiguous uploaded local namespace.`);
2307
- const namespace = requiredString([...namespaces][0], `Container ${plan.name} namespace`);
2308
- if (!/^[a-f0-9]{32}$/.test(namespace)) throw new Error("The uploaded Container namespace ID was invalid.");
2309
- const url = `${options.accountUrl}/containers/applications/${encodeURIComponent(namespace)}`;
2310
- let application;
2311
- try {
2312
- application = await apiResult(url, options.token, "GET", void 0, options.verifyUploader);
2313
- } catch (cause) {
2314
- if (!(cause instanceof CloudflareApiError) || cause.status !== 404) throw cause;
2315
- application = await apiResult(`${options.accountUrl}/containers/applications`, options.token, "POST", {
2316
- name: plan.name,
2317
- scheduling_policy: "durable_object",
2318
- durable_objects: { namespace_id: namespace },
2319
- ...plan.settings
2320
- }, options.verifyUploader);
2321
- }
2322
- assertContainerApplicationIdentity(application, plan, namespace);
2323
- assertContainerApplicationSettings(application, plan);
2324
- const confirmed = await apiResult(url, options.token, "GET", void 0, options.verifyUploader);
2325
- assertContainerApplicationIdentity(confirmed, plan, namespace);
2326
- assertContainerApplicationSettings(confirmed, plan);
2327
- }
2328
- }
2329
- function readAssetHeaders(output) {
2330
- if (!output.assetsDirectory) return;
2331
- try {
2332
- return readFileSync(join(getWorkerAssetsDir(output.directory), "_headers"), "utf8");
2333
- } catch (cause) {
2334
- if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return;
2335
- throw cause;
2336
- }
2337
- }
2338
- async function uploadAssets(options) {
2339
- if (!options.output.assetsDirectory) return;
2340
- const directory = getWorkerAssetsDir(options.output.directory);
2341
- const manifest = {};
2342
- const byHash = /* @__PURE__ */ new Map();
2343
- const ignored = ignore().add([
2344
- ".DS_Store",
2345
- ".env",
2346
- ".env.*",
2347
- ".dev.vars",
2348
- ".dev.vars.*"
2349
- ]);
2350
- const ignorePath = join(directory, ".assetsignore");
2351
- try {
2352
- ignored.add(readFileSync(ignorePath, "utf8"));
2353
- } catch (cause) {
2354
- if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause;
2355
- }
2356
- ignored.add([
2357
- "/.assetsignore",
2358
- "/_headers",
2359
- "/_redirects"
2360
- ]);
2361
- for (const entry of readdirSync(directory, {
2362
- recursive: true,
2363
- withFileTypes: true
2364
- })) {
2365
- if (entry.isDirectory()) continue;
2366
- if (!entry.isFile()) throw new Error("The Cloudflare asset output contains an unsupported entry.");
2367
- const path = join(entry.parentPath, entry.name);
2368
- const relativeName = relative(directory, path).replaceAll("\\", "/");
2369
- if (ignored.ignores(relativeName)) continue;
2370
- const name = `/${relativeName}`;
2371
- const content = readFileSync(path);
2372
- const extension = extname(entry.name).slice(1);
2373
- const hash = createHash("sha256").update(content.toString("base64") + extension).digest("hex").slice(0, 32);
2374
- manifest[name] = {
2375
- hash,
2376
- size: content.length
2377
- };
2378
- byHash.set(hash, path);
2379
- }
2380
- const session = await apiResult(`${options.accountUrl}/workers/scripts/${encodeURIComponent(options.workerName)}/assets-upload-session`, options.token, "POST", { manifest }, options.verifyUploader);
2381
- const uploadJwt = requiredString(session.jwt, "asset upload token");
2382
- if (!Array.isArray(session.buckets)) throw new Error("Cloudflare did not provide asset upload batches.");
2383
- if (session.buckets.length === 0) return uploadJwt;
2384
- let completionJwt;
2385
- for (const bucket of session.buckets) {
2386
- if (!Array.isArray(bucket) || !bucket.every((hash) => typeof hash === "string")) throw new Error("Cloudflare returned an invalid asset upload batch.");
2387
- const form = new FormData();
2388
- for (const hash of bucket) {
2389
- const path = byHash.get(hash);
2390
- if (!path) throw new Error("Cloudflare requested an asset outside the verified Worker output.");
2391
- form.append(hash, new File([readFileSync(path).toString("base64")], hash, { type: mime.getType(path) ?? "application/null" }));
2392
- }
2393
- const uploaded = await apiResult(`${options.accountUrl}/workers/assets/upload?base64=true`, uploadJwt, "POST", form, options.verifyUploader);
2394
- if (uploaded.jwt !== void 0) completionJwt = requiredString(uploaded.jwt, "asset completion token");
2395
- }
2396
- return requiredString(completionJwt, "asset completion token");
2397
- }
2398
- /** The Workers beta API is the only upload endpoint that accepts a version UUID as an inheritance source. */
2399
- async function uploadPinnedCloudflareVersion(options) {
2400
- const activeSecrets = options.output.activeSecrets;
2401
- if (!activeSecrets) throw new Error("The active Worker secret source was not verified.");
2402
- const built = await readBuildOutput(options.output.directory);
2403
- const config = built.workers.default.config;
2404
- if (config.name !== options.workerName || !config.manifest || config.manifest.type !== "complete") throw new Error("The verified Cloudflare Worker output changed before upload.");
2405
- const unsupported = Object.keys(config).filter((key) => !(/* @__PURE__ */ new Set([
2406
- "name",
2407
- "compatibilityDate",
2408
- "compatibilityFlags",
2409
- "assets",
2410
- "domains",
2411
- "observability",
2412
- "workersDev",
2413
- "previewUrls",
2414
- "unsafe",
2415
- "env",
2416
- "exports",
2417
- "manifest",
2418
- "triggers",
2419
- "limits",
2420
- "placement",
2421
- "cache",
2422
- "logpush",
2423
- "tailConsumers"
2424
- ])).has(key));
2425
- if (unsupported.length) throw new Error(`Cloudflare Worker setting ${unsupported[0]} cannot be uploaded with pinned secrets.`);
2426
- const placement = placementFromOutput(config.placement);
2427
- const unsafe = record(config.unsafe);
2428
- const metadata = record(unsafe?.metadata);
2429
- if (unsafe && Object.keys(unsafe).some((key) => key !== "metadata") || metadata && Object.keys(metadata).some((key) => key !== "keep_bindings") || metadata?.keep_bindings !== void 0 && (!Array.isArray(metadata.keep_bindings) || !metadata.keep_bindings.every((type) => typeof type === "string"))) throw new Error("Cloudflare Worker upload metadata has an unsupported setting.");
2430
- const explicitSecrets = options.secretsFilePath ? record(JSON.parse(readFileSync(options.secretsFilePath, "utf8"))) : {};
2431
- if (!explicitSecrets) throw new Error("The explicit Cloudflare secrets file was not readable.");
2432
- const bindings = bindingsFromOutput(config.env ?? {}, options.workerName, activeSecrets, explicitSecrets);
2433
- const exports = exportsFromOutput(config.exports, bindings);
2434
- const containerPlans = containerPlansFromOutput(built.containers, exports, bindings);
2435
- const accountUrl = `${options.apiBaseUrl.replace(/\/$/, "")}/accounts/${encodeURIComponent(options.accountId)}`;
2436
- const active = await apiResult(`${accountUrl}/workers/workers/${encodeURIComponent(options.workerName)}/versions/${encodeURIComponent(activeSecrets.versionId)}`, options.token, "GET", void 0, options.verifyUploader);
2437
- if (active.id !== activeSecrets.versionId || !Array.isArray(active.bindings)) throw new Error("The active Cloudflare Worker bindings could not be verified.");
2438
- const activeBindingNames = /* @__PURE__ */ new Set();
2439
- const candidateNames = new Set(bindings.map((binding) => String(binding.name)));
2440
- const keptTypes = new Set(metadata?.keep_bindings ?? []);
2441
- for (const entry of active.bindings) {
2442
- const binding = record(entry);
2443
- if (!binding || typeof binding.name !== "string" || typeof binding.type !== "string") throw new Error("The active Cloudflare Worker bindings could not be verified.");
2444
- activeBindingNames.add(binding.name);
2445
- if (!candidateNames.has(binding.name) && keptTypes.has(binding.type) && ["plain_text", "json"].includes(binding.type)) {
2446
- bindings.push({
2447
- name: binding.name,
2448
- type: "inherit",
2449
- version_id: activeSecrets.versionId
2450
- });
2451
- candidateNames.add(binding.name);
2452
- }
2453
- }
2454
- if (activeSecrets.bindings.some(({ name }) => !activeBindingNames.has(name))) throw new Error("The active Cloudflare Worker secrets changed before upload.");
2455
- const assetConfig = assetConfigFromOutput(config.assets);
2456
- if (bindings.some((binding) => binding.type === "assets") && !options.output.assetsDirectory) throw new Error("The Cloudflare Worker has an assets binding without verified assets.");
2457
- const modules = [];
2458
- for (const [name, entry] of Object.entries(config.manifest.modules)) {
2459
- const type = moduleContentTypes.get(entry.type);
2460
- if (!type || name.startsWith("/") || name.split("/").includes("..")) throw new Error(`Cloudflare Worker module ${name} cannot be uploaded with pinned secrets.`);
2461
- modules.push({
2462
- name,
2463
- content_type: type,
2464
- content_base64: readFileSync(join(getWorkerBundleDir(options.output.directory), name)).toString("base64")
2465
- });
2466
- }
2467
- const assetHeaders = readAssetHeaders(options.output);
2468
- if (assetHeaders !== void 0) modules.push({
2469
- name: "_headers",
2470
- content_type: "text/plain",
2471
- content_base64: Buffer.from(assetHeaders).toString("base64")
2472
- });
2473
- await preflightWorkflowExports({
2474
- exports,
2475
- accountUrl,
2476
- workerName: options.workerName,
2477
- token: options.token,
2478
- verifyUploader: options.verifyUploader
2479
- });
2480
- await preflightContainerApplications(containerPlans, active.bindings, accountUrl, options.workerName, options.token, options.verifyUploader);
2481
- const containers = await prepareContainerMetadata({
2482
- plans: containerPlans,
2483
- directory: options.output.directory,
2484
- accountUrl,
2485
- accountId: options.accountId,
2486
- token: options.token,
2487
- verifyUploader: options.verifyUploader,
2488
- runCf: options.runCf
2489
- });
2490
- const jwt = await uploadAssets({
2491
- output: options.output,
2492
- accountUrl,
2493
- workerName: options.workerName,
2494
- token: options.token,
2495
- verifyUploader: options.verifyUploader
2496
- });
2497
- const uploaded = await apiResult(`${accountUrl}/workers/workers/${encodeURIComponent(options.workerName)}/versions${options.atomic ? "?deploy=true" : ""}`, options.token, "POST", {
2498
- main_module: config.manifest.mainModule,
2499
- modules,
2500
- compatibility_date: config.compatibilityDate,
2501
- compatibility_flags: config.compatibilityFlags,
2502
- package_dependencies: await readPackageDependencies(options.output.directory),
2503
- bindings,
2504
- ...config.limits ? { limits: {
2505
- cpu_ms: config.limits.cpuMs,
2506
- subrequests: config.limits.subrequests
2507
- } } : {},
2508
- ...placement ? { placement } : {},
2509
- ...config.cache ? { cache_options: {
2510
- enabled: config.cache.enabled,
2511
- cross_version_cache: config.cache.crossVersionCache
2512
- } } : {},
2513
- ...exports ? { exports } : {},
2514
- ...containers.length ? { containers } : {},
2515
- ...jwt ? { assets: {
2516
- jwt,
2517
- ...assetConfig ? { config: assetConfig } : {}
2518
- } } : {},
2519
- annotations: { "workers/message": options.message ?? "" }
2520
- }, options.verifyUploader, void 0, Object.values(exports ?? {}).some((entry) => record(entry)?.type === "workflow") ? { "Cloudflare-Workers-Script-Api-Date": "2026-11-09" } : void 0);
2521
- const versionId = uploaded.id;
2522
- if (typeof versionId !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(versionId)) throw new Error("Cloudflare accepted the Worker upload but returned an invalid version identity. Read back the Worker deployment before retrying.");
2523
- try {
2524
- await ensureContainerApplications({
2525
- plans: containerPlans,
2526
- containers,
2527
- accountUrl,
2528
- workerName: options.workerName,
2529
- versionId,
2530
- token: options.token,
2531
- verifyUploader: options.verifyUploader
2532
- });
2533
- } catch {
2534
- throw new Error(`Cloudflare Worker version ${versionId} was uploaded${options.atomic ? " and may already be published" : ""}, but its Container applications could not be verified. Read back the Worker deployment and Container identities before retrying.`);
2535
- }
2536
- const target = placementTarget(config.placement);
2537
- if (target && !keepsPlacementTarget(uploaded.placement, target)) throw new Error(`Cloudflare did not keep placement.${target.kind} "${target.value}" on Worker version ${versionId}${options.atomic ? ", which is already live" : ", so it was not deployed"}. Deploy again, or set cloudflare.placement to { mode: 'smart' } in void.config.ts.`);
2538
- return {
2539
- id: versionId,
2540
- urls: Array.isArray(uploaded.urls) ? uploaded.urls.filter((url) => typeof url === "string") : []
2541
- };
2542
- }
2543
1623
  // src/cli/cf-version-runner.ts
2544
1624
  function failed(message) {
2545
1625
  return {
@@ -2868,20 +1948,17 @@ function createCfVersionRunner(options) {
2868
1948
  return failed("Cloudflare resources could not be verified before upload.");
2869
1949
  }
2870
1950
  };
2871
- /** Return a failure when the upload target drifted or its resources are not verified. */
2872
- const checkUploadTarget = async (operation, targetChanged) => {
2873
- if (operation.workerName !== workerName || operation.assetsDirectory !== void 0 && operation.assetsDirectory !== output.assetsDirectory) return failed(targetChanged);
2874
- const verified = await verifyResources(output.directory);
2875
- return isCleanCloudflareExit(verified) ? null : verified;
2876
- };
2877
- const uploadPinnedVersion = async (operation, atomic) => {
1951
+ const uploadPinnedVersion = async (operation, atomic, directory) => {
2878
1952
  if (!options.pinnedUpload || !options.pinnedUpload.verifyUploader()) return failed("The version-aware Cloudflare uploader is unavailable.");
2879
1953
  const credential = await readSessionToken(options.pinnedUpload);
2880
1954
  if (!credential.ok) return credentialFailed("Could not get the Cloudflare session credential for the upload", credential.failure);
2881
1955
  const { token } = credential;
2882
1956
  try {
2883
1957
  const version = await uploadPinnedCloudflareVersion({
2884
- output,
1958
+ output: {
1959
+ ...output,
1960
+ directory
1961
+ },
2885
1962
  accountId: options.pinnedUpload.accountId,
2886
1963
  apiBaseUrl: options.pinnedUpload.apiBaseUrl,
2887
1964
  workerName,
@@ -2907,6 +1984,10 @@ function createCfVersionRunner(options) {
2907
1984
  }
2908
1985
  };
2909
1986
  return async (operation, command) => {
1987
+ if (operation.type === "triggers.clear-workflow-schedules") {
1988
+ if (operation.workerName !== workerName || !options.clearWorkflowSchedules) return failed("The Cloudflare Workflow schedule publisher is unavailable for this Worker.");
1989
+ return options.clearWorkflowSchedules(operation, command);
1990
+ }
2910
1991
  if (operation.type === "deployments.status") {
2911
1992
  const result = await run([
2912
1993
  "workers",
@@ -3022,21 +2103,50 @@ function createCfVersionRunner(options) {
3022
2103
  }
3023
2104
  };
3024
2105
  }
3025
- if (operation.type === "versions.upload") {
3026
- const blocked = await checkUploadTarget(operation, "The Cloudflare version upload target changed.");
3027
- if (blocked) return blocked;
3028
- const settings = await prepareSettingsCredential(operation.message);
3029
- if (settings) return settings;
3030
- if (output.activeSecrets) return uploadPinnedVersion(operation, false);
3031
- return uploadedResult(await run([
3032
- "workers",
3033
- "versions",
3034
- "create",
2106
+ if (operation.type === "versions.upload" || operation.type === "worker.deploy") {
2107
+ const atomic = operation.type === "worker.deploy";
2108
+ if (operation.workerName !== workerName || operation.assetsDirectory !== void 0 && operation.assetsDirectory !== output.assetsDirectory) return failed(atomic ? "The Cloudflare bootstrap target changed." : "The Cloudflare version upload target changed.");
2109
+ try {
2110
+ return await withCloudflareVersionMessage(output.directory, output.activeSecrets ? { message: operation.message } : operation, async (directory, message) => {
2111
+ const verified = await verifyResources(directory);
2112
+ if (!isCleanCloudflareExit(verified)) return verified;
2113
+ const settings = await prepareSettingsCredential(operation.message);
2114
+ if (settings) return settings;
2115
+ if (output.activeSecrets) return uploadPinnedVersion({
2116
+ ...operation,
2117
+ message
2118
+ }, atomic, directory);
2119
+ return uploadedResult(await run([
2120
+ ...atomic ? ["deploy"] : [
2121
+ "workers",
2122
+ "versions",
2123
+ "create"
2124
+ ],
2125
+ "--prebuilt",
2126
+ ...message ? [`--message=${message}`] : [],
2127
+ ...operation.secretsFilePath ? ["--secrets-file", operation.secretsFilePath] : [],
2128
+ ...!atomic && operation.previewAlias ? ["--preview-alias", operation.previewAlias] : []
2129
+ ], command.capture, directory));
2130
+ });
2131
+ } catch (cause) {
2132
+ return failed(cause instanceof Error ? cause.message : "Cloudflare version upload failed.");
2133
+ }
2134
+ }
2135
+ if (operation.type === "previews.deploy") {
2136
+ if (operation.workerName !== workerName) return failed("The Cloudflare preview target changed.");
2137
+ const verified = await verifyResources(output.directory);
2138
+ if (!isCleanCloudflareExit(verified)) return verified;
2139
+ const deployed = await run([
2140
+ "previews",
2141
+ "deploy",
3035
2142
  "--prebuilt",
3036
- ...operation.message ? [`--message=${operation.message}`] : [],
3037
- ...operation.secretsFilePath ? ["--secrets-file", operation.secretsFilePath] : [],
3038
- ...operation.previewAlias ? ["--preview-alias", operation.previewAlias] : []
3039
- ], command.capture));
2143
+ `--preview-name=${operation.previewName}`
2144
+ ], command.capture);
2145
+ if (!isCleanCloudflareExit(deployed)) return deployed;
2146
+ return {
2147
+ ...deployed,
2148
+ data: readCfPreviewDeployOutput(deployed.data)
2149
+ };
3040
2150
  }
3041
2151
  if (operation.type === "versions.deploy") {
3042
2152
  if (operation.workerName !== workerName) return failed("The Cloudflare deployment target changed.");
@@ -3059,24 +2169,11 @@ function createCfVersionRunner(options) {
3059
2169
  ...operation.message ? ["--body", JSON.stringify({
3060
2170
  strategy: "percentage",
3061
2171
  versions: parsed,
3062
- annotations: { "workers/message": operation.message }
2172
+ annotations: { "workers/message": cloudflareVersionMessageReference(operation.message) ?? operation.message }
3063
2173
  })] : [],
3064
2174
  ...operation.bypassDeploymentChecks ? ["--bypass-deployment-checks"] : []
3065
2175
  ], command.capture);
3066
2176
  }
3067
- if (operation.type === "worker.deploy") {
3068
- const blocked = await checkUploadTarget(operation, "The Cloudflare bootstrap target changed.");
3069
- if (blocked) return blocked;
3070
- const settings = await prepareSettingsCredential(operation.message);
3071
- if (settings) return settings;
3072
- if (output.activeSecrets) return uploadPinnedVersion(operation, true);
3073
- return uploadedResult(await run([
3074
- "deploy",
3075
- "--prebuilt",
3076
- ...operation.message ? [`--message=${operation.message}`] : [],
3077
- ...operation.secretsFilePath ? ["--secrets-file", operation.secretsFilePath] : []
3078
- ], command.capture));
3079
- }
3080
2177
  if (operation.type === "triggers.deploy") {
3081
2178
  const configPath = operation.configPath;
3082
2179
  if (!configPath || operation.workerName !== workerName) return failed("The Cloudflare trigger target changed.");
@@ -3176,24 +2273,201 @@ function createCfVersionRunner(options) {
3176
2273
  if (item.script_name !== void 0 && !safePositional(item.script_name) || item.script !== void 0 && !safePositional(item.script) || item.script_name !== void 0 && item.script !== void 0 && item.script_name !== item.script || item.type === "worker" && name === void 0) return failed("The Cloudflare Queue consumer Worker identity was ambiguous.");
3177
2274
  if (name === workerName) matching.push(item);
3178
2275
  }
3179
- if (matching.length === 0) return {
3180
- status: 0,
3181
- stdout: "",
3182
- stderr: ""
3183
- };
3184
- if (matching.length !== 1 || !safePositional(matching[0].consumer_id) || matching[0].type !== void 0 && matching[0].type !== "worker") return failed("The Cloudflare Queue consumer identity was ambiguous.");
3185
- return run([
3186
- "queues",
3187
- "consumers",
3188
- "delete",
3189
- matching[0].consumer_id,
3190
- "--queue-id",
3191
- queue.queue_id,
3192
- "--force"
3193
- ], command.capture);
2276
+ if (matching.length === 0) return {
2277
+ status: 0,
2278
+ stdout: "",
2279
+ stderr: ""
2280
+ };
2281
+ if (matching.length !== 1 || !safePositional(matching[0].consumer_id) || matching[0].type !== void 0 && matching[0].type !== "worker") return failed("The Cloudflare Queue consumer identity was ambiguous.");
2282
+ return run([
2283
+ "queues",
2284
+ "consumers",
2285
+ "delete",
2286
+ matching[0].consumer_id,
2287
+ "--queue-id",
2288
+ queue.queue_id,
2289
+ "--force"
2290
+ ], command.capture);
2291
+ }
2292
+ return failed(`Unsupported Cloudflare activation operation: ${operation.type}`);
2293
+ };
2294
+ }
2295
+ // src/cli/deploy-cloudflare-auth.ts
2296
+ var import_ci_info = require_ci_info();
2297
+ /** Run typed provider operations in the pinned account and API context. */
2298
+ function createDeployWranglerRunner(root, accountId, apiBaseUrl) {
2299
+ const runner = createCloudflareProcessRunner({
2300
+ root,
2301
+ accountId,
2302
+ apiBaseUrl,
2303
+ env: () => deployChildEnv(accountId, apiBaseUrl)
2304
+ });
2305
+ return (operation, opts) => runner(operation, opts);
2306
+ }
2307
+ /** Retry an existing-Worker read only when a fresh identity check proves the session is gone. */
2308
+ async function prepareExistingCloudflareDeployWithAuth(options, beforeRun) {
2309
+ try {
2310
+ return await prepareExistingCloudflareDeploy(options);
2311
+ } catch (error) {
2312
+ if (!(error instanceof CloudflareWorkerInspectionError)) throw error;
2313
+ if (!beforeRun()) throw new CloudflareAuthenticationError("The Cloudflare uploader changed during Worker verification.", "uploader-changed");
2314
+ const configPath = existsSync(options.configPath) ? options.configPath : void 0;
2315
+ const identity = await options.runWrangler({
2316
+ type: "auth.whoami",
2317
+ configPath
2318
+ }, { capture: true });
2319
+ const session = isCleanCloudflareExit(identity) ? parseCloudflareAuthSession(identity.data) : null;
2320
+ const wrongAccount = session !== null && session.accounts.length > 0 && !session.accounts.some((account) => account.id === options.accountId);
2321
+ if (session && !wrongAccount) throw error;
2322
+ if (!(identity.data?.loggedIn === false || wrongAccount || /authentication is required|not authenticated|no api token|invalid.*token|expired.*token|unauthorized/i.test(identity.stderr)) || identity.signal || identity.error) throw new Error("Could not verify the Cloudflare session after the Worker check failed. Run `void cloudflare status` and retry.");
2323
+ const overrides = cloudflareCredentialOverrides();
2324
+ if (overrides.length > 0) throw new Error(`Cloudflare credentials from ${overrides.join(", ")} were rejected or cannot access account ${options.accountId}. Correct or unset them, then retry the deploy.`);
2325
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error(wrongAccount ? `The Cloudflare session cannot access account ${options.accountId}. Run \`void cloudflare login\` with the correct user, or set a token for that account in CI, then retry.` : "Cloudflare authentication expired or is unavailable. Run `void cloudflare login` in a terminal, or set CLOUDFLARE_API_TOKEN in CI, then retry.");
2326
+ log.warn(wrongAccount ? "The current Cloudflare session cannot access the deployment account. Signing in before retrying the Worker check." : "Cloudflare session is unavailable. Signing in before retrying the Worker check.");
2327
+ if (!(await ensureCloudflareAuthentication({
2328
+ forceLogin: true,
2329
+ requireAccounts: true,
2330
+ beforeRun,
2331
+ runWrangler: (operation, capture) => options.runWrangler(operation, { capture }),
2332
+ configPath
2333
+ })).accounts.some((account) => account.id === options.accountId)) throw new Error(`The signed-in Cloudflare user cannot access account ${options.accountId}. Sign in with a user who can access it, then retry.`);
2334
+ if (!beforeRun()) throw new CloudflareAuthenticationError("The Cloudflare uploader changed during sign-in.", "uploader-changed");
2335
+ return await prepareExistingCloudflareDeploy(options);
2336
+ }
2337
+ }
2338
+ async function chooseCloudflareDeployAccount(options) {
2339
+ const accounts = (await ensureCloudflareAuthentication({
2340
+ beforeRun: options.beforeWranglerRun,
2341
+ requireAccounts: true,
2342
+ runWrangler: (operation, capture) => options.runWrangler(operation, { capture }),
2343
+ configPath: existsSync(options.configPath) ? options.configPath : void 0
2344
+ })).accounts;
2345
+ let account = accounts[0];
2346
+ if (accounts.length > 1) {
2347
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Multiple Cloudflare accounts are available. Set CLOUDFLARE_ACCOUNT_ID in CI, or run `void init` interactively to choose one.");
2348
+ const accountId = await select({
2349
+ message: "Choose a Cloudflare account:",
2350
+ initialValue: account.id,
2351
+ options: accounts.map((candidate) => ({
2352
+ value: candidate.id,
2353
+ label: candidate.name,
2354
+ hint: candidate.id
2355
+ }))
2356
+ });
2357
+ if (isCancel(accountId) || typeof accountId === "symbol") throw new Error("Cloudflare account selection was cancelled.");
2358
+ account = accounts.find((candidate) => candidate.id === accountId) ?? account;
2359
+ }
2360
+ if (options.persist !== false) writeProvisionedWranglerConfig(options.root, { accountId: account.id }, { configPath: options.configPath });
2361
+ log.step(`Configured Cloudflare account: ${account.name}`);
2362
+ return account.id;
2363
+ }
2364
+ /** Non-interactive when CI is detected or stdin/stdout is not a TTY. */
2365
+ function isWranglerNonInteractiveOrCI() {
2366
+ return import_ci_info.isCI || !(process.stdin.isTTY && process.stdout.isTTY);
2367
+ }
2368
+ const GLOBAL_API_KEY_SESSION = "the session uses a Global API Key (CLOUDFLARE_API_KEY), which this step cannot use. Set CLOUDFLARE_API_TOKEN, or unset CLOUDFLARE_API_KEY and run `void cloudflare login`, then retry.";
2369
+ const fail = (status, signal, stderr) => ({
2370
+ ok: false,
2371
+ failure: {
2372
+ status: status === 0 ? 1 : status,
2373
+ ...signal ? { signal } : {},
2374
+ stdout: "",
2375
+ stderr
2376
+ }
2377
+ });
2378
+ /**
2379
+ * Read the current Cloudflare session bearer through the pinned deploy runner, for API calls
2380
+ * Void makes itself. The token goes only to the caller. A failure is built fresh from the
2381
+ * child's status, signal and stderr: it never carries the child's errorCode, failure, errors
2382
+ * or data, so an auth failure can never be read as a Cloudflare upload error.
2383
+ */
2384
+ async function readWranglerAuthToken(runWrangler, configPath) {
2385
+ let result;
2386
+ try {
2387
+ result = await Promise.resolve(runWrangler({
2388
+ type: "auth.token",
2389
+ configPath
2390
+ }, { capture: true }));
2391
+ } catch (error) {
2392
+ return fail(1, null, `${describeCloudflareChildFailure({
2393
+ status: 1,
2394
+ error: getErrorMessage(error)
2395
+ })}.`);
2396
+ }
2397
+ const parsed = result.data;
2398
+ if (!isCleanCloudflareExit(result)) {
2399
+ if (parsed?.type === "api_key" && !result.error && !result.signal) return fail(result.status, null, GLOBAL_API_KEY_SESSION);
2400
+ return fail(result.status, result.signal, formatCloudflareChildFailure(result));
2401
+ }
2402
+ const type = parsed?.type;
2403
+ const token = parsed?.token;
2404
+ return (type === "oauth" || type === "api_token") && typeof token === "string" && token.length > 0 ? {
2405
+ ok: true,
2406
+ token
2407
+ } : fail(1, null, "the Void CLI helper process returned no session credential.");
2408
+ }
2409
+ /** {@link readWranglerAuthToken} for callers that only need the token; every failure is `null`. */
2410
+ async function runWranglerAuthToken(runWrangler, configPath) {
2411
+ const read = await readWranglerAuthToken(runWrangler, configPath);
2412
+ return read.ok ? read.token : null;
2413
+ }
2414
+ /**
2415
+ * Ensure an auth-enabled worker has one persistent Better Auth secret.
2416
+ *
2417
+ * Existing remote secrets are adopted unchanged. A missing secret is generated
2418
+ * once, streamed to `wrangler secret put` over stdin (never argv), then verified
2419
+ * by listing names again. A not-yet-deployed Worker is the one safe list failure
2420
+ * treated as absence because Wrangler can attach a secret to its draft Worker.
2421
+ */
2422
+ async function ensureCloudflareAuthSecret(options) {
2423
+ let workerWasMissing = false;
2424
+ const beforeRun = () => {
2425
+ if (options.beforeWranglerRun && !options.beforeWranglerRun()) throw new CloudflareAuthSecretError("", "uploader-changed");
2426
+ };
2427
+ const list = async (allowMissingWorker) => {
2428
+ beforeRun();
2429
+ try {
2430
+ return await listSelfHostSecretNames({
2431
+ root: options.root,
2432
+ configPath: options.configPath,
2433
+ accountId: options.accountId,
2434
+ workerName: options.workerName,
2435
+ runWrangler: (args) => options.runWrangler(args, { capture: true })
2436
+ }, [BETTER_AUTH_SECRET_NAME]);
2437
+ } catch (error) {
2438
+ if (allowMissingWorker && error instanceof SelfHostFirstDeployError) {
2439
+ workerWasMissing = true;
2440
+ return [];
2441
+ }
2442
+ if (error instanceof SelfHostSecretListError) throw new CloudflareAuthSecretError(`deploy: could not confirm the remote ${BETTER_AUTH_SECRET_NAME}. No worker was uploaded. Run \`void secret list\` to diagnose the Cloudflare response, then retry.`, allowMissingWorker ? "list-failed" : "verification-failed");
2443
+ throw error;
3194
2444
  }
3195
- return failed(`Unsupported Cloudflare activation operation: ${operation.type}`);
3196
2445
  };
2446
+ if ((await list(true)).includes("BETTER_AUTH_SECRET")) return { created: false };
2447
+ const secret = randomBytes(32).toString("hex");
2448
+ if (workerWasMissing) return {
2449
+ created: true,
2450
+ workerWasMissing: true,
2451
+ candidateSecret: secret
2452
+ };
2453
+ beforeRun();
2454
+ let put;
2455
+ try {
2456
+ put = await Promise.resolve(options.runWrangler({
2457
+ type: "secret.put",
2458
+ name: BETTER_AUTH_SECRET_NAME,
2459
+ configPath: options.configPath,
2460
+ workerName: options.workerName
2461
+ }, {
2462
+ capture: true,
2463
+ input: `${secret}\n`
2464
+ }));
2465
+ } catch {
2466
+ throw new CloudflareAuthSecretError(`deploy: could not create the remote ${BETTER_AUTH_SECRET_NAME}. No worker was uploaded. Run \`void secret put ${BETTER_AUTH_SECRET_NAME}\` and retry.`, "put-failed");
2467
+ }
2468
+ if (!isCleanCloudflareExit(put)) throw new CloudflareAuthSecretError(`deploy: could not create the remote ${BETTER_AUTH_SECRET_NAME} (Cloudflare command exit ${String(put.status)}). No worker was uploaded. Run \`void secret put ${BETTER_AUTH_SECRET_NAME}\` and retry.`, "put-failed");
2469
+ if (!(await list(false)).includes("BETTER_AUTH_SECRET")) throw new CloudflareAuthSecretError(`deploy: Cloudflare reported success but ${BETTER_AUTH_SECRET_NAME} was not present afterward. No worker was uploaded; retry once Cloudflare secret storage is available.`, "verification-failed");
2470
+ return { created: true };
3197
2471
  }
3198
2472
  // src/cli/deploy-cloudflare-helpers.ts
3199
2473
  /**
@@ -3219,19 +2493,19 @@ function createCloudflareUploaderPins(root, deps) {
3219
2493
  usesCf,
3220
2494
  cfUploaderIsPinned: () => {
3221
2495
  const matched = cfUploaderHashBefore !== void 0 && cfUploaderHashBefore === hashCfUploader();
3222
- if (!matched) log$1.error("deploy: refusing to run a changed cf uploader with Cloudflare credentials.");
2496
+ if (!matched) log.error("deploy: refusing to run a changed cf uploader with Cloudflare credentials.");
3223
2497
  return matched;
3224
2498
  },
3225
2499
  assertUploaderStillPinned: () => {
3226
2500
  const check = assertWranglerUploaderUnchanged(wranglerUploaderHashBefore, hashUploader(root));
3227
- if (!check.ok) log$1.error(["deploy: refusing to run the Cloudflare uploader with your Cloudflare credentials.", check.reason].filter(Boolean).join("\n"));
2501
+ if (!check.ok) log.error(["deploy: refusing to run the Cloudflare uploader with your Cloudflare credentials.", check.reason].filter(Boolean).join("\n"));
3228
2502
  return check.ok;
3229
2503
  }
3230
2504
  };
3231
2505
  }
3232
2506
  /** Log a failed Cloudflare sign-in. An uploader change has already reported itself. */
3233
2507
  function logCloudflareAuthFailure(error) {
3234
- if (!(error instanceof CloudflareAuthenticationError && error.reason === "uploader-changed")) log$1.error(`deploy: ${getErrorMessage(error)}`);
2508
+ if (!(error instanceof CloudflareAuthenticationError && error.reason === "uploader-changed")) log.error(`deploy: ${getErrorMessage(error)}`);
3235
2509
  }
3236
2510
  /**
3237
2511
  * Pin the transport, the uploaders and the account, then create the deploy runner. A first
@@ -3244,7 +2518,7 @@ async function connectCloudflareDeployAccount(options) {
3244
2518
  try {
3245
2519
  apiBaseUrl = resolveDeployTransport(root, rootConfig);
3246
2520
  } catch (error) {
3247
- log$1.error(`deploy: ${getErrorMessage(error)}`);
2521
+ log.error(`deploy: ${getErrorMessage(error)}`);
3248
2522
  return null;
3249
2523
  }
3250
2524
  const complianceRegion = resolveWorkersDevComplianceRegion(process.env, readWranglerTopLevelString(rootConfig, "compliance_region"));
@@ -3272,7 +2546,7 @@ async function connectCloudflareDeployAccount(options) {
3272
2546
  workersDevSubdomain = resolveCloudflareWorkersDevSubdomain(root, accountId);
3273
2547
  readinessAccessOrigin = resolveCloudflareReadinessAccessOrigin({ CF_ACCESS_READINESS_ORIGIN: options.readinessAccessOrigin ?? void 0 });
3274
2548
  } catch (error) {
3275
- log$1.error(getErrorMessage(error));
2549
+ log.error(getErrorMessage(error));
3276
2550
  return null;
3277
2551
  }
3278
2552
  return {
@@ -3323,6 +2597,7 @@ function createCfActivationRunner(options) {
3323
2597
  output: cfOutput,
3324
2598
  workerName: options.workerName,
3325
2599
  runCf,
2600
+ clearWorkflowSchedules: runWrangler,
3326
2601
  pinnedUpload: {
3327
2602
  accountId,
3328
2603
  apiBaseUrl,
@@ -3337,6 +2612,18 @@ function createCfActivationRunner(options) {
3337
2612
  })
3338
2613
  });
3339
2614
  }
2615
+ /** Pin the active version when its local Workflow qualifies a removal for atomic publication. */
2616
+ async function activeWorkflowVersionForRemoval(options, readWorker = readExistingCloudflareWorker) {
2617
+ const active = await readWorker(options);
2618
+ if (active.bindings.some((binding) => binding.type === "workflow" && typeof binding.class_name === "string" && isLocalWorkflow(binding, options.workerName)) || Object.keys(workflowExports(active.runtime.exports)).length > 0) return active.versionId;
2619
+ const metadata = parseCloudflareVersionMessage(await resolveCloudflareVersionMessage(active.versionMessage ?? null, active.versionId, options));
2620
+ if (metadata?.schema === 2) for (const cleanup of metadata.triggerConfig.workflowScheduleCleanup ?? []) {
2621
+ const scheduled = await inspectWorkflowSchedule(options, cleanup);
2622
+ if (scheduled === null) throw new Error("deploy: could not verify outstanding Workflow schedule cleanup before atomic publication.");
2623
+ if (scheduled) return active.versionId;
2624
+ }
2625
+ throw new Error("deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.");
2626
+ }
3340
2627
  /**
3341
2628
  * Activation options shared by the Worker and static deploys: candidate tracking, the uploaded
3342
2629
  * binding check, readiness probing and trigger cleanup.
@@ -3348,9 +2635,10 @@ function cloudflareCandidateActivationOptions(options) {
3348
2635
  const candidateReceipt = pinnedHandoffLink?.candidateReceipt;
3349
2636
  return {
3350
2637
  workerName,
2638
+ accountId,
3351
2639
  configPath,
3352
2640
  preserveTriggers: existingWorker !== null,
3353
- expectedPreviousVersionId: existingWorker?.versionId,
2641
+ expectedPreviousVersionId: existingWorker?.versionId ?? options.previousWorkflowVersionId,
3354
2642
  trustedInheritanceVersionIds: existingWorker ? candidateReceipt?.parentVersionId === existingWorker.versionId ? candidateReceipt.versionIds : void 0 : initialCloudflareCandidate?.versionIds,
3355
2643
  validateUploadedVersion: existingWorker ? async (versionId) => {
3356
2644
  if (!options.assertUploaderStillPinned()) throw new Error("The deployment uploader changed.");
@@ -3448,7 +2736,7 @@ async function reportCloudflareActivationFailure(reporter, message, execution) {
3448
2736
  exitCode: 1
3449
2737
  });
3450
2738
  await cliLog.close().catch(() => {});
3451
- log$1.error(`${safeMessage}${cliLog.path ? `\n\nDetailed log: ${cliLog.path}` : ""}`);
2739
+ log.error(`${safeMessage}${cliLog.path ? `\n\nDetailed log: ${cliLog.path}` : ""}`);
3452
2740
  }
3453
2741
  async function activateCloudflareVersionWithProgress(activate, options) {
3454
2742
  const progress = createSpinner();
@@ -3470,24 +2758,39 @@ function formatCloudflareActivationError(result) {
3470
2758
  const message = formatCloudflareActivationFailure(result);
3471
2759
  return result.restoredOlderSecrets ? `${message}\nCloudflare refused to restore the previous version because this deploy changed a secret, so Void forced the restore. The previous version runs with its old secret values; deploy again to apply the new ones.` : message;
3472
2760
  }
2761
+ function formatStagingCleanup(result) {
2762
+ switch (result.rollback) {
2763
+ case "succeeded": return " Void removed its 0% staging deployment, and the previous version still serves all traffic.";
2764
+ case "failed": return " Void tried to remove its 0% staging deployment, but Cloudflare did not confirm it.";
2765
+ case "unsafe": return " Void could not confirm that the newest deployment is its own 0% staging deployment, so it left it unchanged.";
2766
+ default: return "";
2767
+ }
2768
+ }
3473
2769
  function formatCloudflareActivationFailure(result) {
3474
2770
  const status = result.status === void 0 ? "" : ` (exit ${String(result.status)})`;
3475
2771
  const cloudflareCode = result.cloudflareErrorCode === void 0 ? "" : ` Cloudflare error code: ${String(result.cloudflareErrorCode)}.`;
3476
2772
  const diagnostic = result.diagnostic ? `\n\n${result.diagnostic}` : "";
2773
+ const stagingCleanup = result.beforeActivation ? formatStagingCleanup(result) : "";
3477
2774
  switch (result.reason) {
3478
2775
  case "uploader-changed":
3479
2776
  if (result.rollback === "succeeded") return "deploy: the verified Wrangler uploader changed after version activation. Traffic was restored to the previous version.";
3480
2777
  if (result.rollback === "unavailable") return "deploy: the verified Wrangler uploader changed after the first version activated. No previous version is available; inspect `void project status` immediately.";
3481
2778
  if (result.rollback === "failed") return "deploy: the verified Wrangler uploader changed after version activation, and automatic traffic restoration failed. Inspect `void project status` immediately.";
3482
- if (result.rollback === "unsafe") return "deploy: the verified Wrangler uploader changed after version activation. Void did not invoke the changed binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.";
2779
+ if (result.rollback === "unsafe") return result.beforeActivation ? "deploy: Void's verified Cloudflare uploader changed before version activation, so Void did not run it to remove its 0% staging deployment. Reinstall dependencies from your lockfile and inspect `void project status` immediately." : "deploy: the verified Wrangler uploader changed after version activation. Void did not invoke the changed binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.";
3483
2780
  return "deploy: the verified Wrangler uploader changed before version activation.";
3484
2781
  case "status-failed":
3485
2782
  if (result.versionId) {
3486
- if (result.rollback === "not-needed") return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}. Inspect \`void project status\` before retrying.`;
2783
+ if (result.beforeActivation || result.rollback === "not-needed") return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}.${stagingCleanup} Inspect \`void project status\` before retrying.${diagnostic}`;
3487
2784
  return `deploy: Worker version ${result.versionId} was published, but current deployment status could not be verified${status}. Inspect \`void project status\` before retrying.`;
3488
2785
  }
3489
2786
  return `deploy: could not snapshot the current Cloudflare deployment${status}; no version was uploaded.`;
3490
- case "deployment-changed": return result.triggerRepair === "succeeded" ? `deploy: another Cloudflare operation superseded this deployment. Void restored triggers for the active version ${result.activeVersionId ?? "(unknown)"}; retry from fresh deployment status.` : `deploy: another Cloudflare operation superseded this deployment, but its trigger state could not be verified. Inspect the active Worker version ${result.activeVersionId ?? "(unknown)"} immediately.`;
2787
+ case "deployment-changed":
2788
+ if (result.beforeActivation) {
2789
+ const active = result.activeVersionId && result.activeVersionId !== result.previousVersionId ? ` Worker version ${result.activeVersionId} now serves traffic.` : "";
2790
+ return `deploy: Cloudflare deployment status did not show the expected deployment${result.versionId ? `, so Void did not activate Worker version ${result.versionId}` : ""}.${active}${stagingCleanup} Inspect \`void project status\` before retrying.${diagnostic}`;
2791
+ }
2792
+ if (result.diagnostic) return result.diagnostic;
2793
+ return result.triggerRepair === "succeeded" ? `deploy: another Cloudflare operation superseded this deployment. Void restored triggers for the active version ${result.activeVersionId ?? "(unknown)"}; retry from fresh deployment status.` : `deploy: another Cloudflare operation superseded this deployment, but its trigger state could not be verified. Inspect the active Worker version ${result.activeVersionId ?? "(unknown)"} immediately.`;
3491
2794
  case "inheritance-source-unavailable":
3492
2795
  if (result.versionId) return `deploy: Worker version ${result.versionId} was uploaded but not activated because Cloudflare's version history could not confirm which secrets it inherited. Production traffic is unchanged.`;
3493
2796
  return "deploy: could not verify which Worker Version would supply inherited secrets; production traffic is unchanged.";
@@ -3502,7 +2805,7 @@ function formatCloudflareActivationFailure(result) {
3502
2805
  case "traffic-split-unsupported": return [
3503
2806
  "deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.",
3504
2807
  "Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout",
3505
- "in Cloudflare, then retry; no version was uploaded."
2808
+ result.versionId ? `in Cloudflare, then retry. Void uploaded Worker version ${result.versionId} and stopped before activating it.` : "in Cloudflare, then retry; no version was uploaded."
3506
2809
  ].join("\n");
3507
2810
  case "upload-failed": return `deploy: Cloudflare Worker Version upload failed${status}; production traffic is unchanged.${cloudflareCode}${diagnostic}`;
3508
2811
  case "upload-output-invalid": return "deploy: Wrangler uploaded a version but did not report its version id; production traffic is unchanged.";
@@ -3626,12 +2929,12 @@ function customRouteAccessHint(origin) {
3626
2929
  "Set it only if you control this hostname and it serves this Worker, because Void sends your Access credentials to it."
3627
2930
  ];
3628
2931
  }
3629
- const ATOMIC_ACCESS_ALTERNATIVE = "For a Worker with Durable Object migration history, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.";
2932
+ const ATOMIC_ACCESS_ALTERNATIVE = "For a Worker with Durable Object migration history or a local Workflow, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.";
3630
2933
  function formatCloudflareReadinessRestoration(result) {
3631
2934
  switch (result.rollback) {
3632
2935
  case "succeeded": return "The failed version remains inactive, and traffic was restored to the previous version.";
3633
2936
  case "failed": return "Automatic traffic restoration failed; inspect `void project status` immediately.";
3634
- case "unsafe": return "Void did not invoke the changed Wrangler binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.";
2937
+ case "unsafe": return result.activeVersionId === void 0 ? "Void skipped staging cleanup because its verified Cloudflare uploader changed. Reinstall dependencies from your lockfile and inspect `void project status` before retrying." : `${formatStagingCleanup(result).trim()} Inspect \`void project status\` before retrying.`;
3635
2938
  case "unavailable": return "No previous version was available to restore; inspect `void project status` immediately.";
3636
2939
  default: return "The failed version remains inactive for inspection; production traffic is unchanged.";
3637
2940
  }
@@ -3671,7 +2974,7 @@ function cloudflareWorkerReadinessHeaders() {
3671
2974
  const DEFAULT_COMPATIBILITY_DATE = "2026-09-11";
3672
2975
  /** Build the trusted Wrangler pointer for a framework that emits Worker files directly. */
3673
2976
  async function prepareCloudflareFrameworkArtifact(options) {
3674
- const { root, configPath, accountId, workerName, voidConfig, framework, preset, ai } = options;
2977
+ const { root, configPath, accountId, workerName, voidConfig, framework, preset, ai, browser } = options;
3675
2978
  const { requiredSecretNames = [], preserveBindings = false } = options;
3676
2979
  const workerMain = join(root, preset.workerDir, preset.workerMain);
3677
2980
  const assetsDirectory = join(root, preset.assetsDir);
@@ -3719,6 +3022,7 @@ async function prepareCloudflareFrameworkArtifact(options) {
3719
3022
  ...ai,
3720
3023
  gateway: voidConfig.ai?.gateway
3721
3024
  } } : {},
3025
+ ...browser ? { browser } : {},
3722
3026
  runWorkerFirst: voidConfig.cloudflare?.assets?.run_worker_first ?? [...VOID_INTERNAL_WORKER_FIRST],
3723
3027
  ...preset.workerDir === preset.assetsDir ? { assetsIgnore: [
3724
3028
  preset.workerMain,
@@ -3771,7 +3075,7 @@ async function resolveCloudflareVoidStaticPreset(root, voidConfig) {
3771
3075
  hasEmail: routeScan.email !== void 0 && hasEmailHandlers(routeScan.email),
3772
3076
  authEnabled,
3773
3077
  hasLive: bindings.needsLive === true
3774
- }) || analysis.jobs.length > 0 || analysis.queues.length > 0) return null;
3078
+ }) || analysis.jobs.length > 0 || analysis.queues.length > 0 || analysis.workflows.length > 0) return null;
3775
3079
  return {
3776
3080
  buildCommand: resolveFullDeployBuildCommand(root, voidConfig.inference?.build).command,
3777
3081
  outputDir: join(root, "dist", "client"),
@@ -3832,6 +3136,17 @@ function planStaticEdgeRouting(options) {
3832
3136
  async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliLog, deps, initialCloudflareLink, initialCloudflareCandidate, reporter) {
3833
3137
  const exit = deps.exit ?? ((code) => process.exit(code));
3834
3138
  const configPath = discoverRootWranglerConfig(root);
3139
+ if (options.preview !== void 0) {
3140
+ const problem = checkCloudflarePreviewRequest({
3141
+ previewName: options.preview,
3142
+ rootConfig: parseRootWranglerConfig(configPath),
3143
+ configPath
3144
+ });
3145
+ if (problem) {
3146
+ log.error(problem);
3147
+ return exit(1);
3148
+ }
3149
+ }
3835
3150
  const connection = await connectCloudflareDeployAccount({
3836
3151
  root,
3837
3152
  configPath,
@@ -3856,10 +3171,22 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3856
3171
  if (existingWorker && !pinnedHandoffLink) throw new Error("The pending Cloudflare handoff was not saved before deployment.");
3857
3172
  const rootConfig = parseRootWranglerConfig(configPath);
3858
3173
  const workerName = readWranglerTopLevelString(rootConfig, "name") ?? deriveWorkerName(root);
3859
- printDeployContext(workerName, "Cloudflare");
3174
+ let previousWorkflowVersionId;
3175
+ if (options.atomic) try {
3176
+ previousWorkflowVersionId = await activeWorkflowVersionForRemoval({
3177
+ runWrangler,
3178
+ configPath,
3179
+ workerName,
3180
+ accountId
3181
+ }, deps.readExistingWorker);
3182
+ } catch (error) {
3183
+ log.error(getErrorMessage(error));
3184
+ return exit(1);
3185
+ }
3186
+ printDeployContext(workerName, options.preview === void 0 ? "Cloudflare" : `Cloudflare Preview ${options.preview}`);
3860
3187
  const rootConfigBeforeBuild = existsSync(configPath) ? readFileSync(configPath, "utf8") : null;
3861
3188
  if (preset.buildCommand && !options.skipBuild) {
3862
- log$1.step("Building...");
3189
+ log.step("Building...");
3863
3190
  const buildChildEnv = scrubManagedDeployBuildMarkers(scrubWranglerAuthCredentials(deployChildEnv(accountId, apiBaseUrl)));
3864
3191
  deleteEnvVarCaseAware(buildChildEnv, "NODE_ENV");
3865
3192
  buildChildEnv.NODE_ENV = "production";
@@ -3873,18 +3200,18 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3873
3200
  try {
3874
3201
  runStaticBuild(preset.buildCommand, buildChildEnv);
3875
3202
  } catch (error) {
3876
- log$1.error(`deploy: build failed — ${getErrorMessage(error)}`);
3203
+ log.error(`deploy: build failed — ${getErrorMessage(error)}`);
3877
3204
  return exit(getExitCode(error));
3878
3205
  }
3879
3206
  }
3880
- log$1.step("Preparing deployment...");
3207
+ log.step("Preparing deployment...");
3881
3208
  if (!existsSync(preset.outputDir)) {
3882
- log$1.error(`deploy: Output directory '${preset.outputDir}' not found. Run the build first.`);
3209
+ log.error(`deploy: Output directory '${preset.outputDir}' not found. Run the build first.`);
3883
3210
  return exit(1);
3884
3211
  }
3885
3212
  if (!assertUploaderStillPinned()) return exit(1);
3886
3213
  if ((existsSync(configPath) ? readFileSync(configPath, "utf8") : null) !== rootConfigBeforeBuild) {
3887
- log$1.error(["deploy: the root Wrangler config changed during the static build.", "Refusing to upload a config rewritten by project build code. Restore the config and retry."].join("\n"));
3214
+ log.error(["deploy: the root Wrangler config changed during the static build.", "Refusing to upload a config rewritten by project build code. Restore the config and retry."].join("\n"));
3888
3215
  return exit(1);
3889
3216
  }
3890
3217
  const edgeRouting = planStaticEdgeRouting({
@@ -3893,10 +3220,11 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3893
3220
  routing: voidConfig.routing,
3894
3221
  htmlHandling: readWranglerHtmlHandling(rootConfig)
3895
3222
  });
3896
- const entryPath = join(root, ".void", "deploy", "cloudflare", "static-edge.mjs");
3223
+ const stagingDirectory = join(root, ".void", "deploy", options.preview === void 0 ? "cloudflare" : "cloudflare-preview");
3224
+ const entryPath = join(stagingDirectory, "static-edge.mjs");
3897
3225
  mkdirSync(dirname(entryPath), { recursive: true });
3898
3226
  const staticConfigPath = join(dirname(entryPath), "wrangler-static.json");
3899
- writeFileSync(staticConfigPath, `${JSON.stringify(rootConfig, null, 2)}\n`, { mode: 384 });
3227
+ writeFileSync(staticConfigPath, `${JSON.stringify(options.preview === void 0 ? rootConfig : previewStaticWorkerConfig(rootConfig), null, 2)}\n`, { mode: 384 });
3900
3228
  writeCloudflareStaticDeployConfig({
3901
3229
  configPath: staticConfigPath,
3902
3230
  name: workerName,
@@ -3922,7 +3250,7 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3922
3250
  versionMetadataBinding
3923
3251
  }));
3924
3252
  if (existingWorker) assertExistingCloudflareConfig(existingWorker, parseRootWranglerConfig(staticConfigPath), true);
3925
- const stagedAssetsDirectory = join(root, ".void", "deploy", "cloudflare", "assets");
3253
+ const stagedAssetsDirectory = join(stagingDirectory, "assets");
3926
3254
  stageCloudflareStaticAssets({
3927
3255
  sourceDirectory: preset.outputDir,
3928
3256
  destinationDirectory: stagedAssetsDirectory,
@@ -3938,14 +3266,19 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3938
3266
  workerName
3939
3267
  });
3940
3268
  if (usesCf && !cfUploaderIsPinned()) return exit(1);
3269
+ const message = options.preview === void 0 ? encodeCloudflareVersionMessage([], {
3270
+ ...readCloudflareTriggerConfig(staticConfigPath, configPath),
3271
+ ...existingWorker ? { preserve: true } : {}
3272
+ }) : "";
3941
3273
  const cfOutput = usesCf ? await prepareCfStaticBuildOutput({
3942
3274
  projectRoot: root,
3943
3275
  configPath: staticConfigPath,
3944
3276
  assetsDirectory: stagedAssetsDirectory,
3945
- accountId
3277
+ accountId,
3278
+ isPreview: options.preview !== void 0
3946
3279
  }) : null;
3947
3280
  if (!cfOutput && usesCf) {
3948
- log$1.error("deploy: cf could not prepare the static Worker for deployment.");
3281
+ log.error("deploy: cf could not prepare the static Worker for deployment.");
3949
3282
  return exit(1);
3950
3283
  }
3951
3284
  const activationRunner = createCfActivationRunner({
@@ -3959,6 +3292,22 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3959
3292
  verifyCompatibilityRunner: assertUploaderStillPinned,
3960
3293
  reporter
3961
3294
  });
3295
+ const typeLabel = preset.appType === "spa" ? "Static SPA" : "Static Site";
3296
+ if (options.preview !== void 0) return runCloudflareStaticPreview({
3297
+ runWrangler: activationRunner,
3298
+ cfOutput,
3299
+ workerName,
3300
+ previewName: options.preview,
3301
+ accountId,
3302
+ configPath,
3303
+ staticConfigPath,
3304
+ verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned,
3305
+ typeLabel,
3306
+ writeResult: options.writeResult,
3307
+ reporter,
3308
+ cliLog,
3309
+ exit
3310
+ });
3962
3311
  const execution = await activateCloudflareVersionWithProgress(deps.activateVersion ?? activateCloudflareVersion, {
3963
3312
  ...cloudflareCandidateActivationOptions({
3964
3313
  root,
@@ -3978,19 +3327,26 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
3978
3327
  assertUploaderStillPinned,
3979
3328
  approvedKv: [],
3980
3329
  staticAssetsBinding: "ASSETS",
3330
+ previousWorkflowVersionId,
3981
3331
  queueConsumerCleanup
3982
3332
  }),
3983
3333
  runWrangler: activationRunner,
3984
3334
  verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned,
3985
3335
  requireVersionMetadata: existingWorker === null || versionMetadataBinding !== void 0,
3986
3336
  requirePreviewForReadiness: existingWorker !== null && versionMetadataBinding === void 0,
3987
- message: encodeCloudflareVersionMessage([], {
3988
- ...readCloudflareTriggerConfig(staticConfigPath, configPath),
3989
- ...existingWorker ? { preserve: true } : {}
3990
- }),
3991
- assetsDirectoryOverride: stagedAssetsDirectory
3337
+ message,
3338
+ assetsDirectoryOverride: stagedAssetsDirectory,
3339
+ ...options.atomic ? {
3340
+ atomic: true,
3341
+ pinActiveSecrets: createActiveSecretPinner({
3342
+ output: cfOutput,
3343
+ handoffPending: false,
3344
+ requiredNames: []
3345
+ })
3346
+ } : {}
3992
3347
  }).finally(() => cfOutput?.dispose());
3993
3348
  if (!execution.ok) {
3349
+ if (execution.reason === "atomic-readiness-failed" || execution.reason === "atomic-readiness-access-denied") clearCloudflareCandidate(root);
3994
3350
  await reportCloudflareActivationFailure(reporter, formatCloudflareActivationError(execution), execution);
3995
3351
  return exit(1);
3996
3352
  }
@@ -4006,7 +3362,7 @@ async function runCloudflareStaticDeploy(root, options, voidConfig, preset, cliL
4006
3362
  });
4007
3363
  note(formatDeploySummary({
4008
3364
  workerName,
4009
- typeLabel: preset.appType === "spa" ? "Static SPA" : "Static Site"
3365
+ typeLabel
4010
3366
  }), execution.previewUrl);
4011
3367
  printDeploySuccess();
4012
3368
  }
@@ -4312,7 +3668,7 @@ function cloudflareReason(result) {
4312
3668
  }
4313
3669
  /** Name the restore point when deploy stops after it applied D1 migrations. */
4314
3670
  function logD1RestoreAfterDeployFailure(restoreCommand) {
4315
- log$1.error(`deploy: D1 migrations were applied before the deploy stopped. Fix the error and deploy again.
3671
+ log.error(`deploy: D1 migrations were applied before the deploy stopped. Fix the error and deploy again.
4316
3672
  If the live version cannot run against the new schema, restore the point saved before them (discards every later write):\n ${restoreCommand}`);
4317
3673
  }
4318
3674
  /**
@@ -4322,7 +3678,7 @@ If the live version cannot run against the new schema, restore the point saved b
4322
3678
  async function applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runWrangler, assertUploaderStillPinned, restorePlatformFlag = false) {
4323
3679
  let restoreCommand;
4324
3680
  if (d1MigrateToken) {
4325
- log$1.step("Applying D1 migrations...");
3681
+ log.step("Applying D1 migrations...");
4326
3682
  if (!assertUploaderStillPinned()) return false;
4327
3683
  const readPending = async () => {
4328
3684
  const listed = await Promise.resolve(runWrangler({
@@ -4332,7 +3688,7 @@ async function applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runW
4332
3688
  }, { capture: true }));
4333
3689
  const pending = listed.data?.pending;
4334
3690
  if (isCleanCloudflareExit(listed) && Array.isArray(pending)) return pending;
4335
- log$1.error(`deploy: could not read the pending D1 migrations for "${d1MigrateToken}" before applying them ` + (isCleanCloudflareExit(listed) ? "(Cloudflare returned no pending migration list). " : `(exit ${String(listed.status)}). `) + "Refusing to migrate without knowing whether a restore point is needed. Rerun once Cloudflare can be reached." + cloudflareReason(listed));
3691
+ log.error(`deploy: could not read the pending D1 migrations for "${d1MigrateToken}" before applying them ` + (isCleanCloudflareExit(listed) ? "(Cloudflare returned no pending migration list). " : `(exit ${String(listed.status)}). `) + "Refusing to migrate without knowing whether a restore point is needed. Rerun once Cloudflare can be reached." + cloudflareReason(listed));
4336
3692
  };
4337
3693
  const pendingBefore = await readPending();
4338
3694
  if (!pendingBefore) return false;
@@ -4345,7 +3701,7 @@ async function applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runW
4345
3701
  }, { capture: true }));
4346
3702
  const bookmark = restorePoint.data?.bookmark;
4347
3703
  if (!isCleanCloudflareExit(restorePoint) || typeof bookmark !== "string") {
4348
- log$1.error(`deploy: could not save a D1 restore point for "${d1MigrateToken}" before applying ${formatCount(pendingBefore.length, "migration")}. A Worker rollback does not undo a migration. Refusing to migrate without a restore point. Rerun once the restore point can be saved.` + cloudflareReason(restorePoint));
3704
+ log.error(`deploy: could not save a D1 restore point for "${d1MigrateToken}" before applying ${formatCount(pendingBefore.length, "migration")}. A Worker rollback does not undo a migration. Refusing to migrate without a restore point. Rerun once the restore point can be saved.` + cloudflareReason(restorePoint));
4349
3705
  return false;
4350
3706
  }
4351
3707
  const pendingAfterBookmark = await readPending();
@@ -4355,7 +3711,7 @@ async function applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runW
4355
3711
  restoreHint = `
4356
3712
  To undo these migrations, restore this point (discards every later write):
4357
3713
  ${restoreCommand}`;
4358
- log$1.info(`Saved a D1 restore point before applying ${formatCount(pendingAfterBookmark.length, "migration")}.${restoreHint}`);
3714
+ log.info(`Saved a D1 restore point before applying ${formatCount(pendingAfterBookmark.length, "migration")}.${restoreHint}`);
4359
3715
  }
4360
3716
  if (!assertUploaderStillPinned()) return false;
4361
3717
  }
@@ -4365,7 +3721,7 @@ To undo these migrations, restore this point (discards every later write):
4365
3721
  configPath
4366
3722
  }, { capture: false }));
4367
3723
  if (!isCleanCloudflareExit(migrate)) {
4368
- log$1.error(`deploy: remote D1 migrations failed for "${d1MigrateToken}" (exit ${String(migrate.status)}). Fix the migration and rerun. Note: D1 always enforces foreign_keys=ON — a Drizzle table-rebuild using PRAGMA foreign_keys=OFF must use PRAGMA defer_foreign_keys instead.` + restoreHint);
3724
+ log.error(`deploy: remote D1 migrations failed for "${d1MigrateToken}" (exit ${String(migrate.status)}). Fix the migration and rerun. Note: D1 always enforces foreign_keys=ON — a Drizzle table-rebuild using PRAGMA foreign_keys=OFF must use PRAGMA defer_foreign_keys instead.` + restoreHint);
4369
3725
  return false;
4370
3726
  }
4371
3727
  if (!assertUploaderStillPinned()) {
@@ -4378,16 +3734,16 @@ To undo these migrations, restore this point (discards every later write):
4378
3734
  configPath
4379
3735
  }, { capture: true }));
4380
3736
  if (!isCleanCloudflareExit(migrateList)) {
4381
- log$1.error(`deploy: could not verify the remote migration state for "${d1MigrateToken}" (\`d1 migrations list\` exit ${String(migrateList.status)}). Refusing to deploy against an unverified schema — rerun once wrangler can reach your account.` + restoreHint);
3737
+ log.error(`deploy: could not verify the remote migration state for "${d1MigrateToken}" (\`d1 migrations list\` exit ${String(migrateList.status)}). Refusing to deploy against an unverified schema — rerun once wrangler can reach your account.` + restoreHint);
4382
3738
  return false;
4383
3739
  }
4384
3740
  const migrationState = migrateList.data;
4385
3741
  if (Array.isArray(migrationState?.pending) && migrationState.pending.length > 0) {
4386
- log$1.error([`deploy: remote D1 still has UNAPPLIED migrations for "${d1MigrateToken}" after apply.`, "The schema is not current for this deployment. Fix or apply the pending migrations, then retry."].join("\n") + restoreHint);
3742
+ log.error([`deploy: remote D1 still has UNAPPLIED migrations for "${d1MigrateToken}" after apply.`, "The schema is not current for this deployment. Fix or apply the pending migrations, then retry."].join("\n") + restoreHint);
4387
3743
  return false;
4388
3744
  }
4389
3745
  if (!Array.isArray(migrationState?.pending) || !migrationState.pending.every((name) => typeof name === "string")) {
4390
- log$1.error([
3746
+ log.error([
4391
3747
  `deploy: could not confirm the remote migration state for "${d1MigrateToken}".`,
4392
3748
  "Cloudflare returned an invalid pending migration set. Refusing to deploy against an unverified schema.",
4393
3749
  "Retry once the database migration state can be read."
@@ -4401,11 +3757,13 @@ To undo these migrations, restore this point (discards every later write):
4401
3757
  /** Build the Worker without Cloudflare credentials, then run the post-build gates. */
4402
3758
  async function buildCloudflareWorker(input) {
4403
3759
  const { root, voidConfig, deps, exit, atomic, frameworkPreset, detectedFramework } = input;
4404
- const { configPath, needsAI, aiBindingName, migrationsDir, dialect, authEnabled, desired } = input.source;
4405
- const { accountId, apiBaseUrl, usesCf, existingWorker, workerName, schemaFacts, assertUploaderStillPinned, runWrangler, approvedHandoffKv, bindingIdentitySnapshot } = input.preflight;
3760
+ const { configPath, needsAI, aiBindingName, inferredBrowserBinding, migrationsDir, dialect, authEnabled, desired } = input.source;
3761
+ const { accountId, apiBaseUrl, usesCf, existingWorker, workerName, schemaFacts, assertUploaderStillPinned, runWrangler, approvedHandoffKv, verification: { bindingIdentitySnapshot } } = input.preflight;
4406
3762
  const buildChildEnv = scrubManagedDeployBuildMarkers(scrubWranglerAuthCredentials(deployChildEnv(accountId, apiBaseUrl)));
4407
3763
  deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_DEPLOY_BUILD_ENV);
4408
3764
  buildChildEnv[CLOUDFLARE_DEPLOY_BUILD_ENV] = "1";
3765
+ deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_WORKER_NAME_BUILD_ENV);
3766
+ buildChildEnv[CLOUDFLARE_WORKER_NAME_BUILD_ENV] = workerName;
4409
3767
  deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV);
4410
3768
  if (desired.queueNames) buildChildEnv[CLOUDFLARE_QUEUE_NAMES_BUILD_ENV] = JSON.stringify(desired.queueNames);
4411
3769
  deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV);
@@ -4423,10 +3781,10 @@ async function buildCloudflareWorker(input) {
4423
3781
  try {
4424
3782
  runBuild(buildChildEnv);
4425
3783
  } catch (err) {
4426
- log$1.error(`deploy: build failed — ${getErrorMessage(err)}`);
3784
+ log.error(`deploy: build failed — ${getErrorMessage(err)}`);
4427
3785
  return exit(getExitCode(err));
4428
3786
  }
4429
- log$1.step("Preparing deployment...");
3787
+ log.step("Preparing deployment...");
4430
3788
  if (detectedFramework && frameworkPreset) try {
4431
3789
  await (deps.prepareFrameworkArtifact ?? prepareCloudflareFrameworkArtifact)({
4432
3790
  root,
@@ -4438,26 +3796,30 @@ async function buildCloudflareWorker(input) {
4438
3796
  preset: frameworkPreset,
4439
3797
  requiredSecretNames: schemaFacts.requiredKeys,
4440
3798
  ai: needsAI ? { binding: aiBindingName } : void 0,
3799
+ browser: inferredBrowserBinding ? { binding: inferredBrowserBinding } : void 0,
4441
3800
  preserveBindings: existingWorker !== null,
4442
3801
  cloudflareQueueNames: desired.queueNames
4443
3802
  });
4444
3803
  } catch (error) {
4445
- log$1.error(`deploy: could not prepare ${detectedFramework.name} for Cloudflare — ${getErrorMessage(error)}`);
3804
+ log.error(`deploy: could not prepare ${detectedFramework.name} for Cloudflare — ${getErrorMessage(error)}`);
4446
3805
  return exit(1);
4447
3806
  }
4448
3807
  if (!assertUploaderStillPinned()) return exit(1);
4449
3808
  const migrations = collectMigrations(migrationsDir);
4450
3809
  if (existingWorker && migrations.length) throw new Error("The build added database migrations. Link the existing site before making schema changes.");
4451
3810
  if (!input.skipMigrations && dialect !== "sqlite" && migrations.length > 0 && !process.env.DATABASE_URL) {
4452
- log$1.error(`deploy: the build added ${dialect === "mysql" ? "MySQL" : "PostgreSQL"} migrations, but DATABASE_URL is not set. Refusing to upload a Worker against an unmigrated database.`);
3811
+ log.error(`deploy: the build added ${dialect === "mysql" ? "MySQL" : "PostgreSQL"} migrations, but DATABASE_URL is not set. Refusing to upload a Worker against an unmigrated database.`);
4453
3812
  return exit(1);
4454
3813
  }
4455
3814
  const lifecycleConfigPath = (deps.resolveGeneratedConfigPath ?? ((projectRoot) => readGeneratedDeployConfig(projectRoot).path))(root);
4456
- if (atomic && !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations)) {
4457
- log$1.error("deploy: atomic deployment is only for Workers with Durable Object migration history.");
4458
- return exit(1);
4459
- }
3815
+ let previousWorkflowVersionId;
4460
3816
  try {
3817
+ if (atomic && !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations) && !input.preflight.hasLocalWorkflows) previousWorkflowVersionId = await activeWorkflowVersionForRemoval({
3818
+ runWrangler,
3819
+ configPath,
3820
+ workerName,
3821
+ accountId
3822
+ }, deps.readExistingWorker);
4461
3823
  deduplicateGeneratedCompatibilityFlags(lifecycleConfigPath, configPath);
4462
3824
  await (deps.assertDurableObjectLifecycle ?? assertCloudflareDurableObjectLifecycleSupported)({
4463
3825
  runWrangler,
@@ -4468,7 +3830,7 @@ async function buildCloudflareWorker(input) {
4468
3830
  allowPendingAtomicMigration: atomic
4469
3831
  });
4470
3832
  } catch (error) {
4471
- log$1.error(getErrorMessage(error));
3833
+ log.error(getErrorMessage(error));
4472
3834
  return exit(1);
4473
3835
  }
4474
3836
  if (!await validateCloudflarePostBuildEnv({
@@ -4487,7 +3849,7 @@ async function buildCloudflareWorker(input) {
4487
3849
  if (authEnabled && dialect === "sqlite") try {
4488
3850
  await (deps.validateAuthMigrations ?? validateAuthMigrationSchema)(root, migrations);
4489
3851
  } catch (err) {
4490
- log$1.error([
3852
+ log.error([
4491
3853
  "deploy: --platform cloudflare cannot verify the Void-managed Better Auth schema.",
4492
3854
  "The managed platform creates these tables at runtime (POST /__void/migrate/auth)",
4493
3855
  "after deploy; this self-host backend only applies checked-in db/migrations/*.sql, so",
@@ -4503,14 +3865,14 @@ async function buildCloudflareWorker(input) {
4503
3865
  try {
4504
3866
  (deps.assertMigrationsDeployable ?? assertRemoteMigrationsDeployable)(root, dialect, migrationsDir, migrations);
4505
3867
  } catch (err) {
4506
- log$1.error(getErrorMessage(err));
3868
+ log.error(getErrorMessage(err));
4507
3869
  return exit(1);
4508
3870
  }
4509
3871
  if (desired.d1 && migrations.length > 0) {
4510
3872
  const migrateConfig = parseRootWranglerConfig(configPath);
4511
3873
  const d1MigrationsDir = readStoredResourceName(migrateConfig, "d1_databases", desired.d1.binding, "migrations_dir");
4512
3874
  if (!d1MigrationsDir) {
4513
- log$1.error([
3875
+ log.error([
4514
3876
  `deploy: D1 binding ${desired.d1.binding} has no "migrations_dir" in ${configPath}.`,
4515
3877
  "Refusing to run `wrangler d1 migrations apply` — wrangler would default to",
4516
3878
  "`./migrations` (relative to the config) and apply an unrelated folder to your",
@@ -4521,7 +3883,7 @@ async function buildCloudflareWorker(input) {
4521
3883
  }
4522
3884
  const migrateTarget = resolveD1MigrateTarget(migrateConfig, desired.d1.binding);
4523
3885
  if (!migrateTarget.ok) {
4524
- log$1.error([
3886
+ log.error([
4525
3887
  `deploy: cannot safely run D1 migrations for binding ${desired.d1.binding} — ${migrateTarget.reason}`,
4526
3888
  "wrangler resolves `d1 migrations apply <name>` by first-matching the name against",
4527
3889
  "each entry's database_name OR binding, so an ambiguous token could migrate a",
@@ -4534,7 +3896,7 @@ async function buildCloudflareWorker(input) {
4534
3896
  const pinnedD1Id = bindingIdentitySnapshot.get(bindingIdentityKey(d1Field, desired.d1.binding));
4535
3897
  const postBuildD1Id = readStoredResourceName(migrateConfig, d1Field, desired.d1.binding, d1IdField);
4536
3898
  if (pinnedD1Id !== void 0 && postBuildD1Id !== pinnedD1Id) {
4537
- log$1.error([
3899
+ log.error([
4538
3900
  `deploy: the ${desired.d1.binding} D1 database identity changed between validation and the remote migrate.`,
4539
3901
  `Refusing to run \`wrangler d1 migrations apply\` — the build rewrote ${d1IdField} in ${configPath}`,
4540
3902
  `(validated ${JSON.stringify(pinnedD1Id)}, now ${JSON.stringify(postBuildD1Id)}), which would redirect this`,
@@ -4544,22 +3906,26 @@ async function buildCloudflareWorker(input) {
4544
3906
  }
4545
3907
  const applyCheck = await (deps.checkMigrationApplySet ?? checkWranglerMigrationApplySet)(configPath, migrateConfig, desired.d1.binding, d1MigrationsDir, migrations, relative(root, migrationsDir));
4546
3908
  if (!applyCheck.ok) {
4547
- log$1.error(applyCheck.reason);
3909
+ log.error(applyCheck.reason);
4548
3910
  return exit(1);
4549
3911
  }
4550
3912
  d1MigrateToken = migrateTarget.token;
4551
3913
  }
4552
3914
  }
4553
3915
  const generatedConfigPath = (deps.resolveGeneratedConfigPath ?? resolveGeneratedDeployConfigPathDefault)(root);
4554
- const prepareBuildOutput = () => frameworkPreset?.cloudflareArtifact === "worker-output" ? prepareCfFrameworkBuildOutput({
4555
- projectRoot: root,
4556
- configPath: generatedConfigPath,
4557
- accountId
4558
- }) : prepareCfBuildOutput(dirname(generatedConfigPath), accountId, void 0, root);
3916
+ const prepareBuildOutput = async () => {
3917
+ const output = frameworkPreset?.cloudflareArtifact === "worker-output" ? await prepareCfFrameworkBuildOutput({
3918
+ projectRoot: root,
3919
+ configPath: generatedConfigPath,
3920
+ accountId
3921
+ }) : await prepareCfBuildOutput(dirname(generatedConfigPath), accountId, void 0, root);
3922
+ if (output && frameworkPreset !== void 0 && (voidConfig.inference?.appType ?? "framework") === "framework") output.forwardAssetRedirects = true;
3923
+ return output;
3924
+ };
4559
3925
  if (usesCf) {
4560
3926
  const preflight = await prepareBuildOutput();
4561
3927
  if (!preflight) {
4562
- log$1.error("deploy: cf could not prepare the built Worker for deployment.");
3928
+ log.error("deploy: cf could not prepare the built Worker for deployment.");
4563
3929
  return exit(1);
4564
3930
  }
4565
3931
  await preflight.dispose();
@@ -4568,37 +3934,28 @@ async function buildCloudflareWorker(input) {
4568
3934
  migrations,
4569
3935
  d1MigrateToken,
4570
3936
  generatedConfigPath,
3937
+ previousWorkflowVersionId,
4571
3938
  prepareBuildOutput
4572
3939
  };
4573
3940
  }
4574
3941
  // src/cli/deploy-cloudflare-migrate.ts
4575
- /** Provision the auth secret and apply database migrations, then verify the artifact. */
4576
- async function migrateCloudflareWorker(input) {
3942
+ /** Verify the build and prepare migrations for the deploy's pre-upload check. */
3943
+ async function prepareCloudflareWorkerMigrations(input) {
4577
3944
  const { root, deps, exit, cliLog } = input;
4578
- const { configPath, authEnabled, desired, needsAI, aiBindingName, expectedCrons, dialect, migrationsDir } = input.source;
4579
- const { accountId, workerName, bindingIdentitySnapshot, passthroughIdentitySnapshot, passthroughRawFields, expectedContainers, expectedDurableObjectState, runWrangler, assertUploaderStillPinned, schemaFacts } = input.preflight;
3945
+ const { configPath, authEnabled, dialect } = input.source;
3946
+ const { accountId, workerName, verification, runWrangler, assertUploaderStillPinned } = input.preflight;
4580
3947
  const { migrations, d1MigrateToken } = input.build;
4581
3948
  let workerWasMissingBeforeSecretProvisioning = false;
4582
3949
  let initialAuthSecret;
4583
- const verifyOptions = {
4584
- accountId,
4585
- workerName,
4586
- desired,
4587
- bindingIdentitySnapshot,
4588
- passthroughIdentitySnapshot,
4589
- passthroughRawFields,
4590
- needsAI,
4591
- aiBindingName,
4592
- authEnabled,
4593
- expectedContainers,
4594
- expectedDurableObjectBindings: expectedDurableObjectState.bindings,
4595
- expectedMigrations: expectedDurableObjectState.migrations,
4596
- expectedCrons
4597
- };
3950
+ const migrationHistory = input.skipMigrations ? null : migrations.map((migration) => migration.name);
3951
+ const message = encodeCloudflareVersionMessage(migrationHistory, {
3952
+ ...readCloudflareTriggerConfig(input.build.generatedConfigPath, configPath),
3953
+ ...input.preflight.existingWorker ? { preserve: true } : {}
3954
+ });
4598
3955
  if (authEnabled) {
4599
- const inheritance = (deps.verifyDeployConfig ?? verifyGeneratedDeployConfig)(root, verifyOptions);
3956
+ const inheritance = (deps.verifyDeployConfig ?? verifyGeneratedDeployConfig)(root, verification);
4600
3957
  if (!inheritance.ok) {
4601
- log$1.error(["deploy: the generated deploy config cannot preserve the Better Auth secret — refusing to deploy.", inheritance.reason].filter(Boolean).join("\n"));
3958
+ log.error(["deploy: the generated deploy config cannot preserve the Better Auth secret — refusing to deploy.", inheritance.reason].filter(Boolean).join("\n"));
4602
3959
  return exit(1);
4603
3960
  }
4604
3961
  try {
@@ -4615,92 +3972,59 @@ async function migrateCloudflareWorker(input) {
4615
3972
  cliLog.info("cloudflare_auth_secret_ready", { created: authSecret.created });
4616
3973
  } catch (error) {
4617
3974
  if (error instanceof CloudflareAuthSecretError) {
4618
- if (error.reason !== "uploader-changed") log$1.error(error.message);
3975
+ if (error.reason !== "uploader-changed") log.error(error.message);
4619
3976
  return exit(1);
4620
3977
  }
4621
3978
  throw error;
4622
3979
  }
4623
3980
  }
4624
- let appliedMigrations = 0;
3981
+ verifyMigrationArtifact(input);
4625
3982
  if (input.skipMigrations) {
4626
- log$1.info("Skipping database migrations.");
3983
+ log.info("Skipping database migrations.");
4627
3984
  cliLog.info("cloudflare_migrations_skipped");
4628
3985
  }
4629
- if (!input.skipMigrations && dialect !== "sqlite" && migrations.length > 0) {
3986
+ return {
3987
+ workerWasMissingBeforeSecretProvisioning,
3988
+ initialAuthSecret,
3989
+ applyMigrations: !input.skipMigrations && (d1MigrateToken || dialect !== "sqlite" && migrations.length > 0) ? () => migrateCloudflareWorker(input) : void 0,
3990
+ message
3991
+ };
3992
+ }
3993
+ function verifyMigrationArtifact({ root, preflight, deps, exit }) {
3994
+ if (!verifyCloudflareDeployArtifact(root, deps, {
3995
+ ...preflight.verification,
3996
+ requiredSecretNames: preflight.schemaFacts.requiredKeys
3997
+ })) exit(1);
3998
+ }
3999
+ async function migrateCloudflareWorker(input) {
4000
+ const { root, deps, exit, cliLog } = input;
4001
+ const { configPath, dialect, migrationsDir } = input.source;
4002
+ const { runWrangler, assertUploaderStillPinned } = input.preflight;
4003
+ const { migrations, d1MigrateToken } = input.build;
4004
+ let appliedMigrations = 0;
4005
+ if (dialect !== "sqlite" && migrations.length > 0) {
4630
4006
  const mysql = dialect === "mysql";
4631
4007
  const label = mysql ? "MySQL" : "PostgreSQL";
4632
4008
  const databaseUrl = process.env.DATABASE_URL;
4633
4009
  if (!databaseUrl) {
4634
- log$1.error(`deploy: DATABASE_URL disappeared before ${label} migrations could run.`);
4010
+ log.error(`deploy: DATABASE_URL disappeared before ${label} migrations could run.`);
4635
4011
  return exit(1);
4636
4012
  }
4637
4013
  try {
4638
4014
  const applied = await (mysql ? deps.applyMySqlMigrations ?? runMySqlMigrations : deps.applyPostgresMigrations ?? runPgMigrations)(migrationsDir, databaseUrl);
4639
4015
  appliedMigrations = applied.length;
4640
4016
  cliLog.info(mysql ? "cloudflare_mysql_migrations" : "cloudflare_postgres_migrations", { applied: applied.length });
4641
- if (applied.length > 0) log$1.step(`Applied ${applied.length} ${label} migration${applied.length === 1 ? "" : "s"}.`);
4017
+ if (applied.length > 0) log.step(`Applied ${applied.length} ${label} migration${applied.length === 1 ? "" : "s"}.`);
4642
4018
  } catch (err) {
4643
- log$1.error(`deploy: ${label} migrations failed — ${getErrorMessage(err)}`);
4019
+ log.error(`deploy: ${label} migrations failed — ${getErrorMessage(err)}`);
4644
4020
  return exit(1);
4645
4021
  }
4646
4022
  }
4647
- const d1 = input.skipMigrations ? { restoreCommand: void 0 } : await applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runWrangler, assertUploaderStillPinned, readDeploymentPlatform(root) !== "cloudflare");
4023
+ const d1 = await applyAndVerifyRemoteD1Migrations(d1MigrateToken, configPath, runWrangler, assertUploaderStillPinned, readDeploymentPlatform(root) !== "cloudflare");
4648
4024
  if (!d1) return exit(1);
4649
- const d1RestoreCommand = d1.restoreCommand;
4650
- if (!verifyCloudflareDeployArtifact(root, deps, {
4651
- ...verifyOptions,
4652
- requiredSecretNames: schemaFacts.requiredKeys
4653
- })) {
4654
- if (d1RestoreCommand) logD1RestoreAfterDeployFailure(d1RestoreCommand);
4655
- return exit(1);
4656
- }
4657
- return {
4658
- migrationHistory: input.skipMigrations ? null : migrations.map((migration) => migration.name),
4659
- workerWasMissingBeforeSecretProvisioning,
4660
- initialAuthSecret,
4661
- appliedMigrations,
4662
- d1RestoreCommand
4663
- };
4664
- }
4665
- // src/cli/cloudflare-deploy/classify.ts
4666
- /**
4667
- * Narrow native Cloudflare deploys to app shapes whose emitted Worker artifact
4668
- * the current verifier understands. This runs before any account operation;
4669
- * `runCloudflareDeploy` has already rejected node/bun/deno targets.
4670
- */
4671
- function classifyCloudflareDeployApp(root, voidConfig, options, application) {
4672
- const framework = application.framework;
4673
- const configuredAppType = voidConfig.inference?.appType;
4674
- const staticPreset = framework || configuredAppType ? null : detectPreset(root, {
4675
- dir: options.dir,
4676
- spa: options.spa
4677
- });
4678
- if (staticPreset || configuredAppType === "static" || configuredAppType === "spa" || options.dir || options.spa) return unsupported([
4679
- `deploy: --platform cloudflare could not resolve the ${staticPreset?.appType ?? (options.spa ? "spa" : "static")} output to deploy.`,
4680
- "Set inference.outputDir in void.config.ts, pass --dir with an existing build directory,",
4681
- "or add a supported build tool so Void can locate the generated static assets."
4682
- ].join("\n"));
4683
- if (!framework && !hasBackendFiles(root)) return unsupported([
4684
- "deploy: --platform cloudflare found no Void backend to deploy.",
4685
- "A full Void app has at least one of: routes/, pages/, middleware, crons/, queues/,",
4686
- "email/, or an SSR entry. Add your server code, or use `void deploy` for a static site."
4687
- ].join("\n"));
4688
- try {
4689
- const paths = application.paths;
4690
- assertNoRootSourceConventionConflicts(paths);
4691
- validateSsrEntry(root, paths);
4692
- syncWranglerDurableObjects(root, application.durableObjects);
4693
- syncWranglerWebSockets(root, application.websockets);
4694
- } catch (error) {
4695
- return unsupported(`deploy: ${getErrorMessage(error)}`);
4696
- }
4697
- return { supported: true };
4698
- }
4699
- function unsupported(reason) {
4700
- return {
4701
- supported: false,
4702
- reason
4703
- };
4025
+ if (d1.restoreCommand) input.onD1Restore(d1.restoreCommand);
4026
+ verifyMigrationArtifact(input);
4027
+ return appliedMigrations;
4704
4028
  }
4705
4029
  // src/cli/cloudflare-isr.ts
4706
4030
  /** A configured opt-in authorizes only the cache identity declared before the build. */
@@ -4735,7 +4059,7 @@ async function chooseCloudflareIsr(root, config, options) {
4735
4059
  ...config.routing,
4736
4060
  isr: enabled
4737
4061
  };
4738
- log.info(`Saved routing.isr: ${String(enabled)} in void.config.ts. ISR caching ${enabled ? "will be enabled in this deployment" : "stays disabled until you change this setting"}.`);
4062
+ log$1.info(`Saved routing.isr: ${String(enabled)} in void.config.ts. ISR caching ${enabled ? "will be enabled in this deployment" : "stays disabled until you change this setting"}.`);
4739
4063
  return enabled;
4740
4064
  }
4741
4065
  // src/cli/deploy-cloudflare-email.ts
@@ -4770,8 +4094,8 @@ async function runCloudflareEmailStep(input) {
4770
4094
  };
4771
4095
  const from = input.voidConfig.email?.from;
4772
4096
  if (!from) {
4773
- if (hasVoidSendEmailBinding(input.rootConfig) || Array.isArray(input.rootConfig.addresses) && input.rootConfig.addresses.length > 0) log$1.info("deploy: email.from is unset; skipping automatic email setup. Existing Cloudflare email configuration is preserved.");
4774
- else log$1.warn(["deploy: this app uses email, but void.config.ts names no sender.", "Set email.from to \"you@mail.acme.com\" in void.config.ts — automatic email setup skipped."].join("\n"));
4097
+ if (hasVoidSendEmailBinding(input.rootConfig) || Array.isArray(input.rootConfig.addresses) && input.rootConfig.addresses.length > 0) log.info("deploy: email.from is unset; skipping automatic email setup. Existing Cloudflare email configuration is preserved.");
4098
+ else log.warn(["deploy: this app uses email, but void.config.ts names no sender.", "Set email.from to \"you@mail.acme.com\" in void.config.ts — automatic email setup skipped."].join("\n"));
4775
4099
  return without;
4776
4100
  }
4777
4101
  const { rootConfig } = input;
@@ -4793,7 +4117,7 @@ async function runCloudflareEmailStep(input) {
4793
4117
  try {
4794
4118
  pre = await preflightEmail(inputs);
4795
4119
  } catch (err) {
4796
- log$1.warn(`deploy: email preflight failed — ${getErrorMessage(err)}. Deploying without email.`);
4120
+ log.warn(`deploy: email preflight failed — ${getErrorMessage(err)}. Deploying without email.`);
4797
4121
  return without;
4798
4122
  }
4799
4123
  const mapFor = (addresses, sendingReady, creating = []) => ({
@@ -4809,13 +4133,13 @@ async function runCloudflareEmailStep(input) {
4809
4133
  writeProvisionedWranglerConfig(input.root, patch, { configPath: input.configPath });
4810
4134
  return true;
4811
4135
  } catch (err) {
4812
- log$1.error(`deploy: could not update ${configName} — ${getErrorMessage(err)}.`);
4136
+ log.error(`deploy: could not update ${configName} — ${getErrorMessage(err)}.`);
4813
4137
  return false;
4814
4138
  }
4815
4139
  };
4816
4140
  const awaitingOnboarding = isAwaitingSendingOnboarding(pre);
4817
4141
  if (pre.ready || awaitingOnboarding) {
4818
- if (awaitingOnboarding) log$1.warn(formatSendingOnlyPaidHint(pre.domain).join("\n"));
4142
+ if (awaitingOnboarding) log.warn(formatSendingOnlyPaidHint(pre.domain).join("\n"));
4819
4143
  const patch = {};
4820
4144
  const rows = [];
4821
4145
  if (pre.addressesStale) {
@@ -4828,19 +4152,19 @@ async function runCloudflareEmailStep(input) {
4828
4152
  }
4829
4153
  let configWritten = false;
4830
4154
  if (rows.length > 0) {
4831
- for (const foreign of pre.addressesStale ? pre.rules.foreign : []) log$1.message(` ! ${foreign.address}: already routed to ${foreign.owner}; left alone, not in addresses`);
4155
+ for (const foreign of pre.addressesStale ? pre.rules.foreign : []) log.message(` ! ${foreign.address}: already routed to ${foreign.owner}; left alone, not in addresses`);
4832
4156
  if (!writeConfig(patch)) {
4833
- log$1.warn(`deploy: deploying with the email setup ${configName} already carries.`);
4157
+ log.warn(`deploy: deploying with the email setup ${configName} already carries.`);
4834
4158
  return {
4835
4159
  ...without,
4836
4160
  map: mapFor(existingAddresses(rootConfig, pre), pre.sending.state === "ready")
4837
4161
  };
4838
4162
  }
4839
4163
  configWritten = true;
4840
- log$1.message(` ✔ config ${configName} updated (${rows.join(", ")})`);
4164
+ log.message(` ✔ config ${configName} updated (${rows.join(", ")})`);
4841
4165
  }
4842
4166
  if (awaitingOnboarding) {
4843
- log$1.warn(`deploy: deploying with the email setup ${configName} already carries.`);
4167
+ log.warn(`deploy: deploying with the email setup ${configName} already carries.`);
4844
4168
  return {
4845
4169
  satisfied: false,
4846
4170
  configWritten,
@@ -4853,10 +4177,10 @@ async function runCloudflareEmailStep(input) {
4853
4177
  map: mapFor(pre.addresses, pre.sending.state === "ready", pre.rulesPending)
4854
4178
  };
4855
4179
  }
4856
- log$1.message(renderEmailChecklist(pre));
4180
+ log.message(renderEmailChecklist(pre));
4857
4181
  if (isCommittedSubdomainPlanWaitingForDns(pre, rootConfig)) {
4858
4182
  const dnsState = pre.domainMx.state === "empty" ? "this resolver sees no MX records yet" : "the MX lookup failed";
4859
- log$1.error([
4183
+ log.error([
4860
4184
  `deploy: cannot verify Email Routing on ${pre.domain} because ${dnsState}.`,
4861
4185
  `The existing addresses plan in ${configName} is preserved. DNS may still be propagating after \`void email setup\`; run \`void email status --platform cloudflare\` and retry the deploy when this resolver sees Cloudflare's MX records.`,
4862
4186
  "Nothing was built or uploaded."
@@ -4873,10 +4197,10 @@ async function runCloudflareEmailStep(input) {
4873
4197
  if (Array.isArray(rootConfig.addresses) && pre.addressesOwnership.state === "mine" && pre.routing.state !== "ready") {
4874
4198
  if (writeConfig({ addresses: null })) {
4875
4199
  configWritten = true;
4876
- log$1.message(` ! config addresses removed from ${configName} (routing on ${pre.domain} is ${pre.routing.state}); no routing rule is created for ${rootConfig.addresses.map(String).join(", ")}`);
4200
+ log.message(` ! config addresses removed from ${configName} (routing on ${pre.domain} is ${pre.routing.state}); no routing rule is created for ${rootConfig.addresses.map(String).join(", ")}`);
4877
4201
  }
4878
4202
  }
4879
- log$1.warn(`deploy: ${reason} — ${shipsBinding ? `deploying with the email setup ${configName} already carries.` : "deploying without email."}`);
4203
+ log.warn(`deploy: ${reason} — ${shipsBinding ? `deploying with the email setup ${configName} already carries.` : "deploying without email."}`);
4880
4204
  return {
4881
4205
  satisfied: false,
4882
4206
  configWritten,
@@ -4887,9 +4211,9 @@ async function runCloudflareEmailStep(input) {
4887
4211
  if (input.nonInteractive) return leaveAccount([`email on ${pre.domain} is not ${shipsBinding ? "fully " : ""}set up, and this shell cannot ask.`, "Run `void email setup --platform cloudflare` once locally, commit void.lock.json, then redeploy."].join("\n"));
4888
4212
  if (!await input.confirm(`Set up email on ${pre.domain}?`)) return leaveAccount("email setup skipped — run `void email setup --platform cloudflare` later.");
4889
4213
  const out = await applyEmailSetup(pre, inputs);
4890
- if (out.lines.length > 0) log$1.message(out.lines.join("\n"));
4214
+ if (out.lines.length > 0) log.message(out.lines.join("\n"));
4891
4215
  if (!writeConfig(out.patch)) {
4892
- log$1.warn("deploy: deploying without email.");
4216
+ log.warn("deploy: deploying without email.");
4893
4217
  return without;
4894
4218
  }
4895
4219
  const bindingPresent = shipsBinding || out.patch.sendEmail !== void 0;
@@ -5015,7 +4339,7 @@ async function chooseCloudflareQueueNames(input) {
5015
4339
  /** Validate source-level native deploy inputs before account operations or project code. */
5016
4340
  async function prepareCloudflareDeploySource(root, options, voidConfig) {
5017
4341
  if (options.skipBuild) {
5018
- log$1.error([
4342
+ log.error([
5019
4343
  "deploy: --skip-build is not supported with --platform cloudflare.",
5020
4344
  "This backend validates the artifact the build emits — the worker vars in",
5021
4345
  "dist/ssr/wrangler.json and the generated auth schema — so a skipped build would",
@@ -5032,19 +4356,19 @@ async function prepareCloudflareDeploySource(root, options, voidConfig) {
5032
4356
  environment: "prod"
5033
4357
  });
5034
4358
  } catch (error) {
5035
- log$1.error(`deploy: ${getErrorMessage(error)}`);
4359
+ log.error(`deploy: ${getErrorMessage(error)}`);
5036
4360
  return null;
5037
4361
  }
5038
4362
  const classification = classifyCloudflareDeployApp(root, voidConfig, options, application);
5039
4363
  if (!classification.supported) {
5040
- log$1.error(classification.reason);
4364
+ log.error(classification.reason);
5041
4365
  return null;
5042
4366
  }
5043
4367
  const configPath = discoverRootWranglerConfig(root);
5044
4368
  const facts = await computeDesiredCloudflareResources(root, voidConfig, configPath, application);
5045
4369
  const { desired, dialect, migrations: preBuildMigrations, migrationsDir } = facts;
5046
4370
  if (!options.skipMigrations && dialect !== "sqlite" && preBuildMigrations.length > 0 && !process.env.DATABASE_URL) {
5047
- log$1.error([
4371
+ log.error([
5048
4372
  `deploy: ${dialect === "mysql" ? "MySQL" : "PostgreSQL"} migrations require DATABASE_URL for --platform cloudflare.`,
5049
4373
  "Set the production connection string in the deploy environment. Void uses it only to",
5050
4374
  "provision Hyperdrive and apply checked-in migrations before uploading the Worker; it is",
@@ -5057,13 +4381,13 @@ async function prepareCloudflareDeploySource(root, options, voidConfig) {
5057
4381
  const expected = JSON.stringify(desired.d1.migrationsDir);
5058
4382
  let fix = `Set migrations_dir to ${expected} in d1_databases of ${basename(configPath)}, or remove it and Void will fill it in.`;
5059
4383
  if (basename(configPath) === ".void-wrangler.jsonc") fix = `Set migrations_dir to ${expected} in cloudflare.d1_databases of void.config.ts${readStoredResourceName(voidConfig.cloudflare ?? {}, "d1_databases", desired.d1.binding, "migrations_dir") === void 0 ? "." : ", or remove it and Void will fill it in."}`;
5060
- log$1.error(`deploy: D1 binding ${JSON.stringify(desired.d1.binding)} sets migrations_dir ${JSON.stringify(storedDir)}, but Void generates and applies migrations from ${expected}. ${fix}`);
4384
+ log.error(`deploy: D1 binding ${JSON.stringify(desired.d1.binding)} sets migrations_dir ${JSON.stringify(storedDir)}, but Void generates and applies migrations from ${expected}. ${fix}`);
5061
4385
  return null;
5062
4386
  }
5063
4387
  if (desired.d1) {
5064
4388
  const migrationsPattern = resolveWranglerMigrationPattern(parseRootWranglerConfig(configPath), desired.d1.binding, storedDir ?? desired.d1.migrationsDir ?? relative(dirname(configPath), migrationsDir));
5065
4389
  if (!migrationsPattern.ok) {
5066
- log$1.error(migrationsPattern.reason);
4390
+ log.error(migrationsPattern.reason);
5067
4391
  return null;
5068
4392
  }
5069
4393
  }
@@ -5075,12 +4399,12 @@ async function prepareCloudflareDeploySource(root, options, voidConfig) {
5075
4399
  /** Pin the account and uploader, set up email, provision resources and snapshot the pins. */
5076
4400
  async function preflightCloudflareWorker(input) {
5077
4401
  const { root, voidConfig, options, deps, exit, cliLog, reporter, initialCloudflareLink, detectedFramework, source } = input;
5078
- const { configPath, needsSandbox, needsEmail, emailHandlers, authEnabled, needsAI, expectedCrons, desired, migrations: preBuildMigrations, reasons, needsLive } = source;
4402
+ const { configPath, needsSandbox, needsEmail, emailHandlers, authEnabled, needsAI, inferredBrowserBinding, expectedCrons, desired, migrations: preBuildMigrations, reasons, needsLive } = source;
5079
4403
  let rootConfig = parseRootWranglerConfig(configPath);
5080
4404
  if (needsSandbox) try {
5081
4405
  assertSandboxNamespaceConfig(rootConfig, resolveSandboxConfig(voidConfig, root));
5082
4406
  } catch (error) {
5083
- log$1.error(`deploy: ${getErrorMessage(error)}`);
4407
+ log.error(`deploy: ${getErrorMessage(error)}`);
5084
4408
  return exit(1);
5085
4409
  }
5086
4410
  const connection = await connectCloudflareDeployAccount({
@@ -5093,10 +4417,38 @@ async function preflightCloudflareWorker(input) {
5093
4417
  reporter
5094
4418
  });
5095
4419
  if (!connection) return exit(1);
5096
- const { apiBaseUrl, complianceRegion, usesCf, cfUploaderIsPinned, assertUploaderStillPinned, accountId, workersDevSubdomain, readinessAccessOrigin, runWrangler } = connection;
5097
- rootConfig = connection.rootConfig;
4420
+ const { rootConfig: connectedConfig, ...target } = connection;
4421
+ const { apiBaseUrl, complianceRegion, accountId, runWrangler, assertUploaderStillPinned } = target;
4422
+ rootConfig = connectedConfig;
5098
4423
  const workerName = readWranglerTopLevelString(rootConfig, "name") ?? deriveWorkerName(root);
4424
+ const { entries: expectedWorkflows } = planWorkflows(rootConfig, source.analysis.workflows, workerName);
5099
4425
  printDeployContext(workerName, "Cloudflare");
4426
+ const localWorkflows = readWorkflowDeclarations({
4427
+ ...rootConfig,
4428
+ name: workerName,
4429
+ workflows: expectedWorkflows
4430
+ }).filter((workflow) => isLocalWorkflow(workflow, workerName));
4431
+ const required = requestedWorkflowLimits(localWorkflows);
4432
+ const checkWorkflowPlan = !workflowSettingsFit(required);
4433
+ if (checkWorkflowPlan) {
4434
+ if (!await confirmCloudflareDeployAuthentication(connection, configPath) || !assertUploaderStillPinned()) return exit(1);
4435
+ const checked = await runWrangler({
4436
+ type: "workflows.entitlement",
4437
+ ...required,
4438
+ configPath,
4439
+ fedramp: complianceRegion === "fedramp_high"
4440
+ }, { capture: true });
4441
+ if (!isCleanCloudflareExit(checked) || checked.data !== true) {
4442
+ log.error([
4443
+ `deploy: could not confirm the requested Workflow settings for Cloudflare account ${accountId}.`,
4444
+ "Workers Free supports unscheduled Workflows with up to 1,024 steps, 100 concurrent instances and 3 days of retention.",
4445
+ "Workers Paid supports schedules, up to 25,000 steps and up to 30 days of retention.",
4446
+ `Enable Workers Paid at ${CLOUDFLARE_WORKERS_PAID_URL} or use settings within your account limits.`,
4447
+ "The deploy token needs Account Settings: Read to check entitlements and Workers Scripts: Edit to publish."
4448
+ ].join("\n"));
4449
+ return exit(1);
4450
+ }
4451
+ }
5100
4452
  let emailMap = null;
5101
4453
  if (needsEmail) {
5102
4454
  if (!assertUploaderStillPinned()) return exit(1);
@@ -5123,7 +4475,7 @@ async function preflightCloudflareWorker(input) {
5123
4475
  });
5124
4476
  if (email.abortDeploy) return exit(1);
5125
4477
  if (options.requireEmail && !email.satisfied) {
5126
- log$1.error(["deploy: --require-email — email is not fully set up for this deploy (see above); refusing to deploy.", "Nothing was built or uploaded. Set email up, or drop --require-email."].join("\n"));
4478
+ log.error(["deploy: --require-email — email is not fully set up for this deploy (see above); refusing to deploy.", "Nothing was built or uploaded. Set email up, or drop --require-email."].join("\n"));
5127
4479
  return exit(1);
5128
4480
  }
5129
4481
  if (email.configWritten) rootConfig = parseRootWranglerConfig(configPath);
@@ -5131,7 +4483,7 @@ async function preflightCloudflareWorker(input) {
5131
4483
  } else {
5132
4484
  const staleAddresses = Array.isArray(rootConfig.addresses) ? rootConfig.addresses.filter((a) => typeof a === "string") : [];
5133
4485
  const staleBinding = hasVoidSendEmailBinding(rootConfig);
5134
- if (staleAddresses.length > 0 || staleBinding) log$1.warn([
4486
+ if (staleAddresses.length > 0 || staleBinding) log.warn([
5135
4487
  "deploy: this app no longer declares email handlers or imports void/email, but the Cloudflare config still carries the email setup Void wrote:",
5136
4488
  ...staleAddresses.map((a) => ` • ${a} — still routed to worker "${workerName}", which no longer exports email(); inbound mail there will fail.`),
5137
4489
  ...staleBinding ? [` • send_email ${SEND_EMAIL_BINDING} binding`] : [],
@@ -5143,28 +4495,28 @@ async function preflightCloudflareWorker(input) {
5143
4495
  try {
5144
4496
  schemaResult = await (deps.resolveSchemaFacts ?? resolveEnvSchemaFactsDefault)({ root }, schemaProbeEnv);
5145
4497
  } catch (err) {
5146
- log$1.error(`deploy: could not derive the env schema — ${getErrorMessage(err)}`);
4498
+ log.error(`deploy: could not derive the env schema — ${getErrorMessage(err)}`);
5147
4499
  return exit(1);
5148
4500
  }
5149
4501
  if (schemaResult.kind === "schema-error") {
5150
- log$1.error(`deploy: ${selfHostSchemaFailureMessage(schemaResult.reason)}`);
4502
+ log.error(`deploy: ${selfHostSchemaFailureMessage(schemaResult.reason)}`);
5151
4503
  return exit(1);
5152
4504
  }
5153
4505
  const schemaFacts = schemaResult.facts;
5154
4506
  if (!isDeepStrictEqual(rootConfig, parseRootWranglerConfig(configPath))) {
5155
- log$1.error([
4507
+ log.error([
5156
4508
  "deploy: the root wrangler config changed during the pre-build env-schema probe.",
5157
4509
  "Refusing to run an authenticated Cloudflare command with a config rewritten by project",
5158
4510
  "code. Rebuild from a clean checkout, then rerun."
5159
4511
  ].join("\n"));
5160
4512
  return exit(1);
5161
4513
  }
5162
- if (!await confirmCloudflareDeployAuthentication(connection, configPath)) return exit(1);
4514
+ if (checkWorkflowPlan ? !assertUploaderStillPinned() : !await confirmCloudflareDeployAuthentication(connection, configPath)) return exit(1);
5163
4515
  let existingWorker = null;
5164
4516
  let pinnedHandoffLink = null;
5165
4517
  let approvedHandoffKv = [];
5166
4518
  if (options.reuseExistingWorker || initialCloudflareLink) {
5167
- if (authEnabled || needsSandbox || needsAI || expectedCrons.length || desired.queues.length || preBuildMigrations.length) throw new Error("Link the existing site without adding runtime features, auth setup, or database migrations. Make those changes in a later deployment.");
4519
+ if (authEnabled || needsSandbox || needsAI || inferredBrowserBinding !== void 0 || expectedCrons.length || desired.queues.length || preBuildMigrations.length) throw new Error("Link the existing site without adding runtime features, auth setup, or database migrations. Make those changes in a later deployment.");
5168
4520
  approvedHandoffKv = approvedCloudflareIsrBinding(voidConfig, rootConfig);
5169
4521
  existingWorker = await prepareExistingCloudflareDeployWithAuth({
5170
4522
  root,
@@ -5197,8 +4549,8 @@ async function preflightCloudflareWorker(input) {
5197
4549
  }, {
5198
4550
  accountId,
5199
4551
  log: {
5200
- info: (message) => log$1.info(message),
5201
- warn: (message) => log$1.warn(message)
4552
+ info: (message) => log.info(message),
4553
+ warn: (message) => log.warn(message)
5202
4554
  }
5203
4555
  });
5204
4556
  rootConfig = parseRootWranglerConfig(configPath);
@@ -5217,7 +4569,7 @@ async function preflightCloudflareWorker(input) {
5217
4569
  configPath: existsSync(configPath) ? configPath : void 0
5218
4570
  }, { capture: true }));
5219
4571
  if (!isCleanCloudflareExit(containers)) {
5220
- log$1.error(formatCloudflareSandboxUnavailable({ preflight: true }));
4572
+ log.error(formatCloudflareSandboxUnavailable({ preflight: true }));
5221
4573
  return exit(1);
5222
4574
  }
5223
4575
  cliLog.info("cloudflare_sandbox_available");
@@ -5235,18 +4587,18 @@ async function preflightCloudflareWorker(input) {
5235
4587
  result = await provision(root, configPath, desired, {
5236
4588
  accountId,
5237
4589
  log: {
5238
- info: (msg) => log$1.info(msg),
5239
- warn: (msg) => log$1.warn(msg)
4590
+ info: (msg) => log.info(msg),
4591
+ warn: (msg) => log.warn(msg)
5240
4592
  }
5241
4593
  });
5242
4594
  cliLog.info("cloudflare_provisioned", { resources: result.resources.map((r) => `${r.kind}:${r.action}`) });
5243
4595
  } catch (err) {
5244
- log$1.error(`deploy: provisioning failed — ${getErrorMessage(err)}`);
4596
+ log.error(`deploy: provisioning failed — ${getErrorMessage(err)}`);
5245
4597
  return exit(1);
5246
4598
  }
5247
4599
  const skipped = result.resources.filter((r) => r.action === "skipped");
5248
4600
  if (skipped.length > 0) {
5249
- log$1.error([
4601
+ log.error([
5250
4602
  "deploy: these required resources were skipped during provisioning and are NOT available:",
5251
4603
  ...skipped.map((r) => {
5252
4604
  const label = CLOUDFLARE_RESOURCE_LABELS[r.kind] ?? r.kind;
@@ -5261,11 +4613,11 @@ async function preflightCloudflareWorker(input) {
5261
4613
  }
5262
4614
  const { missing } = checkCloudflareProvisionDrift(configPath, desired);
5263
4615
  if (missing.length > 0) {
5264
- log$1.error(formatCloudflareDriftMessage(missing, reasons, "deploy: provisioning did not satisfy every required resource:", "Retry `void deploy --platform cloudflare`, or provision the listed resources manually."));
4616
+ log.error(formatCloudflareDriftMessage(missing, reasons, "deploy: provisioning did not satisfy every required resource:", "Retry `void deploy --platform cloudflare`, or provision the listed resources manually."));
5265
4617
  return exit(1);
5266
4618
  }
5267
4619
  if (desired.d1 && d1MigrationsDirMissing()) {
5268
- log$1.error(`deploy: provisioning did not set migrations_dir for D1 binding ${desired.d1.binding}. Retry \`void deploy --platform cloudflare\`.`);
4620
+ log.error(`deploy: provisioning did not set migrations_dir for D1 binding ${desired.d1.binding}. Retry \`void deploy --platform cloudflare\`.`);
5269
4621
  return exit(1);
5270
4622
  }
5271
4623
  };
@@ -5276,14 +4628,14 @@ async function preflightCloudflareWorker(input) {
5276
4628
  workerName,
5277
4629
  configPath,
5278
4630
  runWrangler,
5279
- info: (message) => log$1.info(message)
4631
+ info: (message) => log.info(message)
5280
4632
  });
5281
4633
  } catch (error) {
5282
- log$1.error(getErrorMessage(error));
4634
+ log.error(getErrorMessage(error));
5283
4635
  return exit(1);
5284
4636
  }
5285
4637
  if (!queueNames.ok) {
5286
- log$1.error(queueNames.message);
4638
+ log.error(queueNames.message);
5287
4639
  return exit(1);
5288
4640
  }
5289
4641
  const absentQueues = queueNames.absent;
@@ -5311,36 +4663,39 @@ async function preflightCloudflareWorker(input) {
5311
4663
  } } : {}
5312
4664
  }, { configPath });
5313
4665
  const preBuildRootConfig = parseRootWranglerConfig(configPath);
5314
- const bindingIdentitySnapshot = snapshotBindingIdentities(preBuildRootConfig);
5315
- const passthroughIdentitySnapshot = snapshotPassthroughIdentities(preBuildRootConfig);
5316
- const passthroughRawFields = snapshotPassthroughRawFields(preBuildRootConfig);
5317
- const expectedContainers = reconstructExpectedContainers(voidConfig, root, preBuildRootConfig, needsSandbox);
5318
4666
  const expectedDurableObjectState = reconstructExpectedDurableObjectState(voidConfig, root, preBuildRootConfig, {
5319
4667
  needsSandbox,
5320
4668
  needsLive,
5321
4669
  analysis: source.analysis
5322
4670
  });
5323
4671
  return {
5324
- apiBaseUrl,
5325
- complianceRegion,
5326
- usesCf,
5327
- cfUploaderIsPinned,
5328
- assertUploaderStillPinned,
5329
- accountId,
5330
- workersDevSubdomain,
5331
- readinessAccessOrigin,
5332
- runWrangler,
4672
+ ...target,
5333
4673
  workerName,
5334
4674
  emailMap,
5335
4675
  schemaFacts,
5336
4676
  existingWorker,
5337
4677
  pinnedHandoffLink,
5338
4678
  approvedHandoffKv,
5339
- bindingIdentitySnapshot,
5340
- passthroughIdentitySnapshot,
5341
- passthroughRawFields,
5342
- expectedContainers,
5343
- expectedDurableObjectState
4679
+ verification: {
4680
+ workerName,
4681
+ accountId,
4682
+ desired,
4683
+ authEnabled,
4684
+ needsAI,
4685
+ aiBindingName: source.aiBindingName,
4686
+ inferredBrowserBinding: source.inferredBrowserBinding,
4687
+ expectedCrons,
4688
+ expectedContainers: reconstructExpectedContainers(voidConfig, root, preBuildRootConfig, needsSandbox),
4689
+ expectedMigrations: expectedDurableObjectState.migrations,
4690
+ expectedDurableObjectBindings: expectedDurableObjectState.bindings,
4691
+ bindingIdentitySnapshot: snapshotBindingIdentities(preBuildRootConfig),
4692
+ passthroughIdentitySnapshot: snapshotPassthroughIdentities({
4693
+ ...preBuildRootConfig,
4694
+ workflows: expectedWorkflows
4695
+ }),
4696
+ passthroughRawFields: snapshotPassthroughRawFields(preBuildRootConfig)
4697
+ },
4698
+ hasLocalWorkflows: localWorkflows.length > 0
5344
4699
  };
5345
4700
  }
5346
4701
  // src/cli/deploy-cloudflare-publish.ts
@@ -5351,9 +4706,9 @@ async function publishCloudflareWorker(input) {
5351
4706
  const { configPath, needsSandbox, desired, analysis } = input.source;
5352
4707
  const { usesCf, existingWorker, pinnedHandoffLink, accountId, workerName, cfUploaderIsPinned, apiBaseUrl, complianceRegion, runWrangler, assertUploaderStillPinned, schemaFacts, approvedHandoffKv, workersDevSubdomain, readinessAccessOrigin } = input.preflight;
5353
4708
  const { d1MigrateToken, generatedConfigPath, prepareBuildOutput } = input.build;
5354
- const { workerWasMissingBeforeSecretProvisioning, initialAuthSecret, appliedMigrations } = input.migration;
4709
+ const { workerWasMissingBeforeSecretProvisioning, initialAuthSecret, message, applyMigrations } = input.migration;
5355
4710
  const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath);
5356
- assertCloudflareDeployTargetUnchanged({
4711
+ const verifyTarget = () => assertCloudflareDeployTargetUnchanged({
5357
4712
  root,
5358
4713
  existingWorker,
5359
4714
  pinnedHandoffLink,
@@ -5361,10 +4716,12 @@ async function publishCloudflareWorker(input) {
5361
4716
  accountId,
5362
4717
  workerName
5363
4718
  });
4719
+ verifyTarget();
5364
4720
  if (usesCf && !cfUploaderIsPinned()) return exit(1);
4721
+ let appliedMigrations = 0;
5365
4722
  const cfOutput = usesCf ? await prepareBuildOutput() : null;
5366
4723
  if (!cfOutput && usesCf) {
5367
- log$1.error("deploy: cf could not prepare the built Worker for deployment.");
4724
+ log.error("deploy: cf could not prepare the built Worker for deployment.");
5368
4725
  return exit(1);
5369
4726
  }
5370
4727
  const activationRunner = createCfActivationRunner({
@@ -5403,15 +4760,17 @@ async function publishCloudflareWorker(input) {
5403
4760
  initialCloudflareCandidate,
5404
4761
  assertUploaderStillPinned,
5405
4762
  approvedKv: approvedHandoffKv,
4763
+ previousWorkflowVersionId: input.build.previousWorkflowVersionId,
5406
4764
  queueConsumerCleanup
5407
4765
  }),
5408
4766
  runWrangler: activationRunner,
5409
4767
  verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned,
5410
4768
  requireVersionMetadata: existingWorker === null || hasVersionMetadata,
5411
4769
  requirePreviewForReadiness: existingWorker !== null && !hasVersionMetadata,
5412
- message: encodeCloudflareVersionMessage(input.migration.migrationHistory, {
5413
- ...readCloudflareTriggerConfig(generatedConfigPath, configPath),
5414
- ...existingWorker ? { preserve: true } : {}
4770
+ message,
4771
+ beforeUpload: applyMigrations && (async () => {
4772
+ appliedMigrations = await applyMigrations();
4773
+ verifyTarget();
5415
4774
  }),
5416
4775
  allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning,
5417
4776
  ...pinActiveSecrets ? { pinActiveSecrets } : {},
@@ -5436,7 +4795,7 @@ async function publishCloudflareWorker(input) {
5436
4795
  note(formatDeploySummary({
5437
4796
  workerName,
5438
4797
  migrations: appliedMigrations,
5439
- d1MigrationsCurrent: input.migration.migrationHistory !== null && d1MigrateToken !== void 0,
4798
+ d1MigrationsCurrent: applyMigrations !== void 0 && d1MigrateToken !== void 0,
5440
4799
  cronJobs: existingWorker ? void 0 : analysis.jobs.length,
5441
4800
  queues: existingWorker ? void 0 : desired.queues.length,
5442
4801
  framework: detectedFramework?.name
@@ -5448,16 +4807,25 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5448
4807
  options = withRecordedReadinessAccessOrigin(options);
5449
4808
  const initialCloudflareLink = readCloudflareLink(root);
5450
4809
  const initialCloudflareCandidate = readCloudflareCandidate(root);
4810
+ let d1RestoreCommand;
4811
+ const reportRestore = () => {
4812
+ const command = d1RestoreCommand;
4813
+ d1RestoreCommand = void 0;
4814
+ if (command) logD1RestoreAfterDeployFailure(command);
4815
+ };
5451
4816
  const exitProcess = deps.exit ?? ((code) => process.exit(code));
5452
4817
  const exit = (code) => {
5453
4818
  if (code === 0) cliLog.info("deploy_end", {
5454
4819
  ok: true,
5455
4820
  exitCode: code
5456
4821
  });
5457
- else cliLog.error("deploy_end", void 0, {
5458
- ok: false,
5459
- exitCode: code
5460
- });
4822
+ else {
4823
+ reportRestore();
4824
+ cliLog.error("deploy_end", void 0, {
4825
+ ok: false,
4826
+ exitCode: code
4827
+ });
4828
+ }
5461
4829
  return exitProcess(code);
5462
4830
  };
5463
4831
  deps = {
@@ -5465,17 +4833,22 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5465
4833
  exit
5466
4834
  };
5467
4835
  const reporter = createCloudflareChildReporter(cliLog);
4836
+ const seedConfig = !initialCloudflareLink && !options.reuseExistingWorker && !hasDeployConfigSource(root);
5468
4837
  const voidConfig = readConfig(root);
5469
4838
  const atomic = options.atomic === true || voidConfig.deploy?.cloudflare?.mode === "atomic";
5470
4839
  if (atomic && (options.reuseExistingWorker || initialCloudflareLink)) {
5471
- log$1.error("deploy: atomic deployment is unavailable during the existing Worker handoff. Complete the handoff first.");
4840
+ log.error("deploy: atomic deployment is unavailable during the existing Worker handoff. Complete the handoff first.");
4841
+ return exit(1);
4842
+ }
4843
+ if (options.preview !== void 0 && (options.reuseExistingWorker || initialCloudflareLink)) {
4844
+ log.error("deploy: previews are unavailable during the existing Worker handoff. Complete the handoff with a production deploy first.");
5472
4845
  return exit(1);
5473
4846
  }
5474
4847
  const detectedFramework = detectFramework(root);
5475
4848
  const frameworkPreset = detectedFramework && hasOwnKey(FRAMEWORK_PRESETS, detectedFramework.name) ? FRAMEWORK_PRESETS[detectedFramework.name] : void 0;
5476
4849
  cliLog.info("cloudflare_deploy_start", { provision: options.provision === true ? true : void 0 });
5477
4850
  if (isNodeTarget(voidConfig.target)) {
5478
- log$1.error([
4851
+ log.error([
5479
4852
  `deploy: --platform cloudflare is not supported for the "${voidConfig.target}" target.`,
5480
4853
  "This backend deploys Cloudflare Workers only. Deploy a node/bun/deno build with its",
5481
4854
  "own host/runtime, or use the default Cloudflare target for --platform cloudflare."
@@ -5483,7 +4856,7 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5483
4856
  return exit(1);
5484
4857
  }
5485
4858
  if (detectedFramework?.class === "a" && hasConfiguredVoidWorkerRoutingRules(voidConfig.routing)) {
5486
- log$1.error([
4859
+ log.error([
5487
4860
  `deploy: native Cloudflare deployment cannot apply Void routing redirects, rewrites, fallbacks, or headers to ${detectedFramework.name}.`,
5488
4861
  "This framework owns its Worker request handler, so these rules would otherwise be ignored.",
5489
4862
  "Move the rules into the framework or its Cloudflare Worker, then retry."
@@ -5492,21 +4865,35 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5492
4865
  }
5493
4866
  const staticPreset = resolveCloudflareStaticPreset(root, voidConfig, options) ?? await resolveCloudflareVoidStaticPreset(root, voidConfig);
5494
4867
  if (staticPreset) {
5495
- if (atomic) {
5496
- log$1.error("deploy: atomic deployment is only for Workers with Durable Objects.");
4868
+ if (atomic && options.preview !== void 0) {
4869
+ log.error("deploy: --atomic is unavailable for static previews.");
5497
4870
  return exit(1);
5498
4871
  }
5499
- return runCloudflareStaticDeploy(root, options, voidConfig, staticPreset, cliLog, deps, initialCloudflareLink, initialCloudflareCandidate, reporter);
4872
+ return runCloudflareStaticDeploy(root, {
4873
+ ...options,
4874
+ atomic
4875
+ }, voidConfig, staticPreset, cliLog, deps, initialCloudflareLink, initialCloudflareCandidate, reporter);
4876
+ }
4877
+ if (options.preview !== void 0) {
4878
+ log.error([
4879
+ "deploy: --preview currently supports static sites and single-page apps only.",
4880
+ "This app needs a Worker (server routes, bindings, migrations or secrets), and a Preview would share or skip them. Deploy it without --preview.",
4881
+ ...options.skipBuild ? ["If this is a static site, no earlier build was found: build it first, or pass --dir <folder>."] : []
4882
+ ].join("\n"));
4883
+ return exit(1);
5500
4884
  }
5501
4885
  if (detectedFramework && voidConfig.routing?.alwaysUseHttps === true) {
5502
- log$1.error([
4886
+ log.error([
5503
4887
  `deploy: native Cloudflare deployment cannot apply Void routing.alwaysUseHttps to ${detectedFramework.name}.`,
5504
4888
  "This framework owns its Worker request handler, so the HTTPS redirect would otherwise be ignored.",
5505
4889
  "Redirect HTTP to HTTPS in the framework, or turn on Cloudflare's Always Use HTTPS setting for your zone, then remove routing.alwaysUseHttps and retry."
5506
4890
  ].join("\n"));
5507
4891
  return exit(1);
5508
4892
  }
5509
- const source = await prepareCloudflareDeploySource(root, options, voidConfig);
4893
+ const source = await prepareCloudflareDeploySource(root, {
4894
+ ...options,
4895
+ seedConfig
4896
+ }, voidConfig);
5510
4897
  if (!source) return exit(1);
5511
4898
  const preflight = await preflightCloudflareWorker({
5512
4899
  root,
@@ -5533,47 +4920,36 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5533
4920
  source,
5534
4921
  preflight
5535
4922
  });
5536
- const migration = await migrateCloudflareWorker({
4923
+ const deployment = {
5537
4924
  root,
5538
4925
  deps,
5539
4926
  exit,
5540
4927
  cliLog,
5541
4928
  source,
5542
4929
  preflight,
5543
- build,
5544
- skipMigrations: options.skipMigrations
5545
- });
5546
- let restoreReported = false;
5547
- const reportRestore = () => {
5548
- if (migration.d1RestoreCommand && !restoreReported) {
5549
- restoreReported = true;
5550
- logD1RestoreAfterDeployFailure(migration.d1RestoreCommand);
5551
- }
5552
- };
5553
- const exitAfterMigrations = (code) => {
5554
- if (code !== 0) reportRestore();
5555
- return exit(code);
4930
+ build
5556
4931
  };
4932
+ const migration = await prepareCloudflareWorkerMigrations({
4933
+ ...deployment,
4934
+ skipMigrations: options.skipMigrations,
4935
+ onD1Restore: (command) => {
4936
+ d1RestoreCommand = command;
4937
+ }
4938
+ });
5557
4939
  try {
5558
4940
  await publishCloudflareWorker({
5559
- root,
5560
- deps,
5561
- exit: exitAfterMigrations,
5562
- cliLog,
4941
+ ...deployment,
5563
4942
  reporter,
5564
4943
  atomic,
5565
4944
  detectedFramework,
5566
4945
  initialCloudflareCandidate,
5567
- source,
5568
- preflight,
5569
- build,
5570
4946
  migration
5571
4947
  });
5572
4948
  } catch (error) {
5573
4949
  reportRestore();
5574
4950
  throw error;
5575
4951
  }
5576
- if (preflight.emailMap) log$1.message(renderAddressMap(preflight.emailMap));
4952
+ if (preflight.emailMap) log.message(renderAddressMap(preflight.emailMap));
5577
4953
  printDeploySuccess();
5578
4954
  }
5579
4955
  // src/cli/deploy-managed-framework.ts
@@ -5581,14 +4957,18 @@ async function runCloudflareDeploy(root, options, cliLog, deps = {}) {
5581
4957
  * Class B/C framework deploy: build with framework CLI, package with preset output paths.
5582
4958
  */
5583
4959
  async function runFrameworkDeploy(root, config, client, detected, fwPreset, voidConfig, skipBuild, gitMetadata, cliLog, skipMigrations) {
5584
- log$1.info(`${detected.name} framework deploy`);
4960
+ log.info(`${detected.name} framework deploy`);
5585
4961
  cliLog?.info("deploy_mode", {
5586
4962
  mode: "framework",
5587
4963
  framework: detected.name
5588
4964
  });
4965
+ if (resolveBrowserBinding(voidConfig, analyzeApplicationSync(root, {
4966
+ config: voidConfig,
4967
+ environment: "prod"
4968
+ }).bindings) !== void 0) await client.requireBrowserRunSupport();
5589
4969
  const buildCmd = voidConfig.inference?.build ?? formatProjectCommand(root, fwPreset.buildCommand);
5590
4970
  if (!skipBuild) {
5591
- log$1.step(`Building (${buildCmd})...`);
4971
+ log.step(`Building (${buildCmd})...`);
5592
4972
  cliLog?.info("build_start", { command: buildCmd });
5593
4973
  const buildStartedAt = Date.now();
5594
4974
  execSync(voidConfig.inference?.build ?? resolveProjectCommand(root, fwPreset.buildCommand), {
@@ -5604,7 +4984,7 @@ async function runFrameworkDeploy(root, config, client, detected, fwPreset, void
5604
4984
  const { headerRules, redirectRules, fallbackRules } = mergeAndLintRoutingRules(assetsDir, voidConfig.routing);
5605
4985
  warnIgnoredNotFoundForFramework(voidConfig.routing?.notFound, detected.name);
5606
4986
  if (!existsSync(workerDir)) {
5607
- log$1.error(`deploy: Worker output '${fwPreset.workerDir}' not found. Run '${buildCmd}' first.`);
4987
+ log.error(`deploy: Worker output '${fwPreset.workerDir}' not found. Run '${buildCmd}' first.`);
5608
4988
  process.exit(1);
5609
4989
  }
5610
4990
  const analysis = analyzeApplicationSync(root, {
@@ -5613,13 +4993,14 @@ async function runFrameworkDeploy(root, config, client, detected, fwPreset, void
5613
4993
  });
5614
4994
  const { paths, bindings, authEnabled, dialect } = analysis;
5615
4995
  if (authEnabled) {
5616
- log$1.error("deploy: Void-managed Better Auth is only supported in Void apps. Use Better Auth's official integration for this framework instead.");
4996
+ log.error("deploy: Void-managed Better Auth is only supported in Void apps. Use Better Auth's official integration for this framework instead.");
5617
4997
  process.exit(1);
5618
4998
  }
5619
4999
  if (bindings.needsLive) {
5620
- log$1.error("deploy: void/live is currently supported in Void apps only.");
5000
+ log.error("deploy: void/live is currently supported in Void apps only.");
5621
5001
  process.exit(1);
5622
5002
  }
5003
+ const browserBinding = resolveBrowserBinding(voidConfig, bindings);
5623
5004
  assertDeploySchemaDriftFree(root, dialect);
5624
5005
  const validatedMigrations = validateDeployMigrations(paths.migrationsDir, analysis.migrations, paths.sourceRelative);
5625
5006
  if (dialect !== "sqlite" && analysis.needsDatabase) await ensureManagedHyperdrive(client, config.projectId, dialect);
@@ -5635,16 +5016,16 @@ async function runFrameworkDeploy(root, config, client, detected, fwPreset, void
5635
5016
  let actualWorkerDir = workerDir;
5636
5017
  let actualWorkerMain = fwPreset.workerMain;
5637
5018
  if (fwPreset.bundle) {
5638
- log$1.step("Bundling worker...");
5019
+ log.step("Bundling worker...");
5639
5020
  const bundleResult = await bundleEntry(root, originalEntry);
5640
5021
  actualWorkerDir = bundleResult.outputDir;
5641
5022
  actualWorkerMain = bundleResult.entryFilename;
5642
- log$1.info("Worker bundled");
5023
+ log.info("Worker bundled");
5643
5024
  }
5644
5025
  if (needsWrapper(wrapperFeatures)) {
5645
- log$1.step("Generating wrapper...");
5026
+ log.step("Generating wrapper...");
5646
5027
  await generateDeployWrapperIfNeeded(root, actualWorkerDir, actualWorkerMain, wrapperFeatures);
5647
- log$1.info("Wrapper generated");
5028
+ log.info("Wrapper generated");
5648
5029
  }
5649
5030
  const wranglerCompat = resolveDeployWranglerCompat(root, voidConfig, workerDir, { dialect });
5650
5031
  const revalidate = collectRevalidate(voidConfig, null);
@@ -5663,7 +5044,7 @@ async function runFrameworkDeploy(root, config, client, detected, fwPreset, void
5663
5044
  needed: needed.length,
5664
5045
  skipped
5665
5046
  });
5666
- if (skipped > 0) log$1.info(`Skipping ${formatCount(skipped, "unchanged asset")}`);
5047
+ if (skipped > 0) log.info(`Skipping ${formatCount(skipped, "unchanged asset")}`);
5667
5048
  s.start("Packaging...");
5668
5049
  cliLog?.info("package_start", {
5669
5050
  mode: "framework",
@@ -5680,6 +5061,7 @@ async function runFrameworkDeploy(root, config, client, detected, fwPreset, void
5680
5061
  frameworkName: detected.name,
5681
5062
  alwaysUseHttps: voidConfig.routing?.alwaysUseHttps,
5682
5063
  storage: voidConfig.storage,
5064
+ browser: browserBinding,
5683
5065
  database: typeof voidConfig.database === "object" ? voidConfig.database : void 0,
5684
5066
  workerMain: actualWorkerMain,
5685
5067
  bindings,
@@ -5745,9 +5127,13 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5745
5127
  mode: "full",
5746
5128
  framework: detected?.name
5747
5129
  });
5130
+ if (resolveBrowserBinding(voidConfig, analyzeApplicationSync(root, {
5131
+ config: voidConfig,
5132
+ environment: "prod"
5133
+ }).bindings) !== void 0) await client.requireBrowserRunSupport();
5748
5134
  if (!skipBuild) {
5749
5135
  const { label: buildCmd, command: buildExec } = resolveFullDeployBuildCommand(root, voidConfig.inference?.build);
5750
- log$1.step(`Building (${buildCmd})...`);
5136
+ log.step(`Building (${buildCmd})...`);
5751
5137
  cliLog?.info("build_start", { command: buildCmd });
5752
5138
  const buildStartedAt = Date.now();
5753
5139
  try {
@@ -5793,7 +5179,7 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5793
5179
  projectId: config.projectId,
5794
5180
  voidToken: await client.createPrerenderToken(config.projectId)
5795
5181
  });
5796
- if (result.paths.length === 0) log$1.info("No pages to prerender");
5182
+ if (result.paths.length === 0) log.info("No pages to prerender");
5797
5183
  else assertNoPrerenderFailures(result.failed);
5798
5184
  }
5799
5185
  const analysis = await analyzeApplication(root, {
@@ -5802,20 +5188,21 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5802
5188
  });
5803
5189
  const { paths, dialect, bindings, authEnabled, scan: routeScan } = analysis;
5804
5190
  if (isFrameworkMode && authEnabled) {
5805
- log$1.error("Void-managed Better Auth is only supported in Void apps. Use Better Auth's official integration for this framework instead.");
5191
+ log.error("Void-managed Better Auth is only supported in Void apps. Use Better Auth's official integration for this framework instead.");
5806
5192
  process.exit(1);
5807
5193
  }
5808
5194
  if (isFrameworkMode && bindings.needsSandbox) {
5809
- log$1.error("deploy: Cloudflare Sandboxes are currently supported in Void apps only.");
5195
+ log.error("deploy: Cloudflare Sandboxes are currently supported in Void apps only.");
5810
5196
  process.exit(1);
5811
5197
  }
5812
5198
  if (isFrameworkMode && bindings.needsLive) {
5813
- log$1.error("deploy: void/live is currently supported in Void apps only.");
5199
+ log.error("deploy: void/live is currently supported in Void apps only.");
5814
5200
  process.exit(1);
5815
5201
  }
5202
+ const browserBinding = resolveBrowserBinding(voidConfig, bindings);
5816
5203
  const sandboxConfig = bindings.needsSandbox ? resolveSandboxConfig(voidConfig, root) : void 0;
5817
5204
  if (bindings.needsSandbox && requiresSandboxPlatformImage(voidConfig)) {
5818
- log$1.error("deploy: `sandbox.image` points at a local Dockerfile. Add `sandbox.platformImage` with a pushed registry image for `void deploy`, or deploy this sandbox directly with Wrangler.");
5205
+ log.error("deploy: `sandbox.image` points at a local Dockerfile. Add `sandbox.platformImage` with a pushed registry image for `void deploy`, or deploy this sandbox directly with Wrangler.");
5819
5206
  process.exit(1);
5820
5207
  }
5821
5208
  const clientDir = join(distDir, "client");
@@ -5854,8 +5241,8 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5854
5241
  authEnabled,
5855
5242
  hasLive: liveConfig !== void 0
5856
5243
  });
5857
- if (allPrerenderable && !nonPageBackend && analysis.durableObjects.length === 0 && schedules.length === 0 && queues.length === 0) {
5858
- log$1.info("All pages prerendered — deploying as static site");
5244
+ if (allPrerenderable && !nonPageBackend && analysis.durableObjects.length === 0 && analysis.workflows.length === 0 && schedules.length === 0 && queues.length === 0) {
5245
+ log.info("All pages prerendered — deploying as static site");
5859
5246
  cliLog?.info("full_to_static_redirect", { reason: "all_pages_prerendered" });
5860
5247
  return runStaticDeploy(root, config, client, {
5861
5248
  buildCommand: null,
@@ -5912,7 +5299,7 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5912
5299
  needed: needed.length,
5913
5300
  skipped
5914
5301
  });
5915
- if (skipped > 0) log$1.info(`Skipping ${formatCount(skipped, "unchanged asset")}`);
5302
+ if (skipped > 0) log.info(`Skipping ${formatCount(skipped, "unchanged asset")}`);
5916
5303
  s.start("Packaging...");
5917
5304
  cliLog?.info("package_start", {
5918
5305
  mode: "full",
@@ -5946,6 +5333,7 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5946
5333
  } : bindings,
5947
5334
  alwaysUseHttps: voidConfig.routing?.alwaysUseHttps,
5948
5335
  storage: voidConfig.storage,
5336
+ browser: browserBinding,
5949
5337
  database: typeof voidConfig.database === "object" ? voidConfig.database : void 0,
5950
5338
  hasEmailHandlers: !isFrameworkMode && routeScan.email !== void 0 && hasEmailHandlers(routeScan.email),
5951
5339
  migrations: validatedMigrations,
@@ -5964,7 +5352,8 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5964
5352
  fallbackRules,
5965
5353
  dialect,
5966
5354
  webSockets,
5967
- durableObjects: analysis.durableObjects
5355
+ durableObjects: analysis.durableObjects,
5356
+ workflows: managedWorkflowDefinitions(voidConfig.cloudflare, analysis.workflows)
5968
5357
  }, voidConfig.routing?.revalidate, voidConfig.routing?.isr !== false);
5969
5358
  if (skipMigrations) manifest.migrationMode = "skip";
5970
5359
  const workerDir = join(distDir, workerDirName);
@@ -5976,12 +5365,12 @@ async function runFullDeploy(root, config, client, voidConfig, fwPreset, skipBui
5976
5365
  migrationDialect: dialect
5977
5366
  };
5978
5367
  if (needsWrapper(wrapperFeatures)) {
5979
- log$1.step("Generating wrapper...");
5368
+ log.step("Generating wrapper...");
5980
5369
  await generateDeployWrapperIfNeeded(root, workerDir, fwPreset?.workerMain ?? "index.js", wrapperFeatures);
5981
- log$1.info("Wrapper generated");
5370
+ log.info("Wrapper generated");
5982
5371
  }
5983
5372
  }
5984
- const workerFiles = collectWorkerFiles(workerDir);
5373
+ const workerFiles = collectWorkerFiles(workerDir, { excludePrecompressed: isNodeTarget(voidConfig.target) });
5985
5374
  assertWorkerMainUploaded(workerFiles, workerMain);
5986
5375
  cliLog?.info("package_end", {
5987
5376
  mode: "full",
@@ -6459,6 +5848,7 @@ async function runDeploy(root, options) {
6459
5848
  spa: options?.spa === true ? true : void 0,
6460
5849
  skipBuild: options?.skipBuild === true ? true : void 0,
6461
5850
  skipMigrations: options?.skipMigrations === true ? true : void 0,
5851
+ preview: options?.preview,
6462
5852
  nodeVersion: process.version,
6463
5853
  platform: process.platform,
6464
5854
  arch: process.arch
@@ -6486,7 +5876,7 @@ const deployTargets = {
6486
5876
  async deploy(root, options, cliLog) {
6487
5877
  if (options.projectSlug !== void 0) throw new Error("deploy: --project is not supported with platform cloudflare — this platform deploys to your own Cloudflare account and no Void project is involved.");
6488
5878
  assertInstalledVoidMatchesCli(root);
6489
- if (migrateLegacyVoidConfig(root)) log$1.step("Migrated project configuration to void.config.ts. Commit void.config.ts and void.lock.json.");
5879
+ if (migrateLegacyVoidConfig(root)) log.step("Migrated project configuration to void.config.ts. Commit void.config.ts and void.lock.json.");
6490
5880
  return runCloudflareDeploy(root, options, cliLog);
6491
5881
  }
6492
5882
  },
@@ -6498,7 +5888,7 @@ const deployTargets = {
6498
5888
  async function runDeployInner(root, options, cliLog) {
6499
5889
  const link = await maybeLinkCloudflareDeploy(root, options);
6500
5890
  if (link === "cancelled") {
6501
- log$1.info("Deployment cancelled.");
5891
+ log.info("Deployment cancelled.");
6502
5892
  return;
6503
5893
  }
6504
5894
  if (link === "existing") options = {
@@ -6539,7 +5929,7 @@ async function runManagedDeploy(root, options, cliLog) {
6539
5929
  }
6540
5930
  token ??= getToken(root);
6541
5931
  if (!token) {
6542
- log$1.error("No auth token found. Run `void account login` first.");
5932
+ log.error("No auth token found. Run `void account login` first.");
6543
5933
  process.exit(1);
6544
5934
  }
6545
5935
  const client = new PlatformClient(token, {
@@ -6561,7 +5951,7 @@ async function runManagedDeploy(root, options, cliLog) {
6561
5951
  else {
6562
5952
  const shouldCreate = await confirm({ message: `Project "${requestedProjectSlug}" does not exist. Create it?` });
6563
5953
  if (isCancel(shouldCreate) || !shouldCreate) {
6564
- log$1.info("Deploy cancelled.");
5954
+ log.info("Deploy cancelled.");
6565
5955
  process.exit(0);
6566
5956
  }
6567
5957
  config = await createProjectFromSlug(root, client, requestedProjectSlug, cliLog);
@@ -6577,7 +5967,7 @@ async function runManagedDeploy(root, options, cliLog) {
6577
5967
  }
6578
5968
  }
6579
5969
  if (!config && !process.stdin.isTTY) {
6580
- log$1.error("No project specified. Set `VOID_PROJECT`, pass `--project <slug>`, or commit `.void/project.json`.");
5970
+ log.error("No project specified. Set `VOID_PROJECT`, pass `--project <slug>`, or commit `.void/project.json`.");
6581
5971
  process.exit(1);
6582
5972
  }
6583
5973
  if (!config) config = await promptDeployProjectConfig(root, client, cliLog);
@@ -6590,20 +5980,18 @@ async function runManagedDeploy(root, options, cliLog) {
6590
5980
  printDeployContext(config.slug, destination);
6591
5981
  displayedProject = config.slug;
6592
5982
  }
6593
- if (migrateLegacyVoidConfig(root)) log$1.step("Migrated project configuration to void.config.ts. Commit void.config.ts and void.lock.json.");
5983
+ if (migrateLegacyVoidConfig(root)) log.step("Migrated project configuration to void.config.ts. Commit void.config.ts and void.lock.json.");
6594
5984
  const voidConfig = readConfig(root);
6595
5985
  cliLog.info("config_resolved", {
6596
5986
  target: voidConfig.target,
6597
5987
  appType: voidConfig.inference?.appType,
6598
5988
  output: voidConfig.output
6599
5989
  });
6600
- let preset = resolveStaticDeployPreset(root, voidConfig, {
6601
- dir: options?.dir,
6602
- spa: options?.spa
6603
- });
5990
+ let preset = resolveStaticDeployPreset(root, voidConfig, options);
6604
5991
  const detected = detectFramework(root);
6605
5992
  const gitMetadata = collectGitDeployMetadata(root, options?.skipBuild ? null : getGitCommit(root), process.env, buildEnv());
6606
5993
  if (!preset && detected) {
5994
+ if (scanWorkflowModules(root).length) throw new Error(FRAMEWORK_WORKFLOWS_ERROR);
6607
5995
  cliLog.info("framework_detected", {
6608
5996
  name: detected.name,
6609
5997
  class: detected.class
@@ -6611,7 +5999,7 @@ async function runManagedDeploy(root, options, cliLog) {
6611
5999
  const fwPreset = hasOwnKey(FRAMEWORK_PRESETS, detected.name) ? FRAMEWORK_PRESETS[detected.name] : void 0;
6612
6000
  if (detected.class === "b" || detected.class === "c") {
6613
6001
  if (!fwPreset) {
6614
- log$1.error(`No deploy preset found for framework "${detected.name}".`);
6002
+ log.error(`No deploy preset found for framework "${detected.name}".`);
6615
6003
  process.exit(1);
6616
6004
  }
6617
6005
  await runFrameworkDeploy(root, config, client, detected, fwPreset, voidConfig, options?.skipBuild, gitMetadata, cliLog, options.skipMigrations);
@@ -6634,9 +6022,9 @@ async function runManagedDeploy(root, options, cliLog) {
6634
6022
  if (isExpiredTokenError(error)) {
6635
6023
  if (getTokenSource() === "ci") throw new Error("`VOID_TOKEN` is invalid or expired. Generate a new token and try again.");
6636
6024
  if (!process.stdin.isTTY || reauthenticated) throw new Error("Auth token expired. Run `void account login` and try again.");
6637
- log$1.warn("Auth token expired. Re-authenticating...");
6025
+ log.warn("Auth token expired. Re-authenticating...");
6638
6026
  await promptForLoginToken(root);
6639
- log$1.step("Re-authenticated. Retrying deploy...");
6027
+ log.step("Re-authenticated. Retrying deploy...");
6640
6028
  reauthenticated = true;
6641
6029
  continue;
6642
6030
  }