@builtbyfriends/bwf 0.0.0-stage → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (448) hide show
  1. package/AGENTS_TEMPLATE.md +4 -0
  2. package/LICENSE +22 -0
  3. package/README.md +48 -2
  4. package/dist/account-cmd-Cj0I2_bJ.mjs +45 -0
  5. package/dist/agents-BLiMq9E1.mjs +113 -0
  6. package/dist/application-analysis-C9Ck2Yeg.mjs +1498 -0
  7. package/dist/application-routing-DbR-W5lG.mjs +25 -0
  8. package/dist/atomic-write-DA6eD1Kp.mjs +17 -0
  9. package/dist/auth-BKsUmWbT.d.mts +77 -0
  10. package/dist/auth-DkvoW5hB.mjs +33 -0
  11. package/dist/auth-aKyIWkdS.mjs +1 -0
  12. package/dist/auth-client-6-Ft9i9T.d.mts +5 -0
  13. package/dist/auth-client-DwCdwKbw.mjs +5 -0
  14. package/dist/auth-client-react-CJdeErvM.mjs +5 -0
  15. package/dist/auth-client-react-DvQLe5Zb.d.mts +5 -0
  16. package/dist/auth-link-D-DddkCQ.mjs +26 -0
  17. package/dist/auth-migrations-DDeifS3v.mjs +206 -0
  18. package/dist/auth-router-tWzIwf8f.mjs +66 -0
  19. package/dist/auth-xnkmpZUl.mjs +311 -0
  20. package/dist/base64-ikl9yBy3.mjs +15 -0
  21. package/dist/better-auth-shared-Br6TNaYJ.mjs +473 -0
  22. package/dist/better-auth-shared-CsBNvPOU.d.mts +56 -0
  23. package/dist/build-cmd-BnZezraT.mjs +153 -0
  24. package/dist/build-output-dir-Clj_unKN.mjs +402 -0
  25. package/dist/cancel-deploy-DKAj5U1Z.mjs +57 -0
  26. package/dist/cf-access-Bhz9wX6p.mjs +131 -0
  27. package/dist/cf-access-CUP5L08W.mjs +67 -0
  28. package/dist/cf-build-output-DA6uJomQ.mjs +1 -0
  29. package/dist/cf-build-output-DNQTwMNU.mjs +438 -0
  30. package/dist/cf-command-values-2kOtxMo1.mjs +26 -0
  31. package/dist/cf-config-migrate-COOCi4Ge.mjs +330 -0
  32. package/dist/cf-worker-settings-CIh4t_yG.mjs +41 -0
  33. package/dist/cli/cli.d.mts +1 -0
  34. package/dist/cli/cli.mjs +88 -0
  35. package/dist/cli/cloudflare-operation-process.d.mts +1 -0
  36. package/dist/cli/cloudflare-operation-process.mjs +1284 -0
  37. package/dist/cli/env-schema-probe.d.mts +43 -0
  38. package/dist/cli/env-schema-probe.mjs +165 -0
  39. package/dist/cli-main-HeXRQml6.mjs +1846 -0
  40. package/dist/client-D3D5RM5h.mjs +940 -0
  41. package/dist/client-VF2Nzc7Z.mjs +1 -0
  42. package/dist/cloudflare-auth-jb-1e43r.mjs +152 -0
  43. package/dist/cloudflare-cmd-B62t8Fm-.mjs +59 -0
  44. package/dist/cloudflare-config-i8yanry0.mjs +186 -0
  45. package/dist/cloudflare-connect-x7IsYghw.mjs +55 -0
  46. package/dist/cloudflare-operations-BeK7bhnP.mjs +627 -0
  47. package/dist/cloudflare-operations-C3Uu0Emj.mjs +1 -0
  48. package/dist/cloudflare-process-Cc6oiJqk.mjs +309 -0
  49. package/dist/cloudflare-user-output-CqONaAbP.mjs +19 -0
  50. package/dist/collect-8i0wU63d.mjs +1 -0
  51. package/dist/collect-C6Blu9yw.mjs +48 -0
  52. package/dist/config-CN_RFRkS.mjs +86 -0
  53. package/dist/config-D5G-Tx6o.mjs +1 -0
  54. package/dist/config-DOaFIK3w.mjs +88 -0
  55. package/dist/config-entry.d.mts +202 -0
  56. package/dist/config-entry.mjs +6 -0
  57. package/dist/config-tNx0HlFv.mjs +516 -0
  58. package/dist/connect-hLPNppu3.mjs +84 -0
  59. package/dist/create-project-B35ux-LA.mjs +126 -0
  60. package/dist/create-project-tJ1KwNss.mjs +1 -0
  61. package/dist/database-provider-DkZo4VwN.mjs +5 -0
  62. package/dist/database-provider.d.mts +25 -0
  63. package/dist/database-provider.mjs +1 -0
  64. package/dist/db-BH_md90k.mjs +1735 -0
  65. package/dist/delete-BSKI7V23.mjs +65 -0
  66. package/dist/deploy-C8KHBNsh.mjs +6512 -0
  67. package/dist/deploy-DCZBr7Ey.mjs +2 -0
  68. package/dist/deploy.d.mts +31 -0
  69. package/dist/deploy.mjs +118 -0
  70. package/dist/dev-inbox-I0nqTCdf.mjs +216 -0
  71. package/dist/discover-DJPmQcL5.mjs +36 -0
  72. package/dist/discover-EVuydEoM.mjs +1 -0
  73. package/dist/dist-B6eN80gc.mjs +1612 -0
  74. package/dist/dist-Cp4b1_T9.mjs +1 -0
  75. package/dist/dist-DMYe8CZJ.mjs +48 -0
  76. package/dist/dist-STQXl8ck.mjs +1878 -0
  77. package/dist/domain-C4ZhEiFG.mjs +149 -0
  78. package/dist/dotenv-4NdUCXbB.mjs +156 -0
  79. package/dist/drizzle-DqVFXtlc.mjs +306 -0
  80. package/dist/drizzle-Ds5P0n-S.mjs +1 -0
  81. package/dist/edge.d.mts +2 -0
  82. package/dist/edge.mjs +1 -0
  83. package/dist/email-B3TWga7x.mjs +742 -0
  84. package/dist/email-C_ATvNIG.mjs +2865 -0
  85. package/dist/email-cloudflare-DuAc9zny.mjs +854 -0
  86. package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
  87. package/dist/env-CTAo8ifZ.mjs +73 -0
  88. package/dist/env-DUyTzroe.mjs +88 -0
  89. package/dist/env-Dl4Wggec.mjs +71 -0
  90. package/dist/env-helpers-BX0APszT.mjs +135 -0
  91. package/dist/env-helpers-U56xuFgL.d.mts +20 -0
  92. package/dist/env-mask-BsHxq3R8.mjs +46 -0
  93. package/dist/env-public-Cw_xPi1D.d.mts +119 -0
  94. package/dist/env-raw-Bo6TtrHU.mjs +41 -0
  95. package/dist/env-types-Bg-dTh8u.mjs +56 -0
  96. package/dist/env-validation-BufZConV.mjs +488 -0
  97. package/dist/env-validation-DPqDo4DU.mjs +1 -0
  98. package/dist/fetch-CBgyyhzm.d.mts +87 -0
  99. package/dist/fetch-error-DmlRM6e4.mjs +264 -0
  100. package/dist/fetch-stream-2GUN3YN1.mjs +102 -0
  101. package/dist/fetch-stream-bUXynOyZ.d.mts +32 -0
  102. package/dist/fetch-tpPiSK10.mjs +25 -0
  103. package/dist/gen-dc13IRXh.mjs +509 -0
  104. package/dist/gen-kQqhFyOP.mjs +1 -0
  105. package/dist/generate-BgtlYpKg.mjs +1 -0
  106. package/dist/generate-Da9mWKzU.mjs +80 -0
  107. package/dist/generated-wrangler-config-CoDaaFsA.mjs +17 -0
  108. package/dist/git-metadata-Cukp5kV5.mjs +82 -0
  109. package/dist/github-cmd-DT5Onu6E.mjs +690 -0
  110. package/dist/handler-CJ7DiiRF.mjs +161 -0
  111. package/dist/handler-CVsIfRv7.d.mts +279 -0
  112. package/dist/help-Bpv6Qeqn.mjs +1946 -0
  113. package/dist/help-CfZ4Bsw5.mjs +1 -0
  114. package/dist/inbound-CqubE-9T.d.mts +311 -0
  115. package/dist/inbound-lHugZPuK.mjs +509 -0
  116. package/dist/index.d.mts +64 -0
  117. package/dist/index.mjs +4163 -0
  118. package/dist/info-CLQoCenb.mjs +109 -0
  119. package/dist/init-DRUR0j8C.mjs +2486 -0
  120. package/dist/limits-CMmYT2l8.d.mts +16 -0
  121. package/dist/limits-D27Lp6FP.mjs +46 -0
  122. package/dist/link-DinwJnon.mjs +52 -0
  123. package/dist/list-B84t4BhW.mjs +130 -0
  124. package/dist/live-Dui0-aj_.d.mts +105 -0
  125. package/dist/live-saC8barp.mjs +410 -0
  126. package/dist/load-user-env-g0ahkZcj.mjs +34 -0
  127. package/dist/local-d1-C3EeOV7-.mjs +103 -0
  128. package/dist/log-JDnPc0cF.mjs +23 -0
  129. package/dist/login-Bl5lH8nH.mjs +87 -0
  130. package/dist/login-DoI7AsbY.mjs +1 -0
  131. package/dist/logs-CaT2N2f7.mjs +129 -0
  132. package/dist/migrate-CbGscX-V.mjs +125 -0
  133. package/dist/migrate-Ce3JKLVs.mjs +1 -0
  134. package/dist/migration-handler-22qiuWPq.mjs +469 -0
  135. package/dist/migration-handler-Bb2BJh6g.d.mts +38 -0
  136. package/dist/mime-BMUN_QKG.mjs +1004 -0
  137. package/dist/mysql-migration-sql-CNuBSqdx.mjs +239 -0
  138. package/dist/neon-CJzQSycr.mjs +52 -0
  139. package/dist/node-tfv-3v0V.mjs +64 -0
  140. package/dist/operator-ai-logging-Ay7M4KWw.mjs +121 -0
  141. package/dist/operator-args-BFg32YyY.mjs +722 -0
  142. package/dist/operator-auth-DdYZYEkO.mjs +47 -0
  143. package/dist/operator-client-DBujdELO.mjs +82 -0
  144. package/dist/operator-cmd-C73WWJBl.mjs +443 -0
  145. package/dist/operator-cmd-CdZytuAF.mjs +1 -0
  146. package/dist/output-Bb34lF0w.mjs +173 -0
  147. package/dist/output-CVolXKC1.mjs +1 -0
  148. package/dist/package-DO4d3Qz5.mjs +1444 -0
  149. package/dist/package-json-DvS6IFRv.mjs +43 -0
  150. package/dist/pg-DoyPxa_X.mjs +15 -0
  151. package/dist/picocolors-D1NxSLw-.mjs +71 -0
  152. package/dist/plan-BHNt1QhK.mjs +1 -0
  153. package/dist/plan-DX4_-OM5.mjs +58 -0
  154. package/dist/platform-args-NI_vfWvD.mjs +538 -0
  155. package/dist/platform-args-ZC1-A1N9.mjs +1 -0
  156. package/dist/platform-auth-config-d-lY5-aY.mjs +371 -0
  157. package/dist/platform-auth-protection-Dhw7lUCk.mjs +231 -0
  158. package/dist/platform-auth-recovery-DaCc0tlx.mjs +309 -0
  159. package/dist/platform-cmd-5Ry-C9im.mjs +193 -0
  160. package/dist/platform-cmd-5oZq91lI.mjs +1 -0
  161. package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
  162. package/dist/platform-domain-DLVdGvGG.mjs +256 -0
  163. package/dist/platform-lifecycle-CUgjipXO.mjs +1 -0
  164. package/dist/platform-lifecycle-fRt5VMls.mjs +8928 -0
  165. package/dist/platform-management-5hEsRfR2.mjs +1 -0
  166. package/dist/platform-management-Djh1hzLP.mjs +1607 -0
  167. package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
  168. package/dist/platform-recovery-Cghx7FCR.mjs +96 -0
  169. package/dist/platform-registry-x1m9HBxf.mjs +450 -0
  170. package/dist/platform-runtime-logs-kkoiYFpF.mjs +72 -0
  171. package/dist/platform-setup-SfwCwnZg.mjs +306 -0
  172. package/dist/prepare-B9mB47T5.mjs +84 -0
  173. package/dist/prepare-DNIq07so.mjs +13 -0
  174. package/dist/prepare-LHkyJqxi.mjs +1 -0
  175. package/dist/project-CC7eN00D.mjs +141 -0
  176. package/dist/project-DcSd4BeI.mjs +1 -0
  177. package/dist/project-cmd-DTF19-fC.mjs +109 -0
  178. package/dist/project-paths-iXHKRTTQ.mjs +159 -0
  179. package/dist/project-slug-BUy0lmyR.mjs +1 -0
  180. package/dist/project-slug-CO6ci9XG.mjs +7 -0
  181. package/dist/project-team-CvdLhDF2.mjs +129 -0
  182. package/dist/project-token-CwZdUEGu.mjs +70 -0
  183. package/dist/project-tsconfig-P9X952KG.mjs +98 -0
  184. package/dist/project-zero-trust-CKDoPdN1.mjs +64 -0
  185. package/dist/providers-Cd3c7wi0.mjs +64 -0
  186. package/dist/providers-Df69hb_X.d.mts +5 -0
  187. package/dist/provision-DGlFJ3T9.mjs +1 -0
  188. package/dist/provision-mYVLuQiy.mjs +1814 -0
  189. package/dist/queues-Bc3FsBQT.d.mts +5 -0
  190. package/dist/r2-conditions-DSLmkiR5.mjs +60 -0
  191. package/dist/requests-DNhfyF3l.mjs +52 -0
  192. package/dist/resolve-project-BCsAMDRA.mjs +47 -0
  193. package/dist/resolve-project-DhU9_lIo.mjs +1 -0
  194. package/dist/resource-name-DlJ9QXzg.mjs +10 -0
  195. package/dist/response-HmNjB30w.mjs +29 -0
  196. package/dist/rollback-BvCHol52.mjs +150 -0
  197. package/dist/rolldown-runtime-uD8oG6U2.mjs +24 -0
  198. package/dist/route-types-CRWhr93D.mjs +592 -0
  199. package/dist/route-url-BIDZT78M.mjs +58 -0
  200. package/dist/route-url-Bla3Upsy.d.mts +42 -0
  201. package/dist/routes-stub.d.mts +24 -0
  202. package/dist/routes-stub.mjs +1 -0
  203. package/dist/routing-assets-CSheDWWM.mjs +54 -0
  204. package/dist/rpc-DcByS_q0.d.mts +39 -0
  205. package/dist/rpc-DtxIN9Tv.mjs +19 -0
  206. package/dist/runner-CPerdjIl.mjs +163 -0
  207. package/dist/runner-CUNtS5x7.mjs +1 -0
  208. package/dist/runner-mysql-7aA5hGoM.mjs +145 -0
  209. package/dist/runner-mysql-DrMKw203.mjs +1 -0
  210. package/dist/runner-pg-2pjltt0t.mjs +1 -0
  211. package/dist/runner-pg-mYc75KfH.mjs +61 -0
  212. package/dist/runtime/ai.d.mts +50 -0
  213. package/dist/runtime/ai.mjs +455 -0
  214. package/dist/runtime/auth-client-react.d.mts +2 -0
  215. package/dist/runtime/auth-client-react.mjs +1 -0
  216. package/dist/runtime/auth-client.d.mts +2 -0
  217. package/dist/runtime/auth-client.mjs +1 -0
  218. package/dist/runtime/auth.d.mts +2 -0
  219. package/dist/runtime/auth.mjs +1 -0
  220. package/dist/runtime/better-auth-mysql.d.mts +5 -0
  221. package/dist/runtime/better-auth-mysql.mjs +21 -0
  222. package/dist/runtime/better-auth-pg.d.mts +5 -0
  223. package/dist/runtime/better-auth-pg.mjs +21 -0
  224. package/dist/runtime/better-auth.d.mts +6 -0
  225. package/dist/runtime/better-auth.mjs +22 -0
  226. package/dist/runtime/client-react.d.mts +5 -0
  227. package/dist/runtime/client-react.mjs +5 -0
  228. package/dist/runtime/client.d.mts +5 -0
  229. package/dist/runtime/client.mjs +5 -0
  230. package/dist/runtime/db-mysql.d.mts +2 -0
  231. package/dist/runtime/db-mysql.mjs +1 -0
  232. package/dist/runtime/db-pg.d.mts +2 -0
  233. package/dist/runtime/db-pg.mjs +1 -0
  234. package/dist/runtime/db.d.mts +17 -0
  235. package/dist/runtime/db.mjs +36 -0
  236. package/dist/runtime/drizzle-arktype.d.mts +1 -0
  237. package/dist/runtime/drizzle-arktype.mjs +2 -0
  238. package/dist/runtime/drizzle-valibot.d.mts +1 -0
  239. package/dist/runtime/drizzle-valibot.mjs +2 -0
  240. package/dist/runtime/drizzle-zod.d.mts +1 -0
  241. package/dist/runtime/drizzle-zod.mjs +2 -0
  242. package/dist/runtime/durable.d.mts +64 -0
  243. package/dist/runtime/durable.mjs +165 -0
  244. package/dist/runtime/email/testing.d.mts +108 -0
  245. package/dist/runtime/email/testing.mjs +268 -0
  246. package/dist/runtime/email-protocol.d.mts +25 -0
  247. package/dist/runtime/email-protocol.mjs +1 -0
  248. package/dist/runtime/email.d.mts +26 -0
  249. package/dist/runtime/email.mjs +524 -0
  250. package/dist/runtime/env-public-client.d.mts +19 -0
  251. package/dist/runtime/env-public-client.mjs +55 -0
  252. package/dist/runtime/env-public.d.mts +4 -0
  253. package/dist/runtime/env-public.mjs +277 -0
  254. package/dist/runtime/env.d.mts +12 -0
  255. package/dist/runtime/env.mjs +1 -0
  256. package/dist/runtime/fetch-server.d.mts +6 -0
  257. package/dist/runtime/fetch-server.mjs +29 -0
  258. package/dist/runtime/fetch-stream.d.mts +3 -0
  259. package/dist/runtime/fetch-stream.mjs +3 -0
  260. package/dist/runtime/fetch.d.mts +2 -0
  261. package/dist/runtime/fetch.mjs +3 -0
  262. package/dist/runtime/handler.d.mts +3 -0
  263. package/dist/runtime/handler.mjs +1 -0
  264. package/dist/runtime/kv.d.mts +45 -0
  265. package/dist/runtime/kv.mjs +103 -0
  266. package/dist/runtime/limits.d.mts +2 -0
  267. package/dist/runtime/limits.mjs +1 -0
  268. package/dist/runtime/live-client.d.mts +40 -0
  269. package/dist/runtime/live-client.mjs +282 -0
  270. package/dist/runtime/live-server.d.mts +11 -0
  271. package/dist/runtime/live-server.mjs +419 -0
  272. package/dist/runtime/live.d.mts +3 -0
  273. package/dist/runtime/live.mjs +1 -0
  274. package/dist/runtime/log.d.mts +24 -0
  275. package/dist/runtime/log.mjs +57 -0
  276. package/dist/runtime/migration-handler-mysql.d.mts +2 -0
  277. package/dist/runtime/migration-handler-mysql.mjs +111 -0
  278. package/dist/runtime/migration-handler-pg.d.mts +2 -0
  279. package/dist/runtime/migration-handler-pg.mjs +94 -0
  280. package/dist/runtime/migration-handler.d.mts +2 -0
  281. package/dist/runtime/migration-handler.mjs +1 -0
  282. package/dist/runtime/procedure.d.mts +27 -0
  283. package/dist/runtime/procedure.mjs +36 -0
  284. package/dist/runtime/procedures.d.mts +24 -0
  285. package/dist/runtime/procedures.mjs +56 -0
  286. package/dist/runtime/queues.d.mts +2 -0
  287. package/dist/runtime/queues.mjs +8 -0
  288. package/dist/runtime/remote/binding-handler.d.mts +11 -0
  289. package/dist/runtime/remote/binding-handler.mjs +227 -0
  290. package/dist/runtime/remote/index.d.mts +12 -0
  291. package/dist/runtime/remote/index.mjs +467 -0
  292. package/dist/runtime/response.d.mts +11 -0
  293. package/dist/runtime/response.mjs +1 -0
  294. package/dist/runtime/route-url.d.mts +2 -0
  295. package/dist/runtime/route-url.mjs +1 -0
  296. package/dist/runtime/routing.d.mts +53 -0
  297. package/dist/runtime/routing.mjs +425 -0
  298. package/dist/runtime/rpc-react.d.mts +16 -0
  299. package/dist/runtime/rpc-react.mjs +50 -0
  300. package/dist/runtime/rpc.d.mts +2 -0
  301. package/dist/runtime/rpc.mjs +1 -0
  302. package/dist/runtime/sandbox-container.d.mts +3 -0
  303. package/dist/runtime/sandbox-container.mjs +1 -0
  304. package/dist/runtime/sandbox.d.mts +5 -0
  305. package/dist/runtime/sandbox.mjs +196 -0
  306. package/dist/runtime/schema-d1.d.mts +1 -0
  307. package/dist/runtime/schema-d1.mjs +2 -0
  308. package/dist/runtime/schema-mysql.d.mts +1 -0
  309. package/dist/runtime/schema-mysql.mjs +2 -0
  310. package/dist/runtime/schema-pg.d.mts +1 -0
  311. package/dist/runtime/schema-pg.mjs +2 -0
  312. package/dist/runtime/seed.d.mts +34 -0
  313. package/dist/runtime/seed.mjs +5 -0
  314. package/dist/runtime/sse-client.d.mts +31 -0
  315. package/dist/runtime/sse-client.mjs +42 -0
  316. package/dist/runtime/sse.d.mts +32 -0
  317. package/dist/runtime/sse.mjs +1 -0
  318. package/dist/runtime/storage.d.mts +4 -0
  319. package/dist/runtime/storage.mjs +13 -0
  320. package/dist/runtime/validator.d.mts +2 -0
  321. package/dist/runtime/validator.mjs +1 -0
  322. package/dist/runtime/ws-server.d.mts +26 -0
  323. package/dist/runtime/ws-server.mjs +297 -0
  324. package/dist/runtime/ws.d.mts +2 -0
  325. package/dist/runtime/ws.mjs +108 -0
  326. package/dist/sandbox-CWDjoEG2.d.mts +50 -0
  327. package/dist/sandbox-container-BqamdFCx.d.mts +73 -0
  328. package/dist/sandbox-container-d1AHLpgn.mjs +291 -0
  329. package/dist/secret-DCF9RXTc.mjs +146 -0
  330. package/dist/skills-Dr3AjuBF.mjs +63 -0
  331. package/dist/sqlite-validation-CLJXXN93.mjs +24 -0
  332. package/dist/sse-CxR30yMF.mjs +174 -0
  333. package/dist/standard-schema-CuDawHOC.d.mts +40 -0
  334. package/dist/static-asset-marker-mWMX2dLa.mjs +38 -0
  335. package/dist/subcommand-prompt-B9yUo--u.mjs +370 -0
  336. package/dist/terminal-log-text-DNsWJREL.mjs +31 -0
  337. package/dist/types-D7-4tBu7.d.mts +1 -0
  338. package/dist/untrusted-env-lL7RkYiC.mjs +50 -0
  339. package/dist/validate-B-zsjhiz.mjs +162 -0
  340. package/dist/validate-DbqGdPPY.mjs +1 -0
  341. package/dist/validator-8-NZs2Xr.mjs +168 -0
  342. package/dist/version-metadata-DsSoNsKJ.mjs +23 -0
  343. package/dist/wrangler-DU784Dkf.mjs +1452 -0
  344. package/dist/wrangler-Rr9_76DQ.mjs +1 -0
  345. package/dist/ws-Q_osq9VK.d.mts +137 -0
  346. package/dist/yarn-pnp-DgWbE7z5.mjs +91 -0
  347. package/docs/guide/ai.md +273 -0
  348. package/docs/guide/app-types.md +101 -0
  349. package/docs/guide/auth.md +255 -0
  350. package/docs/guide/database/d1.md +86 -0
  351. package/docs/guide/database/mysql.md +72 -0
  352. package/docs/guide/database/postgresql.md +94 -0
  353. package/docs/guide/database.md +454 -0
  354. package/docs/guide/deployment.md +124 -0
  355. package/docs/guide/durable-state.md +192 -0
  356. package/docs/guide/edge/headers.md +47 -0
  357. package/docs/guide/edge/redirects.md +85 -0
  358. package/docs/guide/edge/rewrites.md +119 -0
  359. package/docs/guide/edge/static-assets.md +94 -0
  360. package/docs/guide/email/domains.md +119 -0
  361. package/docs/guide/email/receiving.md +142 -0
  362. package/docs/guide/email/sending.md +262 -0
  363. package/docs/guide/email.md +23 -0
  364. package/docs/guide/env-vars.md +115 -0
  365. package/docs/guide/index.md +37 -0
  366. package/docs/guide/jobs.md +80 -0
  367. package/docs/guide/kv.md +100 -0
  368. package/docs/guide/live.md +181 -0
  369. package/docs/guide/platform/administration/access.md +165 -0
  370. package/docs/guide/platform/administration/connected-apps.md +84 -0
  371. package/docs/guide/platform/administration/email.md +169 -0
  372. package/docs/guide/platform/administration/operations.md +100 -0
  373. package/docs/guide/platform/administration/plans.md +156 -0
  374. package/docs/guide/platform/administration/projects.md +74 -0
  375. package/docs/guide/platform/administration/zero-trust.md +205 -0
  376. package/docs/guide/platform/development/local.md +122 -0
  377. package/docs/guide/platform/development/runtime.md +115 -0
  378. package/docs/guide/platform/development/schema-ci.md +44 -0
  379. package/docs/guide/platform/installation/ci.md +62 -0
  380. package/docs/guide/platform/installation/credentials.md +140 -0
  381. package/docs/guide/platform/installation/domains.md +120 -0
  382. package/docs/guide/platform/installation/first-deployment.md +95 -0
  383. package/docs/guide/platform/installation/maintenance.md +250 -0
  384. package/docs/guide/platform/installation/prerequisites.md +176 -0
  385. package/docs/guide/platform/installation/setup.md +300 -0
  386. package/docs/guide/platform/installation/uninstall.md +110 -0
  387. package/docs/guide/platform-administration.md +19 -0
  388. package/docs/guide/platform-development.md +16 -0
  389. package/docs/guide/procedures.md +48 -0
  390. package/docs/guide/project-collaboration.md +99 -0
  391. package/docs/guide/queues.md +149 -0
  392. package/docs/guide/quickstart.md +129 -0
  393. package/docs/guide/remote-dev.md +67 -0
  394. package/docs/guide/sandboxes.md +134 -0
  395. package/docs/guide/self-hosted-platform.md +45 -0
  396. package/docs/guide/server-routing.md +283 -0
  397. package/docs/guide/sse.md +174 -0
  398. package/docs/guide/storage.md +82 -0
  399. package/docs/guide/testing.md +64 -0
  400. package/docs/guide/type-safety.md +270 -0
  401. package/docs/guide/typed-fetch.md +98 -0
  402. package/docs/guide/websockets.md +230 -0
  403. package/docs/index.md +102 -0
  404. package/docs/integrations/agents.md +38 -0
  405. package/docs/integrations/cloudflare.md +241 -0
  406. package/docs/integrations/hono.md +127 -0
  407. package/docs/reference/api/auth.md +195 -0
  408. package/docs/reference/api/client.md +90 -0
  409. package/docs/reference/api/database.md +118 -0
  410. package/docs/reference/api/deploy.md +63 -0
  411. package/docs/reference/api/durable.md +47 -0
  412. package/docs/reference/api/env.md +51 -0
  413. package/docs/reference/api/handlers.md +189 -0
  414. package/docs/reference/api/plugin.md +40 -0
  415. package/docs/reference/api/resources.md +116 -0
  416. package/docs/reference/api/rewrites.md +111 -0
  417. package/docs/reference/api/types.md +126 -0
  418. package/docs/reference/api.md +71 -0
  419. package/docs/reference/cli/auth.md +87 -0
  420. package/docs/reference/cli/database.md +159 -0
  421. package/docs/reference/cli/deploy.md +117 -0
  422. package/docs/reference/cli/domains.md +42 -0
  423. package/docs/reference/cli/email.md +145 -0
  424. package/docs/reference/cli/generate.md +113 -0
  425. package/docs/reference/cli/github.md +181 -0
  426. package/docs/reference/cli/platform-config.md +93 -0
  427. package/docs/reference/cli/platform-email.md +81 -0
  428. package/docs/reference/cli/platform-installation.md +166 -0
  429. package/docs/reference/cli/platform-operations.md +90 -0
  430. package/docs/reference/cli/platform-users.md +159 -0
  431. package/docs/reference/cli/platform-zero-trust.md +60 -0
  432. package/docs/reference/cli/platform.md +78 -0
  433. package/docs/reference/cli/project.md +208 -0
  434. package/docs/reference/cli/secrets.md +79 -0
  435. package/docs/reference/cli/setup.md +88 -0
  436. package/docs/reference/cli.md +115 -0
  437. package/docs/reference/config.md +478 -0
  438. package/docs/reference/resource-inference.md +72 -0
  439. package/docs/reference/structure.md +138 -0
  440. package/package.json +389 -3
  441. package/sandbox.Dockerfile +4 -0
  442. package/schema.json +353 -0
  443. package/skills/bwf/SKILL.md +100 -0
  444. package/skills/migrate-vite-cloudflare-to-bwf/SKILL.md +53 -0
  445. package/templates/assets/bwf.svg +5 -0
  446. package/templates/assets/icons.svg +49 -0
  447. package/templates/assets/react.svg +1 -0
  448. package/templates/assets/stack.svg +35 -0
@@ -0,0 +1,1452 @@
1
+ import { a as join, c as resolve, n as dirname, o as normalize, t as basename } from "./dist-DMYe8CZJ.mjs";
2
+ import { a as persistCloudflareConfig, i as materializeCloudflareConfig, r as ignoreMaterializedCloudflareConfig } from "./cloudflare-config-i8yanry0.mjs";
3
+ import { a as TYPED_CONFIG_FILE, s as loadTypedBwfConfigFile } from "./project-paths-iXHKRTTQ.mjs";
4
+ import { f as readConfig, m as validateConfig } from "./config-tNx0HlFv.mjs";
5
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { parseSync } from "vite";
7
+ import { appendSqliteClassMigration, isRecord } from "@builtbyfriends/deploy-core";
8
+ import { createHash } from "node:crypto";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { SyntaxKind, applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree } from "jsonc-parser";
11
+ // src/config-write.ts
12
+ const GENERATED_MARKERS = [
13
+ "// Generated by bwf migrate.",
14
+ "// Generated from bwf.json by void migrate.",
15
+ "// Generated by bwf init."
16
+ ];
17
+ function renderBwfConfig(config, marker = GENERATED_MARKERS[0]) {
18
+ return `${marker}\nimport { defineConfig } from '@builtbyfriends/bwf/config';\n\nexport default defineConfig(${JSON.stringify(config, null, 2)});\n`;
19
+ }
20
+ function isStaticValue(node) {
21
+ if (!node) return false;
22
+ if (node.type === "Literal") return node.value === null || [
23
+ "string",
24
+ "number",
25
+ "boolean"
26
+ ].includes(typeof node.value);
27
+ if (node.type === "UnaryExpression") return node.operator === "-" && node.argument?.type === "Literal" && typeof node.argument.value === "number";
28
+ if (node.type === "ArrayExpression") return node.elements?.every(isStaticValue) ?? false;
29
+ if (node.type !== "ObjectExpression") return false;
30
+ return node.properties?.every((property) => property.type === "Property" && property.kind === "init" && !property.computed && !property.method && (property.key?.type === "Identifier" || property.key?.type === "Literal") && isStaticValue(property.value)) ?? false;
31
+ }
32
+ function isGeneratedStaticConfig(source) {
33
+ if (!GENERATED_MARKERS.some((marker) => source.startsWith(marker))) return false;
34
+ let program;
35
+ try {
36
+ const parsed = parseSync(TYPED_CONFIG_FILE, source, {
37
+ lang: "js",
38
+ sourceType: "module",
39
+ preserveParens: false,
40
+ showSemanticErrors: true
41
+ });
42
+ if (parsed.errors.length > 0 || parsed.comments.length !== 1 || !GENERATED_MARKERS.includes(`// ${parsed.comments[0]?.value.trim()}`)) return false;
43
+ program = parsed.program;
44
+ } catch {
45
+ return false;
46
+ }
47
+ const [importDeclaration, exportDeclaration] = program.body ?? [];
48
+ const call = exportDeclaration?.declaration;
49
+ return program.body?.length === 2 && importDeclaration?.type === "ImportDeclaration" && importDeclaration.source?.value === "@builtbyfriends/bwf/config" && importDeclaration.specifiers?.length === 1 && importDeclaration.specifiers[0]?.imported?.name === "defineConfig" && importDeclaration.specifiers[0]?.local?.name === "defineConfig" && exportDeclaration?.type === "ExportDefaultDeclaration" && call?.type === "CallExpression" && call.callee?.name === "defineConfig" && call.arguments?.length === 1 && isStaticValue(call.arguments[0]);
50
+ }
51
+ function canRewriteBwfProjectConfig(root) {
52
+ const path = join(root, TYPED_CONFIG_FILE);
53
+ return !existsSync(path) || isGeneratedStaticConfig(readFileSync(path, "utf8"));
54
+ }
55
+ /** Update CLI-owned static config without silently rewriting authored TypeScript. */
56
+ function writeBwfProjectConfig(root, config) {
57
+ validateConfig(config, TYPED_CONFIG_FILE);
58
+ const path = join(root, TYPED_CONFIG_FILE);
59
+ if (existsSync(path)) {
60
+ if (!isGeneratedStaticConfig(readFileSync(path, "utf8"))) throw new Error(`config: ${TYPED_CONFIG_FILE} contains authored TypeScript or comments. Update it directly and rerun the command.`);
61
+ validateConfig(loadTypedBwfConfigFile(path), TYPED_CONFIG_FILE);
62
+ }
63
+ writeFileSync(path, renderBwfConfig(config, "// Generated by bwf init."));
64
+ }
65
+ // src/cli/wrangler.ts
66
+ const COMPAT_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
67
+ /** UTF-8 byte-order mark. Node's utf-8 read preserves a leading one. */
68
+ const UTF8_BOM = "";
69
+ const NODEJS_ALS_FLAG = "nodejs_als";
70
+ const NODEJS_COMPAT_FLAG = "nodejs_compat";
71
+ const BWF_CONFIG_FILE = "bwf.json";
72
+ function projectWranglerPaths(root) {
73
+ if (existsSync(join(root, "bwf.config.ts"))) return [materializeCloudflareConfig(root)];
74
+ return ["wrangler.jsonc", "wrangler.json"].map((name) => join(root, name));
75
+ }
76
+ /** Record a change to the generated Cloudflare config in `bwf.lock.json`. */
77
+ function persistMaterializedWranglerConfig(configPath) {
78
+ if (basename(configPath) === ".bwf-wrangler.jsonc") persistCloudflareConfig(dirname(configPath));
79
+ }
80
+ function writeProjectWranglerFile(configPath, text) {
81
+ writeFileSync(configPath, text);
82
+ persistMaterializedWranglerConfig(configPath);
83
+ }
84
+ /**
85
+ * Read the first existing project Wrangler config. A missing or unparseable one is
86
+ * replaced by the generated config, starting from an empty object.
87
+ */
88
+ function readOrCreateProjectWranglerConfig(root) {
89
+ const configPath = projectWranglerPaths(root).find((path) => existsSync(path));
90
+ if (configPath) {
91
+ let parsed;
92
+ try {
93
+ parsed = parseJsonc(readFileSync(configPath, "utf-8"));
94
+ } catch {}
95
+ if (parsed) return {
96
+ configPath,
97
+ parsed,
98
+ created: false
99
+ };
100
+ }
101
+ return {
102
+ configPath: materializeCloudflareConfig(root),
103
+ parsed: {},
104
+ created: true
105
+ };
106
+ }
107
+ function durableObjectBindingsOf(config) {
108
+ return config.durable_objects?.bindings ?? [];
109
+ }
110
+ const MANAGED_QUEUES_MARKER = /^\s*\/\/ nosam:managed-queues:v1:([A-Za-z0-9_-]+)\s*$/m;
111
+ const PUBLISHED_TRAFFIC_MARKER = /^\s*\/\/ nosam:published-traffic:v1:([A-Za-z0-9_-]+)\s*$/m;
112
+ const DEFAULT_LIVE_BINDING = "BWF_LIVE";
113
+ const DEFAULT_LIVE_CLASS = "NosamLiveStreamDurableObject";
114
+ const LIVE_MIGRATION_TAG = "live-v1";
115
+ /** Read the root Wrangler config with the same JSONC parser used by binding sync. */
116
+ function readRootWranglerConfig(root) {
117
+ for (const configPath of projectWranglerPaths(root)) {
118
+ if (!existsSync(configPath)) continue;
119
+ const parsed = parseJsonc(readFileSync(configPath, "utf-8"));
120
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new SyntaxError(`Failed to parse ${configPath}: expected a JSON object.`);
121
+ return {
122
+ configPath,
123
+ config: parsed
124
+ };
125
+ }
126
+ }
127
+ /** Read the last traffic attachment state bwf successfully published remotely. */
128
+ function readWranglerPublishedTrafficSnapshot(configPath) {
129
+ if (!existsSync(configPath)) return;
130
+ const encoded = PUBLISHED_TRAFFIC_MARKER.exec(readFileSync(configPath, "utf-8"))?.[1];
131
+ if (!encoded) return;
132
+ try {
133
+ const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
134
+ if (!isRecord(value) || typeof value.workers_dev !== "boolean" || typeof value.preview_urls !== "boolean" || !Array.isArray(value.routes)) return;
135
+ return {
136
+ workers_dev: value.workers_dev,
137
+ preview_urls: value.preview_urls,
138
+ routes: value.routes
139
+ };
140
+ } catch {
141
+ return;
142
+ }
143
+ }
144
+ /** Persist traffic attachment provenance without adding unsupported Wrangler fields. */
145
+ function writeWranglerPublishedTrafficSnapshot(configPath, snapshot, options) {
146
+ if (!existsSync(configPath)) return;
147
+ const raw = readFileSync(configPath, "utf-8");
148
+ const marker = `// nosam:published-traffic:v1:${Buffer.from(JSON.stringify(snapshot), "utf8").toString("base64url")}`;
149
+ const existing = PUBLISHED_TRAFFIC_MARKER.exec(raw);
150
+ if (!existing && options?.create === false) return;
151
+ const next = existing ? raw.slice(0, existing.index) + marker + raw.slice(existing.index + existing[0].length) : `${marker}${raw.includes("\r\n") ? "\r\n" : "\n"}${raw}`;
152
+ if (next !== raw) writeProjectWranglerFile(configPath, next);
153
+ }
154
+ /** Latest compatibility date the bwf test suite is pinned against. */
155
+ const LATEST_KNOWN_COMPAT_DATE = "2026-02-24";
156
+ function normalizeWranglerCompatibilityFlags(flags, options) {
157
+ const existingFlags = flags ?? [];
158
+ if (options?.needsNodejsCompat && !existingFlags.includes(NODEJS_COMPAT_FLAG)) return [...existingFlags.filter((flag) => flag !== NODEJS_ALS_FLAG), NODEJS_COMPAT_FLAG];
159
+ if (existingFlags.length === 0 || !existingFlags.includes(NODEJS_ALS_FLAG) && !existingFlags.includes(NODEJS_COMPAT_FLAG)) return [...existingFlags, NODEJS_ALS_FLAG];
160
+ return flags;
161
+ }
162
+ function hasDurableObjectSqliteMigration(migrations, className) {
163
+ return migrations.some((migration) => migration.new_sqlite_classes?.includes(className));
164
+ }
165
+ function nextDurableObjectMigrationTag(migrations, baseTag) {
166
+ const existingTags = new Set(migrations.map((migration) => migration.tag).filter(Boolean));
167
+ if (!existingTags.has(baseTag)) return baseTag;
168
+ let index = 2;
169
+ while (existingTags.has(`${baseTag}-${index}`)) index++;
170
+ return `${baseTag}-${index}`;
171
+ }
172
+ function resolveLiveBindingConfig(root, options) {
173
+ const durableObjectBindings = [...readWranglerDurableObjectBindings(root), ...options?.existingBindings ?? []];
174
+ const generated = findGeneratedLiveBinding(durableObjectBindings);
175
+ if (generated) return {
176
+ bindingName: generated.name,
177
+ className: generated.class_name
178
+ };
179
+ const usedBindings = /* @__PURE__ */ new Set([...durableObjectBindings.map((binding) => binding.name), ...(options?.reservedBindings ?? []).filter((name) => typeof name === "string")]);
180
+ const usedClasses = /* @__PURE__ */ new Set([...durableObjectBindings.map((binding) => binding.class_name), ...(options?.reservedClasses ?? []).filter((name) => typeof name === "string")]);
181
+ return {
182
+ bindingName: resolveGeneratedName(DEFAULT_LIVE_BINDING, usedBindings, "binding"),
183
+ className: resolveGeneratedName(DEFAULT_LIVE_CLASS, usedClasses, "class")
184
+ };
185
+ }
186
+ function readExistingLiveBindingConfig(root) {
187
+ const generated = findGeneratedLiveBinding(readWranglerDurableObjectBindings(root));
188
+ return generated ? {
189
+ bindingName: generated.name,
190
+ className: generated.class_name
191
+ } : void 0;
192
+ }
193
+ function readWranglerDurableObjectBindings(root) {
194
+ for (const path of projectWranglerPaths(root)) try {
195
+ const bindings = parseJsonc(readFileSync(path, "utf-8")).durable_objects?.bindings;
196
+ if (!Array.isArray(bindings)) return [];
197
+ return bindings.filter((binding) => typeof binding.name === "string" && typeof binding.class_name === "string");
198
+ } catch {}
199
+ return [];
200
+ }
201
+ function isGeneratedLiveName(name, base) {
202
+ return name === base || name.match(generatedLiveNamePattern(base)) !== null;
203
+ }
204
+ function generatedLiveNamePattern(base) {
205
+ return new RegExp(`^${escapeRegExp(base)}_[0-9a-f]{8}$`);
206
+ }
207
+ function escapeRegExp(value) {
208
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
209
+ }
210
+ function findGeneratedLiveBinding(bindings) {
211
+ return bindings.find((binding) => isGeneratedLiveName(binding.name, "BWF_LIVE") && isGeneratedLiveName(binding.class_name, "NosamLiveStreamDurableObject"));
212
+ }
213
+ function resolveGeneratedName(base, used, kind) {
214
+ if (!used.has(base)) return base;
215
+ for (let attempt = 0;; attempt++) {
216
+ const candidate = `${base}_${createHash("sha256").update(`@builtbyfriends/bwf/live:${kind}:${base}:${attempt}`).digest("hex").slice(0, 8)}`;
217
+ if (!used.has(candidate)) return candidate;
218
+ }
219
+ }
220
+ /**
221
+ * Read compatibility settings with priority: bwf config > project Wrangler config >
222
+ * `<buildOutputDir>/wrangler.json` > latest known-good date. Read-only; use
223
+ * `ensureWranglerCompat()` to pin the default date.
224
+ */
225
+ function readWranglerCompat(root, config, buildOutputDir) {
226
+ return resolveWranglerCompat(readWranglerCompatFields(root, config, buildOutputDir));
227
+ }
228
+ /**
229
+ * Like `readWranglerCompat()`, but pins the default date when no source sets one.
230
+ * With `rootWrangler`, a project with no config gets the date in a root wrangler.jsonc
231
+ * instead of a new bwf.config.ts, so a framework adapter that reads the root file by
232
+ * default still finds it.
233
+ */
234
+ function ensureWranglerCompat(root, config, buildOutputDir, options) {
235
+ const fields = readWranglerCompatFields(root, config, buildOutputDir);
236
+ const defaultDate = fields.bwfDate ?? fields.wranglerDate ?? fields.buildDate ? void 0 : ensureBwfCompatibilityDate(root, options?.rootWrangler === true);
237
+ return resolveWranglerCompat(fields, defaultDate ? { defaultDate } : void 0);
238
+ }
239
+ function readWranglerCompatFields(root, config, buildOutputDir) {
240
+ const bwfConfig = config ?? readBwfConfigIfExists(root);
241
+ let raw;
242
+ for (const path of projectWranglerPaths(root)) try {
243
+ raw = readFileSync(path, "utf-8");
244
+ break;
245
+ } catch {}
246
+ let wranglerDate;
247
+ let wranglerFlags;
248
+ if (raw) {
249
+ const parsed = parseJsonc(raw);
250
+ if (typeof parsed.compatibility_date === "string") {
251
+ validateCompatDate(parsed.compatibility_date, "wrangler config");
252
+ wranglerDate = parsed.compatibility_date;
253
+ }
254
+ if (Array.isArray(parsed.compatibility_flags) && parsed.compatibility_flags.every((f) => typeof f === "string")) wranglerFlags = parsed.compatibility_flags;
255
+ }
256
+ let buildDate;
257
+ let buildFlags;
258
+ if (buildOutputDir) try {
259
+ const buildRaw = readFileSync(join(buildOutputDir, "wrangler.json"), "utf-8");
260
+ const buildParsed = JSON.parse(buildRaw);
261
+ if (typeof buildParsed.compatibility_date === "string") {
262
+ validateCompatDate(buildParsed.compatibility_date, "build output wrangler.json");
263
+ buildDate = buildParsed.compatibility_date;
264
+ }
265
+ if (Array.isArray(buildParsed.compatibility_flags) && buildParsed.compatibility_flags.every((f) => typeof f === "string")) buildFlags = buildParsed.compatibility_flags;
266
+ } catch {}
267
+ return {
268
+ bwfDate: bwfConfig?.worker?.compatibility_date,
269
+ bwfFlags: bwfConfig?.worker?.compatibility_flags,
270
+ wranglerDate,
271
+ wranglerFlags,
272
+ buildDate,
273
+ buildFlags
274
+ };
275
+ }
276
+ function resolveWranglerCompat(fields, options) {
277
+ const result = { compatibilityDate: fields.bwfDate ?? fields.wranglerDate ?? fields.buildDate ?? options?.defaultDate ?? "2026-02-24" };
278
+ const flags = fields.bwfFlags ?? fields.wranglerFlags ?? fields.buildFlags;
279
+ if (flags && flags.length > 0) result.compatibilityFlags = flags;
280
+ return result;
281
+ }
282
+ function validateCompatDate(value, source) {
283
+ if (!COMPAT_DATE_RE.test(value)) throw new Error(`config: "compatibility_date" in ${source} must use YYYY-MM-DD format, got '${value}'.`);
284
+ }
285
+ function readBwfConfigIfExists(root) {
286
+ return existsSync(join(root, BWF_CONFIG_FILE)) || existsSync(join(root, "bwf.config.ts")) ? readConfig(root) : void 0;
287
+ }
288
+ function ensureBwfCompatibilityDate(root, rootWrangler) {
289
+ if (existsSync(join(root, "bwf.config.ts"))) {
290
+ writeProvisionedWranglerConfig(root, { compatibilityDate: LATEST_KNOWN_COMPAT_DATE });
291
+ return LATEST_KNOWN_COMPAT_DATE;
292
+ }
293
+ const filePath = join(root, BWF_CONFIG_FILE);
294
+ if (!existsSync(filePath)) {
295
+ if (existsSync(join(root, "wrangler.toml"))) writeFileSync(filePath, `${JSON.stringify({ worker: { compatibility_date: LATEST_KNOWN_COMPAT_DATE } }, null, 2)}\n`);
296
+ else if (rootWrangler || projectWranglerPaths(root).some((path) => existsSync(path))) writeProvisionedWranglerConfig(root, { compatibilityDate: LATEST_KNOWN_COMPAT_DATE });
297
+ else {
298
+ writeBwfProjectConfig(root, { worker: { compatibility_date: LATEST_KNOWN_COMPAT_DATE } });
299
+ ignoreMaterializedCloudflareConfig(root);
300
+ }
301
+ return LATEST_KNOWN_COMPAT_DATE;
302
+ }
303
+ let nextConfig;
304
+ try {
305
+ const parsed = JSON.parse(readFileSync(filePath, "utf-8"));
306
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`config: ${BWF_CONFIG_FILE} must be a JSON object.`);
307
+ nextConfig = parsed;
308
+ } catch (error) {
309
+ if (error instanceof SyntaxError) throw new Error(`config: Invalid JSON in ${BWF_CONFIG_FILE}.`);
310
+ throw error;
311
+ }
312
+ nextConfig.worker = {
313
+ ...nextConfig.worker ?? {},
314
+ compatibility_date: LATEST_KNOWN_COMPAT_DATE
315
+ };
316
+ writeFileSync(filePath, `${JSON.stringify(nextConfig, null, 2)}\n`);
317
+ return LATEST_KNOWN_COMPAT_DATE;
318
+ }
319
+ /**
320
+ * Add missing inferred bindings to the project Wrangler config for local dev; existing
321
+ * bindings are kept. Returns true if the file was written.
322
+ */
323
+ function syncWranglerBindings(root, bindings, options) {
324
+ const { configPath, parsed, created } = readOrCreateProjectWranglerConfig(root);
325
+ let modified = false;
326
+ const d1Name = options?.bindingNames?.d1 ?? "DB";
327
+ if (bindings.needsD1) {
328
+ const existing = parsed.d1_databases ?? [];
329
+ if (!existing.some((b) => b.binding === d1Name)) {
330
+ parsed.d1_databases = [...existing, {
331
+ binding: d1Name,
332
+ database_name: "default",
333
+ database_id: "local"
334
+ }];
335
+ modified = true;
336
+ }
337
+ }
338
+ const kvName = options?.bindingNames?.kv ?? "KV";
339
+ if (bindings.needsKV) {
340
+ const existing = parsed.kv_namespaces ?? [];
341
+ if (!existing.some((b) => b.binding === kvName)) {
342
+ parsed.kv_namespaces = [...existing, {
343
+ binding: kvName,
344
+ id: "local"
345
+ }];
346
+ modified = true;
347
+ }
348
+ }
349
+ const r2Name = options?.bindingNames?.r2 ?? "STORAGE";
350
+ if (bindings.needsR2) {
351
+ const existing = parsed.r2_buckets ?? [];
352
+ if (!existing.some((b) => b.binding === r2Name)) {
353
+ parsed.r2_buckets = [...existing, {
354
+ binding: r2Name,
355
+ bucket_name: "default"
356
+ }];
357
+ modified = true;
358
+ }
359
+ }
360
+ if (bindings.needsAI && options?.directCloudflareAi) {
361
+ const existing = parsed.ai;
362
+ const binding = typeof existing?.binding === "string" ? existing.binding : options.bindingNames?.ai ?? "AI";
363
+ const nextAi = {
364
+ ...existing ?? {},
365
+ binding,
366
+ remote: true
367
+ };
368
+ if (JSON.stringify(existing) !== JSON.stringify(nextAi)) {
369
+ parsed.ai = nextAi;
370
+ modified = true;
371
+ }
372
+ if (binding !== "AI" || options.directCloudflareAi.gateway) {
373
+ const vars = parsed.vars ?? {};
374
+ const nextVars = {
375
+ ...vars,
376
+ ...binding !== "AI" ? { __NOSAM_AI_BINDING: binding } : {},
377
+ ...options.directCloudflareAi.gateway ? { __NOSAM_AI_GATEWAY: options.directCloudflareAi.gateway } : {}
378
+ };
379
+ if (JSON.stringify(vars) !== JSON.stringify(nextVars)) {
380
+ parsed.vars = nextVars;
381
+ modified = true;
382
+ }
383
+ }
384
+ }
385
+ if (options?.websockets) {
386
+ const existing = durableObjectBindingsOf(parsed);
387
+ const migrations = Array.isArray(parsed.migrations) ? parsed.migrations : [];
388
+ for (const route of options.websockets) {
389
+ const conflict = existing.find((binding) => binding.name === route.bindingName && binding.class_name !== route.className);
390
+ if (conflict) throw new Error(`websocket: binding '${route.bindingName}' is already configured for class '${conflict.class_name}', but '${route.filePath}' requires '${route.className}'.`);
391
+ }
392
+ const additions = options.websockets.filter((route) => !existing.some((binding) => binding.name === route.bindingName)).map((route) => ({
393
+ name: route.bindingName,
394
+ class_name: route.className
395
+ }));
396
+ const nextBindings = [...existing, ...additions];
397
+ if (nextBindings.length !== existing.length || nextBindings.some((binding, index) => binding.name !== existing[index]?.name || binding.class_name !== existing[index]?.class_name)) {
398
+ parsed.durable_objects = {
399
+ ...parsed.durable_objects ?? {},
400
+ bindings: nextBindings
401
+ };
402
+ modified = true;
403
+ }
404
+ const planned = appendSqliteClassMigration(migrations, options.websockets.map((route) => route.className), "void-ws-v1", existing.map((binding) => binding.class_name));
405
+ if (planned.added) {
406
+ parsed.migrations = planned.migrations;
407
+ modified = true;
408
+ }
409
+ }
410
+ if (bindings.needsLive || options?.live) {
411
+ const existingDurableObjectBindings = durableObjectBindingsOf(parsed);
412
+ const liveConfig = typeof options?.live === "object" ? options.live : resolveLiveBindingConfig(root, {
413
+ existingBindings: existingDurableObjectBindings,
414
+ reservedBindings: options?.websockets?.map((route) => route.bindingName),
415
+ reservedClasses: options?.websockets?.map((route) => route.className)
416
+ });
417
+ if (!existingDurableObjectBindings.some((binding) => binding.name === liveConfig.bindingName)) {
418
+ parsed.durable_objects = { bindings: [...existingDurableObjectBindings, {
419
+ name: liveConfig.bindingName,
420
+ class_name: liveConfig.className
421
+ }] };
422
+ modified = true;
423
+ }
424
+ const migrations = Array.isArray(parsed.migrations) ? parsed.migrations : [];
425
+ if (!hasDurableObjectSqliteMigration(migrations, liveConfig.className)) {
426
+ parsed.migrations = [...migrations, {
427
+ tag: nextDurableObjectMigrationTag(migrations, LIVE_MIGRATION_TAG),
428
+ new_sqlite_classes: [liveConfig.className]
429
+ }];
430
+ modified = true;
431
+ }
432
+ }
433
+ if (created || modified) writeProjectWranglerFile(configPath, JSON.stringify(parsed, null, 2) + "\n");
434
+ return created || modified;
435
+ }
436
+ /** Persist convention-derived Durable Object bindings and append-only migration history. */
437
+ function syncWranglerDurableObjects(root, durableObjects) {
438
+ if (durableObjects.length === 0) return false;
439
+ const { configPath, parsed, created } = readOrCreateProjectWranglerConfig(root);
440
+ let modified = false;
441
+ const existingBindings = durableObjectBindingsOf(parsed);
442
+ for (const module of durableObjects) {
443
+ const conflict = existingBindings.find((binding) => binding.name === module.bindingName && binding.class_name !== module.className);
444
+ if (conflict) throw new Error(`durable: binding '${module.bindingName}' is already configured for class '${conflict.class_name}', but durable-objects/ requires '${module.className}'.`);
445
+ }
446
+ const additions = durableObjects.filter((module) => !existingBindings.some((binding) => binding.name === module.bindingName)).map((module) => ({
447
+ name: module.bindingName,
448
+ class_name: module.className
449
+ }));
450
+ if (additions.length > 0) {
451
+ parsed.durable_objects = { bindings: [...existingBindings, ...additions] };
452
+ modified = true;
453
+ }
454
+ const migrations = Array.isArray(parsed.migrations) ? parsed.migrations : [];
455
+ for (const module of durableObjects) {
456
+ if (migrations.find((migration) => migration.tag === module.migrationTag && !migration.new_sqlite_classes?.includes(module.className))) throw new Error(`durable: migration tag '${module.migrationTag}' is already used by another Durable Object migration.`);
457
+ if (!hasDurableObjectSqliteMigration(migrations, module.className)) {
458
+ migrations.push({
459
+ tag: module.migrationTag,
460
+ new_sqlite_classes: [module.className]
461
+ });
462
+ modified = true;
463
+ }
464
+ }
465
+ if (modified) parsed.migrations = migrations;
466
+ if (created || modified) writeProjectWranglerFile(configPath, JSON.stringify(parsed, null, 2) + "\n");
467
+ return created || modified;
468
+ }
469
+ /** Persist WebSocket Durable Object bindings and SQLite migration history. */
470
+ function syncWranglerWebSockets(root, websockets) {
471
+ if (websockets.length === 0 && !projectWranglerPaths(root).some((path) => existsSync(path))) return false;
472
+ return writeProvisionedWranglerConfig(root, { webSockets: websockets }).modified;
473
+ }
474
+ /**
475
+ * Registered WebSocket classes without a source route. They stay exported while their
476
+ * bindings remain; only classes created by bwf's WebSocket migration tag count.
477
+ */
478
+ function readWranglerWebSocketTombstones(root, websockets) {
479
+ const configPath = projectWranglerPaths(root).find((path) => existsSync(path));
480
+ if (!configPath) return [];
481
+ const parsed = parseJsonc(readFileSync(configPath, "utf-8"));
482
+ const migrations = Array.isArray(parsed.migrations) ? parsed.migrations : [];
483
+ const historicalClasses = new Set(migrations.flatMap((migration) => /^void-ws-v1(?:-\d+)?$/.test(migration.tag ?? "") ? [...migration.new_classes ?? [], ...migration.new_sqlite_classes ?? []] : []));
484
+ const currentClasses = new Set(websockets.map((route) => route.className));
485
+ const bindings = parsed.durable_objects?.bindings;
486
+ return [...new Set((Array.isArray(bindings) ? bindings : []).flatMap((binding) => typeof binding.class_name === "string" && historicalClasses.has(binding.class_name) && !currentClasses.has(binding.class_name) ? [binding.class_name] : []))].sort();
487
+ }
488
+ function readManagedQueueProvenance(text) {
489
+ const none = {
490
+ producerBindings: [],
491
+ consumerQueues: [],
492
+ pendingConsumerRemovals: []
493
+ };
494
+ const encoded = MANAGED_QUEUES_MARKER.exec(text)?.[1];
495
+ if (!encoded) return none;
496
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
497
+ try {
498
+ const parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
499
+ if (!isRecord(parsed)) return none;
500
+ return {
501
+ producerBindings: strings(parsed.producerBindings),
502
+ consumerQueues: strings(parsed.consumerQueues),
503
+ pendingConsumerRemovals: strings(parsed.pendingConsumerRemovals)
504
+ };
505
+ } catch {
506
+ return none;
507
+ }
508
+ }
509
+ function writeManagedQueueProvenance(text, provenance) {
510
+ const normalized = {
511
+ producerBindings: [...new Set(provenance.producerBindings)].sort(),
512
+ consumerQueues: [...new Set(provenance.consumerQueues)].sort(),
513
+ pendingConsumerRemovals: [...new Set(provenance.pendingConsumerRemovals)].sort()
514
+ };
515
+ const existing = MANAGED_QUEUES_MARKER.exec(text);
516
+ if (normalized.producerBindings.length === 0 && normalized.consumerQueues.length === 0 && normalized.pendingConsumerRemovals.length === 0) {
517
+ if (!existing) return text;
518
+ const start = existing.index;
519
+ const end = start + existing[0].length;
520
+ const trailingNewline = text.slice(end).match(/^(\r?\n)/)?.[1] ?? "";
521
+ return text.slice(0, start) + text.slice(end + trailingNewline.length);
522
+ }
523
+ const marker = `// nosam:managed-queues:v1:${Buffer.from(JSON.stringify(normalized), "utf8").toString("base64url")}`;
524
+ if (existing) return text.slice(0, existing.index) + marker + text.slice(existing.index + existing[0].length);
525
+ return `${marker}${text.includes("\r\n") ? "\r\n" : "\n"}${text}`;
526
+ }
527
+ /**
528
+ * Nosam-owned consumer queues that may need remote cleanup: current managed consumers (the
529
+ * caller subtracts desired ones) and pending removals, which survive failed deploys.
530
+ */
531
+ function readWranglerManagedQueueCleanupCandidates(configPath) {
532
+ if (!existsSync(configPath)) return [];
533
+ const raw = readFileSync(configPath, "utf-8");
534
+ const provenance = readManagedQueueProvenance(raw.startsWith(UTF8_BOM) ? raw.slice(1) : raw);
535
+ return [.../* @__PURE__ */ new Set([...provenance.consumerQueues, ...provenance.pendingConsumerRemovals])].sort();
536
+ }
537
+ /** Clear only cleanup tombstones confirmed by a successful trigger reconciliation. */
538
+ function acknowledgeWranglerManagedQueueRemovals(configPath, removedQueues) {
539
+ if (!existsSync(configPath) || removedQueues.length === 0) return;
540
+ const raw = readFileSync(configPath, "utf-8");
541
+ const hasBom = raw.startsWith(UTF8_BOM);
542
+ const text = hasBom ? raw.slice(1) : raw;
543
+ const provenance = readManagedQueueProvenance(text);
544
+ const removed = new Set(removedQueues);
545
+ const updated = writeManagedQueueProvenance(text, {
546
+ ...provenance,
547
+ pendingConsumerRemovals: provenance.pendingConsumerRemovals.filter((queue) => !removed.has(queue))
548
+ });
549
+ const finalText = hasBom ? `${UTF8_BOM}${updated}` : updated;
550
+ if (finalText !== raw) writeProjectWranglerFile(configPath, finalText);
551
+ }
552
+ /**
553
+ * Apply a {@link ProvisionedWranglerPatch} to the root Wrangler config. Edits keep comments
554
+ * and unrelated content, and a second run produces the same bytes.
555
+ */
556
+ function writeProvisionedWranglerConfig(root, patch, options) {
557
+ const configPath = options?.configPath ?? discoverWranglerConfigPath(root);
558
+ const rawContent = existsSync(configPath) ? readFileSync(configPath, "utf-8") : "{}";
559
+ const hasBom = rawContent.startsWith(UTF8_BOM);
560
+ const original = hasBom ? rawContent.slice(1) : rawContent;
561
+ let parsed;
562
+ try {
563
+ parsed = parseJsonc(original);
564
+ } catch (error) {
565
+ throw new Error(`deploy: cannot update "${configPath}" — it is not valid JSON/JSONC. Fix the file and retry. (${error.message})`);
566
+ }
567
+ assertNoDuplicateMembers(original, configPath);
568
+ const formattingOptions = detectFormattingOptions(original);
569
+ let text = original;
570
+ const scalarSetPaths = [];
571
+ const set = (path, value) => {
572
+ scalarSetPaths.push(path);
573
+ text = applyMemberEdit(text, path, value, { formattingOptions });
574
+ };
575
+ if (patch.accountId !== void 0) set(["account_id"], patch.accountId);
576
+ if (patch.name !== void 0 && parsed.name === void 0) set(["name"], patch.name);
577
+ if (patch.compatibilityDate !== void 0 && parsed.compatibility_date === void 0) set(["compatibility_date"], patch.compatibilityDate);
578
+ if (patch.compatibilityFlags !== void 0) {
579
+ const existingFlags = parsed.compatibility_flags;
580
+ if (existingFlags !== void 0 && (!Array.isArray(existingFlags) || !existingFlags.every((flag) => typeof flag === "string"))) throw new Error(`deploy: cannot update "${configPath}" — "compatibility_flags" must be an array of strings.`);
581
+ const flags = existingFlags ?? [];
582
+ for (const flag of patch.compatibilityFlags) if (!flags.includes(flag)) {
583
+ text = applyMemberEdit(text, ["compatibility_flags", flags.length], flag, {
584
+ formattingOptions,
585
+ isArrayInsertion: true
586
+ });
587
+ flags.push(flag);
588
+ }
589
+ }
590
+ let workerBindingOwners;
591
+ if (patch.webSockets && patch.webSockets.length > 0) {
592
+ const requested = /* @__PURE__ */ new Map();
593
+ for (const route of patch.webSockets) {
594
+ const existing = requested.get(route.bindingName);
595
+ if (existing && existing.className !== route.className) throw new Error(`websocket: binding '${route.bindingName}' resolves to both '${existing.className}' and '${route.className}'. Rename one of the route files.`);
596
+ requested.set(route.bindingName, route);
597
+ }
598
+ const knownExistingClasses = bindingEntriesForField("durable_objects", parseJsonc(text).durable_objects).map(({ entry }, index) => {
599
+ if (typeof entry.class_name !== "string" || entry.class_name.length === 0) throw new Error(`deploy: cannot update "${configPath}" — "durable_objects.bindings" entry at index ${index} is missing a non-empty string "class_name".`);
600
+ return entry.class_name;
601
+ });
602
+ for (const route of requested.values()) {
603
+ const currentConfig = parseJsonc(text);
604
+ const durableObjectBindings = bindingEntriesForField("durable_objects", currentConfig.durable_objects);
605
+ const matches = durableObjectBindings.filter(({ name }) => name === route.bindingName);
606
+ if (matches.length > 1) throw new Error(`deploy: cannot update "${configPath}" — Durable Object binding '${route.bindingName}' is declared more than once.`);
607
+ if (matches.length === 1) {
608
+ const entry = matches[0].entry;
609
+ if (entry.class_name !== route.className || entry.script_name !== void 0 || entry.environment !== void 0) throw new Error(`websocket: binding '${route.bindingName}' is already configured for another class, script, or environment, but '${route.filePath}' requires the local class '${route.className}'.`);
610
+ continue;
611
+ }
612
+ const owners = collectWorkerBindingNames(configWithoutField(currentConfig, "durable_objects"));
613
+ addQueueProducerOwners(owners, currentConfig);
614
+ const owner = owners.get(route.bindingName);
615
+ if (owner) throw new Error(`deploy: cannot update "${configPath}" — WebSocket binding '${route.bindingName}' is already used by a ${owner} binding.`);
616
+ text = applyMemberEdit(text, [
617
+ "durable_objects",
618
+ "bindings",
619
+ durableObjectBindings.length
620
+ ], {
621
+ name: route.bindingName,
622
+ class_name: route.className
623
+ }, {
624
+ formattingOptions,
625
+ isArrayInsertion: true
626
+ });
627
+ }
628
+ const rawMigrations = parseJsonc(text).migrations;
629
+ const migrations = validateDurableObjectMigrations(rawMigrations, configPath);
630
+ const planned = appendSqliteClassMigration(migrations, [...requested.values()].map((route) => route.className), "void-ws-v1", knownExistingClasses);
631
+ if (planned.added) text = applyMemberEdit(text, ["migrations", migrations.length], planned.migrations[planned.migrations.length - 1], {
632
+ formattingOptions,
633
+ isArrayInsertion: true
634
+ });
635
+ }
636
+ const upsertAdoptedBinding = (field, binding, properties, identityKey = "binding") => {
637
+ const currentConfig = parseJsonc(text);
638
+ const rawList = currentConfig[field];
639
+ bindingNamesForField(field, rawList);
640
+ const currentList = Array.isArray(rawList) ? [...rawList] : [];
641
+ const matches = [];
642
+ for (let i = 0; i < currentList.length; i++) {
643
+ const entry = currentList[i];
644
+ if (isRecord(entry) && entry[identityKey] === binding) matches.push({
645
+ index: i,
646
+ entry
647
+ });
648
+ }
649
+ if (matches.length > 1) throw new Error(`deploy: cannot update "${configPath}" — binding ${JSON.stringify(binding)} is declared ${matches.length} times in "${field}". bwf cannot choose which entry to update, and wrangler rejects duplicate binding names. Remove the duplicate and retry.`);
650
+ const owners = collectWorkerBindingNames(configWithoutField(currentConfig, field));
651
+ addQueueProducerOwners(owners, currentConfig);
652
+ const owner = owners.get(binding);
653
+ if (owner !== void 0) throw new Error(`deploy: cannot update "${configPath}" — cannot adopt ${JSON.stringify(binding)} into "${field}" because that binding name is already used by a ${owner} binding. Wrangler requires every binding name to be unique across the whole worker, so this would make the config undeployable. Rename the conflicting binding and retry.`);
654
+ if (matches.length === 1) {
655
+ const { index, entry: existing } = matches[0];
656
+ for (const [key, value] of Object.entries(properties)) if (!isDeepStrictEqual(existing[key], value)) set([
657
+ field,
658
+ index,
659
+ key
660
+ ], value);
661
+ } else text = applyMemberEdit(text, [field, currentList.length], {
662
+ [identityKey]: binding,
663
+ ...properties
664
+ }, {
665
+ formattingOptions,
666
+ isArrayInsertion: true
667
+ });
668
+ };
669
+ if (patch.d1) upsertAdoptedBinding("d1_databases", patch.d1.binding, {
670
+ database_name: patch.d1.databaseName,
671
+ database_id: patch.d1.databaseId
672
+ });
673
+ if (patch.kv) upsertAdoptedBinding("kv_namespaces", patch.kv.binding, { id: patch.kv.id });
674
+ if (patch.r2) upsertAdoptedBinding("r2_buckets", patch.r2.binding, { bucket_name: patch.r2.bucketName });
675
+ if (patch.hyperdrive) upsertAdoptedBinding("hyperdrive", patch.hyperdrive.binding, { id: patch.hyperdrive.id });
676
+ if (patch.sendEmail) upsertAdoptedBinding("send_email", patch.sendEmail.name, {}, "name");
677
+ let d1MigrationsDirSkipped = false;
678
+ if (patch.d1MigrationsDir) {
679
+ const currentD1 = parseJsonc(text).d1_databases;
680
+ const d1Entries = Array.isArray(currentD1) ? currentD1 : [];
681
+ const matchIndices = [];
682
+ d1Entries.forEach((entry, i) => {
683
+ if (entry.binding === patch.d1MigrationsDir.binding) matchIndices.push(i);
684
+ });
685
+ if (matchIndices.length > 1) throw new Error(`deploy: cannot update "${configPath}" — binding ${JSON.stringify(patch.d1MigrationsDir.binding)} is declared ${matchIndices.length} times in "d1_databases". A binding name must be unique across the worker (wrangler rejects the config otherwise), so migrations_dir cannot be attached unambiguously. Remove the duplicate D1 entry and retry.`);
686
+ const index = matchIndices.length === 1 ? matchIndices[0] : -1;
687
+ if (index >= 0) {
688
+ const existingPattern = d1Entries[index].migrations_pattern;
689
+ if (existingPattern !== void 0 && typeof existingPattern !== "string") throw new Error(`deploy: cannot update "${configPath}" — the D1 entry for binding ${JSON.stringify(patch.d1MigrationsDir.binding)} has a non-string "migrations_pattern" value; expected a string. Wrangler rejects such a config, so filling "migrations_dir" beside it would commit an invalid file. Fix the config and retry.`);
690
+ const existingDir = d1Entries[index].migrations_dir;
691
+ if (existingDir !== void 0 && typeof existingDir !== "string") throw new Error(`deploy: cannot update "${configPath}" — the D1 entry for binding ${JSON.stringify(patch.d1MigrationsDir.binding)} has a non-string "migrations_dir" value; expected a string. Fix the config and retry.`);
692
+ if (typeof existingDir === "string") {
693
+ if (!sameMigrationsDir(configPath, existingDir, patch.d1MigrationsDir.dir)) throw new Error(`deploy: cannot update "${configPath}" — the D1 entry for binding ${JSON.stringify(patch.d1MigrationsDir.binding)} already sets "migrations_dir": ${JSON.stringify(existingDir)}, but bwf keeps this database's migrations in ${JSON.stringify(patch.d1MigrationsDir.dir)}. Refusing to overwrite an explicit different migrations directory. Either remove "migrations_dir" from the entry (or set it to ${JSON.stringify(patch.d1MigrationsDir.dir)}) to let bwf manage it, or move the migrations and keep your directory, then retry.`);
694
+ } else {
695
+ if (existingPattern !== void 0 && !migrationsPatternMatchesDir(existingPattern, patch.d1MigrationsDir.dir)) throw new Error(`deploy: cannot update "${configPath}" — the D1 entry for binding ${JSON.stringify(patch.d1MigrationsDir.binding)} has "migrations_pattern": ${JSON.stringify(existingPattern)}, which is not under the requested "migrations_dir": ${JSON.stringify(patch.d1MigrationsDir.dir)}. Wrangler requires the pattern to start with the migrations dir, so this change would break \`wrangler d1 migrations\`. Align "migrations_pattern" with the dir (or remove it) and retry.`);
696
+ set([
697
+ "d1_databases",
698
+ index,
699
+ "migrations_dir"
700
+ ], patch.d1MigrationsDir.dir);
701
+ }
702
+ } else d1MigrationsDirSkipped = true;
703
+ }
704
+ const reconcileManagedQueues = patch.queues?.reconcileBwfOwned === true;
705
+ const managedQueueProvenance = readManagedQueueProvenance(text);
706
+ const managedProducerBindings = new Set(managedQueueProvenance.producerBindings);
707
+ const managedConsumerQueues = new Set(managedQueueProvenance.consumerQueues);
708
+ const pendingConsumerRemovals = new Set(managedQueueProvenance.pendingConsumerRemovals);
709
+ const upsertQueueEntries = (section, entries) => {
710
+ if (!entries || entries.length === 0) return;
711
+ const currentQueues = assertObjectContainer(parseJsonc(text).queues, "queues");
712
+ const currentList = section === "producers" ? assertValidQueueProducers(currentQueues?.producers) : Array.isArray(currentQueues?.consumers) ? [...currentQueues.consumers] : [];
713
+ for (const entry of entries) {
714
+ let index;
715
+ if (section === "producers") {
716
+ const matches = [];
717
+ for (let i = 0; i < currentList.length; i++) if (currentList[i].binding === entry.binding) matches.push(i);
718
+ if (matches.length > 1) throw new Error(`deploy: cannot update "${configPath}" — queue producer binding ${JSON.stringify(entry.binding)} is declared ${matches.length} times across producers. A producer binding must map to exactly one queue, so wrangler rejects this config. Remove the duplicate producers and retry.`);
719
+ const bwfOwned = reconcileManagedQueues && managedProducerBindings.has(String(entry.binding));
720
+ if (matches.length === 1) {
721
+ const existing = currentList[matches[0]];
722
+ if (existing.queue !== entry.queue && !bwfOwned) throw new Error(`deploy: cannot update "${configPath}" — queue producer binding ${JSON.stringify(entry.binding)} is already bound to queue ${JSON.stringify(existing.queue)}, but queue ${JSON.stringify(entry.queue)} also requests it. A producer binding must map to exactly one queue. Rename or remove the conflicting producer and retry.`);
723
+ }
724
+ index = matches.length === 1 ? matches[0] : -1;
725
+ workerBindingOwners ??= collectWorkerBindingNames(parseJsonc(text));
726
+ const bindingName = String(entry.binding);
727
+ const owner = workerBindingOwners.get(bindingName);
728
+ if (owner !== void 0) throw new Error(`deploy: cannot update "${configPath}" — queue producer binding ${JSON.stringify(bindingName)} is already used by a ${owner} binding. Wrangler requires every binding name to be unique across the whole worker, so this producer would make the config undeployable. Rename the conflicting binding (or the queue) and retry.`);
729
+ } else index = currentList.findIndex((existing) => isRecord(existing) && existing.queue === entry.queue);
730
+ if (index >= 0) {
731
+ const existing = currentList[index];
732
+ for (const [key, value] of Object.entries(entry)) {
733
+ if (value === void 0) continue;
734
+ if (!isDeepStrictEqual(existing[key], value)) set([
735
+ "queues",
736
+ section,
737
+ index,
738
+ key
739
+ ], value);
740
+ }
741
+ currentList[index] = {
742
+ ...existing,
743
+ ...entry
744
+ };
745
+ } else {
746
+ text = applyMemberEdit(text, [
747
+ "queues",
748
+ section,
749
+ currentList.length
750
+ ], entry, {
751
+ formattingOptions,
752
+ isArrayInsertion: true
753
+ });
754
+ currentList.push(entry);
755
+ if (reconcileManagedQueues) {
756
+ if (section === "producers" && typeof entry.binding === "string") managedProducerBindings.add(entry.binding);
757
+ else if (section === "consumers" && typeof entry.queue === "string") managedConsumerQueues.add(entry.queue);
758
+ }
759
+ }
760
+ }
761
+ };
762
+ if (patch.queues) {
763
+ if (patch.queues.reconcileBwfOwned) {
764
+ const queues = assertObjectContainer(parseJsonc(text).queues, "queues");
765
+ assertValidQueueProducers(queues?.producers);
766
+ const producers = Array.isArray(queues?.producers) ? queues.producers : [];
767
+ const desiredBindings = new Set((patch.queues.producers ?? []).map((producer) => producer.binding));
768
+ const staleProducerIndexes = [];
769
+ for (let index = 0; index < producers.length; index++) {
770
+ const producer = producers[index];
771
+ if (typeof producer.binding === "string" && managedProducerBindings.has(producer.binding) && !desiredBindings.has(producer.binding)) {
772
+ staleProducerIndexes.push(index);
773
+ managedProducerBindings.delete(producer.binding);
774
+ }
775
+ }
776
+ for (const index of staleProducerIndexes.reverse()) set([
777
+ "queues",
778
+ "producers",
779
+ index
780
+ ], void 0);
781
+ const consumers = Array.isArray(queues?.consumers) ? queues.consumers : [];
782
+ const desiredConsumerQueues = new Set((patch.queues.consumers ?? []).map((consumer) => consumer.queue));
783
+ const staleConsumerIndexes = consumers.flatMap((consumer, index) => {
784
+ if (typeof consumer.queue === "string" && managedConsumerQueues.has(consumer.queue) && !desiredConsumerQueues.has(consumer.queue)) {
785
+ managedConsumerQueues.delete(consumer.queue);
786
+ pendingConsumerRemovals.add(consumer.queue);
787
+ return [index];
788
+ }
789
+ return [];
790
+ });
791
+ for (const index of staleConsumerIndexes.reverse()) set([
792
+ "queues",
793
+ "consumers",
794
+ index
795
+ ], void 0);
796
+ }
797
+ upsertQueueEntries("producers", patch.queues.producers);
798
+ upsertQueueEntries("consumers", patch.queues.consumers);
799
+ for (const consumer of patch.queues.consumers ?? []) pendingConsumerRemovals.delete(consumer.queue);
800
+ }
801
+ if (patch.vars) {
802
+ const currentConfig = parseJsonc(text);
803
+ bindingNamesForField("vars", currentConfig.vars);
804
+ const currentVars = isRecord(currentConfig.vars) ? currentConfig.vars : {};
805
+ const owners = collectWorkerBindingNames(configWithoutField(currentConfig, "vars"));
806
+ addQueueProducerOwners(owners, currentConfig);
807
+ for (const [key, value] of Object.entries(patch.vars)) {
808
+ const owner = owners.get(key);
809
+ if (owner !== void 0) throw new Error(`deploy: cannot update "${configPath}" — cannot write var ${JSON.stringify(key)} because that binding name is already used by a ${owner} binding. Wrangler requires every binding name to be unique across the whole worker, so this would make the config undeployable. Rename the conflicting binding and retry.`);
810
+ if (!isDeepStrictEqual(currentVars[key], value)) set(["vars", key], value);
811
+ }
812
+ }
813
+ if (patch.addresses !== void 0) {
814
+ const currentAddresses = parseJsonc(text).addresses;
815
+ if (patch.addresses === null) text = removeMember(text, ["addresses"], { formattingOptions });
816
+ else if (!isDeepStrictEqual(currentAddresses, patch.addresses)) text = applyMemberEdit(text, ["addresses"], patch.addresses, { formattingOptions });
817
+ }
818
+ const droppedComment = findDroppedComment(extractCommentTokens(original), extractCommentTokens(text));
819
+ if (droppedComment !== void 0) {
820
+ const originalRoot = parseTree(original, void 0, { allowTrailingComma: true });
821
+ const compositeField = originalRoot ? scalarSetPaths.find((path) => {
822
+ const node = findNodeAtLocation(originalRoot, path);
823
+ return node?.type === "object" || node?.type === "array";
824
+ }) : void 0;
825
+ if (compositeField) {
826
+ const field = String(compositeField[compositeField.length - 1]);
827
+ throw new Error(`deploy: cannot update "${configPath}" — "${field}" has an object/array value; expected a string. Fix the config and retry.`);
828
+ }
829
+ throw new Error(`deploy: cannot update "${configPath}" — this edit would drop a comment (${droppedComment}); the writer refuses to corrupt the file — simplify the surrounding structure and retry.`);
830
+ }
831
+ if (reconcileManagedQueues) {
832
+ const finalQueues = assertObjectContainer(parseJsonc(text).queues, "queues");
833
+ const finalProducerBindings = new Set((Array.isArray(finalQueues?.producers) ? finalQueues.producers : []).flatMap((entry) => isRecord(entry) && typeof entry.binding === "string" ? [entry.binding] : []));
834
+ const finalConsumerQueues = new Set((Array.isArray(finalQueues?.consumers) ? finalQueues.consumers : []).flatMap((entry) => isRecord(entry) && typeof entry.queue === "string" ? [entry.queue] : []));
835
+ text = writeManagedQueueProvenance(text, {
836
+ producerBindings: [...managedProducerBindings].filter((binding) => finalProducerBindings.has(binding)),
837
+ consumerQueues: [...managedConsumerQueues].filter((queue) => finalConsumerQueues.has(queue)),
838
+ pendingConsumerRemovals: [...pendingConsumerRemovals]
839
+ });
840
+ }
841
+ const finalText = hasBom ? `${UTF8_BOM}${text}` : text;
842
+ const modified = finalText !== rawContent;
843
+ if (modified) writeProjectWranglerFile(configPath, finalText);
844
+ return {
845
+ configPath,
846
+ modified,
847
+ d1MigrationsDirSkipped
848
+ };
849
+ }
850
+ /** Read the custom-domain routes owned by the root Wrangler config. */
851
+ function readWranglerCustomDomains(root) {
852
+ const configPath = discoverWranglerConfigPath(root);
853
+ const raw = existsSync(configPath) ? readFileSync(configPath, "utf-8") : "{}";
854
+ const text = raw.startsWith(UTF8_BOM) ? raw.slice(1) : raw;
855
+ const parsed = parseJsonc(text);
856
+ assertNoDuplicateMembers(text, configPath);
857
+ return {
858
+ configPath,
859
+ domains: parseCustomDomains(parsed.routes, configPath),
860
+ modified: false
861
+ };
862
+ }
863
+ /**
864
+ * Add or remove one Wrangler `custom_domain` route without rewriting unrelated
865
+ * configuration. The returned domain list is the post-edit source of truth used
866
+ * by `bwf domain list|status` on direct Cloudflare projects.
867
+ */
868
+ function updateWranglerCustomDomain(root, hostname, action) {
869
+ const configPath = discoverWranglerConfigPath(root);
870
+ if (!existsSync(configPath)) throw new Error(`domain: No Wrangler config found at "${configPath}". Run \`bwf init\` first.`);
871
+ const raw = readFileSync(configPath, "utf-8");
872
+ const hasBom = raw.startsWith(UTF8_BOM);
873
+ const original = hasBom ? raw.slice(1) : raw;
874
+ const parsed = parseJsonc(original);
875
+ assertNoDuplicateMembers(original, configPath);
876
+ if (parsed.route !== void 0) throw new Error(`domain: "${configPath}" uses the singular "route" field. Convert it to a "routes" array before managing custom domains so the existing route cannot be shadowed.`);
877
+ const routes = parsed.routes;
878
+ if (routes !== void 0 && !Array.isArray(routes)) throw new Error(`domain: "routes" in "${configPath}" must be an array.`);
879
+ const routeArray = routes ?? [];
880
+ const matches = [];
881
+ for (let index = 0; index < routeArray.length; index++) {
882
+ const route = routeArray[index];
883
+ if (typeof route === "string") {
884
+ if (route === hostname) throw new Error(`domain: ${JSON.stringify(hostname)} already exists as a non-custom route in "${configPath}". Remove or convert that route first.`);
885
+ continue;
886
+ }
887
+ if (typeof route !== "object" || route === null || Array.isArray(route)) throw new Error(`domain: "routes[${index}]" in "${configPath}" is malformed.`);
888
+ const entry = route;
889
+ if (entry.pattern !== hostname) continue;
890
+ if (entry.custom_domain !== true) throw new Error(`domain: ${JSON.stringify(hostname)} already exists as a non-custom route in "${configPath}". Remove or convert that route first.`);
891
+ matches.push(index);
892
+ }
893
+ if (matches.length > 1) throw new Error(`domain: ${JSON.stringify(hostname)} is declared more than once in "${configPath}". Remove the duplicate before continuing.`);
894
+ let text = original;
895
+ const formattingOptions = detectFormattingOptions(original);
896
+ if (action === "add" && matches.length === 0) {
897
+ text = applyMemberEdit(text, ["routes", routeArray.length], {
898
+ pattern: hostname,
899
+ custom_domain: true
900
+ }, {
901
+ formattingOptions,
902
+ isArrayInsertion: true
903
+ });
904
+ const dropped = findDroppedComment(extractCommentTokens(original), extractCommentTokens(text));
905
+ if (dropped !== void 0) throw new Error(`domain: cannot update "${configPath}" because the edit would drop a comment (${dropped}).`);
906
+ } else if (action === "delete" && matches.length === 1) text = applyEdits(text, modify(text, ["routes", matches[0]], void 0, { formattingOptions }));
907
+ const finalText = hasBom ? `${UTF8_BOM}${text}` : text;
908
+ const modified = finalText !== raw;
909
+ if (modified) writeProjectWranglerFile(configPath, finalText);
910
+ return {
911
+ configPath,
912
+ domains: parseCustomDomains(parseJsonc(text).routes, configPath),
913
+ modified
914
+ };
915
+ }
916
+ function discoverWranglerConfigPath(root) {
917
+ for (const path of projectWranglerPaths(root)) if (existsSync(path)) return path;
918
+ return materializeCloudflareConfig(root);
919
+ }
920
+ function parseCustomDomains(value, configPath) {
921
+ if (value === void 0) return [];
922
+ if (!Array.isArray(value)) throw new Error(`domain: "routes" in "${configPath}" must be an array.`);
923
+ const domains = [];
924
+ for (let index = 0; index < value.length; index++) {
925
+ const route = value[index];
926
+ if (typeof route === "string") continue;
927
+ if (typeof route !== "object" || route === null || Array.isArray(route)) throw new Error(`domain: "routes[${index}]" in "${configPath}" is malformed.`);
928
+ const entry = route;
929
+ if (entry.custom_domain !== true) continue;
930
+ if (typeof entry.pattern !== "string" || entry.pattern.length === 0) throw new Error(`domain: custom domain route "routes[${index}]" in "${configPath}" needs a non-empty pattern.`);
931
+ domains.push({
932
+ pattern: entry.pattern,
933
+ customDomain: true
934
+ });
935
+ }
936
+ return domains;
937
+ }
938
+ /** Every line and block comment in JSONC source, verbatim, in order. */
939
+ function extractCommentTokens(text) {
940
+ const scanner = createScanner(text, false);
941
+ const tokens = [];
942
+ let kind = scanner.scan();
943
+ while (kind !== SyntaxKind.EOF) {
944
+ if (kind === SyntaxKind.LineCommentTrivia || kind === SyntaxKind.BlockCommentTrivia) {
945
+ const offset = scanner.getTokenOffset();
946
+ tokens.push(text.slice(offset, offset + scanner.getTokenLength()));
947
+ }
948
+ kind = scanner.scan();
949
+ }
950
+ return tokens;
951
+ }
952
+ /** The first comment in `before` missing from `after`, counting repeats, if any. */
953
+ function findDroppedComment(before, after) {
954
+ const counts = /* @__PURE__ */ new Map();
955
+ for (const token of after) counts.set(token, (counts.get(token) ?? 0) + 1);
956
+ for (const token of before) {
957
+ const remaining = counts.get(token) ?? 0;
958
+ if (remaining <= 0) return token;
959
+ counts.set(token, remaining - 1);
960
+ }
961
+ }
962
+ /** Match inserted content to the file's indentation; two spaces by default. */
963
+ function detectFormattingOptions(text) {
964
+ const match = text.match(/^([ \t]+)\S/m);
965
+ if (match) {
966
+ const indent = match[1];
967
+ if (indent.startsWith(" ")) return {
968
+ tabSize: 1,
969
+ insertSpaces: false
970
+ };
971
+ return {
972
+ tabSize: indent.length,
973
+ insertSpaces: true
974
+ };
975
+ }
976
+ return {
977
+ tabSize: 2,
978
+ insertSpaces: true
979
+ };
980
+ }
981
+ function parseJsonc(text) {
982
+ const errors = [];
983
+ const source = text.startsWith(UTF8_BOM) ? text.slice(1) : text;
984
+ const result = parse(source, errors, { allowTrailingComma: true });
985
+ if (errors.length > 0) throw new SyntaxError("Failed to parse JSONC");
986
+ return result;
987
+ }
988
+ /**
989
+ * `modify()` + `applyEdits()` that keeps a trailing inline comment on the sibling it
990
+ * documented. When a member is appended, `modify()` moves that comment after the new
991
+ * member, so edit a copy without it and splice it back after the sibling's comma.
992
+ */
993
+ function applyMemberEdit(text, path, value, options) {
994
+ const plain = () => applyEdits(text, modify(text, path, value, options));
995
+ const root = parseTree(text, void 0, { allowTrailingComma: true });
996
+ if (!root) return plain();
997
+ if (!options.isArrayInsertion && findNodeAtLocation(root, path) !== void 0) return plain();
998
+ let receivingPath = path.slice(0, -1);
999
+ let container = findNodeAtLocation(root, receivingPath);
1000
+ while (!container && receivingPath.length > 0) {
1001
+ receivingPath = receivingPath.slice(0, -1);
1002
+ container = findNodeAtLocation(root, receivingPath);
1003
+ }
1004
+ const members = container?.children;
1005
+ if (!container || !members || members.length === 0) return plain();
1006
+ const last = members[members.length - 1];
1007
+ const trailing = readTrailingComment(text, last.offset + last.length);
1008
+ if (!trailing) return plain();
1009
+ const stripped = text.slice(0, last.offset + last.length) + text.slice(trailing.end);
1010
+ const rewritten = applyEdits(stripped, modify(stripped, path, value, options));
1011
+ const newRoot = parseTree(rewritten, void 0, { allowTrailingComma: true });
1012
+ const newContainer = newRoot ? findNodeAtLocation(newRoot, receivingPath) : void 0;
1013
+ const newMembers = newContainer?.children;
1014
+ if (!newRoot || !newContainer || !newMembers || newMembers.length < 2) return plain();
1015
+ const sibling = newMembers[newMembers.length - 2];
1016
+ const commaPos = rewritten.indexOf(",", sibling.offset + sibling.length);
1017
+ if (commaPos === -1) return plain();
1018
+ const relocated = `${rewritten.slice(0, commaPos + 1)} ${trailing.text}${rewritten.slice(commaPos + 1)}`;
1019
+ const plainResult = plain();
1020
+ let relocatedParsed;
1021
+ try {
1022
+ relocatedParsed = parseJsonc(relocated);
1023
+ } catch {
1024
+ return plainResult;
1025
+ }
1026
+ if (!isDeepStrictEqual(relocatedParsed, parseJsonc(plainResult))) return plainResult;
1027
+ return relocated;
1028
+ }
1029
+ /**
1030
+ * Remove the object member at `path`, keeping every comment. `modify(…, undefined)` also
1031
+ * deletes the comments between the previous member and this one, so splice out the
1032
+ * property, one separating comma (the following one, else the preceding one, so strict
1033
+ * JSON gains no trailing comma) and its blank line. Falls back to `modify()` when the
1034
+ * result's data differs.
1035
+ */
1036
+ function removeMember(text, path, options) {
1037
+ const root = parseTree(text, void 0, { allowTrailingComma: true });
1038
+ const valueNode = root ? findNodeAtLocation(root, path) : void 0;
1039
+ const property = valueNode?.parent;
1040
+ if (!root || !valueNode || !property || property.type !== "property") return valueNode ? applyEdits(text, modify(text, path, void 0, options)) : text;
1041
+ const start = property.offset;
1042
+ const end = property.offset + property.length;
1043
+ const scanner = createScanner(text, false);
1044
+ const tokens = [];
1045
+ for (let kind = scanner.scan(); kind !== SyntaxKind.EOF; kind = scanner.scan()) tokens.push({
1046
+ kind,
1047
+ offset: scanner.getTokenOffset(),
1048
+ length: scanner.getTokenLength()
1049
+ });
1050
+ const isTrivia = (kind) => kind === SyntaxKind.Trivia || kind === SyntaxKind.LineBreakTrivia || kind === SyntaxKind.LineCommentTrivia || kind === SyntaxKind.BlockCommentTrivia;
1051
+ const following = tokens.find((token) => token.offset >= end && !isTrivia(token.kind));
1052
+ const preceding = [...tokens].reverse().find((token) => token.offset + token.length <= start && !isTrivia(token.kind));
1053
+ const comma = following?.kind === SyntaxKind.CommaToken ? following : preceding?.kind === SyntaxKind.CommaToken ? preceding : void 0;
1054
+ const ranges = [{
1055
+ offset: start,
1056
+ length: end - start
1057
+ }];
1058
+ if (comma) ranges.push({
1059
+ offset: comma.offset,
1060
+ length: comma.length
1061
+ });
1062
+ ranges.sort((a, b) => b.offset - a.offset);
1063
+ let spliced = text;
1064
+ for (const range of ranges) spliced = spliced.slice(0, range.offset) + spliced.slice(range.offset + range.length);
1065
+ const cursor = comma && comma.offset < start ? start - comma.length : start;
1066
+ let lineStart = cursor;
1067
+ while (lineStart > 0 && spliced[lineStart - 1] !== "\n" && spliced[lineStart - 1] !== "\r") lineStart--;
1068
+ let lineEnd = cursor;
1069
+ while (lineEnd < spliced.length && spliced[lineEnd] !== "\n" && spliced[lineEnd] !== "\r") lineEnd++;
1070
+ if (spliced.slice(lineStart, lineEnd).trim() === "") {
1071
+ const terminator = spliced.startsWith("\r\n", lineEnd) ? 2 : lineEnd < spliced.length ? 1 : 0;
1072
+ spliced = spliced.slice(0, lineStart) + spliced.slice(lineEnd + terminator);
1073
+ }
1074
+ const plainResult = applyEdits(text, modify(text, path, void 0, options));
1075
+ let splicedParsed;
1076
+ try {
1077
+ splicedParsed = parseJsonc(spliced);
1078
+ } catch {
1079
+ return plainResult;
1080
+ }
1081
+ if (!isDeepStrictEqual(splicedParsed, parseJsonc(plainResult))) return plainResult;
1082
+ return spliced;
1083
+ }
1084
+ /**
1085
+ * The `//` or single-line block comment on the same line after `offset` (just past the
1086
+ * last member's value), allowing one comma before it.
1087
+ */
1088
+ function readTrailingComment(text, offset) {
1089
+ let i = offset;
1090
+ while (i < text.length && (text[i] === " " || text[i] === " ")) i++;
1091
+ if (text[i] === ",") {
1092
+ i++;
1093
+ while (i < text.length && (text[i] === " " || text[i] === " ")) i++;
1094
+ }
1095
+ if (text[i] === "/" && text[i + 1] === "/") {
1096
+ let end = i;
1097
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end++;
1098
+ return {
1099
+ text: text.slice(i, end),
1100
+ end
1101
+ };
1102
+ }
1103
+ if (text[i] === "/" && text[i + 1] === "*") {
1104
+ const close = text.indexOf("*/", i + 2);
1105
+ if (close === -1) return;
1106
+ const end = close + 2;
1107
+ const slice = text.slice(i, end);
1108
+ if (slice.includes("\n") || slice.includes("\r")) return;
1109
+ return {
1110
+ text: slice,
1111
+ end
1112
+ };
1113
+ }
1114
+ }
1115
+ /** Throw if any object in the config, at any depth, declares the same key twice. */
1116
+ function assertNoDuplicateMembers(text, configPath) {
1117
+ const root = parseTree(text, void 0, { allowTrailingComma: true });
1118
+ if (!root) return;
1119
+ const walk = (node) => {
1120
+ if (node.type === "object" && node.children) {
1121
+ const seen = /* @__PURE__ */ new Set();
1122
+ for (const property of node.children) {
1123
+ const keyNode = property.children?.[0];
1124
+ const key = keyNode?.value;
1125
+ if (typeof key !== "string") continue;
1126
+ if (seen.has(key)) {
1127
+ const { line, column } = offsetToLineColumn(text, keyNode.offset);
1128
+ throw new Error(`deploy: cannot update "${configPath}" — duplicate key ${JSON.stringify(key)} at line ${line}, column ${column}. Wrangler reads the last of two duplicate members, but this writer edits the first, so the update would silently not apply. Remove the duplicate and retry.`);
1129
+ }
1130
+ seen.add(key);
1131
+ }
1132
+ }
1133
+ if (node.children) for (const child of node.children) walk(child);
1134
+ };
1135
+ walk(root);
1136
+ }
1137
+ /** 1-based line and column of an offset. */
1138
+ function offsetToLineColumn(text, offset) {
1139
+ let line = 1;
1140
+ let column = 1;
1141
+ const limit = Math.min(offset, text.length);
1142
+ for (let i = 0; i < limit; i++) if (text[i] === "\n") {
1143
+ line += 1;
1144
+ column = 1;
1145
+ } else column += 1;
1146
+ return {
1147
+ line,
1148
+ column
1149
+ };
1150
+ }
1151
+ function validateDurableObjectMigrations(value, configPath) {
1152
+ if (value === void 0) return [];
1153
+ if (!Array.isArray(value)) throw new Error(`deploy: cannot update "${configPath}" — "migrations" must be an array of Durable Object migration steps.`);
1154
+ const tags = /* @__PURE__ */ new Set();
1155
+ for (const [index, migration] of value.entries()) {
1156
+ if (!isRecord(migration) || typeof migration.tag !== "string" || migration.tag.length === 0) throw new Error(`deploy: cannot update "${configPath}" — migration at index ${index} must be an object with a non-empty string "tag".`);
1157
+ if (tags.has(migration.tag)) throw new Error(`deploy: cannot update "${configPath}" — migration tag '${migration.tag}' is declared more than once.`);
1158
+ tags.add(migration.tag);
1159
+ for (const field of [
1160
+ "new_classes",
1161
+ "new_sqlite_classes",
1162
+ "deleted_classes"
1163
+ ]) {
1164
+ const classes = migration[field];
1165
+ if (classes !== void 0 && (!Array.isArray(classes) || classes.some((className) => typeof className !== "string"))) throw new Error(`deploy: cannot update "${configPath}" — "migrations[${index}].${field}" must be an array of class names.`);
1166
+ }
1167
+ const renamed = migration.renamed_classes;
1168
+ if (renamed !== void 0 && (!Array.isArray(renamed) || renamed.some((entry) => !isRecord(entry) || typeof entry.from !== "string" || typeof entry.to !== "string"))) throw new Error(`deploy: cannot update "${configPath}" — "migrations[${index}].renamed_classes" has an invalid entry.`);
1169
+ const transferred = migration.transferred_classes;
1170
+ if (transferred !== void 0 && (!Array.isArray(transferred) || transferred.some((entry) => !isRecord(entry) || typeof entry.from !== "string" || typeof entry.from_script !== "string" || typeof entry.to !== "string"))) throw new Error(`deploy: cannot update "${configPath}" — "migrations[${index}].transferred_classes" has an invalid entry.`);
1171
+ }
1172
+ return value;
1173
+ }
1174
+ /**
1175
+ * Wrangler's `friendlyBindingNames`: the fields `validateBindingsHaveUniqueNames` reads, with
1176
+ * their labels. `queues` is left out because the producer upsert matches its own entries;
1177
+ * including it would make a producer collide with itself.
1178
+ */
1179
+ const FRIENDLY_BINDING_NAMES = {
1180
+ data_blobs: "Data Blob",
1181
+ durable_objects: "Durable Object",
1182
+ kv_namespaces: "KV Namespace",
1183
+ send_email: "Send Email",
1184
+ d1_databases: "D1 Database",
1185
+ vectorize: "Vectorize Index",
1186
+ ai_search_namespaces: "AI Search Namespace",
1187
+ ai_search: "AI Search Instance",
1188
+ websearch: "Web Search",
1189
+ agent_memory: "Agent Memory",
1190
+ hyperdrive: "Hyperdrive Config",
1191
+ r2_buckets: "R2 Bucket",
1192
+ logfwdr: "logfwdr",
1193
+ services: "Worker",
1194
+ analytics_engine_datasets: "Analytics Engine Dataset",
1195
+ text_blobs: "Text Blob",
1196
+ browser: "Browser Run",
1197
+ ai: "AI",
1198
+ images: "Images",
1199
+ stream: "Stream",
1200
+ media: "Media",
1201
+ version_metadata: "Worker Version Metadata",
1202
+ unsafe: "Unsafe Metadata",
1203
+ vars: "Environment Variable",
1204
+ wasm_modules: "Wasm Module",
1205
+ dispatch_namespaces: "Dispatch Namespace",
1206
+ mtls_certificates: "mTLS Certificate",
1207
+ workflows: "Workflow",
1208
+ pipelines: "Pipeline",
1209
+ secrets_store_secrets: "Secrets Store Secret",
1210
+ artifacts: "Artifacts",
1211
+ ratelimits: "Rate Limit",
1212
+ assets: "Assets",
1213
+ unsafe_hello_world: "Hello World",
1214
+ flagship: "Flagship",
1215
+ worker_loaders: "Worker Loader",
1216
+ vpc_services: "VPC Service",
1217
+ vpc_networks: "VPC Network"
1218
+ };
1219
+ /** Every binding name in the config, mapped to its owner's label (first one wins). */
1220
+ function collectWorkerBindingNames(config) {
1221
+ const owners = /* @__PURE__ */ new Map();
1222
+ const claim = (name, friendly) => {
1223
+ if (!owners.has(name)) owners.set(name, friendly);
1224
+ };
1225
+ for (const [field, friendly] of Object.entries(FRIENDLY_BINDING_NAMES)) for (const name of bindingNamesForField(field, config[field])) claim(name, friendly);
1226
+ const secrets = assertObjectContainer(config.secrets, "secrets");
1227
+ if (secrets && secrets.required !== void 0) {
1228
+ if (!Array.isArray(secrets.required)) throw new Error("deploy: cannot verify binding-name uniqueness — \"secrets.required\" must be an array of secret names. Fix the wrangler config and retry.");
1229
+ secrets.required.forEach((name, index) => {
1230
+ if (typeof name !== "string" || name.length === 0) throw bindingSetError(`"secrets.required" contains a malformed entry at index ${index} (expected a non-empty string)`, "dropped entry");
1231
+ claim(name, "Secret");
1232
+ });
1233
+ }
1234
+ return owners;
1235
+ }
1236
+ /** A shallow copy of `config` without `field`. */
1237
+ function configWithoutField(config, field) {
1238
+ const { [field]: _omit, ...rest } = config;
1239
+ return rest;
1240
+ }
1241
+ /** Add queue producer bindings (label "Queue"), which the base collector leaves out. */
1242
+ function addQueueProducerOwners(owners, config) {
1243
+ const queues = assertObjectContainer(config.queues, "queues");
1244
+ if (!queues || queues.producers === void 0) return;
1245
+ for (const producer of assertValidQueueProducers(queues.producers)) {
1246
+ const binding = producer.binding;
1247
+ if (!owners.has(binding)) owners.set(binding, "Queue");
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Validate `queues.producers`: every member needs a non-empty string `binding`. A skipped
1252
+ * member could hide a binding collision, so a malformed one throws.
1253
+ */
1254
+ function assertValidQueueProducers(producers) {
1255
+ if (producers === void 0) return [];
1256
+ if (!Array.isArray(producers)) throw new Error("deploy: cannot verify binding-name uniqueness — \"queues.producers\" must be an array. Fix the wrangler config and retry.");
1257
+ return producers.map((producer, index) => {
1258
+ if (!isRecord(producer) || typeof producer.binding !== "string" || producer.binding.length === 0) throw bindingSetError(`"queues.producers" contains a malformed entry at index ${index} (missing a non-empty string "binding")`, "dropped producer");
1259
+ return producer;
1260
+ });
1261
+ }
1262
+ /** An object-valued container field (`queues`, `secrets`); any other present value throws. */
1263
+ function assertObjectContainer(value, field) {
1264
+ if (value === void 0) return;
1265
+ if (!isRecord(value)) throw bindingSetError(`"${field}" must be an object`, "wrong-shaped container");
1266
+ return value;
1267
+ }
1268
+ /**
1269
+ * The label of another binding type that already uses `name`, or undefined when only
1270
+ * `field` (or nothing) does. Lets a caller refuse a write before its side effects.
1271
+ */
1272
+ function findBindingNameOwner(config, field, name) {
1273
+ bindingNamesForField(field, config[field]);
1274
+ const owners = collectWorkerBindingNames(configWithoutField(config, field));
1275
+ addQueueProducerOwners(owners, config);
1276
+ return owners.get(name);
1277
+ }
1278
+ /**
1279
+ * The one entry in `field` (`d1_databases`, `kv_namespaces`, …) with this binding, or
1280
+ * undefined. Throws on a malformed field, a duplicate entry, or a name another binding
1281
+ * type also uses.
1282
+ */
1283
+ function readProvisionedBindingEntry(config, field, binding, configPath) {
1284
+ bindingNamesForField(field, config[field]);
1285
+ const rawList = config[field];
1286
+ const matches = (Array.isArray(rawList) ? rawList : []).filter((entry) => isRecord(entry) && entry.binding === binding);
1287
+ if (matches.length > 1) throw new Error(`provision: cannot read "${configPath}" — binding ${JSON.stringify(binding)} is declared ${matches.length} times in "${field}". Cannot pick one to reuse/verify, and wrangler rejects duplicate binding names. Remove the duplicate and retry.`);
1288
+ const owners = collectWorkerBindingNames(configWithoutField(config, field));
1289
+ addQueueProducerOwners(owners, config);
1290
+ const owner = owners.get(binding);
1291
+ if (owner !== void 0) throw new Error(`provision: cannot read "${configPath}" — binding ${JSON.stringify(binding)} in "${field}" is also used by a ${owner} binding. Wrangler requires every binding name to be unique across the whole worker, so this config is undeployable. Rename the conflicting binding and retry.`);
1292
+ return matches[0];
1293
+ }
1294
+ /** Fields that are not a `namespace-array`. */
1295
+ const BINDING_FIELD_SHAPES = {
1296
+ vars: { kind: "key-map" },
1297
+ wasm_modules: { kind: "key-map" },
1298
+ text_blobs: { kind: "key-map" },
1299
+ data_blobs: { kind: "key-map" },
1300
+ send_email: { kind: "name-keyed-array" },
1301
+ ratelimits: { kind: "name-keyed-array" },
1302
+ addresses: { kind: "whole-object" },
1303
+ ai: {
1304
+ kind: "singleton",
1305
+ bindingRequired: true
1306
+ },
1307
+ browser: {
1308
+ kind: "singleton",
1309
+ bindingRequired: true
1310
+ },
1311
+ images: {
1312
+ kind: "singleton",
1313
+ bindingRequired: true
1314
+ },
1315
+ stream: {
1316
+ kind: "singleton",
1317
+ bindingRequired: true
1318
+ },
1319
+ media: {
1320
+ kind: "singleton",
1321
+ bindingRequired: true
1322
+ },
1323
+ websearch: {
1324
+ kind: "singleton",
1325
+ bindingRequired: true
1326
+ },
1327
+ version_metadata: {
1328
+ kind: "singleton",
1329
+ bindingRequired: true
1330
+ },
1331
+ assets: {
1332
+ kind: "singleton",
1333
+ bindingRequired: false
1334
+ },
1335
+ durable_objects: {
1336
+ kind: "binding-list",
1337
+ bindingsRequired: true
1338
+ },
1339
+ logfwdr: {
1340
+ kind: "binding-list",
1341
+ bindingsRequired: true
1342
+ },
1343
+ unsafe: {
1344
+ kind: "binding-list",
1345
+ bindingsRequired: false
1346
+ }
1347
+ };
1348
+ /**
1349
+ * Binding names in one config field, read by the field's known shape. Throws on a wrong
1350
+ * shape or a missing required name, which Wrangler would drop silently.
1351
+ */
1352
+ function bindingNamesForField(field, value) {
1353
+ if (BINDING_FIELD_SHAPES[field]?.kind === "key-map") return keyMapBindingNames(field, value);
1354
+ return bindingEntriesForField(field, value).map((entry) => entry.name);
1355
+ }
1356
+ /**
1357
+ * Like {@link bindingNamesForField}, but pairs each name with its config entry so a caller
1358
+ * can also compare what the binding points at.
1359
+ */
1360
+ function bindingEntriesForField(field, value) {
1361
+ const shape = BINDING_FIELD_SHAPES[field] ?? { kind: "namespace-array" };
1362
+ switch (shape.kind) {
1363
+ case "key-map": return keyMapBindingEntries(field);
1364
+ case "name-keyed-array": return nameKeyedBindingEntries(field, value);
1365
+ case "namespace-array": return namespaceArrayBindingEntries(field, value);
1366
+ case "singleton": return singletonBindingEntry(field, value, shape.bindingRequired);
1367
+ case "binding-list": return bindingListEntries(field, value, shape.bindingsRequired);
1368
+ case "whole-object": return [];
1369
+ }
1370
+ }
1371
+ /** Key-map fields have no entry objects; callers never route them here. */
1372
+ function keyMapBindingEntries(field) {
1373
+ throw bindingSetError(`"${field}" must be an object mapping names to values`, "wrong-shaped field");
1374
+ }
1375
+ function namespaceArrayBindingEntries(field, value) {
1376
+ if (value === void 0) return [];
1377
+ if (!Array.isArray(value)) throw bindingSetError(`"${field}" must be an array of binding entries`, "wrong-shaped field");
1378
+ return strictBindingEntries(value, "binding", field);
1379
+ }
1380
+ /**
1381
+ * `send_email` and `ratelimits` are keyed by `.name` only. A `.binding` on such an entry is
1382
+ * not an identity Wrangler uses, so reading it would invent a collision.
1383
+ */
1384
+ function nameKeyedBindingEntries(field, value) {
1385
+ if (value === void 0) return [];
1386
+ if (!Array.isArray(value)) throw bindingSetError(`"${field}" must be an array of binding entries`, "wrong-shaped field");
1387
+ return strictBindingEntries(value, "name", field);
1388
+ }
1389
+ function bindingListEntries(field, value, bindingsRequired) {
1390
+ if (value === void 0) return [];
1391
+ if (!isRecord(value)) throw bindingSetError(`"${field}" must be an object with a "bindings" array`, "wrong-shaped field");
1392
+ if (value.bindings === void 0) {
1393
+ if (bindingsRequired) throw bindingSetError(`"${field}" requires a "bindings" array`, "wrong-shaped field");
1394
+ return [];
1395
+ }
1396
+ if (!Array.isArray(value.bindings)) throw bindingSetError(`"${field}.bindings" must be an array`, "wrong-shaped field");
1397
+ return strictBindingEntries(value.bindings, "name", `${field}.bindings`);
1398
+ }
1399
+ function singletonBindingEntry(field, value, bindingRequired) {
1400
+ if (value === void 0) return [];
1401
+ if (!isRecord(value)) throw bindingSetError(`"${field}" must be an object with a "binding"`, "wrong-shaped field");
1402
+ if (typeof value.binding === "string" && value.binding.length > 0) return [{
1403
+ name: value.binding,
1404
+ entry: value
1405
+ }];
1406
+ if (value.binding !== void 0) throw bindingSetError(`"${field}" has a malformed "binding" (expected a non-empty string)`, "dropped binding");
1407
+ if (bindingRequired) throw bindingSetError(`"${field}" requires a "binding" (a non-empty string)`, "dropped binding");
1408
+ return [];
1409
+ }
1410
+ /** The keys of a key-map field are its binding names; the values are never read. */
1411
+ function keyMapBindingNames(field, value) {
1412
+ if (value === void 0) return [];
1413
+ if (!isRecord(value)) throw bindingSetError(`"${field}" must be an object mapping names to values`, "wrong-shaped field");
1414
+ return Object.keys(value).filter((key) => value[key] !== void 0);
1415
+ }
1416
+ /**
1417
+ * Read `keyField` from every member, paired with the member. A malformed member throws:
1418
+ * dropping it could hide an existing binding from the uniqueness check.
1419
+ */
1420
+ function strictBindingEntries(members, keyField, field) {
1421
+ return members.map((member, index) => {
1422
+ if (!isRecord(member) || typeof member[keyField] !== "string" || member[keyField].length === 0) throw bindingSetError(`"${field}" contains a malformed entry at index ${index} (missing a non-empty string "${keyField}")`, "dropped entry");
1423
+ return {
1424
+ name: member[keyField],
1425
+ entry: member
1426
+ };
1427
+ });
1428
+ }
1429
+ /** A binding field that cannot be read completely; a missed name could hide a collision. */
1430
+ function bindingSetError(problem, hidden) {
1431
+ return /* @__PURE__ */ new Error(`deploy: cannot verify binding-name uniqueness — ${problem}. Refusing to proceed on a partially-readable binding set (a ${hidden} could hide a real collision). Fix the wrangler config and retry.`);
1432
+ }
1433
+ /**
1434
+ * Whether two `migrations_dir` values name the same folder. Wrangler resolves the value
1435
+ * against the config file's directory and accepts either slash.
1436
+ */
1437
+ function sameMigrationsDir(configPath, a, b) {
1438
+ const base = dirname(configPath);
1439
+ return resolve(base, a.replaceAll("\\", "/")) === resolve(base, b.replaceAll("\\", "/"));
1440
+ }
1441
+ /** Wrangler's rule: the normalized pattern starts with `<dir>/`, unless the dir is ".". */
1442
+ function migrationsPatternMatchesDir(pattern, dir) {
1443
+ const normalizedDir = normalizeMigrationsPath(dir);
1444
+ if (normalizedDir === ".") return true;
1445
+ return normalizeMigrationsPath(pattern).startsWith(`${normalizedDir}/`);
1446
+ }
1447
+ /** Wrangler's `normalizeRelativePath`: forward slashes, normalized, no trailing slash. */
1448
+ function normalizeMigrationsPath(p) {
1449
+ const normalized = normalize(p.replace(/\\/g, "/"));
1450
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
1451
+ }
1452
+ export { writeProvisionedWranglerConfig as A, readWranglerWebSocketTombstones as C, syncWranglerDurableObjects as D, syncWranglerBindings as E, writeBwfProjectConfig as F, GENERATED_MARKERS as M, canRewriteBwfProjectConfig as N, syncWranglerWebSockets as O, renderBwfConfig as P, readWranglerPublishedTrafficSnapshot as S, sameMigrationsDir as T, readProvisionedBindingEntry as _, LIVE_MIGRATION_TAG as a, readWranglerCustomDomains as b, bindingEntriesForField as c, findBindingNameOwner as d, hasDurableObjectSqliteMigration as f, readExistingLiveBindingConfig as g, persistMaterializedWranglerConfig as h, LATEST_KNOWN_COMPAT_DATE as i, writeWranglerPublishedTrafficSnapshot as j, updateWranglerCustomDomain as k, bindingNamesForField as l, normalizeWranglerCompatibilityFlags as m, DEFAULT_LIVE_CLASS as n, acknowledgeWranglerManagedQueueRemovals as o, nextDurableObjectMigrationTag as p, FRIENDLY_BINDING_NAMES as r, assertNoDuplicateMembers as s, DEFAULT_LIVE_BINDING as t, ensureWranglerCompat as u, readRootWranglerConfig as v, resolveLiveBindingConfig as w, readWranglerManagedQueueCleanupCandidates as x, readWranglerCompat as y };