@builtbyfriends/bwf 0.0.0-stage → 1.9.2

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-Ddt8lGeL.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-CCl-hJol.mjs +26 -0
  17. package/dist/auth-migrations-DDeifS3v.mjs +206 -0
  18. package/dist/auth-router-BG74WFUf.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-BfYf6fnB.mjs +1846 -0
  40. package/dist/client-D3D5RM5h.mjs +940 -0
  41. package/dist/client-VF2Nzc7Z.mjs +1 -0
  42. package/dist/cloudflare-auth-DzkU9H6r.mjs +152 -0
  43. package/dist/cloudflare-cmd-Bm6UhzAQ.mjs +59 -0
  44. package/dist/cloudflare-config-i8yanry0.mjs +186 -0
  45. package/dist/cloudflare-connect-B4ItSbJi.mjs +55 -0
  46. package/dist/cloudflare-operations-BcK849ue.mjs +1 -0
  47. package/dist/cloudflare-operations-DGF7xH7O.mjs +627 -0
  48. package/dist/cloudflare-process-tThIjEB2.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-CSNWKLzB.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-SOv4E9wr.mjs +1735 -0
  65. package/dist/delete-BSKI7V23.mjs +65 -0
  66. package/dist/deploy-BCSQoKC0.mjs +2 -0
  67. package/dist/deploy-CWJ3JJs_.mjs +6512 -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-BJaAbxuQ.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-C_ATvNIG.mjs +2865 -0
  84. package/dist/email-cloudflare-oXk2G1G3.mjs +854 -0
  85. package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
  86. package/dist/email-rIfZgVAB.mjs +742 -0
  87. package/dist/env-BGTu3KWZ.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-BlXzGgLZ.mjs +1 -0
  97. package/dist/env-validation-DeqFUSKg.mjs +488 -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-B_ocHStk.d.mts +279 -0
  111. package/dist/handler-CNq7aSs1.mjs +161 -0
  112. package/dist/help-BK35YcRa.mjs +1946 -0
  113. package/dist/help-DaRezBj7.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-CXanf5ck.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-B1WAE9Wt.mjs +130 -0
  124. package/dist/live-KkEeda1Z.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-bUoAtFUe.mjs +103 -0
  128. package/dist/log-JDnPc0cF.mjs +23 -0
  129. package/dist/login-BUzyiyHV.mjs +1 -0
  130. package/dist/login-Dbv_T3Ru.mjs +87 -0
  131. package/dist/logs-BjMJooJQ.mjs +129 -0
  132. package/dist/migrate-DjW9_-sS.mjs +1 -0
  133. package/dist/migrate-DtcfKqPW.mjs +125 -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-BiGmSlZx.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-BsHKYJYt.mjs +1 -0
  145. package/dist/operator-cmd-DTIkOAnP.mjs +443 -0
  146. package/dist/output-Bb34lF0w.mjs +173 -0
  147. package/dist/output-CVolXKC1.mjs +1 -0
  148. package/dist/package-BX_giUBX.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-C-DyuCNX.mjs +1 -0
  155. package/dist/platform-args-CyeQWaZ7.mjs +538 -0
  156. package/dist/platform-auth-config-BfXqKSyZ.mjs +371 -0
  157. package/dist/platform-auth-protection-5FR6qoP_.mjs +231 -0
  158. package/dist/platform-auth-recovery-B5ZlqA8K.mjs +309 -0
  159. package/dist/platform-cmd-CcFDxtrl.mjs +1 -0
  160. package/dist/platform-cmd-ChXeBrRH.mjs +193 -0
  161. package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
  162. package/dist/platform-domain-CwatS3cz.mjs +256 -0
  163. package/dist/platform-lifecycle-0cXTmMsh.mjs +8928 -0
  164. package/dist/platform-lifecycle-BcoBAMux.mjs +1 -0
  165. package/dist/platform-management-6Wbdbob5.mjs +1607 -0
  166. package/dist/platform-management-hhnczOzr.mjs +1 -0
  167. package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
  168. package/dist/platform-recovery-DgIwlqB-.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-DX8y_6Kh.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-BydRwr-x.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-BA59NCPO.mjs +1 -0
  188. package/dist/provision-C90fULHJ.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-wi6WK5T6.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-BjSoQ-mW.mjs +1 -0
  209. package/dist/runner-mysql-BmTI2EiF.mjs +145 -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-D5XrWshs.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-DPhqnpaa.mjs +23 -0
  343. package/dist/wrangler-C3uyPadQ.mjs +1 -0
  344. package/dist/wrangler-TqTvJFWS.mjs +1452 -0
  345. package/dist/ws-DZRiIpYw.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
package/dist/index.mjs ADDED
@@ -0,0 +1,4163 @@
1
+ import { n as __toESM } from "./rolldown-runtime-uD8oG6U2.mjs";
2
+ import { a as join, c as resolve, i as isAbsolute, n as dirname, s as relative, t as basename } from "./dist-DMYe8CZJ.mjs";
3
+ import { t as require_picocolors } from "./picocolors-D1NxSLw-.mjs";
4
+ import { C as isIdentifier, E as applyBindingOverrides, S as bindingResolver, T as isMemberExpression, _ as isRouteEnabledForEnvironment, a as hasSandboxSqliteMigration, c as resolveSandboxConfig, d as scanQueuesSync, f as readAppIdentity, i as assertSandboxNamespaceConfig, l as sandboxContainerConfig, m as invalidateSourceAnalysis, n as DEFAULT_SANDBOX_CLASS_NAME, o as isSandboxAttached, p as DEFAULT_SCAN_DIRS, r as SANDBOX_MIGRATION_TAG, t as analyzeApplicationSync, v as inferBindingsFromSource, w as isLiteral, x as scanJobsSync } from "./application-analysis-C9Ck2Yeg.mjs";
5
+ import { c as resolveAssetWorkerBypass, d as hasApiRoutes, f as hasDocumentRoutes, i as mergeRoutingRules, m as resolveAssetRoutingPolicy, n as resolveWorkerDirName, o as isAssetBypassRule, r as lintRoutingPhases, s as isGeneratedAssetHeaders, t as resolveDistDir, u as edgeRulesNeedWorker } from "./build-output-dir-Clj_unKN.mjs";
6
+ import { n as readDeploymentPlatform, r as readProjectConfig } from "./project-CC7eN00D.mjs";
7
+ import { C as readWranglerWebSocketTombstones, D as syncWranglerDurableObjects, O as syncWranglerWebSockets, a as LIVE_MIGRATION_TAG, d as findBindingNameOwner, f as hasDurableObjectSqliteMigration, g as readExistingLiveBindingConfig, m as normalizeWranglerCompatibilityFlags, p as nextDurableObjectMigrationTag, u as ensureWranglerCompat, w as resolveLiveBindingConfig, y as readWranglerCompat } from "./wrangler-TqTvJFWS.mjs";
8
+ import { c as stashCloudflareDeployPointer, i as materializeCloudflareConfig, o as restoreCloudflarePreviewPointer } from "./cloudflare-config-i8yanry0.mjs";
9
+ import { a as removeAuthTypesIfPresent, c as generateDbDts, n as generateQueueTypes, o as syncAuthTypesFile, r as generateProcedureTypes, s as DRIZZLE_OPERATORS, t as generateRouteTypes, u as syncBindingTypes } from "./route-types-CRWhr93D.mjs";
10
+ import { c as getDatabaseCasing, f as readConfig, l as getDatabaseDialect } from "./config-tNx0HlFv.mjs";
11
+ import { n as writeLocalD1PersistState, t as resolveLocalD1Target } from "./local-d1-bUoAtFUe.mjs";
12
+ import { n as bwfLog, r as bwfWarn, t as bwfError } from "./log-JDnPc0cF.mjs";
13
+ import { a as getApiUrl, c as getToken, o as getProxyUrl } from "./auth-xnkmpZUl.mjs";
14
+ import { n as ensurePlatformProxyAccess } from "./cf-access-Bhz9wX6p.mjs";
15
+ import { n as scopedAccessCredentials } from "./cf-access-CUP5L08W.mjs";
16
+ import { n as readGeneratedWranglerConfigFile } from "./generated-wrangler-config-CoDaaFsA.mjs";
17
+ import { t as migrateBuiltWranglerConfig } from "./cf-config-migrate-COOCi4Ge.mjs";
18
+ import { t as writeFileAtomic } from "./atomic-write-DA6eD1Kp.mjs";
19
+ import { a as findReservedEnvKeys, c as loadLocalEnv, i as findLegacyEnvFiles, l as reservedEnvKeysMessage, o as isClientEnvKey, r as LOCAL_ENV_FILE, s as legacyEnvExampleHint, u as resolveRemoteMode } from "./env-DUyTzroe.mjs";
20
+ import { n as readProjectPaths, t as assertNoRootSourceConventionConflicts } from "./project-paths-iXHKRTTQ.mjs";
21
+ import { i as writeFileIfChanged, n as ensureProjectTsconfig, r as syncAuthTypesInProjectTsconfig } from "./project-tsconfig-P9X952KG.mjs";
22
+ import { t as discoverSchema } from "./discover-DJPmQcL5.mjs";
23
+ import { _ as parseCapturedMessage, a as DEV_INBOX_ENV_VAR, c as DEV_INBOX_TOKEN_ENV_VAR, f as clearDevBuffer, g as listDevMessages, l as DEV_INBOX_TOKEN_HEADER, m as findDevMessage, n as DEV_INBOX_ACK_VALUE, o as DEV_INBOX_MAX_CAPTURE_BYTES, s as DEV_INBOX_PREFIX, t as DEV_INBOX_ACK_HEADER, u as DEV_INBOX_TOKEN_QUERY, v as pushToDevBuffer } from "./dev-inbox-I0nqTCdf.mjs";
24
+ import { t as MagicString } from "./dist-B6eN80gc.mjs";
25
+ import { n as findEnvFileForPaths, r as generateEnvTypes, t as findEnvFile } from "./env-types-Bg-dTh8u.mjs";
26
+ import { t as loadUserEnvFile } from "./load-user-env-g0ahkZcj.mjs";
27
+ import { n as scanWranglerDotenvKeys } from "./dotenv-4NdUCXbB.mjs";
28
+ import { i as loadBwfAuthConfig, n as devAuthConfigImporter, o as viteAuthConfigImporter, t as AUTH_CONFIG_ENVIRONMENT } from "./config-CN_RFRkS.mjs";
29
+ import { n as completeApplicationAnalysis } from "./application-routing-DbR-W5lG.mjs";
30
+ import { d as cloudflareQueueName, n as SEND_EMAIL_BINDING, p as readDeployBuildQueueNames } from "./email-cloudflare-oXk2G1G3.mjs";
31
+ import { t as INTERNAL_BINDING_PREFIXES } from "./env-raw-Bo6TtrHU.mjs";
32
+ import { t as ASSET_EXTENSIONS } from "./routing-assets-CSheDWWM.mjs";
33
+ import { r as selectNativeVersionMetadataBinding, t as CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from "./version-metadata-DPhqnpaa.mjs";
34
+ import { a as defineQueue, i as defineMiddleware, n as basicAuth, o as defineScheduled, r as defineHandler, t as BwfAssetRewriteError } from "./handler-CNq7aSs1.mjs";
35
+ import { builtinModules, createRequire } from "node:module";
36
+ import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
37
+ import { createRunnableDevEnvironment, isRunnableDevEnvironment, loadEnv, normalizePath, parseSync, resolveEnvPrefix } from "vite";
38
+ import { fileURLToPath, pathToFileURL } from "node:url";
39
+ import { appendSqliteClassMigration } from "@builtbyfriends/deploy-core";
40
+ import { randomBytes, timingSafeEqual } from "node:crypto";
41
+ import { homedir } from "node:os";
42
+ import { isDeepStrictEqual, parseEnv } from "node:util";
43
+ import { getRootConfigPath, getWorkerAssetsDir, getWorkerConfigPath, readBuildOutput } from "@cloudflare/build-output-utils";
44
+ import { convertToWranglerConfig } from "@cloudflare/config";
45
+ import { cloudflare } from "@cloudflare/vite-plugin";
46
+ import { parse } from "smol-toml";
47
+ import { compilePattern, matchPattern } from "@builtbyfriends/edge";
48
+ // src/plugin-ai-setup.ts
49
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
50
+ /**
51
+ * Decide whether to inject a Workers AI binding into the built wrangler config.
52
+ *
53
+ * Builds use the production binding. During dev, a project explicitly saved
54
+ * with the direct Cloudflare destination uses Cloudflare's remote binding;
55
+ * managed and unsaved projects keep using the bwf HTTPS proxy.
56
+ *
57
+ * `!resolvedAi` is load-bearing: mergeBindings' return is defu-merged over the
58
+ * resolved root-wrangler config and wins, so skipping when the user already
59
+ * declared an `ai` binding avoids clobbering theirs. `!resultAi` is harmless
60
+ * defense-in-depth (nothing else in mergeBindings sets `result.ai`).
61
+ */
62
+ function shouldBindWorkersAi(command, needsAI, resolvedAi, resultAi, directCloudflareDev = false) {
63
+ return needsAI && (command === "build" || command === "serve" && directCloudflareDev) && !resultAi && !resolvedAi;
64
+ }
65
+ /** Resolve the runtime Workers AI binding, preserving a root Wrangler declaration. */
66
+ function resolveWorkersAiBindingName(resolvedAi, configuredName) {
67
+ if (typeof resolvedAi === "object" && resolvedAi !== null) {
68
+ const binding = resolvedAi.binding;
69
+ if (typeof binding === "string") return binding;
70
+ }
71
+ return configuredName ?? "AI";
72
+ }
73
+ /**
74
+ * Read bwf auth credentials for local dev AI proxy access.
75
+ * Returns a discriminated union so callers can distinguish
76
+ * "no token" from "no project" for targeted onboarding guidance.
77
+ */
78
+ function readBwfDevCredentials(root) {
79
+ const token = getToken(root);
80
+ if (!token) return { status: "no-token" };
81
+ const apiUrl = getApiUrl(root);
82
+ const project = readProjectConfig(root);
83
+ if (!project) return {
84
+ status: "no-project",
85
+ apiUrl,
86
+ token
87
+ };
88
+ const proxyUrl = getProxyUrl(root);
89
+ ensurePlatformProxyAccess(apiUrl, proxyUrl);
90
+ return {
91
+ status: "ok",
92
+ token,
93
+ projectId: project.projectId,
94
+ proxyUrl,
95
+ accessCredentials: scopedAccessCredentials(process.env, proxyUrl)
96
+ };
97
+ }
98
+ /**
99
+ * Interactive AI setup prompt shown during dev server startup when the user
100
+ * has a token but no linked project. Runs as fire-and-forget so it doesn't
101
+ * block the server. On completion, writes project.json and restarts the server.
102
+ */
103
+ async function runAiSetupPrompt(root, token, apiUrl, server) {
104
+ const { select, text, isCancel, log } = await import("./dist-Cp4b1_T9.mjs");
105
+ const { PlatformClient } = await import("./client-VF2Nzc7Z.mjs");
106
+ const { attachSelectedPlatform, writeProjectConfig } = await import("./project-DcSd4BeI.mjs");
107
+ const { inferDefaultSlug } = await import("./resolve-project-DhU9_lIo.mjs");
108
+ const { printSuccess } = await import("./output-CVolXKC1.mjs");
109
+ const client = new PlatformClient(token, { apiUrl });
110
+ let projects;
111
+ try {
112
+ projects = await client.listProjects();
113
+ } catch {
114
+ bwfWarn("Failed to fetch projects. Run `bwf project link` to link a project manually.");
115
+ return;
116
+ }
117
+ const options = [{
118
+ value: "__create__",
119
+ label: "Create new project"
120
+ }, ...projects.map((p) => ({
121
+ value: p.id,
122
+ label: p.slug
123
+ }))];
124
+ console.log();
125
+ log.info("[bwf] AI requires a linked project. Let's set one up:");
126
+ const result = await select({
127
+ message: "Select a project:",
128
+ options
129
+ });
130
+ if (isCancel(result)) return;
131
+ let projectId;
132
+ let slug;
133
+ if (result === "__create__") {
134
+ const { validateProjectSlug } = await import("./project-slug-BUy0lmyR.mjs");
135
+ const { createProjectWithSlugRetry } = await import("./create-project-tJ1KwNss.mjs");
136
+ let created;
137
+ try {
138
+ created = await createProjectWithSlugRetry(client, inferDefaultSlug(root), async (defaultSlug) => {
139
+ const slugResult = await text({
140
+ message: "Choose a slug for your new bwf project:",
141
+ placeholder: "my-app",
142
+ initialValue: defaultSlug,
143
+ validate: validateProjectSlug
144
+ });
145
+ if (isCancel(slugResult) || typeof slugResult === "symbol") return;
146
+ return slugResult.trim();
147
+ });
148
+ } catch (err) {
149
+ bwfError(`project: Failed to create project: '${err instanceof Error ? err.message : String(err)}'.`);
150
+ return;
151
+ }
152
+ if (!created) return;
153
+ projectId = created.id;
154
+ slug = created.slug;
155
+ } else {
156
+ const project = projects.find((p) => p.id === result);
157
+ projectId = project.id;
158
+ slug = project.slug;
159
+ }
160
+ writeProjectConfig(root, attachSelectedPlatform({
161
+ projectId,
162
+ slug
163
+ }, client.apiUrl));
164
+ await server.restart();
165
+ printSuccess(`Linked to ${slug}.`);
166
+ }
167
+ // src/plugin-binding-runtime.ts
168
+ const envModuleResolved$1 = fileURLToPath(import.meta.resolve("#self/_env"));
169
+ const kvModuleResolved = fileURLToPath(import.meta.resolve("@builtbyfriends/bwf/kv"));
170
+ const storageModuleResolved = fileURLToPath(import.meta.resolve("@builtbyfriends/bwf/storage"));
171
+ const VIRTUAL_KV_ID = "\0virtual:nosam-kv";
172
+ const VIRTUAL_STORAGE_ID = "\0virtual:nosam-storage";
173
+ function bindingRuntimePlugin(bindingNames) {
174
+ return {
175
+ name: "nosam:binding-runtime",
176
+ enforce: "pre",
177
+ resolveId: {
178
+ filter: { id: /^(@builtbyfriends\/bwf\/kv|@builtbyfriends\/bwf\/storage)$/ },
179
+ handler(id) {
180
+ if (this.environment?.name === "client") return;
181
+ if (id === "@builtbyfriends/bwf/kv" && bindingNames?.kv) return VIRTUAL_KV_ID;
182
+ if (id === "@builtbyfriends/bwf/storage" && bindingNames?.r2) return VIRTUAL_STORAGE_ID;
183
+ }
184
+ },
185
+ load: {
186
+ filter: { id: /^\0virtual:nosam-(?:kv|storage)$/ },
187
+ handler(id) {
188
+ if (id === VIRTUAL_KV_ID) return `
189
+ import { requireRuntimeBinding } from ${JSON.stringify(envModuleResolved$1)};
190
+ import { createKV } from ${JSON.stringify(kvModuleResolved)};
191
+
192
+ const namespace = new Proxy({}, {
193
+ get(_, prop) {
194
+ const ns = requireRuntimeBinding(${JSON.stringify(bindingNames?.kv)});
195
+ const value = Reflect.get(ns, prop, ns);
196
+ return typeof value === 'function' ? value.bind(ns) : value;
197
+ },
198
+ });
199
+
200
+ export { createKV };
201
+ export const kv = createKV(namespace);
202
+ `;
203
+ if (id === VIRTUAL_STORAGE_ID) return `
204
+ import { requireRuntimeBinding } from ${JSON.stringify(envModuleResolved$1)};
205
+ export { createStorage } from ${JSON.stringify(storageModuleResolved)};
206
+
207
+ export const storage = new Proxy({}, {
208
+ get(_, prop) {
209
+ const bucket = requireRuntimeBinding(${JSON.stringify(bindingNames?.r2)});
210
+ const value = Reflect.get(bucket, prop, bucket);
211
+ return typeof value === 'function' ? value.bind(bucket) : value;
212
+ },
213
+ });
214
+ `;
215
+ }
216
+ }
217
+ };
218
+ }
219
+ // src/plugin-client-stubs.ts
220
+ function createClientStubsPlugin() {
221
+ const STUB_PREFIX = "\0nosam-client-stub:";
222
+ const SERVER_ONLY_STUBS = {
223
+ "@builtbyfriends/bwf/db": "export const db = {}; export const createDb = () => ({});",
224
+ "@builtbyfriends/bwf/kv": "export const kv = {}; export const createKV = () => ({});",
225
+ "@builtbyfriends/bwf/ai": "export const ai = {};",
226
+ "@builtbyfriends/bwf/queues": "export const queues = {};",
227
+ "@builtbyfriends/bwf/storage": "export const storage = {}; export const createStorage = () => ({});",
228
+ "@builtbyfriends/bwf/sandbox": `
229
+ export class SandboxLimitError extends Error {
230
+ constructor(reason = 'concurrency', message) {
231
+ super(message ?? 'Sandbox limit reached: ' + reason);
232
+ this.name = 'SandboxLimitError';
233
+ this.reason = reason;
234
+ }
235
+ }
236
+ export class SandboxUnavailableError extends Error {
237
+ constructor(message = 'Managed Sandbox is unavailable on this bwf platform.') {
238
+ super(message);
239
+ this.name = 'SandboxUnavailableError';
240
+ }
241
+ }
242
+ export async function getSandbox() {
243
+ throw new Error('@builtbyfriends/bwf/sandbox is server-only and cannot be imported by browser code.');
244
+ }
245
+ export const sandbox = { get: getSandbox };
246
+ `,
247
+ "@builtbyfriends/bwf/email": `
248
+ const serverOnly = (name) => () => {
249
+ throw new Error(name + ' is server-only and cannot be imported by browser code.');
250
+ };
251
+ export const sendEmail = serverOnly('sendEmail');
252
+ export const createEmail = serverOnly('createEmail');
253
+ export const defineEmail = serverOnly('defineEmail');
254
+ export const parseEmail = serverOnly('parseEmail');
255
+ export const replyEmail = serverOnly('replyEmail');
256
+ export const createMessageProxy = serverOnly('createMessageProxy');
257
+ `,
258
+ "@builtbyfriends/bwf/email/testing": `
259
+ const serverOnly = (name) => () => {
260
+ throw new Error(name + ' is server-only and cannot be imported by browser code.');
261
+ };
262
+ export const createEmailTestHarness = serverOnly('createEmailTestHarness');
263
+ export const createInboundTestHarness = serverOnly('createInboundTestHarness');
264
+ `,
265
+ "@builtbyfriends/bwf/live": "",
266
+ "@builtbyfriends/bwf/durable": ""
267
+ };
268
+ const STUB_RESOLVE_FILTER = new RegExp(`^(${Object.keys(SERVER_ONLY_STUBS).join("|").replaceAll("/", "\\/")})$`);
269
+ const STUB_LOAD_FILTER = new RegExp(`^\\0nosam-client-stub:`);
270
+ return {
271
+ name: "nosam:client-stubs",
272
+ enforce: "pre",
273
+ resolveId: {
274
+ filter: { id: STUB_RESOLVE_FILTER },
275
+ handler(id) {
276
+ if (this.environment?.name === "client") {
277
+ if (id === "@builtbyfriends/bwf/live" || id === "@builtbyfriends/bwf/durable") this.error(id === "@builtbyfriends/bwf/live" ? "@builtbyfriends/bwf/live is server-only and cannot be imported by browser code. Import bwf/live/client instead." : "@builtbyfriends/bwf/durable is server-only and cannot be imported by browser code.");
278
+ return STUB_PREFIX + id;
279
+ }
280
+ }
281
+ },
282
+ load: {
283
+ filter: { id: STUB_LOAD_FILTER },
284
+ handler(id) {
285
+ return SERVER_ONLY_STUBS[id.slice(19)] ?? "export default {};";
286
+ }
287
+ }
288
+ };
289
+ }
290
+ // src/plugin-cloudflare-config.ts
291
+ /** Match the old plugin's patch semantics, including its array concatenation. */
292
+ function mergeCloudflareConfig(patch, fallback) {
293
+ const result = { ...fallback };
294
+ for (const [key, value] of Object.entries(patch)) {
295
+ if (value === void 0) continue;
296
+ const previous = result[key];
297
+ result[key] = Array.isArray(value) && Array.isArray(previous) ? [...value, ...previous] : value && previous && typeof value === "object" && typeof previous === "object" && !Array.isArray(value) && !Array.isArray(previous) ? mergeCloudflareConfig(value, previous) : value;
298
+ }
299
+ return result;
300
+ }
301
+ /** Use Cloudflare's public migration API rather than maintaining a second binding translator. */
302
+ function toNativeCloudflareConfig(raw, root) {
303
+ const packagePath = join(root, "package.json");
304
+ const packageName = existsSync(packagePath) ? JSON.parse(readFileSync(packagePath, "utf8")).name : void 0;
305
+ const name = String(packageName ?? basename(root)).replaceAll("_", "-").replace(/[^a-z0-9- ]/g, "-").replace(/^(-+)|(-+)$/g, "").slice(0, 63) || "my-worker";
306
+ const { env, vars, ...base } = raw;
307
+ const selected = process.env.CLOUDFLARE_ENV ? env?.[process.env.CLOUDFLARE_ENV] : void 0;
308
+ const values = selected ? selected.vars : vars;
309
+ const environments = env && Object.fromEntries(Object.entries(env).map(([name, { vars: _vars, ...config }]) => [`nosam-environment-${name}`, config]));
310
+ const config = migrateBuiltWranglerConfig({
311
+ name,
312
+ compatibility_date: "2026-02-24",
313
+ ...base,
314
+ ...environments && process.env.CLOUDFLARE_ENV ? { env: environments } : {}
315
+ }, process.env.CLOUDFLARE_ENV ? `nosam-environment-${process.env.CLOUDFLARE_ENV}` : "nosam-top-level");
316
+ if (!config.worker) throw new Error("bwf requires a Cloudflare Worker configuration.");
317
+ for (const [name, value] of Object.entries(values ?? {})) {
318
+ config.worker.env ??= {};
319
+ config.worker.env[name] = typeof value === "string" ? {
320
+ type: "text",
321
+ value
322
+ } : {
323
+ type: "json",
324
+ value
325
+ };
326
+ }
327
+ const main = selected?.main ?? raw.main;
328
+ if (main) config.worker.entrypoint = main.startsWith("virtual:") ? main : resolve(root, main);
329
+ return {
330
+ ...config,
331
+ worker: config.worker
332
+ };
333
+ }
334
+ /**
335
+ * Give Container Durable Objects a regular binding in the dev server. Their unsafe
336
+ * binding from `migrateBuiltWranglerConfig()` exists only for the Worker upload, and
337
+ * Miniflare skips unsafe bindings without a dev plugin. Match only that generated form:
338
+ * any other unsafe binding comes from the user's config and may name another Worker,
339
+ * even one with a class of the same name, so it stays as written.
340
+ */
341
+ function restoreLocalContainerBindings(worker) {
342
+ for (const [name, binding] of Object.entries(worker.env ?? {})) {
343
+ if (binding.type !== "unsafe:durable_object_namespace" || Object.keys(binding).some((key) => !["type", "class_name"].includes(key))) continue;
344
+ const className = binding.class_name;
345
+ const declaration = worker.exports?.[className];
346
+ if (declaration && "container" in declaration) worker.env[name] = {
347
+ type: "durable-object",
348
+ worker: worker.name,
349
+ exportName: className
350
+ };
351
+ }
352
+ }
353
+ function nativeAuxiliaryWorkers(workers, root) {
354
+ return workers?.map(({ configPath, config, ...options }) => ({
355
+ ...options,
356
+ config({ entryWorkerConfig }) {
357
+ const path = configPath ? resolve(root, configPath) : void 0;
358
+ const base = path ? path.endsWith(".toml") ? parse(readFileSync(path, "utf8")) : readGeneratedWranglerConfigFile(path) : {};
359
+ return toNativeCloudflareConfig(mergeCloudflareConfig((typeof config === "function" ? config(base, { entryWorkerConfig: convertToWranglerConfig({
360
+ worker: entryWorkerConfig,
361
+ containers: []
362
+ }) }) : config) ?? {}, base), path ? dirname(path) : root).worker;
363
+ }
364
+ }));
365
+ }
366
+ // src/plugin-cloudflare-preview.ts
367
+ /** Give preview local bindings without changing the deployable build or storing their values. */
368
+ function withLocalPreviewBindings(plugins, root) {
369
+ let directory;
370
+ const cleanup = () => {
371
+ if (directory) {
372
+ rmSync(directory, {
373
+ recursive: true,
374
+ force: true
375
+ });
376
+ directory = void 0;
377
+ }
378
+ process.removeListener("exit", cleanup);
379
+ };
380
+ const entry = plugins.find((plugin) => plugin.name === "vite-plugin-cloudflare");
381
+ if (!entry?.config) throw new Error("The Cloudflare plugin no longer exposes its configuration hook.");
382
+ const hook = typeof entry.config === "function" ? entry.config : entry.config.handler;
383
+ entry.config = async function(config, environment) {
384
+ if (!environment.isPreview) return hook.call(this, config, environment);
385
+ cleanup();
386
+ const parent = join(root, ".bwf");
387
+ mkdirSync(parent, { recursive: true });
388
+ directory = mkdtempSync(join(parent, "preview-"));
389
+ process.once("exit", cleanup);
390
+ try {
391
+ const output = dirname(getRootConfigPath(root));
392
+ cpSync(output, dirname(getRootConfigPath(directory)), { recursive: true });
393
+ const path = getWorkerConfigPath(directory);
394
+ const worker = JSON.parse(readFileSync(path, "utf8"));
395
+ worker.env ??= {};
396
+ for (const name of Object.keys(loadLocalEnv(root))) {
397
+ const binding = worker.env[name];
398
+ if (!binding || [
399
+ "text",
400
+ "json",
401
+ "secret"
402
+ ].includes(binding.type)) worker.env[name] = { type: "secret" };
403
+ }
404
+ writeFileAtomic(path, JSON.stringify(worker));
405
+ return await hook.call(this, {
406
+ ...config,
407
+ root: directory,
408
+ envDir: root
409
+ }, environment);
410
+ } catch (error) {
411
+ cleanup();
412
+ throw error;
413
+ }
414
+ };
415
+ return [...plugins, {
416
+ name: "nosam:cloudflare-preview-cleanup",
417
+ configurePreviewServer(server) {
418
+ server.httpServer.once("close", cleanup);
419
+ }
420
+ }];
421
+ }
422
+ // src/plugin-dev-config.ts
423
+ /**
424
+ * Whether Vite is resolving the server that Vitest creates to run tests, whatever its `--mode`.
425
+ * Vitest adds its own plugins (`vitest`, `vitest:*`) to that server's config; a server that a
426
+ * test starts through Vite's API has none. Vitest runs test files in Node.js, so bwf starts no
427
+ * Worker there, applies no local migrations and asks no questions. Check these names again when
428
+ * updating Vitest: `test/integration/vitest-app.test.ts` runs the tests of bwf apps.
429
+ */
430
+ function isVitestServer(config) {
431
+ const pending = [...config.plugins ?? []];
432
+ while (pending.length > 0) {
433
+ const plugin = pending.pop();
434
+ if (Array.isArray(plugin)) pending.push(...plugin);
435
+ else if (plugin && "name" in plugin && typeof plugin.name === "string" && (plugin.name === "vitest" || plugin.name.startsWith("vitest:"))) return true;
436
+ }
437
+ return false;
438
+ }
439
+ /** Run `fn` shortly after Vite prints "ready" so dev messages stay visible. */
440
+ function afterServerReady(server, fn) {
441
+ if (server.httpServer) server.httpServer.once("listening", () => setTimeout(fn, 100));
442
+ else fn();
443
+ }
444
+ /**
445
+ * Best-effort detection of `vite build` (and `vite preview`) so we can skip
446
+ * dev-only side effects — writing the dev-trigger token and the dispatch
447
+ * file — when no dev server will run. Vite's CLI passes the subcommand as
448
+ * `process.argv[2]`; programmatic API users (and `vite` with no subcommand)
449
+ * default to `dev`, which we detect as the absence of a build-shaped first
450
+ * positional. This is intentionally permissive: when in doubt, we behave as
451
+ * if we're in dev so first-request correctness is preserved.
452
+ */
453
+ function isViteBuildOrPreview() {
454
+ const subcommand = process.argv[2];
455
+ return subcommand === "build" || subcommand === "preview";
456
+ }
457
+ /**
458
+ * Point Cloudflare remote bindings opened in this process at the login from
459
+ * `bwf connect` and `bwf cloudflare login`. The Cloudflare Vite plugin and
460
+ * Wrangler's platform proxy authenticate remote bindings here, in dev, preview
461
+ * and build. They read cf's login only when `CLOUDFLARE_CF_AUTH`
462
+ * is present (any value), and Wrangler's separate login otherwise. The keyring
463
+ * flag selects the encrypted cf profile that bwf's login writes. Environment
464
+ * API tokens still take precedence, and the OAuth token stays in the store.
465
+ */
466
+ function selectBwfCloudflareLogin() {
467
+ process.env.CLOUDFLARE_CF_AUTH = "true";
468
+ process.env.CLOUDFLARE_AUTH_USE_KEYRING = "true";
469
+ }
470
+ const DEV_TRIGGER_TOKEN_FILE_MODE = 384;
471
+ /**
472
+ * Persist the dev-trigger token at `<root>/.bwf/dev-trigger-token` so
473
+ * every bwfPlugin() invocation against the same project reads the same
474
+ * value. This matters because `@cloudflare/vite-plugin` spawns a
475
+ * worker-environment child Vite that re-imports vite.config.ts and calls
476
+ * bwfPlugin() again — without persistence the parent and child would
477
+ * generate different UUIDs, the dispatch file would embed one and the
478
+ * hint plugin would print the other, and curls would land on
479
+ * `unauthorized`.
480
+ *
481
+ * The file persists across dev sessions and deploys so saved curl scripts
482
+ * keep working. It lives under `.bwf/` (gitignored) and is safe to remove.
483
+ *
484
+ * The file is owner-only (0600). It is the one credential the dev-inbox
485
+ * routes accept, and loopback is reachable by every account on the host,
486
+ * so a default-umask 0644 file would hand any other local user the raw MIME,
487
+ * the DELETE, and the capture endpoint. A file persisted by an earlier
488
+ * release is tightened in place, never rotated. Windows has no group/other
489
+ * bits — `mode` and `chmod` only toggle write there — so it is left alone.
490
+ */
491
+ function getOrCreateDevTriggerToken(root) {
492
+ const tokenPath = join(root, ".bwf", "dev-trigger-token");
493
+ const readExisting = () => {
494
+ try {
495
+ const existing = readFileSync(tokenPath, "utf-8").trim();
496
+ return existing.length > 0 ? existing : void 0;
497
+ } catch {
498
+ return;
499
+ }
500
+ };
501
+ const tightenExisting = () => {
502
+ if (process.platform === "win32") return;
503
+ try {
504
+ if ((statSync(tokenPath).mode & 63) !== 0) chmodSync(tokenPath, DEV_TRIGGER_TOKEN_FILE_MODE);
505
+ } catch {}
506
+ };
507
+ const existing = readExisting();
508
+ if (existing) {
509
+ tightenExisting();
510
+ return existing;
511
+ }
512
+ mkdirSync(join(root, ".bwf"), { recursive: true });
513
+ const fresh = crypto.randomUUID();
514
+ try {
515
+ const fd = openSync(tokenPath, "wx", DEV_TRIGGER_TOKEN_FILE_MODE);
516
+ try {
517
+ writeSync(fd, fresh);
518
+ } finally {
519
+ closeSync(fd);
520
+ }
521
+ return fresh;
522
+ } catch (err) {
523
+ if (err.code !== "EEXIST") throw err;
524
+ const winner = readExisting();
525
+ if (winner) return winner;
526
+ return fresh;
527
+ }
528
+ }
529
+ const DEV_TRIGGER_SECRET_PATH_RE = /(?:^|\/)\.bwf[. ]*\/(?:.*\/)?(?:dev-trigger|drizzle\.config\.json)/;
530
+ function isDevTriggerSecretRequest(url) {
531
+ if (!url) return false;
532
+ let path = url.split(/[?#]/, 1)[0] ?? "";
533
+ for (let i = 0; i < 3; i++) {
534
+ let decoded;
535
+ try {
536
+ decoded = decodeURIComponent(path);
537
+ } catch {
538
+ break;
539
+ }
540
+ if (decoded === path) break;
541
+ path = decoded;
542
+ }
543
+ return DEV_TRIGGER_SECRET_PATH_RE.test(path.replaceAll("\\", "/").toLowerCase());
544
+ }
545
+ /**
546
+ * Vite serves every root file that `server.fs.deny` does not list, and its default
547
+ * CORS lets any localhost origin read the reply, so the files above would hand their
548
+ * secrets to `--host` peers, other local accounts and other local dev servers.
549
+ * `server.fs.deny` is not used: a plugin's list replaces Vite's defaults, and the
550
+ * Cloudflare worker environment applies the same check when it imports
551
+ * `.bwf/dev-triggers.ts`. The middleware is added in configureServer, so it runs
552
+ * before Vite's transform, /@fs/ and static middlewares.
553
+ */
554
+ function devTriggerSecretGuardPlugin() {
555
+ return {
556
+ name: "nosam:dev-trigger-secret-guard",
557
+ apply: "serve",
558
+ enforce: "pre",
559
+ configureServer(server) {
560
+ server.middlewares.use((req, res, next) => {
561
+ if (!isDevTriggerSecretRequest(req.url)) {
562
+ next();
563
+ return;
564
+ }
565
+ res.statusCode = 404;
566
+ res.end("Not Found");
567
+ });
568
+ }
569
+ };
570
+ }
571
+ /**
572
+ * Warn when the project's `package.json` does not declare `"type": "module"`.
573
+ *
574
+ * Vite's default `configLoader: "bundle"` bundles `vite.config.ts`,
575
+ * externalizes deps, and then loads the bundle. When `package.json` is non-ESM
576
+ * the bundle is written as `.js` and loaded via CJS `require()`, which throws
577
+ * `ERR_REQUIRE_ASYNC_MODULE` if any externalized dep's ESM graph contains
578
+ * top-level await. `@cloudflare/vite-plugin` (which bwfPlugin pulls in) has
579
+ * exactly such a TLA, so non-ESM consumers hit this on every Vite invocation.
580
+ *
581
+ * Runs once per Vite process (factory time), single sync read.
582
+ */
583
+ function warnIfPackageJsonIsNotEsm(root) {
584
+ const pkgPath = join(root, "package.json");
585
+ if (!existsSync(pkgPath)) return;
586
+ let pkg;
587
+ try {
588
+ pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
589
+ } catch {
590
+ return;
591
+ }
592
+ if (pkg.type === "module") return;
593
+ bwfWarn("package.json is missing `\"type\": \"module\"`. Vite's default config loader will fail with ERR_REQUIRE_ASYNC_MODULE on transitive top-level await (e.g. @cloudflare/vite-plugin). Add `\"type\": \"module\"` to package.json, or run vite build with `--configLoader runner`.");
594
+ }
595
+ // src/plugin-cloudflare.ts
596
+ function isInside(directory, path) {
597
+ const child = relative(directory, path);
598
+ return child !== ".." && !child.startsWith("../") && !isAbsolute(child);
599
+ }
600
+ /**
601
+ * Vitest runs tests in Node.js, in a Vite server of its own that turns off dependency
602
+ * prebundling. The Cloudflare plugin needs prebundling to start the Worker, so the Worker would
603
+ * fail before any test runs. Leave these plugins out of that server; bwf's other plugins still
604
+ * resolve `@builtbyfriends/bwf/*`, `@schema` and the generated modules for tests.
605
+ */
606
+ function skipOnVitestServer(plugins) {
607
+ for (const plugin of plugins) {
608
+ const apply = plugin.apply;
609
+ plugin.apply = (config, environment) => !isVitestServer(config) && (typeof apply === "function" ? apply(config, environment) : apply === void 0 || apply === environment.command);
610
+ }
611
+ return plugins;
612
+ }
613
+ /** Keep bwf's public configuration and artifact layout while running the v2 plugin. */
614
+ function cloudflare$1(options) {
615
+ const root = process.cwd();
616
+ let workerConfig;
617
+ let native;
618
+ let pluginNative;
619
+ const outputDirectories = /* @__PURE__ */ new Map();
620
+ const bridge = {
621
+ name: "nosam:cloudflare-config",
622
+ config(_userConfig, environment) {
623
+ if (environment.isPreview) return;
624
+ let base = options.configPath ? readGeneratedWranglerConfigFile(options.configPath) : {};
625
+ if (process.env.CLOUDFLARE_ENV && base.env) {
626
+ const selected = base.env[process.env.CLOUDFLARE_ENV];
627
+ if (!selected) throw new Error(`Cloudflare environment ${process.env.CLOUDFLARE_ENV} is not configured.`);
628
+ const original = base;
629
+ base = convertToWranglerConfig(toNativeCloudflareConfig(base, root));
630
+ base.main = selected.main ?? original.main;
631
+ base.migrations = selected.migrations ?? original.migrations;
632
+ base.assets = {
633
+ ...base.assets,
634
+ directory: selected.assets?.directory ?? original.assets?.directory
635
+ };
636
+ }
637
+ workerConfig = mergeCloudflareConfig(options.config(base), base);
638
+ native = toNativeCloudflareConfig(workerConfig, root);
639
+ pluginNative = structuredClone(native);
640
+ if (environment.command === "build" && native.containers.length > 0) {
641
+ pluginNative.containers = [];
642
+ for (const declaration of Object.values(pluginNative.worker?.exports ?? {})) if ("container" in declaration) delete declaration.container;
643
+ } else if (environment.command === "serve") restoreLocalContainerBindings(pluginNative.worker);
644
+ }
645
+ };
646
+ const directories = {
647
+ name: "nosam:cloudflare-output-directories",
648
+ enforce: "post",
649
+ config(userConfig) {
650
+ const environmentNames = [options.viteEnvironment.name ?? "ssr", ...options.viteEnvironment.childEnvironments ?? []];
651
+ for (const name of [...environmentNames, "client"]) outputDirectories.set(name, resolve(root, userConfig.environments?.[name]?.build?.outDir ?? join(userConfig.build?.outDir ?? "dist", name)));
652
+ }
653
+ };
654
+ const output = {
655
+ name: "nosam:cloudflare-build-output",
656
+ enforce: "post",
657
+ writeBundle: {
658
+ order: "post",
659
+ handler() {
660
+ if (this.environment?.name !== "client") return;
661
+ const source = resolve(root, this.environment.config.build.outDir);
662
+ const destination = outputDirectories.get("client");
663
+ if (destination && source !== destination && existsSync(source)) {
664
+ mkdirSync(destination, { recursive: true });
665
+ cpSync(source, destination, { recursive: true });
666
+ }
667
+ }
668
+ },
669
+ buildApp: {
670
+ order: "post",
671
+ async handler(builder) {
672
+ if (Object.values(native.worker?.env ?? {}).some((binding) => binding.type === "assets")) mkdirSync(getWorkerAssetsDir(root), { recursive: true });
673
+ const worker = (await readBuildOutput(root)).workers.default;
674
+ const environment = options.viteEnvironment.name ?? "ssr";
675
+ const destination = outputDirectories.get(environment);
676
+ const client = outputDirectories.get("client");
677
+ if (!worker.bundleDir || !worker.config.manifest) throw new Error("bwf requires a built Cloudflare Worker.");
678
+ for (const directory of [destination, client]) if (directory !== root && isInside(root, directory) && !isInside(directory, worker.bundleDir)) rmSync(directory, {
679
+ recursive: true,
680
+ force: true
681
+ });
682
+ mkdirSync(destination, { recursive: true });
683
+ cpSync(worker.bundleDir, destination, { recursive: true });
684
+ if (worker.assetsDir) {
685
+ mkdirSync(client, { recursive: true });
686
+ cpSync(worker.assetsDir, client, { recursive: true });
687
+ }
688
+ const config = {
689
+ ...workerConfig,
690
+ name: worker.config.name,
691
+ account_id: native.accountId,
692
+ compatibility_date: worker.config.compatibilityDate,
693
+ compatibility_flags: worker.config.compatibilityFlags,
694
+ main: worker.config.manifest.mainModule,
695
+ no_bundle: true,
696
+ rules: [{
697
+ type: "ESModule",
698
+ globs: ["**/*.js", "**/*.mjs"]
699
+ }],
700
+ ...process.env.CLOUDFLARE_ENV ? { targetEnvironment: process.env.CLOUDFLARE_ENV } : {},
701
+ ...workerConfig.assets || worker.assetsDir ? { assets: {
702
+ ...workerConfig.assets,
703
+ directory: relative(destination, client)
704
+ } } : {}
705
+ };
706
+ delete config.env;
707
+ writeFileAtomic(join(destination, "wrangler.json"), `${JSON.stringify(config, null, 2)}\n`);
708
+ if (options.finalizeAssets) {
709
+ options.finalizeAssets(client, builder.environments.client);
710
+ const finalized = JSON.parse(readFileSync(join(destination, "wrangler.json"), "utf8"));
711
+ if (worker.config.assets && finalized.assets) {
712
+ worker.config.assets.runWorkerFirst = finalized.assets.run_worker_first;
713
+ writeFileAtomic(worker.configPath, JSON.stringify(worker.config));
714
+ }
715
+ if (worker.assetsDir && existsSync(client)) cpSync(client, worker.assetsDir, { recursive: true });
716
+ }
717
+ if (native.containers.length > 0) writeFileAtomic(join(dirname(getRootConfigPath(root)), "nosam-containers.json"), JSON.stringify({ workerDirectory: relative(root, destination) }));
718
+ const pointer = join(root, ".wrangler/deploy/config.json");
719
+ const pointerDestination = existsSync(join(root, "bwf.config.ts")) && process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] !== "1" ? join(root, ".bwf/preview-deploy-config.json") : pointer;
720
+ mkdirSync(dirname(pointerDestination), { recursive: true });
721
+ writeFileAtomic(pointerDestination, JSON.stringify({ configPath: relative(dirname(pointer), join(destination, "wrangler.json")) }));
722
+ for (const name of options.viteEnvironment.childEnvironments ?? []) {
723
+ const source = builder.environments[name]?.config.build.outDir;
724
+ const target = outputDirectories.get(name);
725
+ if (source && target && existsSync(source)) cpSync(source, target, { recursive: true });
726
+ }
727
+ }
728
+ }
729
+ };
730
+ return skipOnVitestServer([
731
+ bridge,
732
+ directories,
733
+ ...withLocalPreviewBindings(cloudflare({
734
+ inspectorPort: options.inspectorPort,
735
+ persistState: options.persistState,
736
+ viteEnvironment: options.viteEnvironment,
737
+ auxiliaryWorkers: nativeAuxiliaryWorkers(options.auxiliaryWorkers, root),
738
+ types: { generate: false },
739
+ config() {
740
+ return pluginNative;
741
+ }
742
+ }), root),
743
+ output
744
+ ]);
745
+ }
746
+ // src/plugin-dev-triggers-hint.ts
747
+ /**
748
+ * Prints a one-shot hint on dev server start when the project has crons
749
+ * or queues, explaining how to trigger them locally through `/__nosam/scheduled`
750
+ * and `/__nosam/queue`.
751
+ */
752
+ function devTriggersHintPlugin(root, devTriggerToken) {
753
+ return {
754
+ name: "nosam:dev-triggers-hint",
755
+ apply: "serve",
756
+ configureServer(server) {
757
+ const paths = readProjectPaths(root);
758
+ const jobs = scanJobsSync(paths.cronsDir);
759
+ const queues = scanQueuesSync(paths.queuesDir);
760
+ if (jobs.length === 0 && queues.length === 0) return;
761
+ afterServerReady(server, () => {
762
+ const address = server.httpServer?.address();
763
+ const port = typeof address === "object" && address ? address.port : null;
764
+ if (port == null) return;
765
+ const baseUrl = `http://localhost:${port}`;
766
+ const summary = [];
767
+ if (jobs.length > 0) summary.push(`${jobs.length} cron${jobs.length === 1 ? "" : "s"}`);
768
+ if (queues.length > 0) summary.push(`${queues.length} queue${queues.length === 1 ? "" : "s"}`);
769
+ console.log();
770
+ bwfLog(`Detected ${summary.join(" and ")}. Trigger locally:`);
771
+ const authHeader = `x-nosam-dev-trigger: ${devTriggerToken}`;
772
+ if (jobs.length > 0) {
773
+ const sample = jobs[0].crons[0];
774
+ console.log(` \x1b[2mcurl -X POST ${baseUrl}/__nosam/scheduled \\\n -H "${authHeader}" \\\n -d '{"cron":"${sample}","scheduledTime":'"$(date +%s000)"'}'\x1b[22m`);
775
+ }
776
+ if (queues.length > 0) {
777
+ const sample = queues[0].name;
778
+ console.log(` \x1b[2mcurl -X POST ${baseUrl}/__nosam/queue \\\n -H "${authHeader}" \\\n -d '{"queue":"${sample}","messages":[{"id":"1","timestamp":'"$(date +%s000)"',"body":{},"attempts":1}]}'\x1b[22m`);
779
+ }
780
+ });
781
+ }
782
+ };
783
+ }
784
+ // src/plugin-drizzle.ts
785
+ const drizzleD1Resolved = fileURLToPath(import.meta.resolve("drizzle-orm/d1"));
786
+ const drizzleOrmResolved = fileURLToPath(import.meta.resolve("drizzle-orm"));
787
+ const envModuleResolved = fileURLToPath(import.meta.resolve("#self/_env"));
788
+ const drizzleNodePgResolved = fileURLToPath(import.meta.resolve("drizzle-orm/node-postgres"));
789
+ const drizzleMysql2Resolved = fileURLToPath(import.meta.resolve("drizzle-orm/mysql2"));
790
+ const VIRTUAL_DB_ID = "\0virtual:nosam-db";
791
+ const VIRTUAL_SCHEMA_DB_ID = "\0virtual:nosam-db-schema";
792
+ const REQUEST_POOL_PROXY = `
793
+ function requestPool(resolve, own = {}) {
794
+ const has = new Map();
795
+ let prototype;
796
+ return new Proxy({}, {
797
+ get(_, prop) {
798
+ if (Object.hasOwn(own, prop)) return own[prop];
799
+ const pool = resolve();
800
+ const value = Reflect.get(pool, prop);
801
+ return typeof value === "function" ? value.bind(pool) : value;
802
+ },
803
+ has(_, prop) {
804
+ if (Object.hasOwn(own, prop)) return true;
805
+ if (!has.has(prop)) has.set(prop, Reflect.has(resolve(), prop));
806
+ return has.get(prop);
807
+ },
808
+ getPrototypeOf: () => (prototype ??= Object.getPrototypeOf(resolve())),
809
+ });
810
+ }
811
+ `;
812
+ /**
813
+ * The app's `@builtbyfriends/bwf/db` module for its dialect, schema and D1 binding. Resolving and loading
814
+ * have no side effects, so the Vite plugin and `bwfDbBundlerPlugin` share them.
815
+ */
816
+ function createBwfDbModule(root, dialect, options, paths = readProjectPaths(root)) {
817
+ const schema = discoverSchema(root, paths);
818
+ const hasDbRuntime = schema != null || options.forceVirtualDb === true || options.casing !== void 0 || dialect !== "sqlite";
819
+ const d1BindingName = options.d1BindingName ?? "DB";
820
+ return {
821
+ schema,
822
+ hasDbRuntime,
823
+ resolveId(id, importer) {
824
+ if (id === "@builtbyfriends/bwf/db") {
825
+ if (!hasDbRuntime) return;
826
+ if (schema && importer) {
827
+ const normalizedImporter = normalizePath(importer);
828
+ const normalizedSchemaPath = normalizePath(schema.path);
829
+ if (schema.type === "file" && (normalizedImporter === normalizedSchemaPath || normalizedImporter.startsWith(normalizePath(paths.schemaDir) + "/"))) return VIRTUAL_SCHEMA_DB_ID;
830
+ if (schema.type === "directory" && normalizedImporter.startsWith(normalizedSchemaPath)) return VIRTUAL_SCHEMA_DB_ID;
831
+ }
832
+ return VIRTUAL_DB_ID;
833
+ }
834
+ if (schema && (id === "@schema" || id.startsWith("@schema/"))) {
835
+ if (id === "@schema") return schema.path;
836
+ return join(schema.path, id.slice(8));
837
+ }
838
+ },
839
+ load: {
840
+ filter: { id: /^\0virtual:nosam-db(?:-schema)?$/ },
841
+ handler(id) {
842
+ if (id === VIRTUAL_SCHEMA_DB_ID) return `
843
+ export { ${DRIZZLE_OPERATORS} } from ${JSON.stringify(drizzleOrmResolved)};
844
+ export const db = {};
845
+ export function createDb() {
846
+ throw new Error("db: createDb() is unavailable when importing bwf/db from a schema file.");
847
+ }
848
+ `;
849
+ const schemaImport = schema ? `import * as schema from ${JSON.stringify(schema.path)};` : "";
850
+ const casingOption = options.casing ? `casing: ${JSON.stringify(options.casing)}` : "";
851
+ const drizzleOptions = [schema ? "schema" : "", casingOption].filter(Boolean);
852
+ const drizzleConfig = drizzleOptions.length > 0 ? `, { ${drizzleOptions.join(", ")} }` : "";
853
+ const drizzleOptionKeys = drizzleOptions.map((option) => `, ${option}`).join("");
854
+ if (dialect === "mysql") {
855
+ const mysqlDrizzleConfig = (schema ? ", schema, mode: \"default\"" : "") + (casingOption ? `, ${casingOption}` : "");
856
+ return `
857
+ export { ${DRIZZLE_OPERATORS} } from ${JSON.stringify(drizzleOrmResolved)};
858
+ import { drizzle } from ${JSON.stringify(drizzleMysql2Resolved)};
859
+ import { getRuntimeBinding, getRuntimeRequestResource } from ${JSON.stringify(envModuleResolved)};
860
+ ${schemaImport}
861
+
862
+ const _requestResourceKey = {};
863
+
864
+ function getConnectionString() {
865
+ const url = getRuntimeBinding("DATABASE_URL");
866
+ if (url) return url;
867
+ const hd = getRuntimeBinding("HYPERDRIVE");
868
+ if (hd?.connectionString) return hd.connectionString;
869
+ throw new Error("db: MySQL is not configured. Add DATABASE_URL to .env for local dev, or configure Hyperdrive for production.");
870
+ }
871
+
872
+ // mysql2 closes idle connections only from a timer that it starts when it builds a pool with
873
+ // maxIdle below connectionLimit, and that timer runs until the pool ends: workerd rejects it in
874
+ // global scope, and nothing ends bwf's pools. Time each connection from its release instead,
875
+ // which runs in the request that ran the query.
876
+ function closeIdleConnections(pool, idleTimeout) {
877
+ const timers = new WeakMap();
878
+ pool.on("release", (connection) => {
879
+ const timer = setTimeout(() => connection.destroy(), idleTimeout);
880
+ // A Node script that ends its pool exits without waiting for this timer.
881
+ timer.unref?.();
882
+ timers.set(connection, timer);
883
+ });
884
+ pool.on("acquire", (connection) => clearTimeout(timers.get(connection)));
885
+ return pool;
886
+ }
887
+
888
+ function createPools() {
889
+ const pool = closeIdleConnections(
890
+ drizzle({
891
+ connection: {
892
+ uri: getConnectionString(),
893
+ connectionLimit: 1,
894
+ // Workers forbid eval, which mysql2 uses to build its row parsers.
895
+ disableEval: true,
896
+ },
897
+ }).$client,
898
+ 1000,
899
+ );
900
+ return { pool, promisePool: pool.promise() };
901
+ }
902
+
903
+ function getPools() {
904
+ // Framework entries that bwf does not own run outside its request scope:
905
+ // they get a client for each use, never one shared across requests.
906
+ return getRuntimeRequestResource(_requestResourceKey, createPools, createPools);
907
+ }
908
+ ${REQUEST_POOL_PROXY}
909
+ const promiseClient = requestPool(() => getPools().promisePool);
910
+ // drizzle asks for the promise API while it builds the database, which can run in global
911
+ // scope. No request exists there to own a pool, so answer without one.
912
+ const client = requestPool(() => getPools().pool, { promise: () => promiseClient });
913
+
914
+ let instance;
915
+
916
+ export const db = new Proxy({}, {
917
+ get(_, prop) {
918
+ // drizzle reports a query's errors as "Failed query", so build the request's pool here:
919
+ // a missing connection string then throws its own message. Outside a request, build none.
920
+ getRuntimeRequestResource(_requestResourceKey, createPools, () => undefined);
921
+ instance ??= drizzle({ client${mysqlDrizzleConfig} });
922
+ const value = Reflect.get(instance, prop);
923
+ return typeof value === "function" ? value.bind(instance) : value;
924
+ },
925
+ });
926
+
927
+ export function createDb(connectionString) {
928
+ const db = drizzle({ connection: { uri: connectionString, disableEval: true }${mysqlDrizzleConfig} });
929
+ // 60 seconds is mysql2's own idleTimeout default.
930
+ closeIdleConnections(db.$client, 60000);
931
+ return db;
932
+ }
933
+ `;
934
+ }
935
+ if (dialect === "postgresql") return `
936
+ export { ${DRIZZLE_OPERATORS} } from ${JSON.stringify(drizzleOrmResolved)};
937
+ import { drizzle } from ${JSON.stringify(drizzleNodePgResolved)};
938
+ import { getRuntimeBinding, getRuntimeRequestResource } from ${JSON.stringify(envModuleResolved)};
939
+ ${schemaImport}
940
+
941
+ const _requestResourceKey = {};
942
+
943
+ function getConnectionString() {
944
+ const url = getRuntimeBinding("DATABASE_URL");
945
+ if (url) return url;
946
+ const hd = getRuntimeBinding("HYPERDRIVE");
947
+ if (hd?.connectionString) return hd.connectionString;
948
+ throw new Error("db: PostgreSQL is not configured. Add DATABASE_URL to .env for local dev, or configure Hyperdrive for production.");
949
+ }
950
+
951
+ function createPool() {
952
+ return drizzle({
953
+ connection: {
954
+ connectionString: getConnectionString(),
955
+ max: 1,
956
+ idleTimeoutMillis: 1000,
957
+ },
958
+ }).$client;
959
+ }
960
+
961
+ function getPool() {
962
+ // Framework entries that bwf does not own run outside its request scope:
963
+ // they get a client for each use, never one shared across requests.
964
+ return getRuntimeRequestResource(_requestResourceKey, createPool, createPool);
965
+ }
966
+ ${REQUEST_POOL_PROXY}
967
+ let instance;
968
+
969
+ export const db = new Proxy({}, {
970
+ get(_, prop) {
971
+ // drizzle reports a query's errors as "Failed query", so build the request's pool here:
972
+ // a missing connection string then throws its own message. Outside a request, build none.
973
+ getRuntimeRequestResource(_requestResourceKey, createPool, () => undefined);
974
+ instance ??= drizzle({ client: requestPool(getPool)${drizzleOptionKeys} });
975
+ const value = Reflect.get(instance, prop);
976
+ return typeof value === "function" ? value.bind(instance) : value;
977
+ },
978
+ });
979
+
980
+ export function createDb(connectionString) {
981
+ return drizzle(connectionString${drizzleConfig});
982
+ }
983
+ `;
984
+ return `
985
+ export { ${DRIZZLE_OPERATORS} } from ${JSON.stringify(drizzleOrmResolved)};
986
+ import { drizzle } from ${JSON.stringify(drizzleD1Resolved)};
987
+ import { getRuntimeRequestResource, requireRuntimeBinding } from ${JSON.stringify(envModuleResolved)};
988
+ ${schemaImport}
989
+
990
+ const _requestResourceKey = {};
991
+
992
+ export const db = new Proxy({}, {
993
+ get(_, prop) {
994
+ const instance = getRuntimeRequestResource(
995
+ _requestResourceKey,
996
+ () => createDb(requireRuntimeBinding(${JSON.stringify(d1BindingName)})),
997
+ () => createPrimaryDb(requireRuntimeBinding(${JSON.stringify(d1BindingName)}))
998
+ );
999
+ return Reflect.get(instance, prop);
1000
+ },
1001
+ });
1002
+
1003
+ export function createDb(d1, options) {
1004
+ return drizzle(d1.withSession(options?.session ?? "first-unconstrained")${drizzleConfig});
1005
+ }
1006
+
1007
+ function createPrimaryDb(d1) {
1008
+ return drizzle(d1.withSession("first-primary")${drizzleConfig});
1009
+ }
1010
+ `;
1011
+ }
1012
+ }
1013
+ };
1014
+ }
1015
+ /**
1016
+ * Vite plugin for Drizzle integration.
1017
+ *
1018
+ * - Intercepts `@builtbyfriends/bwf/db` imports in SSR/worker environments and serves
1019
+ * a virtual module that creates a Drizzle DB instance, using the user's
1020
+ * schema when present.
1021
+ * - Generates `.bwf/db.d.ts` with proper Drizzle types.
1022
+ * - Sets up `@schema` Vite alias for convenient imports when a schema exists.
1023
+ * - Updates `.bwf/tsconfig.json` with TypeScript paths.
1024
+ */
1025
+ function drizzlePlugin(root, hasRouteTypes, dialect = "sqlite", options = {}) {
1026
+ const outDir = join(root, ".bwf");
1027
+ const paths = readProjectPaths(root);
1028
+ const dbModule = createBwfDbModule(root, dialect, options, paths);
1029
+ const { schema, hasDbRuntime } = dbModule;
1030
+ ensureProjectTsconfig(root, hasRouteTypes, hasDbRuntime, schema != null, {
1031
+ redirectDbModule: options.redirectDbTypePaths,
1032
+ paths
1033
+ });
1034
+ if (hasDbRuntime) generateDbDts(outDir, schema ?? null, dialect);
1035
+ return {
1036
+ name: "nosam:drizzle",
1037
+ enforce: "pre",
1038
+ config() {
1039
+ if (!schema) return;
1040
+ return { resolve: { alias: { "@schema": schema.path } } };
1041
+ },
1042
+ resolveId: {
1043
+ filter: { id: /^(@builtbyfriends\/bwf\/db|@schema)/ },
1044
+ handler(id, importer) {
1045
+ if (id === "@builtbyfriends/bwf/db" && this.environment?.name === "client") return;
1046
+ return dbModule.resolveId(id, importer);
1047
+ }
1048
+ },
1049
+ load: dbModule.load,
1050
+ async configureServer() {
1051
+ if (!schema) return;
1052
+ const migrationsDir = paths.migrationsDir;
1053
+ if (!(existsSync(migrationsDir) && readdirSync(migrationsDir).some((f) => f.endsWith(".sql")))) {
1054
+ if (dialect === "sqlite") {
1055
+ const { getApplicationTables, getMiniflareDatabasePath } = await import("./runner-CUNtS5x7.mjs");
1056
+ if ((await getApplicationTables(getMiniflareDatabasePath(options.localD1PersistRoot ?? join(root, ".bwf"), options.localD1DatabaseId ?? "local")).catch(() => [])).length > 0) return;
1057
+ }
1058
+ bwfWarn(`Schema found but no migrations in ${paths.sourceRelative("db/migrations")}/.\n \`bwf db push\` syncs the schema to your local DB without creating migration files.
1059
+ Run \`bwf db generate\` to create migration files for dev startup and deploy.`);
1060
+ }
1061
+ }
1062
+ };
1063
+ }
1064
+ // src/plugin-email-dev-inbox.ts
1065
+ const SECURITY_HEADERS = {
1066
+ "Cache-Control": "no-store",
1067
+ "X-Content-Type-Options": "nosniff",
1068
+ "X-Frame-Options": "DENY",
1069
+ "Referrer-Policy": "no-referrer",
1070
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; frame-src data:; img-src data:; connect-src 'none'"
1071
+ };
1072
+ function emailDevInboxPlugin(options) {
1073
+ const { devTriggerToken } = options;
1074
+ /** `href` for an inbox path that keeps the browser session authorized. */
1075
+ const inboxHref = (path) => `${DEV_INBOX_PREFIX}${path}?${DEV_INBOX_TOKEN_QUERY}=${encodeURIComponent(devTriggerToken)}`;
1076
+ return {
1077
+ name: "nosam:email-dev-inbox",
1078
+ apply: "serve",
1079
+ configureServer(server) {
1080
+ const printInboxUrl = () => {
1081
+ const address = server.httpServer?.address();
1082
+ const port = typeof address === "object" && address ? address.port : null;
1083
+ if (port == null) return;
1084
+ bwfLog(`Email inbox: http://localhost:${port}${inboxHref("")}`);
1085
+ };
1086
+ afterServerReady(server, printInboxUrl);
1087
+ server.middlewares.use(DEV_INBOX_PREFIX, (req, res) => {
1088
+ const url = new URL(req.url ?? "/", "http://localhost");
1089
+ const path = url.pathname;
1090
+ if (!isAuthorized(req.headers["x-nosam-dev-trigger"], url, devTriggerToken)) {
1091
+ res.writeHead(401, {
1092
+ ...SECURITY_HEADERS,
1093
+ "Content-Type": "text/plain; charset=utf-8"
1094
+ });
1095
+ res.end(`Unauthorized: the bwf dev inbox requires the dev-trigger token — send it as the ${DEV_INBOX_TOKEN_HEADER} header or the ?${DEV_INBOX_TOKEN_QUERY}= query (printed as the inbox URL when bwf dev starts; stored in .bwf/dev-trigger-token).`);
1096
+ return;
1097
+ }
1098
+ if (req.method === "POST" && path === "/_capture") {
1099
+ handleCapture(req, res);
1100
+ return;
1101
+ }
1102
+ if (req.method === "DELETE" && path === "/") {
1103
+ clearDevBuffer();
1104
+ res.writeHead(204, SECURITY_HEADERS);
1105
+ res.end();
1106
+ return;
1107
+ }
1108
+ if (req.method !== "GET") {
1109
+ res.writeHead(405, SECURITY_HEADERS);
1110
+ res.end();
1111
+ return;
1112
+ }
1113
+ if (path === "/" || path === "") {
1114
+ res.writeHead(200, {
1115
+ ...SECURITY_HEADERS,
1116
+ "Content-Type": "text/html; charset=utf-8"
1117
+ });
1118
+ res.end(renderListHtml(listDevMessages(), inboxHref));
1119
+ return;
1120
+ }
1121
+ const match = path.match(/^\/([^/]+)(\/raw)?$/);
1122
+ if (!match) {
1123
+ res.writeHead(404, SECURITY_HEADERS);
1124
+ res.end();
1125
+ return;
1126
+ }
1127
+ const id = match[1];
1128
+ const wantsRaw = Boolean(match[2]);
1129
+ const message = findDevMessage(id);
1130
+ if (!message) {
1131
+ res.writeHead(404, {
1132
+ ...SECURITY_HEADERS,
1133
+ "Content-Type": "text/plain"
1134
+ });
1135
+ res.end("Email not found.");
1136
+ return;
1137
+ }
1138
+ if (wantsRaw) {
1139
+ const safeId = id.replace(/["\r\n]/g, "");
1140
+ res.writeHead(200, {
1141
+ ...SECURITY_HEADERS,
1142
+ "Content-Type": "message/rfc822",
1143
+ "Content-Disposition": `attachment; filename="${safeId}.eml"`
1144
+ });
1145
+ res.end(Buffer.from(message.raw));
1146
+ return;
1147
+ }
1148
+ res.writeHead(200, {
1149
+ ...SECURITY_HEADERS,
1150
+ "Content-Type": "text/html; charset=utf-8"
1151
+ });
1152
+ res.end(renderDetailHtml(message, inboxHref));
1153
+ });
1154
+ }
1155
+ };
1156
+ }
1157
+ /**
1158
+ * Constant-time check of the presented token — header first (worker, curl),
1159
+ * then the query (browser). Both are compared against the one project token.
1160
+ */
1161
+ function isAuthorized(headerValue, url, expected) {
1162
+ const presented = typeof headerValue === "string" ? headerValue : url.searchParams.get(DEV_INBOX_TOKEN_QUERY);
1163
+ if (typeof presented !== "string") return false;
1164
+ const a = Buffer.from(presented);
1165
+ const b = Buffer.from(expected);
1166
+ return a.byteLength === b.byteLength && timingSafeEqual(a, b);
1167
+ }
1168
+ /**
1169
+ * `POST /__nosam/inbox/_capture` — the worker's dev-inbox hop.
1170
+ *
1171
+ * Fails with a status the worker can distinguish, and only a success carries
1172
+ * the ack header, so the worker never mistakes an ordinary asset 200 for a
1173
+ * capture. Never throws: an exception here would surface as a dev-server 500
1174
+ * in the middle of the user's `sendEmail`.
1175
+ */
1176
+ async function handleCapture(req, res) {
1177
+ try {
1178
+ if (!String(req.headers["content-type"] ?? "").includes("application/json")) {
1179
+ res.writeHead(415, SECURITY_HEADERS);
1180
+ res.end();
1181
+ return;
1182
+ }
1183
+ const chunks = [];
1184
+ let size = 0;
1185
+ for await (const chunk of req) {
1186
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
1187
+ size += buf.byteLength;
1188
+ if (size > DEV_INBOX_MAX_CAPTURE_BYTES) {
1189
+ res.writeHead(413, SECURITY_HEADERS);
1190
+ res.end();
1191
+ return;
1192
+ }
1193
+ chunks.push(buf);
1194
+ }
1195
+ let parsed;
1196
+ try {
1197
+ parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1198
+ } catch {
1199
+ res.writeHead(400, SECURITY_HEADERS);
1200
+ res.end();
1201
+ return;
1202
+ }
1203
+ const message = parseCapturedMessage(parsed);
1204
+ if (!message) {
1205
+ res.writeHead(400, SECURITY_HEADERS);
1206
+ res.end();
1207
+ return;
1208
+ }
1209
+ pushToDevBuffer(message);
1210
+ res.writeHead(200, {
1211
+ ...SECURITY_HEADERS,
1212
+ [DEV_INBOX_ACK_HEADER]: DEV_INBOX_ACK_VALUE,
1213
+ "Content-Type": "application/json"
1214
+ });
1215
+ res.end(JSON.stringify({
1216
+ ok: true,
1217
+ id: message.id
1218
+ }));
1219
+ } catch {
1220
+ res.writeHead(500, SECURITY_HEADERS);
1221
+ res.end();
1222
+ }
1223
+ }
1224
+ function escapeHtml(s) {
1225
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1226
+ }
1227
+ function formatAddress(a) {
1228
+ return a.name ? `${a.name} <${a.email}>` : a.email;
1229
+ }
1230
+ function formatTime(ts) {
1231
+ return new Date(ts).toLocaleString();
1232
+ }
1233
+ const STYLE = `
1234
+ :root { color-scheme: light dark; }
1235
+ body { font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; margin: 0; padding: 24px; max-width: 1024px; margin: 0 auto; }
1236
+ h1 { font-size: 18px; margin: 0 0 16px; }
1237
+ h2 { font-size: 14px; margin: 24px 0 8px; text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.7; }
1238
+ table { border-collapse: collapse; width: 100%; }
1239
+ th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent); vertical-align: top; }
1240
+ th { font-weight: 600; opacity: 0.7; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; }
1241
+ a { color: #5b8def; text-decoration: none; }
1242
+ a:hover { text-decoration: underline; }
1243
+ .meta { font-size: 12px; opacity: 0.7; }
1244
+ .empty { padding: 48px; text-align: center; opacity: 0.6; }
1245
+ .row { display: flex; gap: 12px; align-items: baseline; }
1246
+ .row .subject { font-weight: 600; }
1247
+ iframe { width: 100%; min-height: 480px; border: 1px solid color-mix(in srgb, currentColor 15%, transparent); border-radius: 8px; background: white; }
1248
+ .actions { display: flex; gap: 12px; margin-bottom: 16px; }
1249
+ .button { display: inline-block; padding: 6px 12px; border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 6px; cursor: pointer; background: transparent; color: inherit; font: inherit; }
1250
+ pre { white-space: pre-wrap; word-break: break-word; padding: 12px; background: color-mix(in srgb, currentColor 5%, transparent); border-radius: 6px; }
1251
+ .header-table th { width: 160px; }
1252
+ `;
1253
+ function renderListHtml(messages, href) {
1254
+ const rows = messages.map((m) => `
1255
+ <tr>
1256
+ <td><a href="${escapeHtml(href(`/${m.id}`))}">${escapeHtml(m.subject || "(no subject)")}</a></td>
1257
+ <td>${escapeHtml(formatAddress(m.from))}</td>
1258
+ <td>${escapeHtml(m.to.map(formatAddress).join(", "))}</td>
1259
+ <td class="meta">${escapeHtml(formatTime(m.capturedAt))}</td>
1260
+ <td class="meta"><a href="${escapeHtml(href(`/${m.id}/raw`))}">.eml</a></td>
1261
+ </tr>`).join("");
1262
+ return `<!DOCTYPE html>
1263
+ <html><head><meta charset="utf-8"><title>bwf — Email inbox</title><style>${STYLE}</style></head>
1264
+ <body>
1265
+ <h1>Email inbox <span class="meta">(${messages.length} message${messages.length === 1 ? "" : "s"})</span></h1>
1266
+ ${messages.length === 0 ? `<div class="empty">No messages captured yet. Call <code>sendEmail()</code> from your app to populate.</div>` : `<table>
1267
+ <thead><tr><th>Subject</th><th>From</th><th>To</th><th>Captured</th><th></th></tr></thead>
1268
+ <tbody>${rows}</tbody>
1269
+ </table>`}
1270
+ </body></html>`;
1271
+ }
1272
+ function renderDetailHtml(m, href) {
1273
+ const headerRows = Object.entries(m.headers).map(([k, v]) => `<tr><th>${escapeHtml(k)}</th><td>${escapeHtml(v)}</td></tr>`).join("");
1274
+ const attachmentRows = m.attachments.map((a) => `<tr><td>${escapeHtml(a.filename)}</td><td>${escapeHtml(a.contentType)}</td><td>${a.size} B</td><td>${a.disposition}</td></tr>`).join("");
1275
+ const bodyHtml = m.html ? `<iframe sandbox srcdoc="${escapeHtml(m.html)}"></iframe>` : `<pre>${escapeHtml(m.text ?? "")}</pre>`;
1276
+ return `<!DOCTYPE html>
1277
+ <html><head><meta charset="utf-8"><title>${escapeHtml(m.subject || "(no subject)")} — bwf inbox</title><style>${STYLE}</style></head>
1278
+ <body>
1279
+ <div class="actions">
1280
+ <a class="button" href="${escapeHtml(href(""))}">← Back</a>
1281
+ <a class="button" href="${escapeHtml(href(`/${m.id}/raw`))}">Download .eml</a>
1282
+ </div>
1283
+ <h1>${escapeHtml(m.subject || "(no subject)")}</h1>
1284
+ <table class="header-table">
1285
+ <tr><th>From</th><td>${escapeHtml(formatAddress(m.from))}</td></tr>
1286
+ <tr><th>To</th><td>${escapeHtml(m.to.map(formatAddress).join(", "))}</td></tr>
1287
+ ${m.cc.length > 0 ? `<tr><th>Cc</th><td>${escapeHtml(m.cc.map(formatAddress).join(", "))}</td></tr>` : ""}
1288
+ ${m.bcc.length > 0 ? `<tr><th>Bcc</th><td>${escapeHtml(m.bcc.map(formatAddress).join(", "))}</td></tr>` : ""}
1289
+ ${m.replyTo ? `<tr><th>Reply-To</th><td>${escapeHtml(formatAddress(m.replyTo))}</td></tr>` : ""}
1290
+ <tr><th>Captured</th><td class="meta">${escapeHtml(formatTime(m.capturedAt))}</td></tr>
1291
+ <tr><th>Message-ID</th><td class="meta">${escapeHtml(m.messageId)}</td></tr>
1292
+ </table>
1293
+ ${headerRows ? `<h2>Custom headers</h2><table class="header-table">${headerRows}</table>` : ""}
1294
+ ${attachmentRows ? `<h2>Attachments</h2><table><thead><tr><th>Filename</th><th>Type</th><th>Size</th><th>Disposition</th></tr></thead><tbody>${attachmentRows}</tbody></table>` : ""}
1295
+ <h2>Body</h2>
1296
+ ${bodyHtml}
1297
+ </body></html>`;
1298
+ }
1299
+ // src/plugin-env-client-guard.ts
1300
+ let cachedModule = null;
1301
+ async function loadEnvPublic() {
1302
+ if (cachedModule) return cachedModule;
1303
+ const mod = await import("./runtime/env-public.mjs");
1304
+ cachedModule = mod;
1305
+ return mod;
1306
+ }
1307
+ const SKIP_EXT = /\.(?:css|s[ac]ss|less|styl|json|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|eot|wasm|mp[34]|webm|md|mdx)(?:\?|$)/;
1308
+ const SCRIPT_LANG_RE = /[?&]lang\.([a-z0-9]+)/i;
1309
+ /**
1310
+ * Cheap prefilter shared with the fold plugin: is this a client script
1311
+ * module that mentions `@builtbyfriends/bwf/env`? Anything we'd want to parse is JS/TS or
1312
+ * has a script sub-resource (a `lang.tsx` / `lang.ts` / `lang.js` query). The `@builtbyfriends/bwf/env` substring check lets most files skip the AST
1313
+ * walk; a false positive only means an unneeded parse.
1314
+ */
1315
+ function isBwfEnvScriptCandidate(id, code) {
1316
+ if (id.includes("/node_modules/") || SKIP_EXT.test(id)) return false;
1317
+ const langMatch = SCRIPT_LANG_RE.exec(id);
1318
+ const isScriptQuery = langMatch !== null && /^(?:m?[jt]sx?|cjs)$/i.test(langMatch[1]);
1319
+ const isPlainScript = /\.(?:[mc]?[jt]sx?)(?:\?|$)/.test(id);
1320
+ if (!isScriptQuery && !isPlainScript) return false;
1321
+ return code.includes("@builtbyfriends/bwf/env");
1322
+ }
1323
+ function extractEnvBindings(program) {
1324
+ const direct = /* @__PURE__ */ new Set();
1325
+ const namespace = /* @__PURE__ */ new Set();
1326
+ let found = false;
1327
+ for (const node of program.body ?? []) {
1328
+ if (node.type !== "ImportDeclaration") continue;
1329
+ if (node.source.value !== "@builtbyfriends/bwf/env") continue;
1330
+ found = true;
1331
+ for (const spec of node.specifiers ?? []) if (spec.type === "ImportSpecifier") {
1332
+ const importedName = spec.imported;
1333
+ if (!isIdentifier(importedName)) continue;
1334
+ if (importedName.name === "env") direct.add(spec.local.name);
1335
+ } else if (spec.type === "ImportNamespaceSpecifier") namespace.add(spec.local.name);
1336
+ }
1337
+ if (!found || direct.size === 0 && namespace.size === 0) return null;
1338
+ return {
1339
+ directNames: direct,
1340
+ namespaceNames: namespace
1341
+ };
1342
+ }
1343
+ function buildOffsetIndex(code) {
1344
+ const lineStarts = [0];
1345
+ for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) lineStarts.push(i + 1);
1346
+ return { lineStarts };
1347
+ }
1348
+ function offsetToLineCol(index, offset) {
1349
+ const lineStarts = index.lineStarts;
1350
+ let lowerBound = 0;
1351
+ let upperBound = lineStarts.length - 1;
1352
+ while (lowerBound < upperBound) {
1353
+ const midpoint = lowerBound + upperBound + 1 >>> 1;
1354
+ if (lineStarts[midpoint] <= offset) lowerBound = midpoint;
1355
+ else upperBound = midpoint - 1;
1356
+ }
1357
+ return {
1358
+ line: lowerBound + 1,
1359
+ column: offset - lineStarts[lowerBound] + 1
1360
+ };
1361
+ }
1362
+ /**
1363
+ * Visit every `env.X` (or `<ns>.env.X`) member expression where `env` is
1364
+ * bound to the `@builtbyfriends/bwf/env` proxy.
1365
+ */
1366
+ function walkEnvReads(program, bindings, visit) {
1367
+ const references = [];
1368
+ const resolve = bindingResolver(program, {
1369
+ names: /* @__PURE__ */ new Set([...bindings.directNames, ...bindings.namespaceNames]),
1370
+ visit(current) {
1371
+ if (!isMemberExpression(current)) return false;
1372
+ if (isIdentifier(current.object) && bindings.directNames.has(current.object.name)) {
1373
+ references.push({
1374
+ node: current,
1375
+ name: current.object.name,
1376
+ bindingType: "ImportSpecifier"
1377
+ });
1378
+ return true;
1379
+ }
1380
+ const obj = current.object;
1381
+ if (isMemberExpression(obj) && !obj.computed && isIdentifier(obj.object) && bindings.namespaceNames.has(obj.object.name) && isIdentifier(obj.property) && obj.property.name === "env") {
1382
+ references.push({
1383
+ node: current,
1384
+ name: obj.object.name,
1385
+ bindingType: "ImportNamespaceSpecifier"
1386
+ });
1387
+ return true;
1388
+ }
1389
+ return false;
1390
+ }
1391
+ });
1392
+ for (const { node, name, bindingType } of references) if (resolve(node, name)?.type === bindingType) visit(node);
1393
+ }
1394
+ /**
1395
+ * Collect every `@builtbyfriends/bwf/env` read. Computed access produces a warning hit
1396
+ * with `property === null`; everything else carries the property name.
1397
+ */
1398
+ function findHits(program, bindings) {
1399
+ const hits = [];
1400
+ walkEnvReads(program, bindings, (node) => recordHit(node, hits));
1401
+ return hits;
1402
+ }
1403
+ function recordHit(node, hits) {
1404
+ if (node.computed) {
1405
+ hits.push({
1406
+ kind: "warn",
1407
+ property: null,
1408
+ start: node.start
1409
+ });
1410
+ return;
1411
+ }
1412
+ if (!isIdentifier(node.property)) return;
1413
+ hits.push({
1414
+ kind: "error",
1415
+ property: node.property.name,
1416
+ start: node.start
1417
+ });
1418
+ }
1419
+ /**
1420
+ * Vite plugin that fails the client build when a server-only env key
1421
+ * (anything in `defineEnv` not prefixed with `VITE_`) is referenced from a
1422
+ * module that ends up in the client bundle. The runtime proxy in
1423
+ * `env-public-client.ts` already throws for the same class of bug at
1424
+ * request time — this plugin moves the diagnosis forward to compile time
1425
+ * so it shows up in `pnpm build` and the dev overlay, not in production
1426
+ * after an admin clicks the offending route.
1427
+ *
1428
+ * No-op when no `env.ts` is registered. Server / SSR / worker environments
1429
+ * are skipped — only the `client` environment is checked.
1430
+ */
1431
+ function envClientGuardPlugin(root) {
1432
+ return {
1433
+ name: "nosam:env-client-guard",
1434
+ enforce: "post",
1435
+ async transform(code, id) {
1436
+ if (this.environment?.name !== "client") return;
1437
+ if (!isBwfEnvScriptCandidate(id, code)) return;
1438
+ const { _hasRegisteredSchema, _getRegisteredSchema } = await loadEnvPublic();
1439
+ if (!_hasRegisteredSchema()) return;
1440
+ const schema = _getRegisteredSchema();
1441
+ if (!schema || Object.keys(schema).length === 0) return;
1442
+ let parsed;
1443
+ try {
1444
+ parsed = parseSync(id, code);
1445
+ } catch {
1446
+ return;
1447
+ }
1448
+ const program = parsed.program;
1449
+ const bindings = extractEnvBindings(program);
1450
+ if (!bindings) return;
1451
+ const hits = findHits(program, bindings);
1452
+ if (hits.length === 0) return;
1453
+ const offsets = buildOffsetIndex(code);
1454
+ const relPath = relative(root, id.split("?")[0]) || id;
1455
+ for (const hit of hits) {
1456
+ const { line, column } = offsetToLineCol(offsets, hit.start);
1457
+ if (hit.kind === "warn") {
1458
+ this.warn({
1459
+ message: `Computed access to "env[…]" at ${relPath}:${line}:${column} cannot be statically verified. If the key being read is server-only, this will throw at runtime in the browser. Prefer literal property access (env.VITE_FOO) so the build can check the split.`,
1460
+ loc: {
1461
+ line,
1462
+ column,
1463
+ file: id
1464
+ }
1465
+ });
1466
+ continue;
1467
+ }
1468
+ const key = hit.property;
1469
+ if (!(key in schema)) continue;
1470
+ if (isClientEnvKey(key)) continue;
1471
+ this.error({
1472
+ message: `Server-only env "${key}" referenced from client code at ${relPath}:${line}:${column}.\nIf this should be available in the browser, rename it with the VITE_* prefix in env.ts.\nIf it must stay server-only, remove this reference and read the value via a server route or loader.`,
1473
+ loc: {
1474
+ line,
1475
+ column,
1476
+ file: id
1477
+ }
1478
+ });
1479
+ }
1480
+ }
1481
+ };
1482
+ }
1483
+ // src/plugin-env-client-fold.ts
1484
+ /**
1485
+ * Walk the AST and collect every static `env.FOO` / `env["FOO"]` (or
1486
+ * `<ns>.env.FOO`) read. Dynamic keys (`env[variable]`) are intentionally
1487
+ * ignored — the Proxy still serves them at runtime, and we can't prove
1488
+ * they'd be folded the same way Vite folds `import.meta.env.FOO`.
1489
+ */
1490
+ function findFoldHits(program, bindings) {
1491
+ const hits = [];
1492
+ walkEnvReads(program, bindings, (node) => pushHit(node, hits));
1493
+ return hits;
1494
+ }
1495
+ function pushHit(node, hits) {
1496
+ if (!node.computed && isIdentifier(node.property)) {
1497
+ hits.push({
1498
+ start: node.start,
1499
+ end: node.end,
1500
+ property: node.property.name
1501
+ });
1502
+ return;
1503
+ }
1504
+ if (node.computed && isLiteral(node.property) && typeof node.property.value === "string") {
1505
+ hits.push({
1506
+ start: node.start,
1507
+ end: node.end,
1508
+ property: node.property.value
1509
+ });
1510
+ return;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Build-time constant folding for client-only `env.FOO` reads.
1515
+ *
1516
+ * Purpose: match what Vite already does for `import.meta.env.FOO` so that
1517
+ * branches like `if (env.VITE_FLAG === "on") { ... }` get dead-code
1518
+ * eliminated in production client bundles. The runtime `env` Proxy on the
1519
+ * client already resolves keys via `import.meta.env`, so *semantics* don't
1520
+ * change — we just move the lookup from runtime to build time, which
1521
+ * unlocks DCE and bundler minification of guarded blocks.
1522
+ *
1523
+ * Safety properties:
1524
+ * • Runs only when `this.environment.name === 'client'`. Server / SSR /
1525
+ * worker builds keep the full runtime Proxy (secrets, runtime-injected
1526
+ * vars, HMR remain live).
1527
+ * • Only folds keys that match bwf's fixed `VITE_` client prefix. A
1528
+ * server-only key is never folded (and the env-client-guard plugin
1529
+ * would have errored out earlier anyway).
1530
+ * • Only folds static member access: `env.FOO` and `env["FOO"]`.
1531
+ * Dynamic access, destructuring, and reassignment fall through to the
1532
+ * runtime Proxy.
1533
+ * • Only folds keys with a known build-time value (build shell, or a schema
1534
+ * `.default(...)` that the env-schema plugin adds). Unknown keys are left as-is
1535
+ * and the Proxy handles them at runtime — no "undefined" shoved in.
1536
+ * • Build-only (`apply: 'build'`). Dev runs through the Proxy so local
1537
+ * `.env` edits take effect without a full rebuild.
1538
+ */
1539
+ function envClientFoldPlugin() {
1540
+ let loadedEnv = {};
1541
+ return {
1542
+ name: "nosam:env-client-fold",
1543
+ apply: "build",
1544
+ enforce: "post",
1545
+ configResolved(config) {
1546
+ loadedEnv = config.env ?? {};
1547
+ },
1548
+ async transform(code, id) {
1549
+ if (this.environment?.name !== "client") return;
1550
+ if (!isBwfEnvScriptCandidate(id, code)) return;
1551
+ let parsed;
1552
+ try {
1553
+ parsed = parseSync(id, code);
1554
+ } catch {
1555
+ return;
1556
+ }
1557
+ const program = parsed.program;
1558
+ const bindings = extractEnvBindings(program);
1559
+ if (!bindings) return;
1560
+ const hits = findFoldHits(program, bindings);
1561
+ if (hits.length === 0) return;
1562
+ let ms = null;
1563
+ for (const hit of hits) {
1564
+ if (!isClientEnvKey(hit.property)) continue;
1565
+ const value = loadedEnv[hit.property];
1566
+ if (value === void 0) continue;
1567
+ if (!ms) ms = new MagicString(code);
1568
+ ms.overwrite(hit.start, hit.end, JSON.stringify(value));
1569
+ }
1570
+ if (!ms) return;
1571
+ return {
1572
+ code: ms.toString(),
1573
+ map: ms.generateMap({ hires: "boundary" })
1574
+ };
1575
+ }
1576
+ };
1577
+ }
1578
+ // src/plugin-env-schema.ts
1579
+ /**
1580
+ * Variables Vite's `loadEnv` copies from env files into `process.env` when
1581
+ * they are unset, as `[file key, process.env key]`.
1582
+ */
1583
+ const VITE_PROCESS_ENV_COPIES = [
1584
+ ["NODE_ENV", "VITE_USER_NODE_ENV"],
1585
+ ["BROWSER", "BROWSER"],
1586
+ ["BROWSER_ARGS", "BROWSER_ARGS"]
1587
+ ];
1588
+ /** The `process.env` values Vite may overwrite, read before it loads env files. */
1589
+ function readProcessEnvCopies() {
1590
+ return Object.fromEntries(VITE_PROCESS_ENV_COPIES.map(([, target]) => [target, process.env[target]]));
1591
+ }
1592
+ /**
1593
+ * Delete the client values Vite took from `<root>/.env` during a build.
1594
+ * Keys come from Vite's own parser (`node:util` `parseEnv`), so every key
1595
+ * Vite read is covered. A key stays when the shell or the `vp run` task
1596
+ * runner supplies it: `loadEnv` with `envDir: false` returns exactly those
1597
+ * values. Nothing is stripped when Vite loads env files from another
1598
+ * `envDir` (or none), since `<root>/.env` was not the source.
1599
+ *
1600
+ * Vite also copies a few `.env` values into `process.env` (see
1601
+ * {@link VITE_PROCESS_ENV_COPIES}), where they would pass as shell values.
1602
+ * `before` holds those variables as they were before Vite loaded the file;
1603
+ * a copy Vite made is removed from `process.env` again, so this check and
1604
+ * the next config resolution in the same build (the app builder resolves
1605
+ * once per environment) see only the shell.
1606
+ */
1607
+ function stripLocalClientEnv(root, config, before) {
1608
+ if (config.envDir === false || realPath(config.envDir) !== realPath(root)) return;
1609
+ const file = join(root, LOCAL_ENV_FILE);
1610
+ if (!existsSync(file)) return;
1611
+ const parsed = parseEnv(readFileSync(file, "utf8"));
1612
+ const keys = new Set(Object.keys(parsed));
1613
+ for (const [source, target] of VITE_PROCESS_ENV_COPIES) {
1614
+ const value = parsed[source];
1615
+ if (value === void 0) continue;
1616
+ keys.add(target);
1617
+ if (before && before[target] === void 0 && process.env[target] === value) delete process.env[target];
1618
+ }
1619
+ const prefixes = resolveEnvPrefix({ envPrefix: config.envPrefix });
1620
+ const shell = loadEnv(config.mode, false, prefixes);
1621
+ for (const key of keys) {
1622
+ if (!prefixes.some((prefix) => key.startsWith(prefix))) continue;
1623
+ const value = shell[key];
1624
+ if (value === void 0) delete config.env[key];
1625
+ else config.env[key] = value;
1626
+ }
1627
+ }
1628
+ /** Match Vite's canonical paths, including Windows short names and filesystem casing. */
1629
+ function realPath(path) {
1630
+ try {
1631
+ return realpathSync.native(path);
1632
+ } catch {
1633
+ return resolve(path);
1634
+ }
1635
+ }
1636
+ /** Module ids that name an env file: its path as found, and as Vite resolves it. */
1637
+ function envFileIdsFor(envFile) {
1638
+ return new Set(envFile ? [normalizePath(envFile), normalizePath(realPath(envFile))] : []);
1639
+ }
1640
+ /** A hook filter pattern that matches exactly `id`. */
1641
+ function exactId(id) {
1642
+ return new RegExp(`^${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`);
1643
+ }
1644
+ /** Patterns Vite's `define` typically uses for env-shaped constants. */
1645
+ const DEFINE_ENV_PATTERN = /^(?:globalThis\.)?(?:process\.env|import\.meta\.env)\.([A-Z_][A-Z0-9_]*)$/;
1646
+ /**
1647
+ * Vite plugin that auto-discovers `env.ts` at the project root and:
1648
+ * - imports it (registering the user's schema via `defineEnv`)
1649
+ * - generates `.bwf/env.d.ts` so `env.X` and `c.env.X` are typed
1650
+ * - validates the local dev env (`.env` + process.env) and warns
1651
+ * on missing/invalid required keys
1652
+ * - regenerates types + re-validates when env.ts changes (HMR)
1653
+ *
1654
+ * Hard errors are reserved for builds and deploys; dev keeps moving with warnings
1655
+ * so unrelated work isn't blocked by a stale local value.
1656
+ */
1657
+ function envSchemaPlugin(root, options = {}) {
1658
+ const outDir = join(root, ".bwf");
1659
+ let envFile = null;
1660
+ let envFileIds = envFileIdsFor(findEnvFile(root));
1661
+ const keepEnvFileImport = {
1662
+ filter: { id: [...envFileIds].map(exactId) },
1663
+ handler(code, id) {
1664
+ if (this.environment.config.consumer === "client" || !envFileIds.has(id)) return;
1665
+ return {
1666
+ code,
1667
+ map: null,
1668
+ moduleSideEffects: true
1669
+ };
1670
+ }
1671
+ };
1672
+ let command = "serve";
1673
+ let processEnvCopiesBefore;
1674
+ const appliedClientDefaults = /* @__PURE__ */ new Map();
1675
+ async function emitSchemaFacts() {
1676
+ if (!envFile || !options.onSchema) return;
1677
+ const { _hasRegisteredSchema, _getRegisteredSchema } = await loadEnvPublic();
1678
+ if (!_hasRegisteredSchema()) return;
1679
+ const schema = _getRegisteredSchema() ?? {};
1680
+ const keys = Object.keys(schema);
1681
+ const clientKeys = keys.filter(isClientEnvKey);
1682
+ const clientKeySet = new Set(clientKeys);
1683
+ const serverKeys = keys.filter((key) => !clientKeySet.has(key));
1684
+ const requiredServerKeys = [];
1685
+ for (const key of serverKeys) {
1686
+ const result = schema[key]["~standard"].validate(void 0);
1687
+ if ((result instanceof Promise ? await result : result).issues) requiredServerKeys.push(key);
1688
+ }
1689
+ options.onSchema({
1690
+ keys,
1691
+ clientKeys,
1692
+ serverKeys,
1693
+ requiredServerKeys
1694
+ });
1695
+ }
1696
+ async function assertNoReservedSchemaKeys() {
1697
+ const { _hasRegisteredSchema, _getRegisteredSchema } = await loadEnvPublic();
1698
+ if (!_hasRegisteredSchema()) return;
1699
+ const reserved = findReservedEnvKeys(Object.keys(_getRegisteredSchema() ?? {}));
1700
+ if (reserved.length > 0) throw new Error(reservedEnvKeysMessage("env.ts", reserved));
1701
+ }
1702
+ function regenerateTypes() {
1703
+ if (!envFile) return;
1704
+ mkdirSync(outDir, { recursive: true });
1705
+ const { dts } = generateEnvTypes(envFile, outDir);
1706
+ writeFileIfChanged(join(outDir, "env.d.ts"), dts);
1707
+ }
1708
+ async function importUserEnv(strict = false) {
1709
+ if (!envFile) return;
1710
+ try {
1711
+ await loadUserEnvFile(envFile);
1712
+ } catch (err) {
1713
+ if (strict) throw err;
1714
+ bwfWarn(err.message);
1715
+ }
1716
+ }
1717
+ async function warnOnDefineOverlap(define) {
1718
+ const { _hasRegisteredSchema, _getRegisteredSchema } = await loadEnvPublic();
1719
+ if (!_hasRegisteredSchema()) return;
1720
+ const schema = _getRegisteredSchema();
1721
+ if (!schema) return;
1722
+ const overlaps = [];
1723
+ for (const defineKey of Object.keys(define)) {
1724
+ const match = DEFINE_ENV_PATTERN.exec(defineKey);
1725
+ if (!match) continue;
1726
+ const name = match[1];
1727
+ if (name in schema) overlaps.push({
1728
+ defineKey,
1729
+ schemaKey: name
1730
+ });
1731
+ }
1732
+ if (overlaps.length === 0) return;
1733
+ const lines = ["Vite `define` is shadowing schema env keys:"];
1734
+ for (const { defineKey, schemaKey } of overlaps) lines.push(` • "${defineKey}" → schema key "${schemaKey}". The compiled client code receives the define value, but the typed env.X proxy and validation still source from the schema. Prefer one or the other for any given key.`);
1735
+ bwfWarn(lines.join("\n"));
1736
+ }
1737
+ async function validateAndWarn() {
1738
+ if (!envFile) return;
1739
+ const { _hasRegisteredSchema, validateAllEnv } = await loadEnvPublic();
1740
+ if (!_hasRegisteredSchema()) return;
1741
+ const report = await validateAllEnv({
1742
+ ...loadLocalEnv(root, { onWarn: (message) => bwfWarn(message) }),
1743
+ ...process.env
1744
+ });
1745
+ if (report.valid) return;
1746
+ const lines = ["Env validation issues:"];
1747
+ for (const key of report.missing) lines.push(` • ${key} is required but missing — add it to .env or set it in your shell`);
1748
+ for (const { key, messages } of report.invalid) lines.push(` • ${key}: ${messages.join("; ")}`);
1749
+ bwfWarn(lines.join("\n"));
1750
+ }
1751
+ async function applyClientValuesToViteEnv(config) {
1752
+ if (!envFile) return;
1753
+ const configEnv = config.env ?? {};
1754
+ for (const [key, value] of appliedClientDefaults) if (configEnv[key] === value) delete configEnv[key];
1755
+ appliedClientDefaults.clear();
1756
+ const { _hasRegisteredSchema, _getRegisteredSchema, _getSchemaDefaults } = await loadEnvPublic();
1757
+ if (!_hasRegisteredSchema()) return;
1758
+ const schema = _getRegisteredSchema() ?? {};
1759
+ const readable = {
1760
+ ...command === "serve" ? loadLocalEnv(root) : {},
1761
+ ...process.env
1762
+ };
1763
+ for (const key of Object.keys(schema)) {
1764
+ if (!isClientEnvKey(key) || configEnv[key] !== void 0) continue;
1765
+ const value = readable[key];
1766
+ if (value !== void 0) configEnv[key] = value;
1767
+ }
1768
+ for (const [key, value] of Object.entries(_getSchemaDefaults())) {
1769
+ if (!isClientEnvKey(key) || configEnv[key] !== void 0) continue;
1770
+ configEnv[key] = value;
1771
+ appliedClientDefaults.set(key, value);
1772
+ }
1773
+ }
1774
+ return {
1775
+ name: "nosam:env-schema",
1776
+ enforce: "pre",
1777
+ async config(_config, environment) {
1778
+ processEnvCopiesBefore = environment.command === "build" ? readProcessEnvCopies() : void 0;
1779
+ const legacyFiles = findLegacyEnvFiles(root);
1780
+ if (legacyFiles.length > 0) throw new Error(`@builtbyfriends/bwf/env supports one local file: .env. Remove ${legacyFiles.join(", ")} and follow the env migration guide.${legacyEnvExampleHint(legacyFiles)}`);
1781
+ const reservedInDotenv = findReservedEnvKeys(scanWranglerDotenvKeys(join(root, LOCAL_ENV_FILE)));
1782
+ if (reservedInDotenv.length > 0) throw new Error(reservedEnvKeysMessage(".env", reservedInDotenv));
1783
+ envFile = findEnvFile(root);
1784
+ envFileIds = envFileIdsFor(envFile);
1785
+ if (!envFile) return;
1786
+ regenerateTypes();
1787
+ await importUserEnv(environment.command === "build");
1788
+ await emitSchemaFacts();
1789
+ await assertNoReservedSchemaKeys();
1790
+ },
1791
+ async configResolved(config) {
1792
+ command = config.command;
1793
+ if (command === "build") stripLocalClientEnv(root, config, processEnvCopiesBefore);
1794
+ await applyClientValuesToViteEnv(config);
1795
+ if (command === "build" && envFile) {
1796
+ const { validateAllEnv } = await loadEnvPublic();
1797
+ const report = await validateAllEnv({
1798
+ ...config.env,
1799
+ ...process.env
1800
+ });
1801
+ const missing = report.missing.filter(isClientEnvKey);
1802
+ const invalid = report.invalid.filter(({ key }) => isClientEnvKey(key));
1803
+ if (missing.length > 0 || invalid.length > 0) {
1804
+ const lines = ["Client env validation failed:"];
1805
+ for (const key of missing) lines.push(` • ${key} is required — set it in the build shell or add a schema default`);
1806
+ for (const { key, messages } of invalid) lines.push(` • ${key}: ${messages.join("; ")}`);
1807
+ throw new Error(lines.join("\n"));
1808
+ }
1809
+ }
1810
+ if (envFile && config.define) await warnOnDefineOverlap(config.define);
1811
+ },
1812
+ async configureServer(server) {
1813
+ if (!envFile) return;
1814
+ afterServerReady(server, () => {
1815
+ validateAndWarn();
1816
+ });
1817
+ server.watcher.add(envFile);
1818
+ server.watcher.on("change", async (file) => {
1819
+ if (file === envFile) {
1820
+ bwfLog("env.ts changed — regenerating types");
1821
+ regenerateTypes();
1822
+ await importUserEnv();
1823
+ await emitSchemaFacts();
1824
+ await applyClientValuesToViteEnv(server.config);
1825
+ await validateAndWarn();
1826
+ server.ws.send({ type: "full-reload" });
1827
+ }
1828
+ });
1829
+ },
1830
+ async buildStart() {
1831
+ if (envFile) await importUserEnv();
1832
+ },
1833
+ ...envFileIds.size > 0 && { transform: keepEnvFileImport }
1834
+ };
1835
+ }
1836
+ // src/plugin-migration.ts
1837
+ function readDatabaseUrl(root) {
1838
+ return loadLocalEnv(root).DATABASE_URL;
1839
+ }
1840
+ /**
1841
+ * DATABASE_URL as Better Auth's local migrations read it: the shell before `.env`. An empty
1842
+ * shell value counts as unset.
1843
+ */
1844
+ function readAuthDatabaseUrl(root) {
1845
+ return process.env.DATABASE_URL || readDatabaseUrl(root) || void 0;
1846
+ }
1847
+ /**
1848
+ * Vite plugin that runs local migrations on dev server startup.
1849
+ * For SQLite/D1: applies migrations to the local miniflare database.
1850
+ * For PostgreSQL/MySQL: connects via DATABASE_URL from .env.
1851
+ */
1852
+ function migrationPlugin(root, dialect, databaseId = "local", persistRoot = join(root, ".bwf"), auth) {
1853
+ return {
1854
+ name: "nosam:migrations",
1855
+ apply: (config, { command }) => command === "serve" && !isVitestServer(config),
1856
+ async configureServer(server) {
1857
+ const paths = readProjectPaths(root);
1858
+ const migrationsDir = paths.migrationsDir;
1859
+ const hasSqlMigrations = existsSync(migrationsDir);
1860
+ if (!hasSqlMigrations && !auth?.enabled) return;
1861
+ const migrateAuth = async (databaseUrl) => {
1862
+ const { runLocalBwfAuthMigrations } = await import("./node-tfv-3v0V.mjs");
1863
+ await runLocalBwfAuthMigrations(root, dialect, persistRoot, databaseId, auth?.configPath, databaseUrl, devAuthConfigImporter(server));
1864
+ };
1865
+ const mysqlAuth = dialect === "mysql" && auth?.enabled === true;
1866
+ const logApplied = (applied) => {
1867
+ if (applied.length > 0) bwfLog(`Applied ${applied.length} migration(s): ${applied.join(", ")}`);
1868
+ };
1869
+ const refuse = (err) => {
1870
+ afterServerReady(server, () => {
1871
+ console.log();
1872
+ bwfError(`${err instanceof Error ? err.message : String(err)}\nNo migrations were applied. Fix the files, then restart the dev server.`);
1873
+ });
1874
+ };
1875
+ try {
1876
+ if (dialect !== "sqlite") {
1877
+ const { collectMigrations } = await import("./collect-8i0wU63d.mjs");
1878
+ const allMigrations = collectMigrations(migrationsDir);
1879
+ const runFiles = dialect === "mysql" ? allMigrations.length > 0 : hasSqlMigrations;
1880
+ const url = runFiles ? readDatabaseUrl(root) : void 0;
1881
+ const authUrl = mysqlAuth ? readAuthDatabaseUrl(root) : void 0;
1882
+ if (runFiles && !url || auth?.enabled && !readAuthDatabaseUrl(root)) {
1883
+ afterServerReady(server, () => {
1884
+ console.log();
1885
+ bwfError(`DATABASE_URL not found in .env — skipping ${dialect === "mysql" ? "MySQL" : "PostgreSQL"} migrations.`);
1886
+ });
1887
+ return;
1888
+ }
1889
+ const authWithFiles = authUrl !== void 0 && authUrl === url;
1890
+ if (url) {
1891
+ const { validateMigrations } = await import("./validate-DbqGdPPY.mjs");
1892
+ const appliedNames = dialect === "mysql" ? await import("./runner-mysql-BjSoQ-mW.mjs").then((runner) => runner.getMySqlAppliedMigrations(url)) : await import("./runner-pg-2pjltt0t.mjs").then((runner) => runner.getPgAppliedMigrations(url));
1893
+ const appliedSet = new Set(appliedNames);
1894
+ const pending = allMigrations.filter((migration) => !appliedSet.has(migration.name));
1895
+ if (pending.length > 0) try {
1896
+ validateMigrations(pending);
1897
+ } catch (err) {
1898
+ refuse(err);
1899
+ return;
1900
+ }
1901
+ const applied = dialect === "mysql" ? await import("./runner-mysql-BjSoQ-mW.mjs").then((runner) => runner.runMySqlMigrations(migrationsDir, url, authWithFiles ? async (names) => {
1902
+ logApplied(names);
1903
+ await migrateAuth(url);
1904
+ } : void 0)) : await import("./runner-pg-2pjltt0t.mjs").then((runner) => runner.runPgMigrations(migrationsDir, url));
1905
+ if (!authWithFiles) logApplied(applied);
1906
+ }
1907
+ if (authUrl && !authWithFiles) {
1908
+ const { withMySqlMigrationLockAt } = await import("./runner-mysql-BjSoQ-mW.mjs");
1909
+ await withMySqlMigrationLockAt(authUrl, () => migrateAuth(authUrl));
1910
+ }
1911
+ } else if (hasSqlMigrations) {
1912
+ const { runMigrations, getMiniflareDatabasePath, getAppliedMigrations } = await import("./runner-CUNtS5x7.mjs");
1913
+ const { collectMigrations } = await import("./collect-8i0wU63d.mjs");
1914
+ const { validateMigrations } = await import("./validate-DbqGdPPY.mjs");
1915
+ const dbPath = getMiniflareDatabasePath(persistRoot, databaseId);
1916
+ const allMigrations = collectMigrations(migrationsDir);
1917
+ const appliedRows = await getAppliedMigrations(dbPath);
1918
+ const appliedSet = new Set(appliedRows.map((r) => r.name));
1919
+ const pending = allMigrations.filter((m) => !appliedSet.has(m.name));
1920
+ if (pending.length > 0) try {
1921
+ validateMigrations(pending);
1922
+ } catch (err) {
1923
+ refuse(err);
1924
+ return;
1925
+ }
1926
+ const applied = await runMigrations(migrationsDir, dbPath, paths.sourceRelative);
1927
+ if (applied.length > 0) bwfLog(`Applied ${applied.length} migration(s): ${applied.join(", ")}`);
1928
+ }
1929
+ if (auth?.enabled) {
1930
+ if (!mysqlAuth) await migrateAuth();
1931
+ bwfLog("Applied Better Auth migrations");
1932
+ }
1933
+ } catch (err) {
1934
+ bwfError(`Migration error: ${err}`);
1935
+ }
1936
+ }
1937
+ };
1938
+ }
1939
+ // src/plugin-restart.ts
1940
+ const BINDING_HINT_RESOLVED = "\0virtual:bwf/binding-hint";
1941
+ const RESTARTING_HTML_HEAD = `<!DOCTYPE html>
1942
+ <html lang="en">
1943
+ <head>
1944
+ <meta charset="UTF-8">
1945
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1946
+ <title>Restarting</title>
1947
+ <style>
1948
+ body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;background:#1a1a2e;color:#e0def4;font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
1949
+ .tag{color:#c4a7e7;font-weight:700}
1950
+ @keyframes d{0%,80%{opacity:0}40%{opacity:1}}
1951
+ .dots span{opacity:0;animation:d 1.4s infinite}
1952
+ .dots span:nth-child(2){animation-delay:.2s}
1953
+ .dots span:nth-child(3){animation-delay:.4s}
1954
+ </style>
1955
+ </head>
1956
+ <body>
1957
+ <div><span class="tag">[bwf]</span> Restarting dev server<span class="dots"><span>.</span><span>.</span><span>.</span></span></div>
1958
+ <script>
1959
+ var target=`;
1960
+ const RESTARTING_HTML_MIDDLE = `;
1961
+ var token=`;
1962
+ const RESTARTING_HTML_TAIL = `;
1963
+ fetch("/__nosam/restart",{method:"POST",headers:{"x-nosam-restart":token}}).catch(function(){});
1964
+ setTimeout(function p(){
1965
+ fetch("/__nosam/ping").then(function(r){
1966
+ if(r.ok)location.href=target;
1967
+ else setTimeout(p,150);
1968
+ }).catch(function(){setTimeout(p,150)});
1969
+ },300);
1970
+ <\/script>
1971
+ </body>
1972
+ </html>`;
1973
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
1974
+ /**
1975
+ * Returns `value` when it is a path on the dev server's own origin, else `/`.
1976
+ * The restarting page navigates to it, so a scheme (`javascript:`) or a
1977
+ * protocol-relative form (`//host`, `/\host`) must never get through.
1978
+ */
1979
+ function sanitizeReturnPath(value) {
1980
+ if (!value || value[0] !== "/" || value[1] === "/" || value[1] === "\\") return "/";
1981
+ if (CONTROL_CHARS.test(value)) return "/";
1982
+ const base = "http://nosam.invalid";
1983
+ try {
1984
+ if (new URL(value, base).origin !== base) return "/";
1985
+ } catch {
1986
+ return "/";
1987
+ }
1988
+ return value;
1989
+ }
1990
+ /**
1991
+ * `token` is the `t` query value the toast navigated with. The page sends it
1992
+ * back with its POST; `/__nosam/restart` checks it, not this page.
1993
+ */
1994
+ function renderRestartingPage(returnPath, token) {
1995
+ return RESTARTING_HTML_HEAD + scriptJson(sanitizeReturnPath(returnPath)) + RESTARTING_HTML_MIDDLE + scriptJson(token ?? "") + RESTARTING_HTML_TAIL;
1996
+ }
1997
+ /** Whether `presented` is this server's restart token, compared in constant time. */
1998
+ function isRestartTokenValid(presented, expected) {
1999
+ if (typeof presented !== "string" || expected.length === 0) return false;
2000
+ const a = Buffer.from(presented);
2001
+ const b = Buffer.from(expected);
2002
+ return a.byteLength === b.byteLength && timingSafeEqual(a, b);
2003
+ }
2004
+ /**
2005
+ * Whether a browser sent `req` from the dev server's own origin. Any page the
2006
+ * developer visits can POST to localhost, so cross-site callers are refused.
2007
+ * `Sec-Fetch-Site` is set by the browser and cannot be forged by a page;
2008
+ * `Origin` is the fallback for browsers that do not send it. Clients that send
2009
+ * neither (curl, scripts) are not browsers acting for another site.
2010
+ */
2011
+ function isSameOriginRequest(req) {
2012
+ const site = req.headers["sec-fetch-site"];
2013
+ if (site !== void 0) return site === "same-origin";
2014
+ const origin = req.headers.origin;
2015
+ if (origin === void 0) return true;
2016
+ const host = req.headers.host;
2017
+ if (!host) return false;
2018
+ return origin === `${req.socket?.encrypted ? "https" : "http"}://${host}`;
2019
+ }
2020
+ /** Whether a browser navigated here from the dev origin itself or from the address bar. */
2021
+ function isSameOriginNavigation(req) {
2022
+ const site = req.headers["sec-fetch-site"];
2023
+ return site === void 0 || site === "same-origin" || site === "none";
2024
+ }
2025
+ /**
2026
+ * The toast is the only in-app way to reach `/__nosam/restarting`, so it is
2027
+ * the only place that knows the restart token. Vite's default `server.cors`
2028
+ * lets only localhost origins read this module, the same exposure as the
2029
+ * HMR token in `/@vite/client`.
2030
+ */
2031
+ const clientModule = (token) => `if (import.meta.hot) {
2032
+ const token = ${JSON.stringify(token)};
2033
+ import.meta.hot.on("nosam:new-binding", (d) => {
2034
+ if (document.getElementById("nosam-binding-hint")) return;
2035
+ const e = document.createElement("div");
2036
+ e.id = "nosam-binding-hint";
2037
+ e.style.cssText = "position:fixed;top:16px;right:16px;z-index:99999;padding:12px 16px;background:rgba(26,26,46,0.95);color:#e0def4;font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;border-radius:8px;border:1px solid rgba(255,255,255,0.08);box-shadow:0 8px 32px rgba(0,0,0,0.4);backdrop-filter:blur(8px);cursor:pointer;max-width:300px;transform:translateX(calc(100% + 16px));transition:transform .3s ease";
2038
+ e.innerHTML = "<strong style=\\"color:#c4a7e7\\">[bwf]</strong> " + d.message + " Click to restart.";
2039
+ e.onclick = () => { location.href = "/__nosam/restarting?return=" + encodeURIComponent(location.pathname + location.search) + "&t=" + encodeURIComponent(token); };
2040
+ document.body.appendChild(e);
2041
+ requestAnimationFrame(() => requestAnimationFrame(() => {
2042
+ e.style.transform = "translateX(0)";
2043
+ }));
2044
+ });
2045
+ }`;
2046
+ /**
2047
+ * Vite plugin that provides controlled dev-server restart via the browser.
2048
+ *
2049
+ * Serves three endpoints:
2050
+ * - `/__nosam/restarting` — standalone loading page (no Vite HMR client);
2051
+ * same-origin navigation only
2052
+ * - `/__nosam/restart` — same-origin POST carrying this server's restart
2053
+ * token triggers `server.restart()` after a short delay
2054
+ * - `/__nosam/ping` — health check; returns 503 on the old server instance
2055
+ * (after restart is triggered) and 200 on the new one
2056
+ *
2057
+ * Also injects a virtual module (`virtual:bwf/binding-hint`) that listens for
2058
+ * `nosam:new-binding` HMR events and shows a toast with a click-to-restart action.
2059
+ */
2060
+ function restartPlugin() {
2061
+ let restartToken = "";
2062
+ return {
2063
+ name: "nosam:restart",
2064
+ apply: "serve",
2065
+ resolveId: {
2066
+ filter: { id: /^virtual:bwf\/binding-hint$/ },
2067
+ handler() {
2068
+ return BINDING_HINT_RESOLVED;
2069
+ }
2070
+ },
2071
+ load: {
2072
+ filter: { id: /^\0virtual:bwf\/binding-hint$/ },
2073
+ handler() {
2074
+ return clientModule(restartToken);
2075
+ }
2076
+ },
2077
+ configureServer(server) {
2078
+ let restartPending = false;
2079
+ const token = randomBytes(16).toString("base64url");
2080
+ restartToken = token;
2081
+ server.middlewares.use("/__nosam/ping", (_req, res) => {
2082
+ res.writeHead(restartPending ? 503 : 200);
2083
+ res.end();
2084
+ });
2085
+ server.middlewares.use("/__nosam/restart", (req, res) => {
2086
+ if (req.method !== "POST") {
2087
+ res.writeHead(405);
2088
+ res.end();
2089
+ return;
2090
+ }
2091
+ if (!isSameOriginRequest(req) || !isRestartTokenValid(req.headers["x-nosam-restart"], token)) {
2092
+ res.writeHead(403);
2093
+ res.end();
2094
+ return;
2095
+ }
2096
+ restartPending = true;
2097
+ res.writeHead(200);
2098
+ res.end();
2099
+ setTimeout(() => server.restart(), 50);
2100
+ });
2101
+ server.middlewares.use("/__nosam/restarting", (req, res) => {
2102
+ if (!isSameOriginNavigation(req)) {
2103
+ res.writeHead(403, { "Content-Type": "text/plain" });
2104
+ res.end("Restart the dev server from its own page.");
2105
+ return;
2106
+ }
2107
+ let returnPath = null;
2108
+ let presented = null;
2109
+ try {
2110
+ const params = new URL(req.url ?? "/", "http://nosam.invalid").searchParams;
2111
+ returnPath = params.get("return");
2112
+ presented = params.get("t");
2113
+ } catch {}
2114
+ res.writeHead(200, {
2115
+ "Content-Type": "text/html",
2116
+ "Cache-Control": "no-store",
2117
+ "Referrer-Policy": "no-referrer"
2118
+ });
2119
+ res.end(renderRestartingPage(returnPath, presented));
2120
+ });
2121
+ }
2122
+ };
2123
+ }
2124
+ function scriptJson(value) {
2125
+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
2126
+ }
2127
+ // src/client-asset-manifest.ts
2128
+ /**
2129
+ * Attach cache provenance to the existing manifest without changing its entry inventory.
2130
+ * Returns the stamped immutable files, sorted, relative to the client root.
2131
+ */
2132
+ function stampClientAssetCachePolicy(bundle, manifestPath, headerRules = []) {
2133
+ const asset = bundle[manifestPath];
2134
+ if (asset?.type !== "asset") return [];
2135
+ const fingerprinted = /* @__PURE__ */ new Set();
2136
+ const authoredCachePatterns = headerRules.filter((rule) => rule.headers.some(([name]) => name.toLowerCase() === "cache-control")).map((rule) => rule.pattern);
2137
+ for (const pattern of authoredCachePatterns) compilePattern(pattern);
2138
+ for (const item of Object.values(bundle)) if (item.type === "chunk" && typeof item.preliminaryFileName === "string" && item.preliminaryFileName !== item.fileName) {
2139
+ if (!authoredCachePatterns.some((pattern) => matchPattern(pattern, "/" + item.fileName))) fingerprinted.add(item.fileName);
2140
+ }
2141
+ const manifest = JSON.parse(String(asset.source));
2142
+ const stamped = /* @__PURE__ */ new Set();
2143
+ for (const entry of Object.values(manifest)) if (entry.file && fingerprinted.has(entry.file)) {
2144
+ entry.immutableFiles = [entry.file];
2145
+ stamped.add(entry.file);
2146
+ } else delete entry.immutableFiles;
2147
+ asset.source = JSON.stringify(manifest, null, 2);
2148
+ return [...stamped].sort();
2149
+ }
2150
+ // src/queues/dispatch.ts
2151
+ /**
2152
+ * Emit the queue-name resolver used by generated native workers and framework
2153
+ * wrappers. Hosted relays send the exact logical name. Native Queue events may
2154
+ * expose a project-prefixed physical name, so fallback matching selects the
2155
+ * unique longest known `-name` suffix. Unknown or ambiguous inputs fail closed.
2156
+ *
2157
+ * `cloudflareNames` (aligned with `queueNames`) comes from
2158
+ * `bwf deploy --platform cloudflare`, which knows each queue's exact name.
2159
+ * Its events then match exactly: a suffix could pick the wrong queue, as
2160
+ * `app-jobs` would for queues `jobs` and `app-jobs` in Worker `app`. Logical
2161
+ * names still match, for the trigger endpoint.
2162
+ */
2163
+ function generateQueueResolverSource(queueNames, cloudflareNames) {
2164
+ if (cloudflareNames) {
2165
+ const indexByName = {};
2166
+ cloudflareNames.forEach((name, index) => {
2167
+ indexByName[name] = index;
2168
+ });
2169
+ queueNames.forEach((name, index) => {
2170
+ if (!Object.hasOwn(indexByName, name)) indexByName[name] = index;
2171
+ });
2172
+ return `const __queueIndexByName = ${JSON.stringify(indexByName)};
2173
+ function __resolveQueueIndex(queueName) {
2174
+ if (typeof queueName !== "string" || !Object.hasOwn(__queueIndexByName, queueName)) return -1;
2175
+ return __queueIndexByName[queueName];
2176
+ }`;
2177
+ }
2178
+ return `const __queueNames = ${JSON.stringify(queueNames)};
2179
+ function __resolveQueueIndex(queueName) {
2180
+ if (typeof queueName !== "string") return -1;
2181
+ const exact = __queueNames.indexOf(queueName);
2182
+ if (exact !== -1) return exact;
2183
+ let match = -1;
2184
+ let matchLength = -1;
2185
+ for (let i = 0; i < __queueNames.length; i++) {
2186
+ const name = __queueNames[i];
2187
+ if (!queueName.endsWith("-" + name)) continue;
2188
+ if (name.length > matchLength) {
2189
+ match = i;
2190
+ matchLength = name.length;
2191
+ } else if (name.length === matchLength) {
2192
+ match = -1;
2193
+ }
2194
+ }
2195
+ return match;
2196
+ }`;
2197
+ }
2198
+ // src/router/compile.ts
2199
+ const FETCH_SERVER_PATH = fileURLToPath(import.meta.resolve("#self/runtime/fetch-server"));
2200
+ const ROUTING_RUNTIME_PATH = fileURLToPath(import.meta.resolve("#self/runtime/routing"));
2201
+ /**
2202
+ * Returns a lookup that gives each key its own identifier suffix. The suffix
2203
+ * keeps the key's ASCII letters and digits; keys that clean up to the same
2204
+ * text (user-list.ts and user_list.ts, or two CJK names of one length) get a
2205
+ * counter so the generated consts never clash.
2206
+ */
2207
+ function createIdentifierNames() {
2208
+ const byKey = /* @__PURE__ */ new Map();
2209
+ const used = /* @__PURE__ */ new Set();
2210
+ return (key) => {
2211
+ const known = byKey.get(key);
2212
+ if (known !== void 0) return known;
2213
+ let base = "";
2214
+ for (const char of key.split("")) base += char >= "0" && char <= "9" || char >= "a" && char <= "z" || char >= "A" && char <= "Z" ? char : "_";
2215
+ let name = base;
2216
+ for (let n = 2; used.has(name); n++) name = `${base}_${n}`;
2217
+ used.add(name);
2218
+ byKey.set(key, name);
2219
+ return name;
2220
+ };
2221
+ }
2222
+ /**
2223
+ * Generate the code for the virtual route table module (virtual:nosam-routes).
2224
+ * This module creates a Hono app with:
2225
+ * - Middleware registered via app.use()
2226
+ * - Routes registered with lazy-loaded handlers and auto-conversion
2227
+ */
2228
+ function compileRouteTable(scan, routesDir, middlewareDir, jobsDir, queuesDir, options) {
2229
+ const lines = [];
2230
+ const auth = options.auth;
2231
+ const webSockets = scan.websockets ?? [];
2232
+ const managedDispatch = options.dev !== true && options.managedDispatch === true;
2233
+ lines.push(`import { AsyncLocalStorage } from "node:async_hooks";`);
2234
+ lines.push(`import { Hono } from ${JSON.stringify(options.honoPath)};`);
2235
+ lines.push(`import { createRoutingRuntime as __createRoutingRuntime, createHttpRouteHandler as __createHttpRouteHandler, createModuleLoader as __createModuleLoader, createAssetNotFound as __createAssetNotFound } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};`);
2236
+ lines.push(`import { withRuntimeEnv } from ${JSON.stringify(options.runtimeEnvPath)};`);
2237
+ if (auth) {
2238
+ const authImports = [
2239
+ "runBwfAuthMiddleware",
2240
+ "handleBwfAuthRequest",
2241
+ "runBwfAuthMigrations"
2242
+ ];
2243
+ if (webSockets.length > 0) authImports.push("resolveBwfAuthState as __resolveBwfAuthStateRuntime");
2244
+ lines.push(`import { ${authImports.join(", ")} } from ${JSON.stringify(auth.authRuntimePath)};`);
2245
+ lines.push(`import { __nosamAuthDatabase } from ${JSON.stringify(auth.authDatabasePath)};`);
2246
+ lines.push(`import { migrationSchema as __nosamAuthMigrationSchema } from ${JSON.stringify(auth.authSchemaPath)};`);
2247
+ if (auth.authConfigPath) lines.push(`import __nosamAuthConfig from ${JSON.stringify(auth.authConfigPath)};`);
2248
+ }
2249
+ if ((webSockets.length > 0 || options.webSocketTombstones?.length) && options.webSocketRuntimePath) lines.push(`import { createWebSocketDurableObject as __createWebSocketDurableObject, createWebSocketTombstoneDurableObject as __createWebSocketTombstoneDurableObject, forwardWebSocketRequest as __forwardWebSocketRequest } from ${JSON.stringify(options.webSocketRuntimePath)};`);
2250
+ if (options.hasLive && options.liveRuntimePath) lines.push(`import { createLiveDurableObject as __createLiveDurableObject } from ${JSON.stringify(options.liveRuntimePath)};`);
2251
+ lines.push("");
2252
+ for (let i = 0; i < scan.middleware.length; i++) {
2253
+ const mw = scan.middleware[i];
2254
+ lines.push(`import middleware${i} from ${JSON.stringify(`${middlewareDir}/${mw.filePath}`)};`);
2255
+ }
2256
+ for (let i = 0; i < webSockets.length; i++) {
2257
+ const route = webSockets[i];
2258
+ lines.push(`import websocket${i} from ${JSON.stringify(`${routesDir}/${route.filePath}`)};`);
2259
+ }
2260
+ const procedureFiles = options.procedures ? scan.procedures ?? [] : [];
2261
+ if (procedureFiles.length > 0) lines.push(`import { mountProcedures as __mountProcedures } from ${JSON.stringify(options.procedures.runtimePath)};`);
2262
+ for (let i = 0; i < procedureFiles.length; i++) lines.push(`import * as procedures${i} from ${JSON.stringify(`${options.procedures.dir}/${procedureFiles[i].filePath}`)};`);
2263
+ lines.push("");
2264
+ if (auth) {
2265
+ lines.push(`const __nosamAuthOptions = { dialect: ${JSON.stringify(auth.dialect)}, providers: ${JSON.stringify(auth.providers)}, userConfig: ${auth.authConfigPath ? "__nosamAuthConfig" : "undefined"}, dev: ${JSON.stringify(options.dev === true)} };`);
2266
+ if (webSockets.length > 0) lines.push("const __resolveBwfAuthState = (request, env, runtime) => __resolveBwfAuthStateRuntime(request, env, runtime, __nosamAuthDatabase);");
2267
+ lines.push("");
2268
+ }
2269
+ lines.push(`const app = new Hono();`);
2270
+ const routePatterns = [];
2271
+ for (const r of scan.routes) routePatterns.push(r.pattern);
2272
+ const usedExts = /* @__PURE__ */ new Set();
2273
+ for (const p of routePatterns) {
2274
+ const m = /\.([A-Za-z0-9]+)$/.exec(p);
2275
+ if (m) usedExts.add(m[1].toLowerCase());
2276
+ }
2277
+ const blockedExts = ASSET_EXTENSIONS.filter((e) => !usedExts.has(e));
2278
+ lines.push(`const __routingRuntime = __createRoutingRuntime(app, ${JSON.stringify({
2279
+ dev: options.dev === true,
2280
+ managedDispatch,
2281
+ blockedAssetExtensions: blockedExts
2282
+ })});`);
2283
+ lines.push("export const requestContext = __routingRuntime.requestContext;");
2284
+ lines.push("app.use(__routingRuntime.contextMiddleware);");
2285
+ lines.push("app.use(__routingRuntime.requestMiddleware);");
2286
+ lines.push("");
2287
+ const emitEdgeRules = !managedDispatch;
2288
+ const fallbackRulesJson = JSON.stringify(emitEdgeRules && options.fallbackRules?.length ? options.dev ? options.fallbackRules : stripOriginForProd(options.fallbackRules) : void 0);
2289
+ if (emitEdgeRules && options.redirectRules?.length) compileRoutingRulesMiddleware(lines, options.redirectRules, options.dev === true);
2290
+ const headerRules = emitEdgeRules ? options.headerRules : void 0;
2291
+ if (headerRules?.length) lines.push(`const __headerRules = ${JSON.stringify(headerRules)};`);
2292
+ if (auth) {
2293
+ if (headerRules?.length) lines.push("app.use(\"*\", __routingRuntime.headerMiddleware(__headerRules, \"auth-error\"));");
2294
+ lines.push("app.use(async (c, next) => {");
2295
+ lines.push(" return runBwfAuthMiddleware(c, next, __nosamAuthOptions, __nosamAuthDatabase);");
2296
+ lines.push("});");
2297
+ lines.push("");
2298
+ }
2299
+ if (headerRules?.length) lines.push("app.use(\"*\", __routingRuntime.headerMiddleware(__headerRules));");
2300
+ for (let i = 0; i < scan.middleware.length; i++) lines.push(`app.use(middleware${i});`);
2301
+ if (scan.middleware.length > 0) lines.push("");
2302
+ for (let i = 0; i < webSockets.length; i++) {
2303
+ const route = webSockets[i];
2304
+ lines.push(`app.all(${JSON.stringify(route.pattern)}, async (c, next) => {`);
2305
+ lines.push(` if (c.req.raw.headers.get("upgrade")?.toLowerCase() !== "websocket") return next();`);
2306
+ lines.push(` return __forwardWebSocketRequest(c.req.raw, c.env, __nosamWebSocketRoutes[${i}]);`);
2307
+ lines.push("});");
2308
+ }
2309
+ if (webSockets.length > 0) lines.push("");
2310
+ if (auth) {
2311
+ lines.push("app.all(\"/api/auth\", async (c) => {");
2312
+ lines.push(" return handleBwfAuthRequest(c, __nosamAuthOptions, __nosamAuthDatabase);");
2313
+ lines.push("});");
2314
+ lines.push("");
2315
+ lines.push("app.all(\"/api/auth/*\", async (c) => {");
2316
+ lines.push(" return handleBwfAuthRequest(c, __nosamAuthOptions, __nosamAuthDatabase);");
2317
+ lines.push("});");
2318
+ lines.push("");
2319
+ }
2320
+ if (procedureFiles.length > 0) {
2321
+ const modules = procedureFiles.map((file, i) => `[${JSON.stringify(file.prefix)}, procedures${i}]`);
2322
+ const { name, version } = options.procedures;
2323
+ lines.push(`__mountProcedures(app, [${modules.join(", ")}], ${JSON.stringify({
2324
+ dev: options.dev === true,
2325
+ name,
2326
+ version
2327
+ })});`);
2328
+ lines.push("");
2329
+ }
2330
+ const seenFiles = /* @__PURE__ */ new Set();
2331
+ const routeNames = createIdentifierNames();
2332
+ for (const route of scan.routes) {
2333
+ const filePath = `${routesDir}/${route.filePath}`;
2334
+ const loaderName = `_load_${routeNames(route.filePath)}`;
2335
+ if (!seenFiles.has(route.filePath)) {
2336
+ seenFiles.add(route.filePath);
2337
+ lines.push(`const ${loaderName} = __createModuleLoader(() => import(${JSON.stringify(filePath)}), ${JSON.stringify(options.dev !== true)});`);
2338
+ }
2339
+ if (route.methods.length === 0) lines.push(`app.all(${JSON.stringify(route.pattern)}, __createHttpRouteHandler(${loaderName}, "default"));`);
2340
+ else for (const method of route.methods) {
2341
+ const honoMethod = method.toLowerCase();
2342
+ lines.push(`app.${honoMethod}(${JSON.stringify(route.pattern)}, __createHttpRouteHandler(${loaderName}, ${JSON.stringify(method)}));`);
2343
+ }
2344
+ }
2345
+ lines.push("");
2346
+ if (webSockets.length > 0) {
2347
+ for (let i = 0; i < webSockets.length; i++) {
2348
+ const route = webSockets[i];
2349
+ lines.push(`export const ${route.className} = __createWebSocketDurableObject(websocket${i}, ${JSON.stringify({
2350
+ pattern: route.pattern,
2351
+ params: route.params,
2352
+ className: route.className,
2353
+ bindingName: route.bindingName,
2354
+ ...route.name !== void 0 && { name: route.name }
2355
+ })}, ${auth ? "__nosamAuthOptions" : "undefined"}, ${auth ? "__resolveBwfAuthState" : "undefined"});`);
2356
+ }
2357
+ lines.push("");
2358
+ lines.push(`const __nosamWebSocketRoutes = ${JSON.stringify(webSockets.map((route) => ({
2359
+ pattern: route.pattern,
2360
+ params: route.params,
2361
+ className: route.className,
2362
+ bindingName: route.bindingName,
2363
+ ...route.name !== void 0 && { name: route.name }
2364
+ })))};`);
2365
+ lines.push("");
2366
+ }
2367
+ for (let i = 0; i < webSockets.length; i++) lines.push(`__nosamWebSocketRoutes[${i}].key = websocket${i}.key;`);
2368
+ for (const className of options.webSocketTombstones ?? []) lines.push(`export const ${className} = __createWebSocketTombstoneDurableObject(${JSON.stringify(className)});`);
2369
+ if (options.webSocketTombstones?.length) lines.push("");
2370
+ if (options.hasLive) {
2371
+ lines.push("export const NosamLiveStreamDurableObject = __createLiveDurableObject();");
2372
+ lines.push("");
2373
+ }
2374
+ for (let i = 0; i < webSockets.length; i++) lines.push(`app.all(${JSON.stringify(webSockets[i].pattern)}, (c) => __forwardWebSocketRequest(c.req.raw, c.env, __nosamWebSocketRoutes[${i}]));`);
2375
+ if (webSockets.length > 0) lines.push("");
2376
+ const trackAssetMisses = !managedDispatch;
2377
+ const registerNotFound = (handler) => {
2378
+ const tracked = trackAssetMisses ? `__routingRuntime.trackNotFound(${handler})` : handler;
2379
+ lines.push(`app.notFound(${tracked});`);
2380
+ };
2381
+ if (trackAssetMisses) lines.push("app.notFound(__routingRuntime.trackNotFound());");
2382
+ if (emitEdgeRules && (options.fallbackRules?.length || options.redirectRules?.some((rule) => rule.status === 200) || options.headerRules?.length)) registerNotFound(`__createAssetNotFound({ routing: __routingRuntime, assetsDir: ${JSON.stringify(options.assetsDir)}, fallbackRules: ${fallbackRulesJson} })`);
2383
+ if (scan.jobs.length > 0) {
2384
+ for (let i = 0; i < scan.jobs.length; i++) {
2385
+ const job = scan.jobs[i];
2386
+ lines.push(`const job${i}Crons = ${JSON.stringify(job.crons)};`);
2387
+ }
2388
+ lines.push("");
2389
+ lines.push("export async function scheduled(controller, env, ctx) {");
2390
+ lines.push(" const run = async (job, loadJob) => {");
2391
+ lines.push(" try {");
2392
+ lines.push(" const mod = await loadJob();");
2393
+ lines.push(" if (typeof mod.default === 'function') await mod.default(controller, env, ctx);");
2394
+ lines.push(" } catch (error) {");
2395
+ lines.push(" console.error(`[bwf] Scheduled job ${job} failed for cron \"${controller.cron}\":`, error);");
2396
+ lines.push(" return { job, error };");
2397
+ lines.push(" }");
2398
+ lines.push(" };");
2399
+ lines.push(" const tasks = [];");
2400
+ for (let i = 0; i < scan.jobs.length; i++) {
2401
+ const job = scan.jobs[i];
2402
+ const filePath = JSON.stringify(`${jobsDir}/${job.filePath}`);
2403
+ const label = JSON.stringify(relative(options.projectRoot, `${jobsDir}/${job.filePath}`));
2404
+ lines.push(` if (job${i}Crons.includes(controller.cron)) tasks.push(run(${label}, () => import(${filePath})));`);
2405
+ }
2406
+ lines.push(" const failures = (await Promise.all(tasks)).filter(Boolean);");
2407
+ lines.push(" if (failures.length) {");
2408
+ lines.push(" throw new AggregateError(failures.map((failure) => failure.error), `Scheduled jobs failed: ${failures.map((failure) => failure.job).join(\", \")}`);");
2409
+ lines.push(" }");
2410
+ lines.push("}");
2411
+ lines.push("");
2412
+ } else {
2413
+ lines.push("export async function scheduled() {}");
2414
+ lines.push("");
2415
+ }
2416
+ if (scan.jobs.length > 0 || scan.queues.length > 0) {
2417
+ lines.push("function __nosamTriggerUnauthorized(c) {");
2418
+ lines.push(" const __token = c.req.header(\"x-nosam-internal\");");
2419
+ lines.push(" const __expected = __getRawEnv()?.__NOSAM_PROXY_TOKEN;");
2420
+ lines.push(" const __devToken = c.req.header(\"x-nosam-dev-trigger\");");
2421
+ lines.push(" return __NOSAM_SERVE ? __devToken !== __NOSAM_DEV_TRIGGER_TOKEN : __expected ? __token !== __expected : __token !== __NOSAM_BUILD_KEY;");
2422
+ lines.push("}");
2423
+ lines.push("");
2424
+ }
2425
+ if (scan.jobs.length > 0) {
2426
+ lines.push("const __scheduledHandler = async (c) => {");
2427
+ lines.push(" if (__nosamTriggerUnauthorized(c)) return c.json({ error: \"unauthorized\" }, 401);");
2428
+ lines.push(" const { cron, scheduledTime } = await c.req.json();");
2429
+ lines.push(" const controller = { cron, scheduledTime, noRetry() {} };");
2430
+ lines.push(" await scheduled(controller, c.env, c.executionCtx);");
2431
+ lines.push(" return c.json({ ok: true });");
2432
+ lines.push("};");
2433
+ lines.push("app.post(\"/__nosam/scheduled\", __scheduledHandler);");
2434
+ lines.push("");
2435
+ }
2436
+ if (scan.queues.length > 0) {
2437
+ const queueNames = scan.queues.map((queue) => queue.name);
2438
+ const cloudflareNames = options.cloudflareQueueNames;
2439
+ lines.push(generateQueueResolverSource(queueNames, cloudflareNames && queueNames.map((name) => cloudflareQueueName(name, cloudflareNames))));
2440
+ lines.push("");
2441
+ const queueLabels = scan.queues.map((queue) => relative(options.projectRoot, `${queuesDir}/${queue.filePath}`));
2442
+ lines.push(`const __queueLabels = ${JSON.stringify(queueLabels)};`);
2443
+ lines.push("export async function __processQueue(payload, env) {");
2444
+ lines.push(" const queueSuffix = payload.queue;");
2445
+ lines.push(" const __queueIndex = __resolveQueueIndex(queueSuffix);");
2446
+ lines.push(" if (__queueIndex === -1) {");
2447
+ lines.push(" const __error = `No unambiguous queue handler matches \"${String(queueSuffix)}\"`;");
2448
+ lines.push(" console.error(`[bwf] ${__error}`);");
2449
+ lines.push(" return { ok: false, error: __error };");
2450
+ lines.push(" }");
2451
+ lines.push(" const __decisions = new Map();");
2452
+ lines.push(" function __wrapMsg(m) {");
2453
+ lines.push(" let decided = false;");
2454
+ lines.push(" return {");
2455
+ lines.push(" id: m.id, timestamp: new Date(m.timestamp), body: m.body, attempts: m.attempts,");
2456
+ lines.push(" ack() { if (!decided) { decided = true; __decisions.set(m.id, { action: \"ack\" }); } },");
2457
+ lines.push(" retry(opts) { if (!decided) { decided = true; __decisions.set(m.id, { action: \"retry\", ...(opts?.delaySeconds != null ? { delaySeconds: opts.delaySeconds } : {}) }); } },");
2458
+ lines.push(" };");
2459
+ lines.push(" }");
2460
+ lines.push(" const __msgs = payload.messages.map(__wrapMsg);");
2461
+ lines.push(" const batch = {");
2462
+ lines.push(" queue: queueSuffix,");
2463
+ lines.push(" messages: __msgs,");
2464
+ lines.push(" ackAll() { for (const m of __msgs) m.ack(); },");
2465
+ lines.push(" retryAll(opts) { for (const m of __msgs) m.retry(opts); },");
2466
+ lines.push(" };");
2467
+ lines.push(" let __ok = true;");
2468
+ lines.push(" try {");
2469
+ lines.push(" switch (__queueIndex) {");
2470
+ for (let i = 0; i < scan.queues.length; i++) {
2471
+ const q = scan.queues[i];
2472
+ lines.push(` case ${i}: {`);
2473
+ lines.push(` const mod = await import(${JSON.stringify(`${queuesDir}/${q.filePath}`)});`);
2474
+ lines.push(" if (typeof mod.default === 'function') await mod.default(batch, env);");
2475
+ lines.push(" break;");
2476
+ lines.push(" }");
2477
+ }
2478
+ lines.push(" }");
2479
+ lines.push(" } catch (error) {");
2480
+ lines.push(" console.error(`[bwf] Queue handler ${__queueLabels[__queueIndex]} failed for queue \"${String(queueSuffix)}\":`, error);");
2481
+ lines.push(" __ok = false;");
2482
+ lines.push(" }");
2483
+ lines.push(" return { ok: __ok, ...(__decisions.size > 0 ? { decisions: Object.fromEntries(__decisions) } : {}) };");
2484
+ lines.push("}");
2485
+ lines.push("");
2486
+ lines.push("const __queueHandler = async (c) => {");
2487
+ lines.push(" if (__nosamTriggerUnauthorized(c)) return c.json({ error: \"unauthorized\" }, 401);");
2488
+ lines.push(" const payload = await c.req.json();");
2489
+ lines.push(" const result = await __processQueue(payload, c.env);");
2490
+ lines.push(" return c.json(result);");
2491
+ lines.push("};");
2492
+ lines.push("app.post(\"/__nosam/queue\", __queueHandler);");
2493
+ lines.push("");
2494
+ }
2495
+ const email = scan.email;
2496
+ const emailDir = options.emailDir;
2497
+ if (emailDir && email && (email.addresses.length > 0 || email.defaultHandler)) {
2498
+ if (email.defaultHandler) lines.push(`const __emailDefault = () => import(${JSON.stringify(`${emailDir}/${email.defaultHandler}`)});`);
2499
+ for (let i = 0; i < email.addresses.length; i++) {
2500
+ const def = email.addresses[i];
2501
+ lines.push(`const __emailAddr${i} = () => import(${JSON.stringify(`${emailDir}/${def.filePath}`)});`);
2502
+ }
2503
+ if (email.addresses.length > 0) {
2504
+ lines.push("const __emailPatterns = [");
2505
+ for (let i = 0; i < email.addresses.length; i++) {
2506
+ const def = email.addresses[i];
2507
+ const path = `${emailDir}/${def.filePath}`;
2508
+ lines.push(` { re: new RegExp(${JSON.stringify(def.pattern.regexSource)}, "i"), params: ${JSON.stringify(def.pattern.paramNames)}, path: ${JSON.stringify(path)}, load: __emailAddr${i} },`);
2509
+ }
2510
+ lines.push("];");
2511
+ }
2512
+ lines.push("");
2513
+ lines.push("export async function __emailHandler(message, env, ctx, __opts) {");
2514
+ lines.push(" const __platformTo = message ? message.__nosamPlatformTo : undefined;");
2515
+ lines.push(" const __to = String((__platformTo ?? (message && message.to)) || \"\");");
2516
+ lines.push(" const __localFull = __to.split(\"@\")[0] || \"\";");
2517
+ lines.push(" let __local = __localFull;");
2518
+ lines.push(" if (__opts && __opts.slug) {");
2519
+ lines.push(" const __plus = __localFull.indexOf(\"+\");");
2520
+ lines.push(" __local = __plus === -1 ? \"\" : __localFull.slice(__plus + 1);");
2521
+ lines.push(" }");
2522
+ if (email.addresses.length > 0) {
2523
+ lines.push(" for (const __p of __emailPatterns) {");
2524
+ lines.push(" const __m = __p.re.exec(__local);");
2525
+ lines.push(" if (!__m) continue;");
2526
+ lines.push(" const __params = {};");
2527
+ lines.push(" for (let __i = 0; __i < __p.params.length; __i++) {");
2528
+ lines.push(" __params[__p.params[__i]] = __m[__i + 1];");
2529
+ lines.push(" }");
2530
+ lines.push(" const __mod = await __p.load();");
2531
+ lines.push(" if (typeof __mod.default !== \"function\") {");
2532
+ lines.push(" throw new Error(\"email handler at \" + __p.path + \" has no default export\");");
2533
+ lines.push(" }");
2534
+ lines.push(" return await __mod.default(message, env, ctx, { params: __params });");
2535
+ lines.push(" }");
2536
+ }
2537
+ if (email.defaultHandler) {
2538
+ const defaultPath = `${emailDir}/${email.defaultHandler}`;
2539
+ lines.push(" const __dmod = await __emailDefault();");
2540
+ lines.push(" if (typeof __dmod.default !== \"function\") {");
2541
+ lines.push(` throw new Error("email handler at " + ${JSON.stringify(defaultPath)} + " has no default export");`);
2542
+ lines.push(" }");
2543
+ lines.push(" return await __dmod.default(message, env, ctx, { params: {} });");
2544
+ } else {
2545
+ lines.push(" if (typeof message.setReject === \"function\") {");
2546
+ lines.push(" message.setReject(\"no handler matched recipient \\\"\" + __to + \"\\\" — add email/_default.ts to handle unmatched mail\");");
2547
+ lines.push(" }");
2548
+ }
2549
+ lines.push("}");
2550
+ lines.push("");
2551
+ }
2552
+ if (options.migrationHandlerPath && (options.migrations?.length || auth)) {
2553
+ const d1BindingName = options.bindingNames?.d1;
2554
+ lines.push(`import { createMigrationHandler as __createMigrationHandler } from ${JSON.stringify(options.migrationHandlerPath)};`);
2555
+ lines.push(`const __migrations = ${JSON.stringify(options.migrations)};`);
2556
+ lines.push(`const __migrationPlanBundle = ${JSON.stringify(options.migrationPlanBundle)};`);
2557
+ if (d1BindingName) lines.push(`function __nosamGetMigrationEnv() {
2558
+ const env = __getRawEnv();
2559
+ if (!env || env[${JSON.stringify(d1BindingName)}] == null) return env;
2560
+ return { ...env, DB: env[${JSON.stringify(d1BindingName)}] };
2561
+ }`);
2562
+ else lines.push("function __nosamGetMigrationEnv() { return __getRawEnv(); }");
2563
+ lines.push("function __nosamCreateMigrationRequestHandler(includeAuthMigrations, includePlanBundle) {");
2564
+ lines.push(" return __createMigrationHandler(");
2565
+ lines.push(" __nosamGetMigrationEnv(),");
2566
+ lines.push(" __migrations,");
2567
+ if (auth) lines.push(" includeAuthMigrations ? () => runBwfAuthMigrations(__nosamGetMigrationEnv(), __nosamAuthOptions, __nosamAuthMigrationSchema) : undefined,");
2568
+ else lines.push(" undefined,");
2569
+ lines.push(" includePlanBundle ? __migrationPlanBundle : undefined,");
2570
+ lines.push(" );");
2571
+ lines.push("}");
2572
+ lines.push("export async function __nosamHandleInternalRoute(request) {");
2573
+ lines.push(" const url = new URL(request.url);");
2574
+ lines.push(" if (request.method === \"POST\" && url.pathname === \"/__nosam/migrate\") {");
2575
+ lines.push(` return __nosamCreateMigrationRequestHandler(${auth ? "true" : "false"}, false)(request);`);
2576
+ lines.push(" }");
2577
+ lines.push(" if (request.method === \"GET\" && url.pathname === \"/__nosam/migrate/capabilities\") {");
2578
+ lines.push(` return __nosamCreateMigrationRequestHandler(${auth ? "true" : "false"}, true)(request);`);
2579
+ lines.push(" }");
2580
+ lines.push(" if (request.method === \"POST\" && url.pathname === \"/__nosam/migrate/app\") {");
2581
+ lines.push(" return __nosamCreateMigrationRequestHandler(false, true)(request);");
2582
+ lines.push(" }");
2583
+ lines.push(" if (request.method === \"GET\" && url.pathname.startsWith(\"/__nosam/migrate/app/attempt/\")) {");
2584
+ lines.push(" return __nosamCreateMigrationRequestHandler(false, true)(request);");
2585
+ lines.push(" }");
2586
+ if (auth) {
2587
+ lines.push(" if (request.method === \"POST\" && url.pathname === \"/__nosam/migrate/auth\") {");
2588
+ lines.push(" return __nosamCreateMigrationRequestHandler(true, true)(request);");
2589
+ lines.push(" }");
2590
+ }
2591
+ lines.push(" return null;");
2592
+ lines.push("}");
2593
+ lines.push(`app.post("/__nosam/migrate", (c) => __nosamCreateMigrationRequestHandler(${auth ? "true" : "false"}, false)(c.req.raw));`);
2594
+ lines.push(`app.get("/__nosam/migrate/capabilities", (c) => __nosamCreateMigrationRequestHandler(${auth ? "true" : "false"}, true)(c.req.raw));`);
2595
+ lines.push("app.post(\"/__nosam/migrate/app\", (c) => __nosamCreateMigrationRequestHandler(false, true)(c.req.raw));");
2596
+ lines.push("app.get(\"/__nosam/migrate/app/attempt/:attemptId\", (c) => __nosamCreateMigrationRequestHandler(false, true)(c.req.raw));");
2597
+ if (auth) lines.push("app.post(\"/__nosam/migrate/auth\", (c) => __nosamCreateMigrationRequestHandler(true, true)(c.req.raw));");
2598
+ lines.push("");
2599
+ } else {
2600
+ lines.push("export async function __nosamHandleInternalRoute() { return null; }");
2601
+ lines.push("");
2602
+ }
2603
+ if (options.bindingHandlerPath) {
2604
+ lines.push(`import { createBindingHandler as __createBindingHandler } from ${JSON.stringify(options.bindingHandlerPath)};`);
2605
+ lines.push("let __nosamBindingApp;");
2606
+ lines.push("app.all(\"/__nosam/*\", async (c) => {");
2607
+ lines.push(" if (!__nosamBindingApp) __nosamBindingApp = __createBindingHandler(__getRawEnv());");
2608
+ lines.push(" const url = new URL(c.req.url);");
2609
+ lines.push(" url.pathname = url.pathname.slice(7);");
2610
+ lines.push(" return __nosamBindingApp.fetch(new Request(url.toString(), c.req.raw));");
2611
+ lines.push("});");
2612
+ lines.push("");
2613
+ }
2614
+ lines.push("const __rawEnvStore = new AsyncLocalStorage();");
2615
+ lines.push("export function __withRawEnv(env, fn) { return __rawEnvStore.run(env, fn); }");
2616
+ lines.push("function __getRawEnv() { return __rawEnvStore.getStore(); }");
2617
+ lines.push(`export const __NOSAM_BUILD_KEY = ${JSON.stringify(crypto.randomUUID())};`);
2618
+ lines.push(`export const __NOSAM_DEV_TRIGGER_TOKEN = ${JSON.stringify(options.devTriggerToken ?? crypto.randomUUID())};`);
2619
+ lines.push(`const __NOSAM_SERVE = ${JSON.stringify(options.dev === true)};`);
2620
+ lines.push("");
2621
+ lines.push(`export default app;`);
2622
+ return lines.join("\n");
2623
+ }
2624
+ /** Asset fallthrough for native bwf workers. */
2625
+ function compileAssetFallbackHelper(assetsDir = "assets", serveSpaFallback = false, notFound = "none") {
2626
+ return `import { createAssetFallback as __createAssetFallback } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};
2627
+ const serveWithAssets = __createAssetFallback(${JSON.stringify({
2628
+ assetsDir,
2629
+ serveSpaFallback,
2630
+ notFound
2631
+ })});
2632
+ `;
2633
+ }
2634
+ /**
2635
+ * Generate the Worker entry module code.
2636
+ * Re-exports the Hono app from the virtual module with an asset-serving
2637
+ * fallthrough: when the app returns 404, the entry tries env.ASSETS.fetch()
2638
+ * and adds proper Cache-Control headers (immutable for Vite-hashed /assets/*).
2639
+ *
2640
+ * When `hasQueues` is true, also exports a `queue()` method that passes the
2641
+ * native MessageBatch to `__processQueue` and applies its ack/retry
2642
+ * decisions. Managed delivery uses the `/__nosam/queue` route instead.
2643
+ *
2644
+ * When `remote` is provided, wraps the fetch handler to detect
2645
+ * remote mode (`__NOSAM_REMOTE`) and replace local bindings with
2646
+ * proxy-backed versions.
2647
+ */
2648
+ function compileWorkerEntry(options = {}) {
2649
+ const { hasQueues = false, versionMetadataBinding, alwaysUseHttps = false, remote, assetsDir = "assets", webSocketClasses = [], runtimeEnvPath = "@builtbyfriends/bwf/_env", runtimeEmailPath = "@builtbyfriends/bwf/email", envSchemaModule, sandbox, serveSpaFallback = false, hasEmail = false, live, dev = false, notFound = "none", durableObjects = [] } = options;
2650
+ const remotePath = remote?.remotePath;
2651
+ const remoteBindingNames = JSON.stringify(remote?.bindingNames);
2652
+ const createRemoteEnvCall = `createRemoteEnv(env${remote?.bindingNames ? `, ${remoteBindingNames}` : ""})`;
2653
+ const hasSandbox = sandbox === true || typeof sandbox === "object";
2654
+ const sandboxClassName = typeof sandbox === "object" ? sandbox.className ?? "SandboxV1" : DEFAULT_SANDBOX_CLASS_NAME;
2655
+ const sandboxBindingName = typeof sandbox === "object" ? sandbox.bindingName ?? "SANDBOX" : "SANDBOX";
2656
+ const sandboxRuntimePath = typeof sandbox === "object" ? sandbox.runtimePath ?? "@builtbyfriends/bwf/sandbox" : "@builtbyfriends/bwf/sandbox";
2657
+ const sandboxImport = hasSandbox ? `import { BwfPlatformSandbox as __NosamSandbox, __setSandboxBindingName } from ${JSON.stringify(sandboxRuntimePath)};\n` : "";
2658
+ const sandboxInstanceType = typeof sandbox === "object" ? sandbox.instanceType : void 0;
2659
+ const sandboxExport = hasSandbox ? sandboxClassName === "SandboxV1" && !sandboxInstanceType ? `export { __NosamSandbox as SandboxV1 };\n__setSandboxBindingName(${JSON.stringify(sandboxBindingName)});\n` : `export class ${sandboxClassName} extends __NosamSandbox {${sandboxInstanceType ? ` protected override instanceType = ${JSON.stringify(sandboxInstanceType)} as const; ` : ""}}\n__setSandboxBindingName(${JSON.stringify(sandboxBindingName)});\n` : "";
2660
+ const hasLive = live === true || typeof live === "object";
2661
+ const liveBindingName = typeof live === "object" ? live.bindingName ?? "BWF_LIVE" : "BWF_LIVE";
2662
+ const liveClassName = typeof live === "object" ? live.className ?? "NosamLiveStreamDurableObject" : "NosamLiveStreamDurableObject";
2663
+ const liveRouteImport = hasLive ? ", NosamLiveStreamDurableObject" : "";
2664
+ const liveDev = hasLive && dev === true;
2665
+ const liveRuntimeImport = hasLive ? `import { __setLiveBindingName${liveDev ? ", __setLiveDev" : ""} } from "@builtbyfriends/bwf/live";\n` : "";
2666
+ const liveDevCall = liveDev ? "__setLiveDev(true);\n" : "";
2667
+ const liveExport = hasLive ? liveClassName === "NosamLiveStreamDurableObject" ? `export { NosamLiveStreamDurableObject };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : `export { NosamLiveStreamDurableObject as ${liveClassName} };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : "";
2668
+ const durableObjectImports = durableObjects.map(({ filePath }, index) => `import __nosamDurableObject${index} from ${JSON.stringify(filePath)};`).join("\n");
2669
+ const durableObjectExports = durableObjects.map(({ bindingName, className, name }, index) => `__nosamDurableObject${index}.__bind(${JSON.stringify(bindingName)}${name !== void 0 ? `, ${JSON.stringify(name)}` : ""});\nexport const ${className} = __nosamDurableObject${index}.class;`).join("\n");
2670
+ const runtimeEnvImport = `import { withRuntimeEnv } from ${JSON.stringify(runtimeEnvPath)};\n`;
2671
+ const remoteImport = remote ? `import { createRemoteEnv } from ${JSON.stringify(remote.remotePath)};\n` : "";
2672
+ const envSchemaImport = envSchemaModule ? `import ${JSON.stringify(envSchemaModule.importPath)};\nimport { _validateEnvOnce } from ${JSON.stringify(envSchemaModule.helperPath)};\n` : "";
2673
+ const envValidateCall = envSchemaModule ? " await _validateEnvOnce(env);\n" : "";
2674
+ const filterBindingsHelper = `import { filterInternalBindings as __filterBindings, createWorkerFetch as __createWorkerFetch } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};
2675
+ const __filterInternalBindings = (env) => __filterBindings(env, ${JSON.stringify(INTERNAL_BINDING_PREFIXES)});
2676
+ `;
2677
+ const assetHelper = compileAssetFallbackHelper(assetsDir, serveSpaFallback, notFound);
2678
+ const fetchHandler = `__createWorkerFetch({
2679
+ app, assets: serveWithAssets, withRawEnv: __withRawEnv, withRuntimeEnv,
2680
+ filterBindings: __filterInternalBindings,
2681
+ internalRoute: __nosamHandleInternalRoute${alwaysUseHttps ? ", alwaysUseHttps: true" : ""}${versionMetadataBinding ? ", versionMetadataBinding: " + JSON.stringify(versionMetadataBinding) : ""}${envSchemaModule ? ", validateEnv: _validateEnvOnce" : ""}${remotePath ? ", remoteEnv: (env) => " + createRemoteEnvCall : ""}${hasEmail ? ", emailReceipt: __handleEmailReceipt" : ""}
2682
+ })`;
2683
+ const remoteEnvSwap = remotePath ? ` if (env.__NOSAM_REMOTE === "1") env = ${createRemoteEnvCall};\n` : "";
2684
+ const scheduledHandler = `async function handleScheduled(controller, env, ctx) {
2685
+ ${envValidateCall}${remoteEnvSwap} const userEnv = __filterInternalBindings(env);
2686
+ return withRuntimeEnv(env, () => scheduled(controller, userEnv, ctx));
2687
+ }`;
2688
+ const emailImport = hasEmail ? ", __emailHandler" : "";
2689
+ const emailProxyImport = hasEmail ? `import { createMessageProxy as __createMessageProxy, enactEmailActions as __enactEmailActions, isForwardableEmailMessage as __isForwardableEmailMessage } from ${JSON.stringify(runtimeEmailPath)};\nimport { EMAIL_PROTOCOL_VERSION as __EMAIL_PROTOCOL_VERSION, encodeEmailActions as __encodeEmailActions, readEmailEnvelope as __readEmailEnvelope, verifyEmailReceiptThroughProxy as __verifyEmailReceiptThroughProxy } from "@builtbyfriends/bwf/_email-protocol";\n` : "";
2690
+ const emailHandler = hasEmail ? `async function handleEmail(envelope, env, ctx) {
2691
+ ${envValidateCall}${remoteEnvSwap} const userEnv = __filterInternalBindings(env);
2692
+ const __relayed = typeof envelope.viaDomain === "string" && envelope.viaDomain.length > 0;
2693
+ const __slug = __relayed || typeof env.__NOSAM_PROJECT_SLUG !== "string" || env.__NOSAM_PROJECT_SLUG.length === 0 ? undefined : (String(envelope.to || "").split("@")[0].split("+")[0] || env.__NOSAM_PROJECT_SLUG);
2694
+ const { message, getActions } = __createMessageProxy(envelope, { slug: __slug });
2695
+ await __withRawEnv(env, () => withRuntimeEnv(env, () => __emailHandler(message, userEnv, ctx, { slug: __slug })));
2696
+ const __actions = getActions();
2697
+ if (__isForwardableEmailMessage(envelope)) await __enactEmailActions(envelope, __actions);
2698
+ return __actions;
2699
+ }` : "";
2700
+ const emailReceiptHandler = hasEmail ? `async function __handleEmailReceipt(request, env, ctx) {
2701
+ if (request.method !== "POST" || request.headers.get("content-encoding")) return new Response(null, { status: 404 });
2702
+ const __token = request.headers.get("x-nosam-email-receipt");
2703
+ const __recipient = request.headers.get("x-nosam-email-recipient");
2704
+ if (!__token || __token.length > 1536 || !__recipient || __recipient.length > 320 ||
2705
+ !env.__NOSAM_PROXY_TOKEN || !env.__PROJECT_ID || !env.__NOSAM_EMAIL_DEPLOYMENT_ID || !env.__NOSAM_PROXY) {
2706
+ return new Response(null, { status: 404 });
2707
+ }
2708
+ const __verified = await __verifyEmailReceiptThroughProxy(env.__NOSAM_PROXY, env.__NOSAM_PROXY_TOKEN, {
2709
+ receipt: __token, projectId: env.__PROJECT_ID,
2710
+ deploymentId: env.__NOSAM_EMAIL_DEPLOYMENT_ID, recipient: __recipient,
2711
+ });
2712
+ if (!__verified) return new Response(null, { status: 404 });
2713
+ let __envelope;
2714
+ try { __envelope = await __readEmailEnvelope(request.body); }
2715
+ catch { return new Response(null, { status: 400 }); }
2716
+ if (__envelope.to !== __recipient) return new Response(null, { status: 400 });
2717
+ const __actions = await handleEmail(__envelope, env, ctx);
2718
+ return new Response(__encodeEmailActions(__actions), {
2719
+ headers: { "content-type": "application/vnd.nosam.email-actions; version=" + __EMAIL_PROTOCOL_VERSION,
2720
+ "cache-control": "no-store" },
2721
+ });
2722
+ }` : "";
2723
+ const entryImport = `import { WorkerEntrypoint } from "cloudflare:workers";\n`;
2724
+ const fetchDeclaration = `const __nosamFetch = ${fetchHandler};`;
2725
+ const entryClass = `export default class extends WorkerEntrypoint {
2726
+ async fetch(request) { return __nosamFetch(request, this.env, this.ctx); }
2727
+ async scheduled(controller) { return handleScheduled(controller, this.env, this.ctx); }
2728
+ ${hasQueues ? ` async queue(batch) { return __nosamQueue(batch, this.env, this.ctx); }\n` : ""}${hasEmail ? ` async email(message) {
2729
+ if (this.env.__NOSAM_EMAIL_DEPLOYMENT_ID || !__isForwardableEmailMessage(message)) {
2730
+ throw new TypeError("Native email event required");
2731
+ }
2732
+ await handleEmail(message, this.env, this.ctx);
2733
+ }\n` : ""}}`;
2734
+ const queueImport = hasQueues ? ", __processQueue" : "";
2735
+ const queueFunction = hasQueues ? `async function __nosamQueue(batch, env, ctx) {
2736
+ ${envValidateCall}${remoteEnvSwap} const userEnv = __filterInternalBindings(env);
2737
+ const messages = [...batch.messages].map(m => ({
2738
+ id: m.id, timestamp: m.timestamp.toISOString(),
2739
+ body: m.body, attempts: m.attempts,
2740
+ }));
2741
+ const payload = { queue: batch.queue, messages };
2742
+ const __qr = await __withRawEnv(env, () => withRuntimeEnv(env, () => __processQueue(payload, userEnv)));
2743
+ if (__qr.decisions) {
2744
+ const __msgMap = new Map();
2745
+ for (const m of batch.messages) __msgMap.set(m.id, m);
2746
+ for (const [id, d] of Object.entries(__qr.decisions)) {
2747
+ const m = __msgMap.get(id);
2748
+ if (!m) continue;
2749
+ if (d.action === "ack") m.ack();
2750
+ else if (d.action === "retry") m.retry(d.delaySeconds != null ? { delaySeconds: d.delaySeconds } : undefined);
2751
+ }
2752
+ }
2753
+ if (!__qr.ok) throw new Error("queue: Handler failed.");
2754
+ }
2755
+
2756
+ ` : "";
2757
+ return `${sandboxImport}${entryImport}${liveRuntimeImport}import app, { scheduled, __nosamHandleInternalRoute, __withRawEnv${queueImport}${emailImport}${webSocketClasses.length > 0 ? `, ${webSocketClasses.join(", ")}` : ""}${liveRouteImport} } from 'virtual:nosam-routes';
2758
+ ${durableObjectImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${filterBindingsHelper}${assetHelper}
2759
+ ${fetchDeclaration}
2760
+ ${scheduledHandler}
2761
+ ${emailHandler}
2762
+ ${emailReceiptHandler}
2763
+ ${queueFunction}${webSocketClasses.map((name) => `export { ${name} };`).join("\n")}
2764
+ ${liveExport}
2765
+ ${sandboxExport}
2766
+ ${durableObjectExports}
2767
+ ${entryClass}`;
2768
+ }
2769
+ /** Generate the browser client module: re-exports the HTTP fetch, stream, and auth clients. */
2770
+ function compileBrowserClient(authClientPath, fetchPath, fetchStreamPath) {
2771
+ return `export { fetch, FetchError } from ${JSON.stringify(fetchPath)};
2772
+ export { fetchStream, StreamError } from ${JSON.stringify(fetchStreamPath)};
2773
+ export { auth, createAuthClient } from ${JSON.stringify(authClientPath)};`;
2774
+ }
2775
+ function stripOriginForProd(rules) {
2776
+ return rules.map(({ origin: _origin, ...rest }) => rest);
2777
+ }
2778
+ function compileRoutingRulesMiddleware(lines, rules, dev) {
2779
+ lines.push("// Routing rules: redirects + rewrites (applied before route handlers)");
2780
+ lines.push(`const __routingRules = ${JSON.stringify(dev ? rules : stripOriginForProd(rules))};`);
2781
+ lines.push("app.use(\"*\", __routingRuntime.routingMiddleware(__routingRules));");
2782
+ }
2783
+ /** Generate the server-side fetch client, which calls `app.fetch()` with the current request's credentials. */
2784
+ function compileWorkerClient(authClientPath) {
2785
+ return `import app, { requestContext } from "virtual:nosam-routes";
2786
+ import { createServerFetch } from ${JSON.stringify(FETCH_SERVER_PATH)};
2787
+ export { FetchError } from ${JSON.stringify(FETCH_SERVER_PATH)};
2788
+ import { env } from "cloudflare:workers";
2789
+ export { auth, createAuthClient } from ${JSON.stringify(authClientPath)};
2790
+
2791
+ export const fetch = createServerFetch(
2792
+ (request, store) => app.fetch(request, env, store?.executionCtx ?? { waitUntil() {}, passThroughOnException() {} }),
2793
+ () => requestContext.getStore(),
2794
+ "http://worker.local",
2795
+ );
2796
+ `;
2797
+ }
2798
+ // src/plugin-routing.ts
2799
+ const VIRTUAL_ROUTES_ID = "virtual:nosam-routes";
2800
+ const VIRTUAL_CLIENT_WORKER_ID = "virtual:nosam-client-worker";
2801
+ const VIRTUAL_CLIENT_BROWSER_ID = "virtual:nosam-client-browser";
2802
+ const CLIENT_IMPORT_RE = /^@builtbyfriends\/bwf\/client(?:\/(react))?$/;
2803
+ const VIRTUAL_CLIENT_RE = /^virtual:nosam-client-(browser|worker)(?::(react))?$/;
2804
+ const RESOLVE_ID_FILTER = /^(virtual:nosam-(routes|client-worker(?::(react))?|client-browser(?::(react))?)|@builtbyfriends\/bwf(\/client(\/(react))?|\/queues)?)$/;
2805
+ const LOAD_ID_FILTER = /^virtual:nosam-(routes|client-worker(?::(react))?|client-browser(?::(react))?)$/;
2806
+ /**
2807
+ * Vite plugin that provides file-based routing.
2808
+ * - Scans routes/ and middleware/ directories
2809
+ * - Generates virtual modules for the route table and worker entry
2810
+ * - Watches for file changes and triggers HMR
2811
+ */
2812
+ function routingPlugin(root, options) {
2813
+ let scan = null;
2814
+ let routeEnvironment = "prod";
2815
+ let previewing = false;
2816
+ let authConfigPath = null;
2817
+ const routeInputsKey = () => JSON.stringify([
2818
+ scan,
2819
+ authConfigPath,
2820
+ compileOptions.auth
2821
+ ]);
2822
+ let generatedRouteInputs;
2823
+ let generatedFiles;
2824
+ let pendingRegeneration = Promise.resolve();
2825
+ function regenerateInOrder(regenerate) {
2826
+ const result = pendingRegeneration.then(regenerate);
2827
+ pendingRegeneration = result.then(() => {}, () => {});
2828
+ return result;
2829
+ }
2830
+ const paths = readProjectPaths(root);
2831
+ const routesDir = paths.routesDir;
2832
+ const middlewareDir = paths.middlewareDir;
2833
+ const jobsDir = paths.cronsDir;
2834
+ const queuesDir = paths.queuesDir;
2835
+ const proceduresDir = paths.proceduresDir;
2836
+ const emailDir = paths.emailDir;
2837
+ const authConfigPaths = new Set(paths.authConfigCandidates.map((path) => normalizePath(path)));
2838
+ let authConfigEnvironment;
2839
+ let authConfigStale = false;
2840
+ const envFilePaths = new Set(paths.envFileCandidates.map((path) => normalizePath(path)));
2841
+ const normalizedRoutesDir = normalizePath(routesDir);
2842
+ const normalizedMiddlewareDir = normalizePath(middlewareDir);
2843
+ const normalizedJobsDir = normalizePath(jobsDir);
2844
+ const normalizedQueuesDir = normalizePath(queuesDir);
2845
+ const normalizedProceduresDir = normalizePath(proceduresDir);
2846
+ const normalizedEmailDir = normalizePath(emailDir);
2847
+ function hasEmailHandlers() {
2848
+ const email = scan?.email;
2849
+ return Boolean(email && (email.addresses.length > 0 || email.defaultHandler));
2850
+ }
2851
+ function isInDirectory(path, directory) {
2852
+ return path === directory || path.startsWith(directory + "/");
2853
+ }
2854
+ function writeRouteTypes() {
2855
+ if (!scan) return;
2856
+ const { dts } = generateRouteTypes(scan, routesDir, outDir, { typedRoutes: options.routing?.typedRoutes });
2857
+ writeFileIfChanged(join(outDir, "routes.d.ts"), dts);
2858
+ }
2859
+ function writeQueueTypes() {
2860
+ if (!scan) return;
2861
+ const dts = generateQueueTypes(scan.queues, queuesDir, outDir);
2862
+ writeFileIfChanged(join(outDir, "queues.d.ts"), dts);
2863
+ }
2864
+ function writeProcedureTypes() {
2865
+ if (!scan || !existsSync(proceduresDir)) return;
2866
+ const dts = generateProcedureTypes(scan.procedures ?? [], proceduresDir, outDir);
2867
+ writeFileIfChanged(join(outDir, "procedures.d.ts"), dts);
2868
+ }
2869
+ async function rescan(refresh = false) {
2870
+ const analysis = options.getApplicationAnalysis(routeEnvironment, refresh);
2871
+ scan = (await completeApplicationAnalysis(analysis)).scan;
2872
+ authConfigPath = analysis.authConfigPath;
2873
+ }
2874
+ const resolveFile = (specifier) => fileURLToPath(import.meta.resolve(specifier));
2875
+ const handlerFile = resolveFile("#self/handler");
2876
+ const runtimeDir = dirname(resolveFile("#self/client"));
2877
+ const fetchPath = resolveFile("#self/runtime/fetch");
2878
+ const fetchStreamPath = resolveFile("#self/runtime/fetch-stream");
2879
+ const sandboxRuntimePath = resolveFile("#self/sandbox");
2880
+ const drizzleAdapterPath = resolveFile("better-auth/adapters/drizzle");
2881
+ const authClientPath = join(runtimeDir, "auth-client.mjs");
2882
+ const explicitAuthClientPaths = { react: join(runtimeDir, "auth-client-react.mjs") };
2883
+ const remote = options.remoteMode ? {
2884
+ bindingNames: options.bindingNames,
2885
+ remotePath: resolveFile("#self/remote")
2886
+ } : void 0;
2887
+ function getEnvSchemaModule() {
2888
+ const envFile = findEnvFileForPaths(root, paths);
2889
+ if (!envFile) return;
2890
+ return {
2891
+ importPath: envFile,
2892
+ helperPath: resolveFile("#self/env")
2893
+ };
2894
+ }
2895
+ const runtimeEmailPath = resolveFile("#self/email");
2896
+ const compileOptions = {
2897
+ honoPath: resolveFile("hono"),
2898
+ honoRoutePath: resolveFile("hono/route"),
2899
+ runtimeEnvPath: resolveFile("#self/_env"),
2900
+ emailDir,
2901
+ projectRoot: root,
2902
+ homeDir: homedir(),
2903
+ webSocketRuntimePath: resolveFile("#self/runtime/ws-server"),
2904
+ liveRuntimePath: resolveFile("#self/runtime/live-server"),
2905
+ hasLive: options.live !== void 0,
2906
+ webSocketTombstones: options.websocketTombstones,
2907
+ dev: false,
2908
+ devTriggerToken: options.devTriggerToken,
2909
+ auth: null,
2910
+ managedDispatch: false,
2911
+ bindingHandlerPath: resolveFile("#self/remote/binding-handler"),
2912
+ procedures: {
2913
+ dir: proceduresDir,
2914
+ runtimePath: resolveFile("#self/runtime/procedures"),
2915
+ ...readAppIdentity(root)
2916
+ },
2917
+ bindingNames: options.bindingNames
2918
+ };
2919
+ let publicDir = join(root, "public");
2920
+ function reloadFileRules() {
2921
+ const merged = mergeRoutingRules({
2922
+ dir: publicDir,
2923
+ routing: options.routing
2924
+ });
2925
+ lintRoutingPhases(merged);
2926
+ compileOptions.headerRules = merged.headerRules.length > 0 ? merged.headerRules : void 0;
2927
+ compileOptions.redirectRules = merged.redirectRules.length > 0 ? merged.redirectRules : void 0;
2928
+ compileOptions.fallbackRules = merged.fallbackRules;
2929
+ }
2930
+ reloadFileRules();
2931
+ function resolveAuthCompileOptions() {
2932
+ if (!options.isAuthEnabled() && !authConfigPath) {
2933
+ compileOptions.auth = null;
2934
+ return;
2935
+ }
2936
+ const config = readConfig(root);
2937
+ const dialect = getDatabaseDialect(config);
2938
+ compileOptions.auth = {
2939
+ authRuntimePath: dialect === "postgresql" ? join(runtimeDir, "better-auth-pg.mjs") : dialect === "mysql" ? join(runtimeDir, "better-auth-mysql.mjs") : join(runtimeDir, "better-auth.mjs"),
2940
+ authConfigPath,
2941
+ authDatabasePath: join(outDir, "better-auth-db.ts"),
2942
+ authSchemaPath: join(outDir, "better-auth-schema.ts"),
2943
+ dialect,
2944
+ providers: config.auth?.providers ?? null
2945
+ };
2946
+ }
2947
+ /**
2948
+ * Size and mtime of every generated file, or undefined when one is missing.
2949
+ * Another void process in the same root (a build, `bwf db generate`) can
2950
+ * rewrite them, and the dev watcher ignores `.bwf/`.
2951
+ */
2952
+ function generatedFilesSignature() {
2953
+ const files = [
2954
+ "routes.d.ts",
2955
+ "queues.d.ts",
2956
+ ...existsSync(proceduresDir) ? ["procedures.d.ts"] : [],
2957
+ "entry.ts",
2958
+ ...compileOptions.auth ? [
2959
+ "better-auth-db.ts",
2960
+ "better-auth-schema.ts",
2961
+ ...compileOptions.auth.authConfigPath ? ["auth.d.ts"] : []
2962
+ ] : []
2963
+ ];
2964
+ const parts = [];
2965
+ for (const file of files) {
2966
+ const stat = statSync(join(outDir, file), { throwIfNoEntry: false });
2967
+ if (!stat?.isFile()) return;
2968
+ parts.push(`${file}:${stat.size}:${stat.mtimeMs}`);
2969
+ }
2970
+ return parts.join("|");
2971
+ }
2972
+ async function loadAuthConfig(configPath) {
2973
+ const environment = authConfigEnvironment;
2974
+ if (authConfigStale && environment) environment.moduleGraph.invalidateAll();
2975
+ authConfigStale = false;
2976
+ try {
2977
+ return await loadBwfAuthConfig(configPath, environment ? (path) => environment.runner.import(path) : viteAuthConfigImporter(root, resolvedConfig?.mode, resolvedConfig?.resolve));
2978
+ } catch (error) {
2979
+ authConfigStale = true;
2980
+ throw error;
2981
+ }
2982
+ }
2983
+ async function writeAuthDatabaseFiles() {
2984
+ if (!compileOptions.auth) {
2985
+ if (removeAuthTypesIfPresent(outDir)) syncAuthTypesInProjectTsconfig(root);
2986
+ return;
2987
+ }
2988
+ const { generateBwfAuthDatabaseModule, generateBwfAuthDrizzleSchema } = await import("./drizzle-Ds5P0n-S.mjs");
2989
+ const authRuntime = {
2990
+ dialect: compileOptions.auth.dialect,
2991
+ providers: compileOptions.auth.providers,
2992
+ userConfig: await loadAuthConfig(compileOptions.auth.authConfigPath)
2993
+ };
2994
+ const env = {
2995
+ ...resolvedConfig?.command === "serve" ? loadLocalEnv(root) : {},
2996
+ ...process.env
2997
+ };
2998
+ const { authSchemaPath, authDatabasePath } = compileOptions.auth;
2999
+ writeFileIfChanged(authSchemaPath, generateBwfAuthDrizzleSchema(authRuntime, env));
3000
+ writeFileIfChanged(authDatabasePath, generateBwfAuthDatabaseModule({
3001
+ dialect: compileOptions.auth.dialect,
3002
+ schemaImportPath: authSchemaPath,
3003
+ drizzleAdapterPath,
3004
+ d1BindingName: options.bindingNames?.d1
3005
+ }));
3006
+ syncAuthTypesFile(compileOptions.auth.authConfigPath, outDir);
3007
+ syncAuthTypesInProjectTsconfig(root);
3008
+ }
3009
+ let resolvedConfig = null;
3010
+ function getClientAuthPath(id) {
3011
+ const framework = VIRTUAL_CLIENT_RE.exec(id)?.[2];
3012
+ return framework ? explicitAuthClientPaths[framework] : authClientPath;
3013
+ }
3014
+ function resolveVirtualClientId(id, environmentName) {
3015
+ const framework = CLIENT_IMPORT_RE.exec(id)?.[1];
3016
+ const base = environmentName === "client" ? VIRTUAL_CLIENT_BROWSER_ID : VIRTUAL_CLIENT_WORKER_ID;
3017
+ return framework ? `${base}:${framework}` : base;
3018
+ }
3019
+ function isPotentialAuthConfigPath(path) {
3020
+ const normalized = normalizePath(path);
3021
+ return authConfigPaths.has(normalized) || (authConfigEnvironment?.moduleGraph.getModulesByFile(normalized)?.size ?? 0) > 0;
3022
+ }
3023
+ function isPotentialEnvFilePath(path) {
3024
+ return envFilePaths.has(normalizePath(path));
3025
+ }
3026
+ function resolveCurrentAssetRoutingPolicy() {
3027
+ const { routes, websockets = [], middleware } = scan;
3028
+ return resolveAssetRoutingPolicy({
3029
+ hasApiRoutes: hasApiRoutes(routes) || hasApiRoutes(websockets) || compileOptions.auth !== null,
3030
+ hasDocumentRoutes: hasDocumentRoutes(routes),
3031
+ hasMiddleware: middleware.length > 0,
3032
+ hasWebSockets: hasDocumentRoutes(websockets),
3033
+ authEnabled: compileOptions.auth !== null,
3034
+ liveEnabled: options.live !== void 0,
3035
+ notFound: options.routing?.notFound
3036
+ });
3037
+ }
3038
+ let clientImmutableFiles = [];
3039
+ /**
3040
+ * The generated `_headers` text when this build can skip the Worker for its
3041
+ * hashed files, and the new `wrangler.json` text when it changes; null when
3042
+ * there is no built Worker config. Reads only, so a read failure leaves the
3043
+ * output unchanged.
3044
+ */
3045
+ function planAssetWorkerBypass(clientDir, assetsDir, userHeaders) {
3046
+ if (!scan || !resolvedConfig || compileOptions.managedDispatch) return null;
3047
+ let wranglerPath;
3048
+ let wrangler;
3049
+ try {
3050
+ const distDir = resolveDistDir(root);
3051
+ wranglerPath = join(distDir, resolveWorkerDirName(distDir), "wrangler.json");
3052
+ wrangler = JSON.parse(readFileSync(wranglerPath, "utf8"));
3053
+ } catch {
3054
+ return null;
3055
+ }
3056
+ const assets = wrangler?.assets;
3057
+ if (!assets || typeof assets !== "object" || typeof assets.directory !== "string" || resolve(dirname(wranglerPath), assets.directory) !== clientDir) return null;
3058
+ const workerBuildRule = isAssetBypassRule(assets.run_worker_first, assetsDir) ? ["/**"] : assets.run_worker_first;
3059
+ const routePatterns = [...scan.routes, ...scan.websockets ?? []].map((route) => route.pattern);
3060
+ const facts = {
3061
+ runWorkerFirst: workerBuildRule,
3062
+ notFoundHandling: assets.not_found_handling,
3063
+ base: resolvedConfig.base,
3064
+ hasMiddleware: scan.middleware.length > 0,
3065
+ authEnabled: compileOptions.auth !== null,
3066
+ headerRuleCount: compileOptions.headerRules?.length ?? 0,
3067
+ redirectRuleCount: compileOptions.redirectRules?.length ?? 0,
3068
+ fallbackRuleCount: compileOptions.fallbackRules?.length ?? 0,
3069
+ publicEdgeFiles: publicDir !== null && (existsSync(join(publicDir, "_headers")) || existsSync(join(publicDir, "_redirects"))),
3070
+ patterns: routePatterns,
3071
+ assetsDir,
3072
+ immutableFiles: clientImmutableFiles
3073
+ };
3074
+ const bypass = userHeaders ? null : resolveAssetWorkerBypass(facts);
3075
+ const runWorkerFirst = bypass?.runWorkerFirst ?? workerBuildRule;
3076
+ return {
3077
+ headers: bypass?.headers ?? null,
3078
+ wranglerPath,
3079
+ wranglerText: isDeepStrictEqual(runWorkerFirst, assets.run_worker_first) ? null : JSON.stringify({
3080
+ ...wrangler,
3081
+ assets: {
3082
+ ...assets,
3083
+ run_worker_first: runWorkerFirst
3084
+ }
3085
+ })
3086
+ };
3087
+ }
3088
+ function finalizeCloudflareAssets(clientDir, assetsDir) {
3089
+ if (!options.assetWorkerBypass || resolvedConfig?.command !== "build") return;
3090
+ const headersPath = join(clientDir, "_headers");
3091
+ let generatedHeaders = false;
3092
+ let userHeaders = false;
3093
+ if (existsSync(headersPath)) {
3094
+ try {
3095
+ generatedHeaders = isGeneratedAssetHeaders(readFileSync(headersPath, "utf8"));
3096
+ } catch {
3097
+ return;
3098
+ }
3099
+ userHeaders = !generatedHeaders;
3100
+ }
3101
+ const plan = planAssetWorkerBypass(clientDir, assetsDir, userHeaders);
3102
+ if (plan?.headers) writeFileSync(headersPath, plan.headers);
3103
+ else if (generatedHeaders) rmSync(headersPath);
3104
+ if (plan?.wranglerText) writeFileSync(plan.wranglerPath, plan.wranglerText);
3105
+ }
3106
+ const sandboxEntry = options.hasSandbox ? {
3107
+ bindingName: options.sandboxBindingName,
3108
+ className: options.sandboxClassName,
3109
+ instanceType: options.sandboxInstanceType,
3110
+ runtimePath: sandboxRuntimePath
3111
+ } : false;
3112
+ /** Write the Cloudflare worker entry from the completed scan. */
3113
+ function writeWorkerEntry() {
3114
+ const policy = resolveCurrentAssetRoutingPolicy();
3115
+ writeFileIfChanged(join(outDir, "entry.ts"), compileWorkerEntry({
3116
+ versionMetadataBinding: options.getVersionMetadataBinding?.(),
3117
+ alwaysUseHttps: options.routing?.alwaysUseHttps === true && resolvedConfig?.command === "build" && !compileOptions.managedDispatch,
3118
+ hasQueues: scan.queues.length > 0,
3119
+ remote,
3120
+ assetsDir: resolvedConfig?.build.assetsDir,
3121
+ webSocketClasses: [...(scan.websockets ?? []).map((route) => route.className), ...options.websocketTombstones ?? []],
3122
+ runtimeEnvPath: compileOptions.runtimeEnvPath,
3123
+ runtimeEmailPath,
3124
+ envSchemaModule: getEnvSchemaModule(),
3125
+ sandbox: sandboxEntry,
3126
+ hasEmail: hasEmailHandlers(),
3127
+ serveSpaFallback: policy.workerSpaFallback,
3128
+ live: options.live,
3129
+ dev: compileOptions.dev,
3130
+ notFound: policy.assetConfig.not_found_handling ?? "none",
3131
+ durableObjects: options.durableObjects
3132
+ }));
3133
+ }
3134
+ const outDir = join(root, ".bwf");
3135
+ mkdirSync(outDir, { recursive: true });
3136
+ writeFileIfChanged(join(outDir, "entry.ts"), compileWorkerEntry({
3137
+ versionMetadataBinding: options.getVersionMetadataBinding?.(),
3138
+ remote,
3139
+ webSocketClasses: options.websocketTombstones,
3140
+ runtimeEnvPath: compileOptions.runtimeEnvPath,
3141
+ runtimeEmailPath,
3142
+ envSchemaModule: getEnvSchemaModule(),
3143
+ sandbox: sandboxEntry,
3144
+ live: options.live,
3145
+ durableObjects: options.durableObjects
3146
+ }));
3147
+ return {
3148
+ name: "nosam:routing",
3149
+ api: { finalizeCloudflareAssets },
3150
+ enforce: "pre",
3151
+ configResolved(config) {
3152
+ resolvedConfig = config;
3153
+ compileOptions.dev = config.command === "serve" && !previewing;
3154
+ compileOptions.assetsDir = config.build.assetsDir;
3155
+ compileOptions.cloudflareQueueNames = config.command === "build" ? readDeployBuildQueueNames() : void 0;
3156
+ const resolvedPublicDir = config.publicDir && config.publicDir.length > 0 ? config.publicDir : null;
3157
+ if (resolvedPublicDir !== publicDir) {
3158
+ publicDir = resolvedPublicDir;
3159
+ reloadFileRules();
3160
+ }
3161
+ },
3162
+ config(_, env) {
3163
+ previewing = env.isPreview === true;
3164
+ routeEnvironment = env.command === "serve" && !env.isPreview ? "dev" : "prod";
3165
+ const authConfigEnvironmentConfig = routeEnvironment === "dev" ? { environments: { [AUTH_CONFIG_ENVIRONMENT]: {
3166
+ consumer: "server",
3167
+ dev: { createEnvironment: (name, config) => createRunnableDevEnvironment(name, config, {
3168
+ hot: false,
3169
+ runnerOptions: { hmr: false }
3170
+ }) }
3171
+ } } } : {};
3172
+ compileOptions.hasLive = options.live !== void 0;
3173
+ compileOptions.managedDispatch = env.command === "build" && Boolean(process.env.NOSAM_DEPLOY_PROJECT_ID);
3174
+ if (env.command === "serve" && options.isAuthEnabled()) {
3175
+ const resolvedAliases = ["client", "react"].flatMap((sub) => {
3176
+ try {
3177
+ return [{
3178
+ find: new RegExp(`^better-auth/${sub}$`),
3179
+ replacement: resolveFile(`better-auth/${sub}`)
3180
+ }];
3181
+ } catch {
3182
+ return [];
3183
+ }
3184
+ });
3185
+ return {
3186
+ ...authConfigEnvironmentConfig,
3187
+ resolve: { alias: resolvedAliases }
3188
+ };
3189
+ }
3190
+ if (env.command !== "build") return authConfigEnvironmentConfig;
3191
+ return { build: { manifest: _.build?.manifest ?? true } };
3192
+ },
3193
+ generateBundle: {
3194
+ order: "post",
3195
+ handler(_output, bundle) {
3196
+ const manifest = this.environment.config.build.manifest;
3197
+ if (this.environment.name === "client") clientImmutableFiles = manifest ? stampClientAssetCachePolicy(bundle, typeof manifest === "string" ? manifest : ".vite/manifest.json", compileOptions.headerRules) : [];
3198
+ }
3199
+ },
3200
+ buildStart() {
3201
+ return regenerateInOrder(async () => {
3202
+ generatedRouteInputs = void 0;
3203
+ await rescan();
3204
+ resolveAuthCompileOptions();
3205
+ const nextRouteInputs = routeInputsKey();
3206
+ await writeAuthDatabaseFiles();
3207
+ writeRouteTypes();
3208
+ writeQueueTypes();
3209
+ writeProcedureTypes();
3210
+ const migrationsDir = paths.migrationsDir;
3211
+ if (existsSync(migrationsDir) || compileOptions.auth) {
3212
+ const { collectMigrations } = await import("./collect-8i0wU63d.mjs");
3213
+ const { buildMigrationPlanBundle } = await import("./plan-BHNt1QhK.mjs");
3214
+ const migrations = existsSync(migrationsDir) ? collectMigrations(migrationsDir) : [];
3215
+ const dialect = getDatabaseDialect(readConfig(root));
3216
+ compileOptions.migrationHandlerPath = resolveFile(dialect === "postgresql" ? "#self/runtime/migration-handler-pg" : dialect === "mysql" ? "#self/runtime/migration-handler-mysql" : "#self/runtime/migration-handler");
3217
+ compileOptions.migrations = migrations;
3218
+ compileOptions.migrationPlanBundle = dialect === "sqlite" ? buildMigrationPlanBundle(migrations) : void 0;
3219
+ }
3220
+ writeWorkerEntry();
3221
+ generatedRouteInputs = nextRouteInputs;
3222
+ generatedFiles = generatedFilesSignature();
3223
+ });
3224
+ },
3225
+ watchChange(id) {
3226
+ invalidateSourceAnalysis(id);
3227
+ },
3228
+ resolveId: {
3229
+ filter: { id: RESOLVE_ID_FILTER },
3230
+ handler(id) {
3231
+ if (id === VIRTUAL_ROUTES_ID) return VIRTUAL_ROUTES_ID;
3232
+ if (id === VIRTUAL_CLIENT_WORKER_ID) return VIRTUAL_CLIENT_WORKER_ID;
3233
+ if (id === VIRTUAL_CLIENT_BROWSER_ID) return VIRTUAL_CLIENT_BROWSER_ID;
3234
+ if (id === "@builtbyfriends/bwf") return handlerFile;
3235
+ if (id === "@builtbyfriends/bwf/queues") return resolveFile("#self/queues");
3236
+ if (CLIENT_IMPORT_RE.test(id)) return resolveVirtualClientId(id, this.environment?.name);
3237
+ }
3238
+ },
3239
+ load: {
3240
+ filter: { id: LOAD_ID_FILTER },
3241
+ async handler(id) {
3242
+ const virtualClient = VIRTUAL_CLIENT_RE.exec(id);
3243
+ if (virtualClient?.[1] === "browser") return compileBrowserClient(getClientAuthPath(id), fetchPath, fetchStreamPath);
3244
+ if (virtualClient?.[1] === "worker") return compileWorkerClient(getClientAuthPath(id));
3245
+ if (id !== VIRTUAL_ROUTES_ID) return;
3246
+ if (this?.environment?.name === "client") throw new Error(`${VIRTUAL_ROUTES_ID} is server-only and cannot be loaded by client code.`);
3247
+ if (!scan) await regenerateInOrder(() => rescan());
3248
+ return compileRouteTable(scan, routesDir, middlewareDir, jobsDir, queuesDir, compileOptions);
3249
+ }
3250
+ },
3251
+ hotUpdate() {
3252
+ if (this.environment.name === "nosam_auth_config") return [];
3253
+ },
3254
+ async configureServer(devServer) {
3255
+ const authEnvironment = devServer.environments[AUTH_CONFIG_ENVIRONMENT];
3256
+ authConfigEnvironment = authEnvironment && isRunnableDevEnvironment(authEnvironment) ? authEnvironment : void 0;
3257
+ const watcher = devServer.watcher;
3258
+ const handleFileChange = async (path, event) => {
3259
+ const normalizedPath = normalizePath(path);
3260
+ invalidateSourceAnalysis(normalizedPath);
3261
+ const authConfigChanged = isPotentialAuthConfigPath(normalizedPath);
3262
+ if (authConfigChanged) authConfigStale = true;
3263
+ const authImportCreated = event === "add" && authConfigStale && compileOptions.auth !== null;
3264
+ if (!(isInDirectory(normalizedPath, normalizedRoutesDir) || isInDirectory(normalizedPath, normalizedMiddlewareDir) || isInDirectory(normalizedPath, normalizedJobsDir) || isInDirectory(normalizedPath, normalizedQueuesDir) || isInDirectory(normalizedPath, normalizedProceduresDir) || isInDirectory(normalizedPath, normalizedEmailDir) || authConfigChanged || authImportCreated || isPotentialEnvFilePath(normalizedPath))) return;
3265
+ if (await regenerateInOrder(async () => {
3266
+ invalidateSourceAnalysis(normalizedPath);
3267
+ if (event !== "change" || authConfigChanged || isPotentialEnvFilePath(normalizedPath)) generatedRouteInputs = void 0;
3268
+ try {
3269
+ await rescan(true);
3270
+ } catch (error) {
3271
+ const message = error instanceof Error ? error.message : String(error);
3272
+ devServer.config.logger.error(message, {
3273
+ error: error instanceof Error ? error : void 0,
3274
+ timestamp: true
3275
+ });
3276
+ return;
3277
+ }
3278
+ resolveAuthCompileOptions();
3279
+ const nextRouteInputs = routeInputsKey();
3280
+ const currentFiles = generatedFilesSignature();
3281
+ const routeInputsChanged = nextRouteInputs !== generatedRouteInputs || currentFiles === void 0 || currentFiles !== generatedFiles;
3282
+ if (routeInputsChanged) generatedRouteInputs = void 0;
3283
+ if (event !== "change" && options.onDevAssetRoutingPolicyChange?.(resolveCurrentAssetRoutingPolicy()) === true) return true;
3284
+ if (routeInputsChanged) {
3285
+ await writeAuthDatabaseFiles();
3286
+ writeRouteTypes();
3287
+ writeQueueTypes();
3288
+ writeProcedureTypes();
3289
+ writeProcedureTypes();
3290
+ writeWorkerEntry();
3291
+ }
3292
+ const structural = event !== "change";
3293
+ for (const env of Object.values(devServer.environments)) {
3294
+ const mod = env.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID);
3295
+ if (mod && routeInputsChanged) {
3296
+ env.moduleGraph.invalidateModule(mod);
3297
+ if (structural) env.hot.send({ type: "full-reload" });
3298
+ }
3299
+ }
3300
+ if (routeInputsChanged) {
3301
+ generatedRouteInputs = nextRouteInputs;
3302
+ generatedFiles = generatedFilesSignature();
3303
+ }
3304
+ })) await devServer.restart();
3305
+ };
3306
+ const onFileChange = (path, event) => handleFileChange(path, event).catch((error) => {
3307
+ devServer.config.logger.error(error instanceof Error ? error.message : String(error), {
3308
+ error: error instanceof Error ? error : void 0,
3309
+ timestamp: true
3310
+ });
3311
+ });
3312
+ watcher.on("add", (path) => onFileChange(path, "add"));
3313
+ watcher.on("change", (path) => onFileChange(path, "change"));
3314
+ watcher.on("unlink", (path) => onFileChange(path, "unlink"));
3315
+ if (publicDir) {
3316
+ const redirectsPath = join(publicDir, "_redirects");
3317
+ const headersPath = join(publicDir, "_headers");
3318
+ const handleRulesFileChange = (path) => {
3319
+ if (path !== redirectsPath && path !== headersPath) return;
3320
+ reloadFileRules();
3321
+ for (const env of Object.values(devServer.environments)) {
3322
+ const mod = env.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID);
3323
+ if (mod) {
3324
+ env.moduleGraph.invalidateModule(mod);
3325
+ env.hot.send({ type: "full-reload" });
3326
+ }
3327
+ }
3328
+ };
3329
+ watcher.on("add", handleRulesFileChange);
3330
+ watcher.on("change", handleRulesFileChange);
3331
+ watcher.on("unlink", handleRulesFileChange);
3332
+ }
3333
+ if (options.isAuthEnabled()) await regenerateInOrder(async () => {
3334
+ await rescan();
3335
+ resolveAuthCompileOptions();
3336
+ await writeAuthDatabaseFiles();
3337
+ });
3338
+ }
3339
+ };
3340
+ }
3341
+ // src/cloudflare-durable-patch.ts
3342
+ function entries(value, label) {
3343
+ if (value === void 0) return [];
3344
+ if (!Array.isArray(value) || value.some((entry) => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new Error(`Cloudflare ${label} configuration must be an array of objects.`);
3345
+ return value;
3346
+ }
3347
+ function byIdentity(rows, field, label, unique = false) {
3348
+ const map = /* @__PURE__ */ new Map();
3349
+ for (const row of rows) {
3350
+ const id = row[field];
3351
+ if (typeof id !== "string" || !id) throw new Error(`Cloudflare ${label} is missing its ${field}.`);
3352
+ const previous = map.get(id);
3353
+ if (previous && unique) throw new Error(`Cloudflare ${label} ${JSON.stringify(id)} is configured more than once.`);
3354
+ if (previous && !isDeepStrictEqual(previous, row)) throw new Error(`Cloudflare ${label} ${JSON.stringify(id)} has conflicting configuration.`);
3355
+ if (!previous) map.set(id, row);
3356
+ }
3357
+ return map;
3358
+ }
3359
+ /** Finish cumulative feature planning without repeating the Cloudflare plugin's array fallback. */
3360
+ function finalizeDurableObjectPatch(resolved, patch, generatedLocalBindings) {
3361
+ const baselineObjects = resolved.durable_objects;
3362
+ const pendingObjects = patch.durable_objects;
3363
+ const baselineBindings = byIdentity(entries(baselineObjects?.bindings, "Durable Object bindings"), "name", "Durable Object binding", true);
3364
+ const pendingBindings = byIdentity(entries(pendingObjects?.bindings, "Durable Object bindings"), "name", "Durable Object binding");
3365
+ const history = entries(resolved.migrations, "Durable Object migrations");
3366
+ const baselineMigrations = byIdentity(history, "tag", "Durable Object migration", true);
3367
+ for (const local of generatedLocalBindings) for (const map of [baselineBindings, pendingBindings]) {
3368
+ const existing = map.get(local.name);
3369
+ if (existing && (existing.class_name !== local.class_name || existing.script_name !== void 0 || existing.environment !== void 0)) throw new Error(`Cloudflare generated Durable Object binding ${JSON.stringify(local.name)} conflicts with its configured identity.`);
3370
+ }
3371
+ if (pendingObjects?.bindings !== void 0) {
3372
+ const additions = [];
3373
+ for (const [name, row] of pendingBindings) {
3374
+ const existing = baselineBindings.get(name);
3375
+ if (existing && !isDeepStrictEqual(existing, row)) throw new Error(`Cloudflare Durable Object binding ${JSON.stringify(name)} has conflicting configuration.`);
3376
+ if (!existing) additions.push(row);
3377
+ }
3378
+ patch.durable_objects = {
3379
+ ...pendingObjects,
3380
+ bindings: additions
3381
+ };
3382
+ }
3383
+ if (patch.migrations !== void 0) {
3384
+ const pending = byIdentity(entries(patch.migrations, "Durable Object migrations"), "tag", "Durable Object migration");
3385
+ const additions = [];
3386
+ for (const [tag, row] of pending) {
3387
+ const previous = baselineMigrations.get(tag);
3388
+ if (previous && !isDeepStrictEqual(previous, row)) throw new Error(`Cloudflare Durable Object migration ${JSON.stringify(tag)} has conflicting configuration.`);
3389
+ if (!previous) additions.push(row);
3390
+ }
3391
+ patch.migrations = [...history, ...additions];
3392
+ resolved.migrations = [];
3393
+ }
3394
+ }
3395
+ // src/plugin-binding-utils.ts
3396
+ /** Check whether a binding name already exists in a resolved bindings array. */
3397
+ function hasBinding(list, name) {
3398
+ return Array.isArray(list) && list.some((b) => b.binding === name);
3399
+ }
3400
+ /**
3401
+ * Decide whether to inject the `bwf dev` email-inbox loopback var.
3402
+ *
3403
+ * The dev inbox buffer lives in the Vite dev server's Node process;
3404
+ * `sendEmail` runs in workerd and reaches it by fetching the inbox capture
3405
+ * endpoint through the worker's assets binding, which
3406
+ * `@cloudflare/vite-plugin` wires straight into the dev server's middleware
3407
+ * stack. The var carries that binding's NAME (`ASSETS` for a bwf app) and its
3408
+ * presence is what arms the dev path at runtime — so it must never reach a
3409
+ * production build's `wrangler.json`, exactly like the `__NOSAM_TOKEN`
3410
+ * credential gate.
3411
+ *
3412
+ * Gated on `routeEnvironment`, not on `command`: `vite preview` also reports
3413
+ * `command: 'serve'`, but it runs the BUILT worker whose assets binding is a
3414
+ * real asset directory rather than a dev-server loopback. `routeEnvironment`
3415
+ * is the existing `command === 'serve' && !isPreview` distinction.
3416
+ *
3417
+ * Without an assets binding there is no loopback, so injecting the var would
3418
+ * only arm a path that must then fail; gate on it instead.
3419
+ */
3420
+ function shouldInjectEmailDevInboxVar(routeEnvironment, needsEmail, assetsBinding) {
3421
+ return routeEnvironment === "dev" && !!needsEmail && typeof assetsBinding === "string" && !!assetsBinding;
3422
+ }
3423
+ // src/plugin-worker-bindings.ts
3424
+ /** Durable Object bindings already in the patch, else in the resolved config. */
3425
+ function currentDurableObjectBindings(result, resolved) {
3426
+ return (result.durable_objects ?? resolved.durable_objects)?.bindings ?? [];
3427
+ }
3428
+ /** Migrations already in the patch, else in the resolved config. */
3429
+ function currentMigrations(result, resolved) {
3430
+ const current = result.migrations ?? resolved.migrations;
3431
+ return Array.isArray(current) ? current : [];
3432
+ }
3433
+ function mergeWorkerBindings(resolved, input) {
3434
+ const { websocketRoutes, routeEnvironment, workerConfig, envSchemaFacts, authEnabled, viteCommand, bindingNames, dialect, application, bindings, directCloudflareDestination, config, devTriggerToken, queues, durableObjects, sandboxConfig, shouldEmitLive, liveConfig, root, remoteMode } = input;
3435
+ const environmentWebsocketRoutes = websocketRoutes.filter((route) => isRouteEnabledForEnvironment(route, routeEnvironment));
3436
+ const result = { ...workerConfig };
3437
+ result.compatibility_flags = [.../* @__PURE__ */ new Set([...result.compatibility_flags ?? [], ...resolved.compatibility_flags ?? []])];
3438
+ resolved.compatibility_flags = [];
3439
+ if (envSchemaFacts || authEnabled && process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] === "1") {
3440
+ const plaintextVars = {
3441
+ ...resolved.vars ?? {},
3442
+ ...result.vars ?? {}
3443
+ };
3444
+ const plaintextServerKeys = (envSchemaFacts?.serverKeys ?? []).filter((key) => key in plaintextVars);
3445
+ if (viteCommand === "build" && plaintextServerKeys.length > 0) throw new Error(`Server env keys cannot be Worker plaintext vars: ${plaintextServerKeys.join(", ")}. Remove them from worker.vars/wrangler vars and set them with the remote secret store.`);
3446
+ const configuredRequired = resolved.secrets?.required ?? [];
3447
+ const required = [.../* @__PURE__ */ new Set([
3448
+ ...configuredRequired,
3449
+ ...envSchemaFacts?.requiredServerKeys ?? [],
3450
+ ...authEnabled && process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] === "1" ? ["BETTER_AUTH_SECRET"] : []
3451
+ ])];
3452
+ if (required.length > 0) result.secrets = { required };
3453
+ }
3454
+ if (workerConfig.assets && resolved.assets) {
3455
+ delete resolved.assets.not_found_handling;
3456
+ delete resolved.assets.run_worker_first;
3457
+ }
3458
+ const d1Name = bindingNames?.d1 ?? "DB";
3459
+ const d1 = [];
3460
+ if (dialect === "sqlite" && application.needsDatabase && !hasBinding(resolved.d1_databases, d1Name)) d1.push({
3461
+ binding: d1Name,
3462
+ database_name: "default",
3463
+ database_id: "local"
3464
+ });
3465
+ if (d1.length > 0) result.d1_databases = d1;
3466
+ const kvName = bindingNames?.kv ?? "KV";
3467
+ const kv = [];
3468
+ if (bindings.needsKV && !hasBinding(resolved.kv_namespaces, kvName)) kv.push({
3469
+ binding: kvName,
3470
+ id: "local"
3471
+ });
3472
+ if (kv.length > 0) result.kv_namespaces = kv;
3473
+ const r2Name = bindingNames?.r2 ?? "STORAGE";
3474
+ if (bindings.needsR2 && !hasBinding(resolved.r2_buckets, r2Name)) result.r2_buckets = [{
3475
+ binding: r2Name,
3476
+ bucket_name: "default"
3477
+ }];
3478
+ const analyticsDatasets = resolved.analytics_engine_datasets;
3479
+ if (application.procedures.length > 0 && !hasBinding(analyticsDatasets, "ANALYTICS")) result.analytics_engine_datasets = [{
3480
+ binding: "ANALYTICS",
3481
+ dataset: `${(workerConfig.name || resolved.name || readAppIdentity(root).name).replace(/[^A-Za-z0-9_]/g, "_")}_events`
3482
+ }];
3483
+ const resolvedAi = resolved.ai;
3484
+ const aiBindingName = resolveWorkersAiBindingName(resolvedAi, bindingNames?.ai);
3485
+ if (viteCommand === "serve" && bindings.needsAI && directCloudflareDestination && typeof resolvedAi === "object" && resolvedAi !== null && "binding" in resolvedAi && typeof resolvedAi.binding === "string") result.ai = {
3486
+ ...resolvedAi,
3487
+ remote: true
3488
+ };
3489
+ else if (shouldBindWorkersAi(viteCommand, bindings.needsAI, resolvedAi, result.ai, directCloudflareDestination)) result.ai = {
3490
+ binding: aiBindingName,
3491
+ ...viteCommand === "serve" && { remote: true }
3492
+ };
3493
+ if (aiBindingName !== "AI" || config.ai?.gateway) {
3494
+ const vars = result.vars ?? {};
3495
+ if (aiBindingName !== "AI") vars.__NOSAM_AI_BINDING = aiBindingName;
3496
+ if (config.ai?.gateway) vars.__NOSAM_AI_GATEWAY = config.ai.gateway;
3497
+ result.vars = vars;
3498
+ }
3499
+ const emailDevInboxBinding = workerConfig.assets?.binding ?? resolved.assets?.binding;
3500
+ if (shouldInjectEmailDevInboxVar(routeEnvironment, bindings.needsEmail, emailDevInboxBinding)) {
3501
+ const vars = result.vars ?? {};
3502
+ vars[DEV_INBOX_ENV_VAR] = emailDevInboxBinding;
3503
+ vars[DEV_INBOX_TOKEN_ENV_VAR] = devTriggerToken;
3504
+ result.vars = vars;
3505
+ }
3506
+ if (viteCommand === "serve" && bindings.needsEmail) {
3507
+ const sendEmail = resolved.send_email;
3508
+ if (Array.isArray(sendEmail)) {
3509
+ const kept = sendEmail.filter((entry) => entry?.name !== SEND_EMAIL_BINDING);
3510
+ if (kept.length > 0) resolved.send_email = kept;
3511
+ else delete resolved.send_email;
3512
+ }
3513
+ }
3514
+ if (viteCommand === "serve" && config.email?.from) {
3515
+ const vars = result.vars ?? {};
3516
+ vars.__NOSAM_EMAIL_FROM = config.email.from;
3517
+ result.vars = vars;
3518
+ }
3519
+ if (queues.length > 0) {
3520
+ const cloudflareNames = viteCommand === "build" ? readDeployBuildQueueNames() : void 0;
3521
+ result.queues = {
3522
+ producers: queues.map((q) => ({
3523
+ queue: cloudflareQueueName(q.name, cloudflareNames),
3524
+ binding: q.bindingName
3525
+ })),
3526
+ consumers: queues.map((q) => ({
3527
+ queue: cloudflareQueueName(q.name, cloudflareNames),
3528
+ ...q.maxBatchSize != null && { max_batch_size: q.maxBatchSize },
3529
+ ...q.maxBatchTimeout != null && { max_batch_timeout: q.maxBatchTimeout },
3530
+ ...q.maxRetries != null && { max_retries: q.maxRetries },
3531
+ ...q.retryDelay != null && { retry_delay: q.retryDelay }
3532
+ }))
3533
+ };
3534
+ }
3535
+ if (environmentWebsocketRoutes.length > 0) {
3536
+ const existingDurableObjectBindings = resolved.durable_objects?.bindings ?? [];
3537
+ for (const route of environmentWebsocketRoutes) {
3538
+ const conflict = existingDurableObjectBindings.find((binding) => binding.name === route.bindingName && binding.class_name !== route.className);
3539
+ if (conflict) throw new Error(`websocket: binding '${route.bindingName}' is already configured for class '${conflict.class_name}', but '${route.filePath}' requires '${route.className}'.`);
3540
+ }
3541
+ const missingDurableObjectBindings = environmentWebsocketRoutes.filter((route) => !existingDurableObjectBindings.some((binding) => binding.name === route.bindingName)).map((route) => ({
3542
+ name: route.bindingName,
3543
+ class_name: route.className
3544
+ }));
3545
+ if (missingDurableObjectBindings.length > 0) result.durable_objects = { bindings: [...existingDurableObjectBindings, ...missingDurableObjectBindings] };
3546
+ const resolvedMigrations = resolved.migrations;
3547
+ const planned = appendSqliteClassMigration(Array.isArray(resolvedMigrations) ? resolvedMigrations : [], environmentWebsocketRoutes.map((route) => route.className), "void-ws-v1", existingDurableObjectBindings.map((binding) => binding.class_name));
3548
+ if (planned.added) result.migrations = planned.migrations;
3549
+ }
3550
+ if (durableObjects.length > 0) {
3551
+ const existingBindings = currentDurableObjectBindings(result, resolved);
3552
+ for (const module of durableObjects) {
3553
+ const conflict = existingBindings.find((binding) => binding.name === module.bindingName && binding.class_name !== module.className);
3554
+ if (conflict) throw new Error(`durable: binding '${module.bindingName}' is already configured for class '${conflict.class_name}', but durable-objects/ requires '${module.className}'.`);
3555
+ }
3556
+ const additions = durableObjects.filter((module) => !existingBindings.some((binding) => binding.name === module.bindingName)).map((module) => ({
3557
+ name: module.bindingName,
3558
+ class_name: module.className
3559
+ }));
3560
+ if (additions.length > 0) result.durable_objects = { bindings: [...existingBindings, ...additions] };
3561
+ const existingMigrations = currentMigrations(result, resolved);
3562
+ for (const module of durableObjects) if (existingMigrations.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.`);
3563
+ const migrationAdditions = durableObjects.filter((module) => !existingMigrations.some((migration) => migration.tag === module.migrationTag || migration.new_sqlite_classes?.includes(module.className))).map((module) => ({
3564
+ tag: module.migrationTag,
3565
+ new_sqlite_classes: [module.className]
3566
+ }));
3567
+ if (migrationAdditions.length > 0) result.migrations = [...existingMigrations, ...migrationAdditions];
3568
+ }
3569
+ if (bindings.needsSandbox && sandboxConfig) {
3570
+ assertSandboxNamespaceConfig({
3571
+ ...resolved,
3572
+ ...result
3573
+ }, sandboxConfig);
3574
+ const existingDurableObjectBindings = currentDurableObjectBindings(result, resolved);
3575
+ if (!isSandboxAttached(sandboxConfig) && !existingDurableObjectBindings.some((binding) => binding.name === sandboxConfig.binding)) result.durable_objects = { bindings: [...existingDurableObjectBindings, {
3576
+ name: sandboxConfig.binding,
3577
+ class_name: sandboxConfig.className
3578
+ }] };
3579
+ result.containers = [...(result.containers ?? resolved.containers ?? []).filter((container) => container.class_name !== sandboxConfig.className), sandboxContainerConfig(sandboxConfig)];
3580
+ resolved.containers = [];
3581
+ const existingMigrations = currentMigrations(result, resolved);
3582
+ if (!isSandboxAttached(sandboxConfig) && !hasSandboxSqliteMigration(existingMigrations, sandboxConfig.className)) result.migrations = [...existingMigrations, {
3583
+ tag: SANDBOX_MIGRATION_TAG,
3584
+ new_sqlite_classes: [sandboxConfig.className]
3585
+ }];
3586
+ }
3587
+ if (shouldEmitLive() && liveConfig) {
3588
+ const existingDurableObjectBindings = currentDurableObjectBindings(result, resolved);
3589
+ if (!existingDurableObjectBindings.some((binding) => binding.name === liveConfig.bindingName)) result.durable_objects = { bindings: [...existingDurableObjectBindings, {
3590
+ name: liveConfig.bindingName,
3591
+ class_name: liveConfig.className
3592
+ }] };
3593
+ const existingMigrations = currentMigrations(result, resolved);
3594
+ if (!hasDurableObjectSqliteMigration(existingMigrations, liveConfig.className)) result.migrations = [...existingMigrations, {
3595
+ tag: nextDurableObjectMigrationTag(existingMigrations, LIVE_MIGRATION_TAG),
3596
+ new_sqlite_classes: [liveConfig.className]
3597
+ }];
3598
+ }
3599
+ if (viteCommand === "serve" && bindings.needsAI && !directCloudflareDestination) {
3600
+ const credentials = readBwfDevCredentials(root);
3601
+ if (credentials.status === "ok") {
3602
+ const vars = result.vars ?? {};
3603
+ vars.__NOSAM_TOKEN = credentials.token;
3604
+ vars.__NOSAM_PROJECT_ID = credentials.projectId;
3605
+ vars.__NOSAM_PROXY_URL = credentials.proxyUrl;
3606
+ if (credentials.accessCredentials) vars.__NOSAM_ACCESS_CREDENTIALS = credentials.accessCredentials;
3607
+ result.vars = vars;
3608
+ }
3609
+ }
3610
+ if (viteCommand === "serve" && remoteMode && (bindings.needsD1 || bindings.needsKV || bindings.needsR2)) {
3611
+ const credentials = readBwfDevCredentials(root);
3612
+ if (credentials.status === "ok") {
3613
+ const vars = result.vars ?? {};
3614
+ vars.__NOSAM_PROXY_URL = credentials.proxyUrl;
3615
+ if (credentials.accessCredentials) vars.__NOSAM_ACCESS_CREDENTIALS = credentials.accessCredentials;
3616
+ vars.__NOSAM_TOKEN = credentials.token;
3617
+ vars.__NOSAM_PROJECT_ID = credentials.projectId;
3618
+ vars.__NOSAM_REMOTE = "1";
3619
+ result.vars = vars;
3620
+ }
3621
+ }
3622
+ const versionMetadataBinding = selectNativeVersionMetadataBinding(resolved, {
3623
+ nativeBuild: viteCommand === "build" && process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] === "1",
3624
+ preserveBindings: process.env[CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV] === "1"
3625
+ });
3626
+ if (versionMetadataBinding) {
3627
+ const owner = findBindingNameOwner(result, "version_metadata", versionMetadataBinding);
3628
+ if (owner) throw new Error(`Cloudflare version metadata binding ${versionMetadataBinding} conflicts with ${owner}.`);
3629
+ if (!resolved.version_metadata) result.version_metadata = { binding: versionMetadataBinding };
3630
+ }
3631
+ finalizeDurableObjectPatch(resolved, result, [
3632
+ ...environmentWebsocketRoutes.map((route) => ({
3633
+ name: route.bindingName,
3634
+ class_name: route.className
3635
+ })),
3636
+ ...durableObjects.map((module) => ({
3637
+ name: module.bindingName,
3638
+ class_name: module.className
3639
+ })),
3640
+ ...bindings.needsSandbox && sandboxConfig && !isSandboxAttached(sandboxConfig) ? [{
3641
+ name: sandboxConfig.binding,
3642
+ class_name: sandboxConfig.className
3643
+ }] : [],
3644
+ ...shouldEmitLive() && liveConfig ? [{
3645
+ name: liveConfig.bindingName,
3646
+ class_name: liveConfig.className
3647
+ }] : []
3648
+ ]);
3649
+ return {
3650
+ patch: result,
3651
+ versionMetadataBinding
3652
+ };
3653
+ }
3654
+ // src/plugin-worker-environment.ts
3655
+ const CLOUDFLARE_BUILTIN_IMPORT = /^cloudflare:/;
3656
+ const SANDBOX_SDK_IMPORT = "@cloudflare/sandbox";
3657
+ const SANDBOX_SDK_IMPORT_FILTER = /^@cloudflare\/sandbox$/;
3658
+ const DEFAULT_WORKER_ENVIRONMENT_NAME = "nosam_worker";
3659
+ const DEFAULT_WORKER_OUT_DIR = "dist/ssr";
3660
+ const DEV_ASSET_ROUTING_EXCLUSIONS = [
3661
+ "!/@vite/*",
3662
+ "!/@id/*",
3663
+ "!/@fs/*",
3664
+ "!/@react-refresh",
3665
+ "!/node_modules/*",
3666
+ "!/__uno.css"
3667
+ ];
3668
+ function resolveSandboxSdkEntry() {
3669
+ return fileURLToPath(import.meta.resolve(SANDBOX_SDK_IMPORT));
3670
+ }
3671
+ function createCloudflareBuiltinsExternalPlugin() {
3672
+ return {
3673
+ name: "nosam:cloudflare-builtins-external",
3674
+ config(_, env) {
3675
+ if (env.command !== "build") return;
3676
+ return { build: { rollupOptions: { external: [CLOUDFLARE_BUILTIN_IMPORT] } } };
3677
+ }
3678
+ };
3679
+ }
3680
+ /**
3681
+ * Send a bare `nosam` import in server code to the handler helpers (`defineScheduled`,
3682
+ * `defineQueue`, ...), as bwf apps and the cron/queue deploy bundles do. The package entry is the
3683
+ * Vite plugin: loaded in a worker environment, it pulls Wrangler into the dependency optimizer.
3684
+ */
3685
+ function createDefaultWorkerEnvironmentPlugin() {
3686
+ return {
3687
+ name: "nosam:default-worker-environment",
3688
+ config(config) {
3689
+ const currentEnvironment = config.environments?.[DEFAULT_WORKER_ENVIRONMENT_NAME];
3690
+ return { environments: { [DEFAULT_WORKER_ENVIRONMENT_NAME]: {
3691
+ ...currentEnvironment,
3692
+ build: {
3693
+ ...currentEnvironment?.build,
3694
+ outDir: currentEnvironment?.build?.outDir ?? DEFAULT_WORKER_OUT_DIR
3695
+ }
3696
+ } } };
3697
+ }
3698
+ };
3699
+ }
3700
+ function createWorkerEnvironmentSanitizerPlugin(environmentNames) {
3701
+ const names = new Set(environmentNames);
3702
+ return {
3703
+ name: "nosam:worker-environment-sanitizer",
3704
+ enforce: "pre",
3705
+ configResolved(config) {
3706
+ for (const name of names) {
3707
+ const resolve = config.environments[name]?.resolve;
3708
+ if (resolve && "external" in resolve) resolve.external = [];
3709
+ }
3710
+ }
3711
+ };
3712
+ }
3713
+ function createSandboxSdkResolvePlugin() {
3714
+ let resolved;
3715
+ return {
3716
+ name: "nosam:sandbox-sdk-resolve",
3717
+ enforce: "pre",
3718
+ resolveId: {
3719
+ filter: { id: SANDBOX_SDK_IMPORT_FILTER },
3720
+ handler(id) {
3721
+ if (id !== SANDBOX_SDK_IMPORT) return;
3722
+ resolved ??= resolveSandboxSdkEntry();
3723
+ return resolved;
3724
+ }
3725
+ }
3726
+ };
3727
+ }
3728
+ function createWranglerCompatPersistPlugin(root, config) {
3729
+ let persisted = false;
3730
+ const persist = () => {
3731
+ if (persisted) return;
3732
+ persisted = true;
3733
+ ensureWranglerCompat(root, config);
3734
+ };
3735
+ return {
3736
+ name: "nosam:wrangler-compat-persist",
3737
+ buildStart() {
3738
+ persist();
3739
+ },
3740
+ configureServer() {
3741
+ persist();
3742
+ }
3743
+ };
3744
+ }
3745
+ const DATABASE_DRIVER_DEPS = {
3746
+ sqlite: [],
3747
+ postgresql: ["@builtbyfriends/bwf > pg"],
3748
+ mysql: ["@builtbyfriends/bwf > mysql2"]
3749
+ };
3750
+ const NODE_BUILTIN = new RegExp(`^(?:node:)?(?:${builtinModules.join("|")})$`);
3751
+ const NODE_BUILTIN_REQUIRE_PREFIX = "\0nosam:node-require:";
3752
+ /**
3753
+ * The Node built-ins that workerd provides for the given compatibility settings, from the preset
3754
+ * the Cloudflare plugin builds Workers with (a dependency of `@cloudflare/vite-plugin`). Before
3755
+ * 2025-09-15 the preset fills in parts of `node:process` instead of listing it, but workerd
3756
+ * provides that module at every date.
3757
+ */
3758
+ async function readWorkerdNodeBuiltins(compat) {
3759
+ const vitePlugin = fileURLToPath(import.meta.resolve("@cloudflare/vite-plugin"));
3760
+ const manifestPath = createRequire(vitePlugin).resolve("@cloudflare/unenv-preset/package.json");
3761
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
3762
+ const { getCloudflarePreset } = await import(pathToFileURL(join(dirname(manifestPath), manifest.exports["."].import)).href);
3763
+ const { external } = getCloudflarePreset({
3764
+ compatibilityDate: compat.compatibilityDate,
3765
+ compatibilityFlags: compat.compatibilityFlags ?? []
3766
+ });
3767
+ return /* @__PURE__ */ new Set([...external.map((name) => name.replace(/^node:/, "")), "process"]);
3768
+ }
3769
+ function createServerRuntimeOptimizerPlugin(dialect, readCompat) {
3770
+ let workerdNodeBuiltins;
3771
+ return {
3772
+ name: "nosam:server-runtime-optimizer",
3773
+ configEnvironment(name, environment) {
3774
+ if (name === "client") return;
3775
+ if (!environment.resolve?.conditions?.includes("workerd")) return { optimizeDeps: { exclude: ["@builtbyfriends/bwf"] } };
3776
+ return { optimizeDeps: {
3777
+ exclude: ["@builtbyfriends/bwf", "better-auth"],
3778
+ include: ["@builtbyfriends/bwf > email-validator", ...DATABASE_DRIVER_DEPS[dialect]]
3779
+ } };
3780
+ },
3781
+ resolveId: {
3782
+ order: "pre",
3783
+ filter: { id: NODE_BUILTIN },
3784
+ async handler(id, _importer, options) {
3785
+ if (dialect === "sqlite" || options.kind !== "require-call" || this.environment?.mode !== "build" || !this.environment.config.resolve.conditions.includes("workerd")) return;
3786
+ const name = id.replace(/^node:/, "");
3787
+ workerdNodeBuiltins ??= readWorkerdNodeBuiltins(readCompat());
3788
+ if (!(await workerdNodeBuiltins).has(name)) return;
3789
+ return `${NODE_BUILTIN_REQUIRE_PREFIX}${name}`;
3790
+ }
3791
+ },
3792
+ load: {
3793
+ filter: { id: /^\0nosam:node-require:/ },
3794
+ handler(id) {
3795
+ return `import builtin from "node:${id.slice(20)}";\nexport { builtin as "module.exports" };\n`;
3796
+ }
3797
+ }
3798
+ };
3799
+ }
3800
+ // src/index.ts
3801
+ const scheduledPreviewPointerCleanups = /* @__PURE__ */ new Set();
3802
+ /** Returns the Vite plugins that build and serve a bwf app on Cloudflare. */
3803
+ function bwfPlugin(options) {
3804
+ const root = process.cwd();
3805
+ const directCloudflareDestination = readDeploymentPlatform(root) === "cloudflare";
3806
+ if (directCloudflareDestination) selectBwfCloudflareLogin();
3807
+ warnIfPackageJsonIsNotEsm(root);
3808
+ const devTriggerToken = isViteBuildOrPreview() ? crypto.randomUUID() : getOrCreateDevTriggerToken(root);
3809
+ const config = readConfig(root);
3810
+ syncBindingTypes(root, config);
3811
+ const projectCloudflareConfigPath = materializeCloudflareConfig(root);
3812
+ const cloudflareConfigPath = projectCloudflareConfigPath && existsSync(projectCloudflareConfigPath) ? projectCloudflareConfigPath : void 0;
3813
+ let previewing = false;
3814
+ const restorePreviewPointer = () => {
3815
+ if (!existsSync(join(root, "bwf.config.ts")) || process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] === "1") return;
3816
+ if (restoreCloudflarePreviewPointer(root) && !scheduledPreviewPointerCleanups.has(root)) {
3817
+ scheduledPreviewPointerCleanups.add(root);
3818
+ process.once("exit", () => {
3819
+ rmSync(join(root, ".wrangler", "deploy", "config.json"), { force: true });
3820
+ });
3821
+ }
3822
+ };
3823
+ const implicitDeployGuard = {
3824
+ name: "nosam:remove-implicit-cloudflare-deploy-pointer",
3825
+ enforce: "pre",
3826
+ config(_config, environment) {
3827
+ previewing = environment.isPreview === true;
3828
+ if (previewing) restorePreviewPointer();
3829
+ },
3830
+ closeBundle() {
3831
+ if (!previewing && existsSync(join(root, "bwf.config.ts")) && process.env["BWF_CLOUDFLARE_DEPLOY_BUILD"] !== "1") stashCloudflareDeployPointer(root);
3832
+ }
3833
+ };
3834
+ let application = analyzeApplicationSync(root, { config });
3835
+ const { paths, dialect, bindingNames, authConfigPath } = application;
3836
+ const analyses = /* @__PURE__ */ new Map();
3837
+ const getApplicationAnalysis = (environment, refresh = false) => {
3838
+ let result = refresh ? void 0 : analyses.get(environment);
3839
+ if (!result) {
3840
+ result = analyzeApplicationSync(root, {
3841
+ config,
3842
+ environment
3843
+ });
3844
+ analyses.set(environment, result);
3845
+ }
3846
+ application = result;
3847
+ return result;
3848
+ };
3849
+ let routeEnvironment = "prod";
3850
+ assertNoRootSourceConventionConflicts(paths);
3851
+ const localD1PersistRoot = options?.persistTo ?? join(root, ".bwf");
3852
+ const localD1 = resolveLocalD1Target(root, {
3853
+ bindingName: bindingNames?.d1 ?? "DB",
3854
+ persistRoot: localD1PersistRoot
3855
+ });
3856
+ writeLocalD1PersistState(root, options?.persistTo);
3857
+ let bindings = application.bindings;
3858
+ const sandboxConfig = bindings.needsSandbox ? resolveSandboxConfig(config, root) : void 0;
3859
+ let authEnabled = application.authEnabled;
3860
+ const clientStubsPlugin = createClientStubsPlugin();
3861
+ const serverRuntimeOptimizerPlugin = createServerRuntimeOptimizerPlugin(dialect, () => readWranglerCompat(root, config));
3862
+ const queues = application.queues;
3863
+ const websocketRoutes = application.allWebsockets;
3864
+ const durableObjects = application.durableObjects;
3865
+ for (const module of durableObjects) {
3866
+ const websocketCollision = websocketRoutes.find((route) => route.bindingName === module.bindingName || route.className === module.className);
3867
+ if (websocketCollision) throw new Error(`durable: durable-objects/${module.filePath.split("/").pop()} conflicts with WebSocket route '${websocketCollision.filePath}'. Rename one of the files.`);
3868
+ if (sandboxConfig && !isSandboxAttached(sandboxConfig) && (sandboxConfig.binding === module.bindingName || sandboxConfig.className === module.className)) throw new Error(`durable: durable-objects/${module.filePath.split("/").pop()} conflicts with the configured Sandbox binding or class. Rename the Durable Object file.`);
3869
+ }
3870
+ syncWranglerDurableObjects(root, durableObjects);
3871
+ const productionWebSocketRoutes = websocketRoutes.filter((route) => isRouteEnabledForEnvironment(route, "prod"));
3872
+ syncWranglerWebSockets(root, productionWebSocketRoutes);
3873
+ const websocketTombstones = readWranglerWebSocketTombstones(root, productionWebSocketRoutes);
3874
+ const existingLiveConfig = readExistingLiveBindingConfig(root);
3875
+ const liveConfig = bindings.needsLive ? resolveLiveBindingConfig(root, {
3876
+ reservedBindings: [...websocketRoutes.map((route) => route.bindingName), ...durableObjects.map((module) => module.bindingName)],
3877
+ reservedClasses: [
3878
+ ...websocketRoutes.map((route) => route.className),
3879
+ ...durableObjects.map((module) => module.className),
3880
+ sandboxConfig?.className
3881
+ ]
3882
+ }) : existingLiveConfig;
3883
+ const shouldEmitLive = () => bindings.needsLive || existingLiveConfig !== void 0;
3884
+ const remoteMode = resolveRemoteMode(config.remote);
3885
+ const workerConfig = {};
3886
+ const jobs = application.jobs;
3887
+ if (jobs.length > 0) workerConfig.triggers = { crons: [...new Set(jobs.flatMap((job) => job.crons))] };
3888
+ let envSchemaFacts;
3889
+ let assetRouting;
3890
+ if (config.worker?.vars) workerConfig.vars = { ...config.worker.vars };
3891
+ let viteCommand = "build";
3892
+ let versionMetadataBinding;
3893
+ const wranglerCompat = readWranglerCompat(root, config);
3894
+ workerConfig.compatibility_date = wranglerCompat.compatibilityDate;
3895
+ if (wranglerCompat.compatibilityFlags) workerConfig.compatibility_flags = wranglerCompat.compatibilityFlags;
3896
+ if (config.worker?.limits?.cpu_ms) workerConfig.limits = { cpu_ms: config.worker.limits.cpu_ms };
3897
+ const inspectorPortEnv = process.env.BWF_INSPECTOR_PORT;
3898
+ const inspectorPort = inspectorPortEnv === "false" ? false : typeof inspectorPortEnv === "string" && inspectorPortEnv.length > 0 ? Number.parseInt(inspectorPortEnv, 10) : void 0;
3899
+ const inspectorPortOption = inspectorPort === false ? { inspectorPort: false } : typeof inspectorPort === "number" ? { inspectorPort } : {};
3900
+ const outDir = join(root, ".bwf");
3901
+ mkdirSync(outDir, { recursive: true });
3902
+ function mergeBindings(resolved) {
3903
+ const merged = mergeWorkerBindings(resolved, {
3904
+ websocketRoutes,
3905
+ routeEnvironment,
3906
+ workerConfig,
3907
+ envSchemaFacts,
3908
+ authEnabled,
3909
+ viteCommand,
3910
+ bindingNames,
3911
+ dialect,
3912
+ application,
3913
+ bindings,
3914
+ directCloudflareDestination,
3915
+ config,
3916
+ devTriggerToken,
3917
+ queues,
3918
+ durableObjects,
3919
+ sandboxConfig,
3920
+ shouldEmitLive,
3921
+ liveConfig,
3922
+ root,
3923
+ remoteMode
3924
+ });
3925
+ versionMetadataBinding = merged.versionMetadataBinding;
3926
+ return merged.patch;
3927
+ }
3928
+ function applyEnvSchema(facts) {
3929
+ envSchemaFacts = facts;
3930
+ }
3931
+ const envPlugin = {
3932
+ name: "nosam:env",
3933
+ config(userConfig, { command, isPreview }) {
3934
+ viteCommand = command;
3935
+ routeEnvironment = command === "serve" && !isPreview ? "dev" : "prod";
3936
+ application = getApplicationAnalysis(routeEnvironment);
3937
+ bindings = application.bindings;
3938
+ authEnabled = application.authEnabled;
3939
+ managedCloudflareBuild = command === "build" && Boolean(process.env.NOSAM_DEPLOY_PROJECT_ID);
3940
+ assetRoutingPublicDir = userConfig.publicDir === false ? null : typeof userConfig.publicDir === "string" ? resolve(root, userConfig.publicDir) : join(root, "public");
3941
+ assetRouting = resolveConfiguredAssetRoutingPolicy();
3942
+ applyAssetRoutingPolicy(assetRouting);
3943
+ const ignored = ["**/.bwf/**"];
3944
+ if (command === "serve") {
3945
+ const local = loadLocalEnv(root, { onWarn: (message) => bwfWarn(message) });
3946
+ const env = { ...local };
3947
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(local), ...envSchemaFacts?.keys ?? []])) if (process.env[key] !== void 0) env[key] = process.env[key];
3948
+ workerConfig.vars = {
3949
+ ...workerConfig.vars,
3950
+ ...env
3951
+ };
3952
+ if (isPreview) for (const [key, value] of Object.entries(env)) process.env[key] ??= value;
3953
+ }
3954
+ const assets = workerConfig.assets;
3955
+ if (command === "serve" && !isPreview && assets?.run_worker_first?.includes("/**")) assets.run_worker_first = [...DEV_ASSET_ROUTING_EXCLUSIONS, "/**"];
3956
+ return {
3957
+ server: { watch: { ignored } },
3958
+ environments: { ssr: { build: { minify: true } } }
3959
+ };
3960
+ },
3961
+ configureServer(server) {
3962
+ if (remoteMode && (bindings.needsD1 || bindings.needsKV || bindings.needsR2)) {
3963
+ const credentials = readBwfDevCredentials(root);
3964
+ if (credentials.status === "ok") {
3965
+ const lines = [import_picocolors.default.blue("Remote bindings active")];
3966
+ if (bindings.needsD1) lines.push(` DB ${import_picocolors.default.dim("→ remote D1")}`);
3967
+ if (bindings.needsKV) lines.push(` KV ${import_picocolors.default.dim("→ remote KV")}`);
3968
+ if (bindings.needsR2) lines.push(` STORAGE ${import_picocolors.default.dim("→ remote R2")}`);
3969
+ afterServerReady(server, () => {
3970
+ console.log();
3971
+ bwfLog(lines.join("\n "));
3972
+ });
3973
+ } else if (credentials.status === "no-token") afterServerReady(server, () => {
3974
+ console.log();
3975
+ bwfWarn("Remote mode requires authentication. Run `bwf account login`, then restart.");
3976
+ bwfWarn("Falling back to local bindings.");
3977
+ });
3978
+ else afterServerReady(server, () => {
3979
+ console.log();
3980
+ bwfWarn("Remote mode requires a linked project. Run `bwf project link` first.");
3981
+ bwfWarn("Falling back to local bindings.");
3982
+ });
3983
+ }
3984
+ if (bindings.needsAI && !directCloudflareDestination) {
3985
+ const credentials = readBwfDevCredentials(root);
3986
+ if (credentials.status === "no-token") afterServerReady(server, () => {
3987
+ console.log();
3988
+ bwfWarn("AI requires authentication. Run `bwf account login`, then restart the dev server.");
3989
+ });
3990
+ else if (credentials.status === "no-project") {
3991
+ if (process.stdin.isTTY && !isVitestServer(server.config)) afterServerReady(server, () => {
3992
+ console.log();
3993
+ runAiSetupPrompt(root, credentials.token, credentials.apiUrl, server);
3994
+ });
3995
+ else afterServerReady(server, () => {
3996
+ console.log();
3997
+ bwfWarn("AI requires a linked project. Run `bwf project link` to set one up.");
3998
+ });
3999
+ }
4000
+ }
4001
+ }
4002
+ };
4003
+ const autoDetectAuth = !authEnabled;
4004
+ const bindingWatchPlugin = {
4005
+ name: "nosam:binding-watch",
4006
+ apply: "serve",
4007
+ configureServer(server) {
4008
+ const effectiveDirs = config.inference?.scanDirs ?? DEFAULT_SCAN_DIRS;
4009
+ const watchDirs = [.../* @__PURE__ */ new Set([...effectiveDirs, "src"])].map((d) => join(root, d));
4010
+ let hintShown = false;
4011
+ const check = (path) => {
4012
+ if (hintShown) return;
4013
+ if (!watchDirs.some((d) => path.startsWith(d))) return;
4014
+ try {
4015
+ const code = readFileSync(path, "utf-8");
4016
+ const fileBindings = applyBindingOverrides(inferBindingsFromSource(code, path.split("/").pop()), config.inference?.bindings);
4017
+ const newBindings = [];
4018
+ if (fileBindings.needsD1 && !bindings.needsD1) newBindings.push("D1 (bwf/db)");
4019
+ if (fileBindings.needsKV && !bindings.needsKV) newBindings.push("KV (bwf/kv)");
4020
+ if (fileBindings.needsR2 && !bindings.needsR2) newBindings.push("R2 (bwf/storage)");
4021
+ if (fileBindings.needsAI && !bindings.needsAI) newBindings.push("AI (bwf/ai)");
4022
+ if (fileBindings.needsSandbox && !bindings.needsSandbox) newBindings.push("Sandbox (bwf/sandbox)");
4023
+ if (fileBindings.needsEmail && !bindings.needsEmail) newBindings.push("Email (bwf/email)");
4024
+ if (autoDetectAuth && fileBindings.needsAuth) newBindings.push("Auth (bwf/auth)");
4025
+ if (newBindings.length > 0) {
4026
+ hintShown = true;
4027
+ const detected = newBindings.join(", ");
4028
+ setTimeout(() => {
4029
+ bwfLog(`New ${detected} binding detected. Restart to apply.`);
4030
+ }, 300);
4031
+ server.hot.send({
4032
+ type: "custom",
4033
+ event: "nosam:new-binding",
4034
+ data: { message: `New ${detected} binding detected.` }
4035
+ });
4036
+ }
4037
+ } catch {}
4038
+ };
4039
+ const attach = () => {
4040
+ server.watcher.on("add", check);
4041
+ server.watcher.on("change", check);
4042
+ };
4043
+ if (server.httpServer) server.httpServer.once("listening", attach);
4044
+ else attach();
4045
+ }
4046
+ };
4047
+ const existingFlags = workerConfig.compatibility_flags ?? [];
4048
+ const needsNodejsCompat = authEnabled || dialect !== "sqlite" || bindings.needsSandbox;
4049
+ const normalizedFlags = normalizeWranglerCompatibilityFlags(existingFlags, { needsNodejsCompat });
4050
+ if (normalizedFlags && normalizedFlags !== existingFlags) workerConfig.compatibility_flags = normalizedFlags;
4051
+ let assetRoutingPublicDir = join(root, "public");
4052
+ let managedCloudflareBuild = false;
4053
+ function resolveConfiguredAssetRoutingPolicy() {
4054
+ const routePatterns = application.routes;
4055
+ const environmentWebsocketRoutes = websocketRoutes.filter((route) => isRouteEnabledForEnvironment(route, routeEnvironment));
4056
+ const policy = resolveAssetRoutingPolicy({
4057
+ hasApiRoutes: hasApiRoutes(routePatterns) || hasApiRoutes(environmentWebsocketRoutes) || authEnabled,
4058
+ hasDocumentRoutes: hasDocumentRoutes(routePatterns),
4059
+ hasMiddleware: application.middleware.length > 0,
4060
+ hasWebSockets: hasDocumentRoutes(environmentWebsocketRoutes),
4061
+ authEnabled,
4062
+ liveEnabled: shouldEmitLive() && liveConfig !== void 0,
4063
+ notFound: config.routing?.notFound
4064
+ });
4065
+ const rules = mergeRoutingRules({
4066
+ dir: assetRoutingPublicDir,
4067
+ routing: config.routing
4068
+ });
4069
+ if (!managedCloudflareBuild && edgeRulesNeedWorker({
4070
+ ...rules,
4071
+ alwaysUseHttps: config.routing?.alwaysUseHttps
4072
+ })) {
4073
+ policy.assetConfig.run_worker_first = ["/**"];
4074
+ if (rules.fallbackRules?.length && policy.assetConfig.not_found_handling === "single-page-application") {
4075
+ policy.assetConfig.not_found_handling = "none";
4076
+ policy.workerSpaFallback = true;
4077
+ }
4078
+ }
4079
+ return policy;
4080
+ }
4081
+ assetRouting = resolveConfiguredAssetRoutingPolicy();
4082
+ workerConfig.main = join(root, ".bwf", "entry.ts");
4083
+ function applyAssetRoutingPolicy(policy) {
4084
+ workerConfig.assets = {
4085
+ binding: "ASSETS",
4086
+ ...policy.assetConfig
4087
+ };
4088
+ }
4089
+ function updateDevAssetRoutingPolicy(next) {
4090
+ const previous = assetRouting;
4091
+ const requiresRestart = previous.workerFirst !== next.workerFirst || previous.apiWorkerFirst !== next.apiWorkerFirst || previous.assetConfig.not_found_handling !== next.assetConfig.not_found_handling || JSON.stringify(previous.assetConfig.run_worker_first) !== JSON.stringify(next.assetConfig.run_worker_first);
4092
+ assetRouting = next;
4093
+ if (requiresRestart) applyAssetRoutingPolicy(next);
4094
+ return requiresRestart;
4095
+ }
4096
+ applyAssetRoutingPolicy(assetRouting);
4097
+ const routes = routingPlugin(root, {
4098
+ getApplicationAnalysis,
4099
+ isAuthEnabled: () => authEnabled,
4100
+ getVersionMetadataBinding: () => versionMetadataBinding,
4101
+ devTriggerToken,
4102
+ remoteMode,
4103
+ routing: config.routing,
4104
+ bindingNames,
4105
+ get hasSandbox() {
4106
+ return bindings.needsSandbox && !isSandboxAttached(sandboxConfig);
4107
+ },
4108
+ sandboxBindingName: sandboxConfig?.binding,
4109
+ sandboxClassName: sandboxConfig?.className,
4110
+ sandboxInstanceType: sandboxConfig?.instanceType,
4111
+ get live() {
4112
+ return shouldEmitLive() ? liveConfig : void 0;
4113
+ },
4114
+ durableObjects,
4115
+ websocketTombstones,
4116
+ onDevAssetRoutingPolicyChange: updateDevAssetRoutingPolicy,
4117
+ assetWorkerBypass: true
4118
+ });
4119
+ return [
4120
+ createCloudflareBuiltinsExternalPlugin(),
4121
+ createDefaultWorkerEnvironmentPlugin(),
4122
+ createWorkerEnvironmentSanitizerPlugin([DEFAULT_WORKER_ENVIRONMENT_NAME]),
4123
+ createWranglerCompatPersistPlugin(root, config),
4124
+ devTriggerSecretGuardPlugin(),
4125
+ restartPlugin(),
4126
+ bindingWatchPlugin,
4127
+ ...bindings.needsEmail ? [emailDevInboxPlugin({ devTriggerToken })] : [],
4128
+ envPlugin,
4129
+ envSchemaPlugin(root, { onSchema: applyEnvSchema }),
4130
+ envClientGuardPlugin(root),
4131
+ envClientFoldPlugin(),
4132
+ clientStubsPlugin,
4133
+ serverRuntimeOptimizerPlugin,
4134
+ bindingRuntimePlugin(bindingNames),
4135
+ ...bindings.needsSandbox && !isSandboxAttached(sandboxConfig) ? [createSandboxSdkResolvePlugin()] : [],
4136
+ routes,
4137
+ drizzlePlugin(root, true, dialect, {
4138
+ d1BindingName: bindingNames?.d1,
4139
+ forceVirtualDb: authEnabled || bindingNames?.d1 !== void 0,
4140
+ casing: getDatabaseCasing(config),
4141
+ localD1DatabaseId: localD1.databaseId,
4142
+ localD1PersistRoot: localD1.persistRoot
4143
+ }),
4144
+ migrationPlugin(root, dialect, localD1.databaseId, localD1.persistRoot, {
4145
+ enabled: authEnabled,
4146
+ configPath: authConfigPath
4147
+ }),
4148
+ devTriggersHintPlugin(root, devTriggerToken),
4149
+ ...cloudflare$1({
4150
+ configPath: cloudflareConfigPath,
4151
+ ...inspectorPortOption,
4152
+ persistState: { path: localD1.persistRoot },
4153
+ auxiliaryWorkers: options?.auxiliaryWorkers,
4154
+ viteEnvironment: { name: DEFAULT_WORKER_ENVIRONMENT_NAME },
4155
+ config: mergeBindings,
4156
+ finalizeAssets(clientDir, environment) {
4157
+ (environment?.config.plugins.find((plugin) => plugin.name === routes.name))?.api.finalizeCloudflareAssets(clientDir, environment.config.build.assetsDir);
4158
+ }
4159
+ }),
4160
+ implicitDeployGuard
4161
+ ];
4162
+ }
4163
+ export { BwfAssetRewriteError, basicAuth, bwfPlugin, defineHandler, defineMiddleware, defineQueue, defineScheduled, resolveWorkersAiBindingName, shouldBindWorkersAi, shouldInjectEmailDevInboxVar };