@builtbyfriends/bwf 0.0.0-stage → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (448) hide show
  1. package/AGENTS_TEMPLATE.md +4 -0
  2. package/LICENSE +22 -0
  3. package/README.md +48 -2
  4. package/dist/account-cmd-Cj0I2_bJ.mjs +45 -0
  5. package/dist/agents-BLiMq9E1.mjs +113 -0
  6. package/dist/application-analysis-C9Ck2Yeg.mjs +1498 -0
  7. package/dist/application-routing-DbR-W5lG.mjs +25 -0
  8. package/dist/atomic-write-DA6eD1Kp.mjs +17 -0
  9. package/dist/auth-BKsUmWbT.d.mts +77 -0
  10. package/dist/auth-DkvoW5hB.mjs +33 -0
  11. package/dist/auth-aKyIWkdS.mjs +1 -0
  12. package/dist/auth-client-6-Ft9i9T.d.mts +5 -0
  13. package/dist/auth-client-DwCdwKbw.mjs +5 -0
  14. package/dist/auth-client-react-CJdeErvM.mjs +5 -0
  15. package/dist/auth-client-react-DvQLe5Zb.d.mts +5 -0
  16. package/dist/auth-link-D-DddkCQ.mjs +26 -0
  17. package/dist/auth-migrations-DDeifS3v.mjs +206 -0
  18. package/dist/auth-router-tWzIwf8f.mjs +66 -0
  19. package/dist/auth-xnkmpZUl.mjs +311 -0
  20. package/dist/base64-ikl9yBy3.mjs +15 -0
  21. package/dist/better-auth-shared-Br6TNaYJ.mjs +473 -0
  22. package/dist/better-auth-shared-CsBNvPOU.d.mts +56 -0
  23. package/dist/build-cmd-BnZezraT.mjs +153 -0
  24. package/dist/build-output-dir-Clj_unKN.mjs +402 -0
  25. package/dist/cancel-deploy-DKAj5U1Z.mjs +57 -0
  26. package/dist/cf-access-Bhz9wX6p.mjs +131 -0
  27. package/dist/cf-access-CUP5L08W.mjs +67 -0
  28. package/dist/cf-build-output-DA6uJomQ.mjs +1 -0
  29. package/dist/cf-build-output-DNQTwMNU.mjs +438 -0
  30. package/dist/cf-command-values-2kOtxMo1.mjs +26 -0
  31. package/dist/cf-config-migrate-COOCi4Ge.mjs +330 -0
  32. package/dist/cf-worker-settings-CIh4t_yG.mjs +41 -0
  33. package/dist/cli/cli.d.mts +1 -0
  34. package/dist/cli/cli.mjs +88 -0
  35. package/dist/cli/cloudflare-operation-process.d.mts +1 -0
  36. package/dist/cli/cloudflare-operation-process.mjs +1284 -0
  37. package/dist/cli/env-schema-probe.d.mts +43 -0
  38. package/dist/cli/env-schema-probe.mjs +165 -0
  39. package/dist/cli-main-HeXRQml6.mjs +1846 -0
  40. package/dist/client-D3D5RM5h.mjs +940 -0
  41. package/dist/client-VF2Nzc7Z.mjs +1 -0
  42. package/dist/cloudflare-auth-jb-1e43r.mjs +152 -0
  43. package/dist/cloudflare-cmd-B62t8Fm-.mjs +59 -0
  44. package/dist/cloudflare-config-i8yanry0.mjs +186 -0
  45. package/dist/cloudflare-connect-x7IsYghw.mjs +55 -0
  46. package/dist/cloudflare-operations-BeK7bhnP.mjs +627 -0
  47. package/dist/cloudflare-operations-C3Uu0Emj.mjs +1 -0
  48. package/dist/cloudflare-process-Cc6oiJqk.mjs +309 -0
  49. package/dist/cloudflare-user-output-CqONaAbP.mjs +19 -0
  50. package/dist/collect-8i0wU63d.mjs +1 -0
  51. package/dist/collect-C6Blu9yw.mjs +48 -0
  52. package/dist/config-CN_RFRkS.mjs +86 -0
  53. package/dist/config-D5G-Tx6o.mjs +1 -0
  54. package/dist/config-DOaFIK3w.mjs +88 -0
  55. package/dist/config-entry.d.mts +202 -0
  56. package/dist/config-entry.mjs +6 -0
  57. package/dist/config-tNx0HlFv.mjs +516 -0
  58. package/dist/connect-hLPNppu3.mjs +84 -0
  59. package/dist/create-project-B35ux-LA.mjs +126 -0
  60. package/dist/create-project-tJ1KwNss.mjs +1 -0
  61. package/dist/database-provider-DkZo4VwN.mjs +5 -0
  62. package/dist/database-provider.d.mts +25 -0
  63. package/dist/database-provider.mjs +1 -0
  64. package/dist/db-BH_md90k.mjs +1735 -0
  65. package/dist/delete-BSKI7V23.mjs +65 -0
  66. package/dist/deploy-C8KHBNsh.mjs +6512 -0
  67. package/dist/deploy-DCZBr7Ey.mjs +2 -0
  68. package/dist/deploy.d.mts +31 -0
  69. package/dist/deploy.mjs +118 -0
  70. package/dist/dev-inbox-I0nqTCdf.mjs +216 -0
  71. package/dist/discover-DJPmQcL5.mjs +36 -0
  72. package/dist/discover-EVuydEoM.mjs +1 -0
  73. package/dist/dist-B6eN80gc.mjs +1612 -0
  74. package/dist/dist-Cp4b1_T9.mjs +1 -0
  75. package/dist/dist-DMYe8CZJ.mjs +48 -0
  76. package/dist/dist-STQXl8ck.mjs +1878 -0
  77. package/dist/domain-C4ZhEiFG.mjs +149 -0
  78. package/dist/dotenv-4NdUCXbB.mjs +156 -0
  79. package/dist/drizzle-DqVFXtlc.mjs +306 -0
  80. package/dist/drizzle-Ds5P0n-S.mjs +1 -0
  81. package/dist/edge.d.mts +2 -0
  82. package/dist/edge.mjs +1 -0
  83. package/dist/email-B3TWga7x.mjs +742 -0
  84. package/dist/email-C_ATvNIG.mjs +2865 -0
  85. package/dist/email-cloudflare-DuAc9zny.mjs +854 -0
  86. package/dist/email-protocol-CZ0bAkI8.mjs +81 -0
  87. package/dist/env-CTAo8ifZ.mjs +73 -0
  88. package/dist/env-DUyTzroe.mjs +88 -0
  89. package/dist/env-Dl4Wggec.mjs +71 -0
  90. package/dist/env-helpers-BX0APszT.mjs +135 -0
  91. package/dist/env-helpers-U56xuFgL.d.mts +20 -0
  92. package/dist/env-mask-BsHxq3R8.mjs +46 -0
  93. package/dist/env-public-Cw_xPi1D.d.mts +119 -0
  94. package/dist/env-raw-Bo6TtrHU.mjs +41 -0
  95. package/dist/env-types-Bg-dTh8u.mjs +56 -0
  96. package/dist/env-validation-BufZConV.mjs +488 -0
  97. package/dist/env-validation-DPqDo4DU.mjs +1 -0
  98. package/dist/fetch-CBgyyhzm.d.mts +87 -0
  99. package/dist/fetch-error-DmlRM6e4.mjs +264 -0
  100. package/dist/fetch-stream-2GUN3YN1.mjs +102 -0
  101. package/dist/fetch-stream-bUXynOyZ.d.mts +32 -0
  102. package/dist/fetch-tpPiSK10.mjs +25 -0
  103. package/dist/gen-dc13IRXh.mjs +509 -0
  104. package/dist/gen-kQqhFyOP.mjs +1 -0
  105. package/dist/generate-BgtlYpKg.mjs +1 -0
  106. package/dist/generate-Da9mWKzU.mjs +80 -0
  107. package/dist/generated-wrangler-config-CoDaaFsA.mjs +17 -0
  108. package/dist/git-metadata-Cukp5kV5.mjs +82 -0
  109. package/dist/github-cmd-DT5Onu6E.mjs +690 -0
  110. package/dist/handler-CJ7DiiRF.mjs +161 -0
  111. package/dist/handler-CVsIfRv7.d.mts +279 -0
  112. package/dist/help-Bpv6Qeqn.mjs +1946 -0
  113. package/dist/help-CfZ4Bsw5.mjs +1 -0
  114. package/dist/inbound-CqubE-9T.d.mts +311 -0
  115. package/dist/inbound-lHugZPuK.mjs +509 -0
  116. package/dist/index.d.mts +64 -0
  117. package/dist/index.mjs +4163 -0
  118. package/dist/info-CLQoCenb.mjs +109 -0
  119. package/dist/init-DRUR0j8C.mjs +2486 -0
  120. package/dist/limits-CMmYT2l8.d.mts +16 -0
  121. package/dist/limits-D27Lp6FP.mjs +46 -0
  122. package/dist/link-DinwJnon.mjs +52 -0
  123. package/dist/list-B84t4BhW.mjs +130 -0
  124. package/dist/live-Dui0-aj_.d.mts +105 -0
  125. package/dist/live-saC8barp.mjs +410 -0
  126. package/dist/load-user-env-g0ahkZcj.mjs +34 -0
  127. package/dist/local-d1-C3EeOV7-.mjs +103 -0
  128. package/dist/log-JDnPc0cF.mjs +23 -0
  129. package/dist/login-Bl5lH8nH.mjs +87 -0
  130. package/dist/login-DoI7AsbY.mjs +1 -0
  131. package/dist/logs-CaT2N2f7.mjs +129 -0
  132. package/dist/migrate-CbGscX-V.mjs +125 -0
  133. package/dist/migrate-Ce3JKLVs.mjs +1 -0
  134. package/dist/migration-handler-22qiuWPq.mjs +469 -0
  135. package/dist/migration-handler-Bb2BJh6g.d.mts +38 -0
  136. package/dist/mime-BMUN_QKG.mjs +1004 -0
  137. package/dist/mysql-migration-sql-CNuBSqdx.mjs +239 -0
  138. package/dist/neon-CJzQSycr.mjs +52 -0
  139. package/dist/node-tfv-3v0V.mjs +64 -0
  140. package/dist/operator-ai-logging-Ay7M4KWw.mjs +121 -0
  141. package/dist/operator-args-BFg32YyY.mjs +722 -0
  142. package/dist/operator-auth-DdYZYEkO.mjs +47 -0
  143. package/dist/operator-client-DBujdELO.mjs +82 -0
  144. package/dist/operator-cmd-C73WWJBl.mjs +443 -0
  145. package/dist/operator-cmd-CdZytuAF.mjs +1 -0
  146. package/dist/output-Bb34lF0w.mjs +173 -0
  147. package/dist/output-CVolXKC1.mjs +1 -0
  148. package/dist/package-DO4d3Qz5.mjs +1444 -0
  149. package/dist/package-json-DvS6IFRv.mjs +43 -0
  150. package/dist/pg-DoyPxa_X.mjs +15 -0
  151. package/dist/picocolors-D1NxSLw-.mjs +71 -0
  152. package/dist/plan-BHNt1QhK.mjs +1 -0
  153. package/dist/plan-DX4_-OM5.mjs +58 -0
  154. package/dist/platform-args-NI_vfWvD.mjs +538 -0
  155. package/dist/platform-args-ZC1-A1N9.mjs +1 -0
  156. package/dist/platform-auth-config-d-lY5-aY.mjs +371 -0
  157. package/dist/platform-auth-protection-Dhw7lUCk.mjs +231 -0
  158. package/dist/platform-auth-recovery-DaCc0tlx.mjs +309 -0
  159. package/dist/platform-cmd-5Ry-C9im.mjs +193 -0
  160. package/dist/platform-cmd-5oZq91lI.mjs +1 -0
  161. package/dist/platform-discovery-Bxg9aZXU.mjs +40 -0
  162. package/dist/platform-domain-DLVdGvGG.mjs +256 -0
  163. package/dist/platform-lifecycle-CUgjipXO.mjs +1 -0
  164. package/dist/platform-lifecycle-fRt5VMls.mjs +8928 -0
  165. package/dist/platform-management-5hEsRfR2.mjs +1 -0
  166. package/dist/platform-management-Djh1hzLP.mjs +1607 -0
  167. package/dist/platform-plans-config-CkbUKFpm.mjs +447 -0
  168. package/dist/platform-recovery-Cghx7FCR.mjs +96 -0
  169. package/dist/platform-registry-x1m9HBxf.mjs +450 -0
  170. package/dist/platform-runtime-logs-kkoiYFpF.mjs +72 -0
  171. package/dist/platform-setup-SfwCwnZg.mjs +306 -0
  172. package/dist/prepare-B9mB47T5.mjs +84 -0
  173. package/dist/prepare-DNIq07so.mjs +13 -0
  174. package/dist/prepare-LHkyJqxi.mjs +1 -0
  175. package/dist/project-CC7eN00D.mjs +141 -0
  176. package/dist/project-DcSd4BeI.mjs +1 -0
  177. package/dist/project-cmd-DTF19-fC.mjs +109 -0
  178. package/dist/project-paths-iXHKRTTQ.mjs +159 -0
  179. package/dist/project-slug-BUy0lmyR.mjs +1 -0
  180. package/dist/project-slug-CO6ci9XG.mjs +7 -0
  181. package/dist/project-team-CvdLhDF2.mjs +129 -0
  182. package/dist/project-token-CwZdUEGu.mjs +70 -0
  183. package/dist/project-tsconfig-P9X952KG.mjs +98 -0
  184. package/dist/project-zero-trust-CKDoPdN1.mjs +64 -0
  185. package/dist/providers-Cd3c7wi0.mjs +64 -0
  186. package/dist/providers-Df69hb_X.d.mts +5 -0
  187. package/dist/provision-DGlFJ3T9.mjs +1 -0
  188. package/dist/provision-mYVLuQiy.mjs +1814 -0
  189. package/dist/queues-Bc3FsBQT.d.mts +5 -0
  190. package/dist/r2-conditions-DSLmkiR5.mjs +60 -0
  191. package/dist/requests-DNhfyF3l.mjs +52 -0
  192. package/dist/resolve-project-BCsAMDRA.mjs +47 -0
  193. package/dist/resolve-project-DhU9_lIo.mjs +1 -0
  194. package/dist/resource-name-DlJ9QXzg.mjs +10 -0
  195. package/dist/response-HmNjB30w.mjs +29 -0
  196. package/dist/rollback-BvCHol52.mjs +150 -0
  197. package/dist/rolldown-runtime-uD8oG6U2.mjs +24 -0
  198. package/dist/route-types-CRWhr93D.mjs +592 -0
  199. package/dist/route-url-BIDZT78M.mjs +58 -0
  200. package/dist/route-url-Bla3Upsy.d.mts +42 -0
  201. package/dist/routes-stub.d.mts +24 -0
  202. package/dist/routes-stub.mjs +1 -0
  203. package/dist/routing-assets-CSheDWWM.mjs +54 -0
  204. package/dist/rpc-DcByS_q0.d.mts +39 -0
  205. package/dist/rpc-DtxIN9Tv.mjs +19 -0
  206. package/dist/runner-CPerdjIl.mjs +163 -0
  207. package/dist/runner-CUNtS5x7.mjs +1 -0
  208. package/dist/runner-mysql-7aA5hGoM.mjs +145 -0
  209. package/dist/runner-mysql-DrMKw203.mjs +1 -0
  210. package/dist/runner-pg-2pjltt0t.mjs +1 -0
  211. package/dist/runner-pg-mYc75KfH.mjs +61 -0
  212. package/dist/runtime/ai.d.mts +50 -0
  213. package/dist/runtime/ai.mjs +455 -0
  214. package/dist/runtime/auth-client-react.d.mts +2 -0
  215. package/dist/runtime/auth-client-react.mjs +1 -0
  216. package/dist/runtime/auth-client.d.mts +2 -0
  217. package/dist/runtime/auth-client.mjs +1 -0
  218. package/dist/runtime/auth.d.mts +2 -0
  219. package/dist/runtime/auth.mjs +1 -0
  220. package/dist/runtime/better-auth-mysql.d.mts +5 -0
  221. package/dist/runtime/better-auth-mysql.mjs +21 -0
  222. package/dist/runtime/better-auth-pg.d.mts +5 -0
  223. package/dist/runtime/better-auth-pg.mjs +21 -0
  224. package/dist/runtime/better-auth.d.mts +6 -0
  225. package/dist/runtime/better-auth.mjs +22 -0
  226. package/dist/runtime/client-react.d.mts +5 -0
  227. package/dist/runtime/client-react.mjs +5 -0
  228. package/dist/runtime/client.d.mts +5 -0
  229. package/dist/runtime/client.mjs +5 -0
  230. package/dist/runtime/db-mysql.d.mts +2 -0
  231. package/dist/runtime/db-mysql.mjs +1 -0
  232. package/dist/runtime/db-pg.d.mts +2 -0
  233. package/dist/runtime/db-pg.mjs +1 -0
  234. package/dist/runtime/db.d.mts +17 -0
  235. package/dist/runtime/db.mjs +36 -0
  236. package/dist/runtime/drizzle-arktype.d.mts +1 -0
  237. package/dist/runtime/drizzle-arktype.mjs +2 -0
  238. package/dist/runtime/drizzle-valibot.d.mts +1 -0
  239. package/dist/runtime/drizzle-valibot.mjs +2 -0
  240. package/dist/runtime/drizzle-zod.d.mts +1 -0
  241. package/dist/runtime/drizzle-zod.mjs +2 -0
  242. package/dist/runtime/durable.d.mts +64 -0
  243. package/dist/runtime/durable.mjs +165 -0
  244. package/dist/runtime/email/testing.d.mts +108 -0
  245. package/dist/runtime/email/testing.mjs +268 -0
  246. package/dist/runtime/email-protocol.d.mts +25 -0
  247. package/dist/runtime/email-protocol.mjs +1 -0
  248. package/dist/runtime/email.d.mts +26 -0
  249. package/dist/runtime/email.mjs +524 -0
  250. package/dist/runtime/env-public-client.d.mts +19 -0
  251. package/dist/runtime/env-public-client.mjs +55 -0
  252. package/dist/runtime/env-public.d.mts +4 -0
  253. package/dist/runtime/env-public.mjs +277 -0
  254. package/dist/runtime/env.d.mts +12 -0
  255. package/dist/runtime/env.mjs +1 -0
  256. package/dist/runtime/fetch-server.d.mts +6 -0
  257. package/dist/runtime/fetch-server.mjs +29 -0
  258. package/dist/runtime/fetch-stream.d.mts +3 -0
  259. package/dist/runtime/fetch-stream.mjs +3 -0
  260. package/dist/runtime/fetch.d.mts +2 -0
  261. package/dist/runtime/fetch.mjs +3 -0
  262. package/dist/runtime/handler.d.mts +3 -0
  263. package/dist/runtime/handler.mjs +1 -0
  264. package/dist/runtime/kv.d.mts +45 -0
  265. package/dist/runtime/kv.mjs +103 -0
  266. package/dist/runtime/limits.d.mts +2 -0
  267. package/dist/runtime/limits.mjs +1 -0
  268. package/dist/runtime/live-client.d.mts +40 -0
  269. package/dist/runtime/live-client.mjs +282 -0
  270. package/dist/runtime/live-server.d.mts +11 -0
  271. package/dist/runtime/live-server.mjs +419 -0
  272. package/dist/runtime/live.d.mts +3 -0
  273. package/dist/runtime/live.mjs +1 -0
  274. package/dist/runtime/log.d.mts +24 -0
  275. package/dist/runtime/log.mjs +57 -0
  276. package/dist/runtime/migration-handler-mysql.d.mts +2 -0
  277. package/dist/runtime/migration-handler-mysql.mjs +111 -0
  278. package/dist/runtime/migration-handler-pg.d.mts +2 -0
  279. package/dist/runtime/migration-handler-pg.mjs +94 -0
  280. package/dist/runtime/migration-handler.d.mts +2 -0
  281. package/dist/runtime/migration-handler.mjs +1 -0
  282. package/dist/runtime/procedure.d.mts +27 -0
  283. package/dist/runtime/procedure.mjs +36 -0
  284. package/dist/runtime/procedures.d.mts +24 -0
  285. package/dist/runtime/procedures.mjs +56 -0
  286. package/dist/runtime/queues.d.mts +2 -0
  287. package/dist/runtime/queues.mjs +8 -0
  288. package/dist/runtime/remote/binding-handler.d.mts +11 -0
  289. package/dist/runtime/remote/binding-handler.mjs +227 -0
  290. package/dist/runtime/remote/index.d.mts +12 -0
  291. package/dist/runtime/remote/index.mjs +467 -0
  292. package/dist/runtime/response.d.mts +11 -0
  293. package/dist/runtime/response.mjs +1 -0
  294. package/dist/runtime/route-url.d.mts +2 -0
  295. package/dist/runtime/route-url.mjs +1 -0
  296. package/dist/runtime/routing.d.mts +53 -0
  297. package/dist/runtime/routing.mjs +425 -0
  298. package/dist/runtime/rpc-react.d.mts +16 -0
  299. package/dist/runtime/rpc-react.mjs +50 -0
  300. package/dist/runtime/rpc.d.mts +2 -0
  301. package/dist/runtime/rpc.mjs +1 -0
  302. package/dist/runtime/sandbox-container.d.mts +3 -0
  303. package/dist/runtime/sandbox-container.mjs +1 -0
  304. package/dist/runtime/sandbox.d.mts +5 -0
  305. package/dist/runtime/sandbox.mjs +196 -0
  306. package/dist/runtime/schema-d1.d.mts +1 -0
  307. package/dist/runtime/schema-d1.mjs +2 -0
  308. package/dist/runtime/schema-mysql.d.mts +1 -0
  309. package/dist/runtime/schema-mysql.mjs +2 -0
  310. package/dist/runtime/schema-pg.d.mts +1 -0
  311. package/dist/runtime/schema-pg.mjs +2 -0
  312. package/dist/runtime/seed.d.mts +34 -0
  313. package/dist/runtime/seed.mjs +5 -0
  314. package/dist/runtime/sse-client.d.mts +31 -0
  315. package/dist/runtime/sse-client.mjs +42 -0
  316. package/dist/runtime/sse.d.mts +32 -0
  317. package/dist/runtime/sse.mjs +1 -0
  318. package/dist/runtime/storage.d.mts +4 -0
  319. package/dist/runtime/storage.mjs +13 -0
  320. package/dist/runtime/validator.d.mts +2 -0
  321. package/dist/runtime/validator.mjs +1 -0
  322. package/dist/runtime/ws-server.d.mts +26 -0
  323. package/dist/runtime/ws-server.mjs +297 -0
  324. package/dist/runtime/ws.d.mts +2 -0
  325. package/dist/runtime/ws.mjs +108 -0
  326. package/dist/sandbox-CWDjoEG2.d.mts +50 -0
  327. package/dist/sandbox-container-BqamdFCx.d.mts +73 -0
  328. package/dist/sandbox-container-d1AHLpgn.mjs +291 -0
  329. package/dist/secret-DCF9RXTc.mjs +146 -0
  330. package/dist/skills-Dr3AjuBF.mjs +63 -0
  331. package/dist/sqlite-validation-CLJXXN93.mjs +24 -0
  332. package/dist/sse-CxR30yMF.mjs +174 -0
  333. package/dist/standard-schema-CuDawHOC.d.mts +40 -0
  334. package/dist/static-asset-marker-mWMX2dLa.mjs +38 -0
  335. package/dist/subcommand-prompt-B9yUo--u.mjs +370 -0
  336. package/dist/terminal-log-text-DNsWJREL.mjs +31 -0
  337. package/dist/types-D7-4tBu7.d.mts +1 -0
  338. package/dist/untrusted-env-lL7RkYiC.mjs +50 -0
  339. package/dist/validate-B-zsjhiz.mjs +162 -0
  340. package/dist/validate-DbqGdPPY.mjs +1 -0
  341. package/dist/validator-8-NZs2Xr.mjs +168 -0
  342. package/dist/version-metadata-DsSoNsKJ.mjs +23 -0
  343. package/dist/wrangler-DU784Dkf.mjs +1452 -0
  344. package/dist/wrangler-Rr9_76DQ.mjs +1 -0
  345. package/dist/ws-Q_osq9VK.d.mts +137 -0
  346. package/dist/yarn-pnp-DgWbE7z5.mjs +91 -0
  347. package/docs/guide/ai.md +273 -0
  348. package/docs/guide/app-types.md +101 -0
  349. package/docs/guide/auth.md +255 -0
  350. package/docs/guide/database/d1.md +86 -0
  351. package/docs/guide/database/mysql.md +72 -0
  352. package/docs/guide/database/postgresql.md +94 -0
  353. package/docs/guide/database.md +454 -0
  354. package/docs/guide/deployment.md +124 -0
  355. package/docs/guide/durable-state.md +192 -0
  356. package/docs/guide/edge/headers.md +47 -0
  357. package/docs/guide/edge/redirects.md +85 -0
  358. package/docs/guide/edge/rewrites.md +119 -0
  359. package/docs/guide/edge/static-assets.md +94 -0
  360. package/docs/guide/email/domains.md +119 -0
  361. package/docs/guide/email/receiving.md +142 -0
  362. package/docs/guide/email/sending.md +262 -0
  363. package/docs/guide/email.md +23 -0
  364. package/docs/guide/env-vars.md +115 -0
  365. package/docs/guide/index.md +37 -0
  366. package/docs/guide/jobs.md +80 -0
  367. package/docs/guide/kv.md +100 -0
  368. package/docs/guide/live.md +181 -0
  369. package/docs/guide/platform/administration/access.md +165 -0
  370. package/docs/guide/platform/administration/connected-apps.md +84 -0
  371. package/docs/guide/platform/administration/email.md +169 -0
  372. package/docs/guide/platform/administration/operations.md +100 -0
  373. package/docs/guide/platform/administration/plans.md +156 -0
  374. package/docs/guide/platform/administration/projects.md +74 -0
  375. package/docs/guide/platform/administration/zero-trust.md +205 -0
  376. package/docs/guide/platform/development/local.md +122 -0
  377. package/docs/guide/platform/development/runtime.md +115 -0
  378. package/docs/guide/platform/development/schema-ci.md +44 -0
  379. package/docs/guide/platform/installation/ci.md +62 -0
  380. package/docs/guide/platform/installation/credentials.md +140 -0
  381. package/docs/guide/platform/installation/domains.md +120 -0
  382. package/docs/guide/platform/installation/first-deployment.md +95 -0
  383. package/docs/guide/platform/installation/maintenance.md +250 -0
  384. package/docs/guide/platform/installation/prerequisites.md +176 -0
  385. package/docs/guide/platform/installation/setup.md +300 -0
  386. package/docs/guide/platform/installation/uninstall.md +110 -0
  387. package/docs/guide/platform-administration.md +19 -0
  388. package/docs/guide/platform-development.md +16 -0
  389. package/docs/guide/procedures.md +48 -0
  390. package/docs/guide/project-collaboration.md +99 -0
  391. package/docs/guide/queues.md +149 -0
  392. package/docs/guide/quickstart.md +129 -0
  393. package/docs/guide/remote-dev.md +67 -0
  394. package/docs/guide/sandboxes.md +134 -0
  395. package/docs/guide/self-hosted-platform.md +45 -0
  396. package/docs/guide/server-routing.md +283 -0
  397. package/docs/guide/sse.md +174 -0
  398. package/docs/guide/storage.md +82 -0
  399. package/docs/guide/testing.md +64 -0
  400. package/docs/guide/type-safety.md +270 -0
  401. package/docs/guide/typed-fetch.md +98 -0
  402. package/docs/guide/websockets.md +230 -0
  403. package/docs/index.md +102 -0
  404. package/docs/integrations/agents.md +38 -0
  405. package/docs/integrations/cloudflare.md +241 -0
  406. package/docs/integrations/hono.md +127 -0
  407. package/docs/reference/api/auth.md +195 -0
  408. package/docs/reference/api/client.md +90 -0
  409. package/docs/reference/api/database.md +118 -0
  410. package/docs/reference/api/deploy.md +63 -0
  411. package/docs/reference/api/durable.md +47 -0
  412. package/docs/reference/api/env.md +51 -0
  413. package/docs/reference/api/handlers.md +189 -0
  414. package/docs/reference/api/plugin.md +40 -0
  415. package/docs/reference/api/resources.md +116 -0
  416. package/docs/reference/api/rewrites.md +111 -0
  417. package/docs/reference/api/types.md +126 -0
  418. package/docs/reference/api.md +71 -0
  419. package/docs/reference/cli/auth.md +87 -0
  420. package/docs/reference/cli/database.md +159 -0
  421. package/docs/reference/cli/deploy.md +117 -0
  422. package/docs/reference/cli/domains.md +42 -0
  423. package/docs/reference/cli/email.md +145 -0
  424. package/docs/reference/cli/generate.md +113 -0
  425. package/docs/reference/cli/github.md +181 -0
  426. package/docs/reference/cli/platform-config.md +93 -0
  427. package/docs/reference/cli/platform-email.md +81 -0
  428. package/docs/reference/cli/platform-installation.md +166 -0
  429. package/docs/reference/cli/platform-operations.md +90 -0
  430. package/docs/reference/cli/platform-users.md +159 -0
  431. package/docs/reference/cli/platform-zero-trust.md +60 -0
  432. package/docs/reference/cli/platform.md +78 -0
  433. package/docs/reference/cli/project.md +208 -0
  434. package/docs/reference/cli/secrets.md +79 -0
  435. package/docs/reference/cli/setup.md +88 -0
  436. package/docs/reference/cli.md +115 -0
  437. package/docs/reference/config.md +478 -0
  438. package/docs/reference/resource-inference.md +72 -0
  439. package/docs/reference/structure.md +138 -0
  440. package/package.json +389 -3
  441. package/sandbox.Dockerfile +4 -0
  442. package/schema.json +353 -0
  443. package/skills/bwf/SKILL.md +100 -0
  444. package/skills/migrate-vite-cloudflare-to-bwf/SKILL.md +53 -0
  445. package/templates/assets/bwf.svg +5 -0
  446. package/templates/assets/icons.svg +49 -0
  447. package/templates/assets/react.svg +1 -0
  448. package/templates/assets/stack.svg +35 -0
@@ -0,0 +1,2486 @@
1
+ import { A as confirm, K as select, L as log, O as cancel, X as text, tt as isCancel } from "./dist-STQXl8ck.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 { i as materializeCloudflareConfig, l as ensureGitignoreLines } from "./cloudflare-config-i8yanry0.mjs";
4
+ import { n as ensureProjectTsconfig, t as createProjectTsconfig } from "./project-tsconfig-P9X952KG.mjs";
5
+ import { n as readProjectPaths } from "./project-paths-iXHKRTTQ.mjs";
6
+ import { A as writeProvisionedWranglerConfig, F as writeBwfProjectConfig, N as canRewriteBwfProjectConfig, P as renderBwfConfig } from "./wrangler-DU784Dkf.mjs";
7
+ import { c as getDatabaseCasing, f as readConfig, l as getDatabaseDialect, s as databaseConfigValue } from "./config-tNx0HlFv.mjs";
8
+ import { r as writeDrizzleConfig, t as PLACEHOLDER_DB_URL } from "./config-DOaFIK3w.mjs";
9
+ import { n as snapshotDrizzleOutputs } from "./generate-Da9mWKzU.mjs";
10
+ import { i as readPackageJson, n as hasPackageDependency } from "./package-json-DvS6IFRv.mjs";
11
+ import { n as getOwnVersion, r as getPackageDir, t as detectAgents } from "./agents-BLiMq9E1.mjs";
12
+ import { t as connectCloudflare } from "./cloudflare-connect-x7IsYghw.mjs";
13
+ import { c as getToken } from "./auth-xnkmpZUl.mjs";
14
+ import { r as PlatformClient } from "./client-D3D5RM5h.mjs";
15
+ import { a as promptProjectSelection, r as promptAndCreateProject } from "./create-project-B35ux-LA.mjs";
16
+ import { t as promptForLoginToken } from "./login-Bl5lH8nH.mjs";
17
+ import { l as writeProjectConfig, n as readDeploymentPlatform, r as readProjectConfig, s as writeDeploymentPlatform, t as attachSelectedPlatform } from "./project-CC7eN00D.mjs";
18
+ import { t as parseDotenvFile } from "./dotenv-4NdUCXbB.mjs";
19
+ import { t as migrateLegacyBwfConfig } from "./migrate-CbGscX-V.mjs";
20
+ import { l as formatUrl, m as printSuccess, p as note } from "./output-Bb34lF0w.mjs";
21
+ import { i as saveDiscoveredPlatform, t as discoverPlatform } from "./platform-cmd-5Ry-C9im.mjs";
22
+ import { o as formatProjectCommand } from "./cloudflare-process-Cc6oiJqk.mjs";
23
+ import { t as MagicString } from "./dist-B6eN80gc.mjs";
24
+ import { i as hasLocalLockfile, n as drizzleKitBin, r as findInstalledYarnPnpRuntime, t as buildDrizzleKitSpawnEnv } from "./yarn-pnp-DgWbE7z5.mjs";
25
+ import { createRequire } from "node:module";
26
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
27
+ import { parseSync } from "vite";
28
+ import { isRecord } from "@builtbyfriends/deploy-core";
29
+ import { parseArgs } from "node:util";
30
+ import { parse } from "jsonc-parser";
31
+ import { spawnSync } from "node:child_process";
32
+ import { parseDocument } from "yaml";
33
+ // src/cli/deploy-setup.ts
34
+ async function maybeSetupDeployProject(root) {
35
+ const existing = readProjectConfig(root);
36
+ if (existing) {
37
+ log.info(`Project already linked: ${existing.slug}`);
38
+ return existing;
39
+ }
40
+ const existingToken = getToken(root);
41
+ const shouldSetup = await confirm({ message: existingToken ? "Link your bwf project now?" : "Log in now and link or create a bwf project?" });
42
+ if (isCancel(shouldSetup)) {
43
+ cancel("Setup cancelled.");
44
+ process.exit(0);
45
+ }
46
+ if (!shouldSetup) return null;
47
+ let token = existingToken;
48
+ if (!token) {
49
+ token = await promptForLoginToken(root);
50
+ log.step("Token saved.");
51
+ }
52
+ const client = new PlatformClient(token, { root });
53
+ const projects = await client.listProjects();
54
+ if (projects.length === 0) return promptAndCreateProject(root, client);
55
+ const result = await promptProjectSelection(projects, "Select a project to link:", root, { confirmExisting: true });
56
+ if (result.action === "select") {
57
+ const config = {
58
+ projectId: result.project.id,
59
+ slug: result.project.slug
60
+ };
61
+ writeProjectConfig(root, attachSelectedPlatform(config, client.apiUrl));
62
+ log.step(`Linked project: ${config.slug}`);
63
+ return config;
64
+ }
65
+ return promptAndCreateProject(root, client);
66
+ }
67
+ // src/cli/env-scaffold.ts
68
+ /**
69
+ * `bwf init` hook — when the project has no `env.ts` but has dotenv files
70
+ * on disk, scaffold an `env.ts` whose keys mirror what the user already
71
+ * has. Inference is intentionally permissive: we only upgrade from the
72
+ * default `string()` helper when the value is unambiguously a boolean,
73
+ * URL, or small integer. Everything else stays a string and carries a
74
+ * one-line banner nudging the user to tighten the schema.
75
+ *
76
+ * This is a best-effort DX sweetener, not a correctness boundary — a
77
+ * wrong guess only costs the user a single-line edit.
78
+ */
79
+ const BOOLEAN_LITERAL = /^(true|false)$/i;
80
+ const HTTP_URL = /^https?:\/\/\S+$/;
81
+ const SMALL_INTEGER = /^(?:0|[1-9]\d{0,4})$/;
82
+ /**
83
+ * Classify a single `.env` value into the bwf built-in helper to use.
84
+ * Returns `'string'` whenever inference is ambiguous — the comment in the
85
+ * scaffolded file asks the user to tighten any wrong guesses.
86
+ */
87
+ function inferHelperForValue(value) {
88
+ if (!value) return "string";
89
+ const trimmed = value.trim();
90
+ if (!trimmed) return "string";
91
+ if (BOOLEAN_LITERAL.test(trimmed)) return "boolean";
92
+ if (HTTP_URL.test(trimmed)) return "url";
93
+ if (SMALL_INTEGER.test(trimmed)) return "number";
94
+ return "string";
95
+ }
96
+ /** Collect the inferred entries from the local `.env`, sorted by key. */
97
+ function collectInferredEntries(root) {
98
+ const values = parseDotenvFile(join(root, ".env"));
99
+ return Object.keys(values).sort((a, b) => a.localeCompare(b)).map((key) => ({
100
+ key,
101
+ helper: inferHelperForValue(values[key])
102
+ }));
103
+ }
104
+ /**
105
+ * Render the scaffolded `env.ts` body. The imports are pulled in lazily
106
+ * so only helpers we reference appear in the import statement.
107
+ */
108
+ function renderEnvTs(entries) {
109
+ if (entries.length === 0) return [
110
+ `import { defineEnv } from '@builtbyfriends/bwf/env';`,
111
+ ``,
112
+ `// Define your environment variables here. See https://void.cloud/guide/env-vars`,
113
+ `export default defineEnv({});`,
114
+ ``
115
+ ].join("\n");
116
+ const helpers = /* @__PURE__ */ new Set(["string"]);
117
+ for (const e of entries) helpers.add(e.helper);
118
+ const importList = [
119
+ "string",
120
+ "number",
121
+ "boolean",
122
+ "url"
123
+ ].filter((h) => helpers.has(h));
124
+ const lines = [];
125
+ lines.push(`import { defineEnv, ${importList.join(", ")} } from '@builtbyfriends/bwf/env';`);
126
+ lines.push("");
127
+ lines.push(`// Scaffolded from .env. Inference is conservative — review each`);
128
+ lines.push(`// entry and tighten types as needed (e.g. oneOf([...]), url(), .optional(),`);
129
+ lines.push(`// .default(value), or a Standard Schema validator from valibot/zod/arktype).`);
130
+ lines.push(`export default defineEnv({`);
131
+ for (const entry of entries) lines.push(` ${entry.key}: ${entry.helper}(),`);
132
+ lines.push(`});`);
133
+ lines.push("");
134
+ return lines.join("\n");
135
+ }
136
+ /**
137
+ * If the project has no `env.ts`, scaffold one based on the local `.env`
138
+ * user already has. Safe to call unconditionally during `bwf init` — it
139
+ * no-ops when `env.ts` is present. Never overwrites an existing file.
140
+ */
141
+ function maybeScaffoldEnvTs(root) {
142
+ for (const dir of ["", "src/"]) for (const ext of [
143
+ "ts",
144
+ "mts",
145
+ "js",
146
+ "mjs"
147
+ ]) if (existsSync(join(root, `${dir}env.${ext}`))) return {
148
+ written: null,
149
+ skipReason: "env-ts-exists",
150
+ entries: []
151
+ };
152
+ if (!existsSync(join(root, ".env"))) return {
153
+ written: null,
154
+ skipReason: "no-dotenv-files",
155
+ entries: []
156
+ };
157
+ const entries = collectInferredEntries(root);
158
+ const target = join(root, "env.ts");
159
+ writeFileSync(target, renderEnvTs(entries));
160
+ return {
161
+ written: target,
162
+ entries
163
+ };
164
+ }
165
+ // src/cli/init-git.ts
166
+ async function setupGit(root, git) {
167
+ if (git === false) return false;
168
+ let directory = resolve(root);
169
+ while (true) {
170
+ if (existsSync(join(directory, ".git"))) return false;
171
+ const parent = dirname(directory);
172
+ if (parent === directory) break;
173
+ directory = parent;
174
+ }
175
+ if (git === void 0) {
176
+ if (process.env.CI || !process.stdin.isTTY) return false;
177
+ const selected = await confirm({
178
+ message: "Initialize a git repository?",
179
+ initialValue: true
180
+ });
181
+ if (isCancel(selected)) {
182
+ cancel("Setup cancelled.");
183
+ process.exit(0);
184
+ }
185
+ if (!selected) return false;
186
+ }
187
+ const result = spawnSync("git", ["init"], {
188
+ cwd: root,
189
+ encoding: "utf-8",
190
+ stdio: [
191
+ "ignore",
192
+ "pipe",
193
+ "pipe"
194
+ ]
195
+ });
196
+ if (result.status !== 0) {
197
+ log.warn("Failed to initialize git repository");
198
+ const detail = result.stderr?.trim() || result.error?.message;
199
+ if (detail) log.info(detail);
200
+ return false;
201
+ }
202
+ return true;
203
+ }
204
+ function initialCommitCommand(root) {
205
+ const directory = resolve(root);
206
+ const argument = /^[A-Za-z0-9_@./:-]+$/.test(directory) ? directory : process.platform === "win32" ? `"${directory}"` : `'${directory.replaceAll("'", "'\\''")}'`;
207
+ const git = directory === resolve(process.cwd()) ? "git" : `git -C ${argument}`;
208
+ return `${git} add -A && ${git} commit -m "chore: initial commit"`;
209
+ }
210
+ // src/cli/starter-ui.css?raw
211
+ var starter_ui_default = ":root {\n --text: rgb(22 23 29 / 70%);\n --text-h: #16171d;\n --bg: #fff;\n --border: #e5e4e7;\n --code-bg: #f2f1f4;\n --accent: #6c3bff;\n --error: #b42318;\n --social-bg: #f2f1f4;\n --radius-inner: 4px;\n --radius-element: 6px;\n --shadow: rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;\n\n --sans: system-ui, 'Segoe UI', Roboto, sans-serif;\n --heading: system-ui, 'Segoe UI', Roboto, sans-serif;\n --mono: ui-monospace, Consolas, monospace;\n\n font: 18px/145% var(--sans);\n letter-spacing: 0.18px;\n color-scheme: light dark;\n color: var(--text);\n background: var(--bg);\n font-synthesis: none;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n\n @media (max-width: 1024px) {\n font-size: 16px;\n }\n}\n\n@supports (corner-shape: squircle) {\n :root {\n /* Squircle curves need about twice the radius to read as rounded. */\n --radius-inner: 8px;\n --radius-element: 12px;\n }\n\n :where(.starter, .starter *),\n .starter *::before,\n .starter *::after {\n corner-shape: squircle;\n }\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n --text: rgb(255 255 255 / 70%);\n --text-h: #fff;\n --bg: #16171d;\n --border: #3b3440;\n --code-bg: #3b3440;\n --accent: #b39aff;\n --error: #fda29b;\n --social-bg: #3b3440;\n --shadow: rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;\n }\n}\n\n.starter {\n width: 1126px;\n max-width: 100%;\n margin: 0 auto;\n text-align: center;\n border-inline: 1px solid var(--border);\n min-height: 100svh;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n}\n\nh1,\nh2 {\n font-family: var(--heading);\n font-weight: 500;\n color: var(--text-h);\n}\n\nh1 {\n font-size: 56px;\n letter-spacing: -1.68px;\n margin: 32px 0;\n @media (max-width: 1024px) {\n font-size: 36px;\n margin: 20px 0;\n }\n}\nh2 {\n font-size: 24px;\n line-height: 118%;\n letter-spacing: -0.24px;\n margin: 0 0 8px;\n @media (max-width: 1024px) {\n font-size: 20px;\n }\n}\np {\n margin: 0;\n}\n\ncode {\n font-family: var(--mono);\n display: inline-flex;\n border-radius: var(--radius-inner);\n color: var(--text-h);\n font-size: 15px;\n line-height: 135%;\n padding: 4px 8px;\n background: var(--code-bg);\n}\n\n.hero {\n position: relative;\n\n .base,\n .framework,\n .bwf {\n inset-inline: 0;\n margin: 0 auto;\n }\n\n .base {\n width: 170px;\n position: relative;\n z-index: 0;\n }\n\n .framework,\n .bwf {\n position: absolute;\n }\n\n .framework {\n z-index: 1;\n top: 34px;\n height: 28px;\n transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) scale(1.4);\n }\n\n .bwf {\n z-index: 0;\n top: 107px;\n height: 22px;\n width: auto;\n transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) scale(0.8);\n }\n}\n\n#center {\n display: flex;\n flex-direction: column;\n gap: 25px;\n padding-bottom: 24px;\n place-content: center;\n place-items: center;\n flex-grow: 1;\n\n @media (max-width: 1024px) {\n padding: 32px 20px 24px;\n gap: 18px;\n }\n}\n\n.starter-intro {\n width: min(720px, 100%);\n padding-inline: 20px;\n box-sizing: border-box;\n\n a {\n color: var(--accent);\n }\n\n @media (max-width: 1024px) {\n padding-inline: 0;\n }\n}\n\n.starter-description {\n display: grid;\n gap: 12px;\n\n > p:nth-child(2) {\n text-wrap: balance;\n }\n}\n\n.starter-demo {\n border-top: 1px solid var(--border);\n padding: 32px;\n text-align: left;\n\n @media (max-width: 1024px) {\n padding: 24px 20px;\n }\n}\n\n.demo-content {\n max-width: 640px;\n margin: 0 auto;\n display: grid;\n gap: 24px;\n\n h2 {\n margin: 0;\n }\n}\n\n.messages {\n list-style: none;\n margin: 0;\n padding: 0;\n display: grid;\n gap: 12px;\n\n li {\n padding: 12px 16px;\n border: 1px solid var(--border);\n border-radius: var(--radius-element);\n overflow-wrap: anywhere;\n }\n\n strong {\n display: block;\n color: var(--text-h);\n font-weight: 500;\n }\n\n small {\n font-size: 14px;\n }\n}\n\n.message-form {\n display: grid;\n gap: 12px;\n\n label {\n color: var(--text-h);\n }\n\n input,\n button {\n font: inherit;\n color: var(--text-h);\n background: var(--social-bg);\n border: 1px solid var(--border);\n border-radius: var(--radius-element);\n padding: 10px 12px;\n\n &:focus-visible {\n outline: 2px solid var(--accent);\n outline-offset: 2px;\n }\n }\n\n input {\n flex: 1;\n min-width: 0;\n }\n\n button {\n cursor: pointer;\n\n &:hover {\n border-color: var(--accent);\n }\n\n &:disabled {\n cursor: wait;\n opacity: 0.6;\n }\n }\n}\n\n.message-fields {\n display: flex;\n gap: 8px;\n\n @media (max-width: 480px) {\n flex-direction: column;\n }\n}\n\n.message-form [data-nosam-form-error] {\n color: var(--error);\n font-size: 14px;\n}\n\n#next-steps {\n display: flex;\n border-top: 1px solid var(--border);\n text-align: left;\n\n & > div {\n flex: 1 1 0;\n padding: 32px;\n @media (max-width: 1024px) {\n padding: 24px 20px;\n }\n }\n\n .icon {\n color: var(--accent);\n margin-bottom: 16px;\n width: 22px;\n height: 22px;\n }\n\n @media (max-width: 1024px) {\n flex-direction: column;\n text-align: center;\n }\n}\n\n#docs {\n border-right: 1px solid var(--border);\n\n @media (max-width: 1024px) {\n border-right: none;\n border-bottom: 1px solid var(--border);\n }\n}\n\n#next-steps ul {\n list-style: none;\n padding: 0;\n display: flex;\n gap: 8px;\n margin: 32px 0 0;\n\n a {\n color: var(--text-h);\n font-size: 16px;\n border-radius: var(--radius-element);\n background: var(--social-bg);\n display: flex;\n padding: 6px 12px;\n align-items: center;\n gap: 8px;\n text-decoration: none;\n transition: box-shadow 0.3s;\n\n &:hover {\n box-shadow: var(--shadow);\n }\n .button-icon {\n height: 18px;\n width: 18px;\n }\n }\n\n @media (max-width: 1024px) {\n margin-top: 20px;\n flex-wrap: wrap;\n justify-content: center;\n\n li {\n flex: 1 1 calc(50% - 8px);\n }\n\n a {\n width: 100%;\n justify-content: center;\n box-sizing: border-box;\n }\n }\n}\n\n#spacer {\n height: 88px;\n border-top: 1px solid var(--border);\n @media (max-width: 1024px) {\n height: 48px;\n }\n}\n\n.ticks {\n position: relative;\n width: 100%;\n\n &::before,\n &::after {\n content: '';\n position: absolute;\n top: -4.5px;\n border: 5px solid transparent;\n }\n\n &::before {\n left: 0;\n border-left-color: var(--border);\n }\n &::after {\n right: 0;\n border-right-color: var(--border);\n }\n}\n";
212
+ // src/cli/template.ts
213
+ const SCAFFOLD_GITIGNORE_LINES = [
214
+ "node_modules",
215
+ "dist",
216
+ ".bwf",
217
+ ".wrangler",
218
+ ".cloudflare",
219
+ ".bwf-wrangler.jsonc",
220
+ ".env",
221
+ ".env.*",
222
+ "*.tsbuildinfo",
223
+ ".DS_Store"
224
+ ];
225
+ const SCAFFOLD_BASE_DEPENDENCIES = { hono: "^4.11.9" };
226
+ const SCAFFOLD_BASE_DEV_DEPENDENCIES = {
227
+ vite: "^8.0.10",
228
+ typescript: "^7.0.2"
229
+ };
230
+ const SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES = {
231
+ vite: "npm:@voidzero-dev/vite-plus-core@^1.6.0",
232
+ "vite-plus": "^1.6.0"
233
+ };
234
+ const SCAFFOLD_TOOLCHAIN_OPTIONS = [{
235
+ value: "vite-plus",
236
+ label: "Vite+",
237
+ hint: "Uses the Vite+ toolchain and vp commands."
238
+ }, {
239
+ value: "vite",
240
+ label: "Vite",
241
+ hint: "Uses plain Vite commands without Vite+."
242
+ }];
243
+ const SCAFFOLD_FRAMEWORK_OPTIONS = [{
244
+ value: "react",
245
+ label: "React",
246
+ hint: "React single-page app with an optional backend."
247
+ }];
248
+ const SCAFFOLD_FRAMEWORKS = { react: {
249
+ label: "React",
250
+ docsUrl: "https://react.dev/",
251
+ detectPackage: "react",
252
+ dependencies: {
253
+ react: "^19.2.4",
254
+ "react-dom": "^19.2.4"
255
+ },
256
+ devDependencies: {
257
+ "@vitejs/plugin-react": "^6.3.0",
258
+ "@types/react": "^19.2.14",
259
+ "@types/react-dom": "^19.2.3"
260
+ },
261
+ tsconfigCompilerOptions: { jsx: "react-jsx" }
262
+ } };
263
+ function detectScaffoldFrameworkFromDependencies(deps) {
264
+ for (const [framework, config] of Object.entries(SCAFFOLD_FRAMEWORKS)) if (config.detectPackage in deps) return framework;
265
+ }
266
+ function getScaffoldTsconfigCompilerOptions(framework) {
267
+ return framework ? { ...SCAFFOLD_FRAMEWORKS[framework].tsconfigCompilerOptions } : {};
268
+ }
269
+ function createSpaStarterTemplate(options) {
270
+ const { framework, starterMode, toolchain = "vite", bwfPackageSpec } = options;
271
+ const config = SCAFFOLD_FRAMEWORKS[framework];
272
+ const assets = join(getPackageDir(), "templates", "assets");
273
+ const files = {
274
+ "bwf.config.ts": renderBwfConfig({ routing: { typedRoutes: true } }, "// Generated by bwf init."),
275
+ "vite.config.ts": getViteConfig(),
276
+ "index.html": getIndexHtml(),
277
+ "src/main.tsx": getMain(),
278
+ "src/App.tsx": getApp(framework, starterMode),
279
+ "src/style.css": starter_ui_default,
280
+ "src/vite-env.d.ts": "/// <reference types=\"vite/client\" />\n",
281
+ "public/stack.svg": readFileSync(join(assets, "stack.svg"), "utf8"),
282
+ "public/bwf.svg": readFileSync(join(assets, "bwf.svg"), "utf8"),
283
+ [`public/${framework}.svg`]: readFileSync(join(assets, `${framework}.svg`), "utf8"),
284
+ "public/icons.svg": readFileSync(join(assets, "icons.svg"), "utf8")
285
+ };
286
+ if (starterMode !== "spa") {
287
+ files["routes/api/messages.ts"] = getMessagesRoute();
288
+ files["routes/api/hello.ts"] = getHelloRoute(config.label, starterMode);
289
+ files["db/schema.ts"] = getSchemaFile(starterMode);
290
+ files["db/seed.ts"] = getSeedFile();
291
+ }
292
+ return {
293
+ scripts: {
294
+ dev: toolchain === "vite-plus" ? "vp dev" : "vite",
295
+ build: toolchain === "vite-plus" ? "vp build" : "vite build",
296
+ preview: toolchain === "vite-plus" ? "vp preview" : "vite preview",
297
+ postinstall: "bwf prepare"
298
+ },
299
+ dependencies: {
300
+ ...SCAFFOLD_BASE_DEPENDENCIES,
301
+ ...config.dependencies,
302
+ ...starterMode !== "spa" ? { zod: "^4.6.7" } : {}
303
+ },
304
+ devDependencies: {
305
+ "@builtbyfriends/bwf": bwfPackageSpec,
306
+ ...SCAFFOLD_BASE_DEV_DEPENDENCIES,
307
+ ...toolchain === "vite-plus" ? SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES : {},
308
+ ...config.devDependencies
309
+ },
310
+ files
311
+ };
312
+ }
313
+ function getViteConfig() {
314
+ return `import react from "@vitejs/plugin-react";
315
+ import { defineConfig } from "vite";
316
+ import { bwfPlugin } from "@builtbyfriends/bwf";
317
+
318
+ export default defineConfig({
319
+ plugins: [react(), bwfPlugin()],
320
+ });
321
+ `;
322
+ }
323
+ function getIndexHtml() {
324
+ return `<!doctype html>
325
+ <html lang="en">
326
+ <head>
327
+ <meta charset="UTF-8" />
328
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
329
+ <title>bwf</title>
330
+ </head>
331
+ <body>
332
+ <div id="root"></div>
333
+ <script type="module" src="/src/main.tsx"><\/script>
334
+ </body>
335
+ </html>
336
+ `;
337
+ }
338
+ function getMain() {
339
+ return `import { StrictMode } from "react";
340
+ import { createRoot } from "react-dom/client";
341
+ import App from "./App";
342
+ import "./style.css";
343
+
344
+ createRoot(document.getElementById("root")!).render(
345
+ <StrictMode>
346
+ <App />
347
+ </StrictMode>,
348
+ );
349
+ `;
350
+ }
351
+ function getMessagesRoute() {
352
+ return `import { defineHandler } from "@builtbyfriends/bwf";
353
+ import { db, desc } from "@builtbyfriends/bwf/db";
354
+ import { messages } from "@schema";
355
+ import { createInsertSchema } from "@builtbyfriends/bwf/drizzle-zod";
356
+
357
+ export const GET = defineHandler(async () => {
358
+ return db.select().from(messages).orderBy(desc(messages.id));
359
+ });
360
+
361
+ export const POST = defineHandler.withValidator({
362
+ body: createInsertSchema(messages, { text: (schema) => schema.trim().min(1).max(1000) }).pick({
363
+ text: true,
364
+ }),
365
+ })(async (_c, { body }) => {
366
+ await db.insert(messages).values(body);
367
+ return { ok: true };
368
+ });
369
+ `;
370
+ }
371
+ function getHelloRoute(frameworkLabel, starterMode) {
372
+ return `import { defineHandler } from "@builtbyfriends/bwf";
373
+
374
+ export const GET = defineHandler(() => {
375
+ return {
376
+ message: "Hello from bwf",
377
+ framework: "${frameworkLabel}",
378
+ database: "${starterMode === "postgresql" ? "PostgreSQL" : starterMode === "mysql" ? "MySQL" : "D1"}",
379
+ };
380
+ });
381
+ `;
382
+ }
383
+ function getSchemaFile(starterMode) {
384
+ if (starterMode === "postgresql") return `import { pgTable, serial, text, timestamp } from "@builtbyfriends/bwf/schema-pg";
385
+
386
+ export const messages = pgTable("messages", {
387
+ id: serial("id").primaryKey(),
388
+ text: text("text").notNull(),
389
+ createdAt: timestamp("created_at").notNull().defaultNow(),
390
+ });
391
+ `;
392
+ if (starterMode === "mysql") return `import { int, mysqlTable, text, timestamp } from "@builtbyfriends/bwf/schema-mysql";
393
+
394
+ export const messages = mysqlTable("messages", {
395
+ id: int("id").autoincrement().primaryKey(),
396
+ text: text("text").notNull(),
397
+ createdAt: timestamp("created_at").notNull().defaultNow(),
398
+ });
399
+ `;
400
+ return `import { sql } from "@builtbyfriends/bwf/db";
401
+ import { integer, sqliteTable, text } from "@builtbyfriends/bwf/schema-d1";
402
+
403
+ export const messages = sqliteTable("messages", {
404
+ id: integer("id").primaryKey({ autoIncrement: true }),
405
+ text: text("text").notNull(),
406
+ createdAt: text("created_at").notNull().default(sql\`(datetime('now'))\`),
407
+ });
408
+ `;
409
+ }
410
+ function getSeedFile() {
411
+ return `import { defineSeed } from "@builtbyfriends/bwf/seed";
412
+
413
+ const SAMPLE_MESSAGES = ["Hello from bwf"];
414
+
415
+ export default defineSeed<typeof import("./schema")>(async ({ db, schema }) => {
416
+ await db.insert(schema.messages).values(
417
+ SAMPLE_MESSAGES.map((text) => ({
418
+ text,
419
+ })),
420
+ );
421
+ });
422
+ `;
423
+ }
424
+ function getApp(framework, starterMode) {
425
+ const { label, docsUrl } = SCAFFOLD_FRAMEWORKS[framework];
426
+ const hasDatabase = starterMode !== "spa";
427
+ const jsx = `<main class="starter">
428
+ <section id="center" aria-labelledby="welcome-title">
429
+ <div class="hero">
430
+ <img class="base" src="/stack.svg" width="170" height="179" alt="" />
431
+ <img class="framework" src="/${framework}.svg" alt="${label} logo" />
432
+ <img class="nosam" src="/bwf.svg" alt="bwf logo" />
433
+ </div>
434
+ <div class="starter-intro">
435
+ <h1 id="welcome-title">Welcome to bwf</h1>
436
+ <div class="starter-description">
437
+ ${indent(hasDatabase ? `<p>
438
+ This React app talks to its backend in <code>routes/</code>. The list below is loaded from
439
+ your database through <code>routes/api/messages.ts</code>.
440
+ </p>
441
+ <p>API example: <a href="/api/hello">/api/hello</a></p>` : `<p>This starter is a React single-page app with no backend yet.</p>
442
+ <p>
443
+ Add <code>routes/</code> or <code>bwf/db</code> when you want to grow into full-stack
444
+ features.
445
+ </p>`, 8)}
446
+ </div>
447
+ </div>
448
+ </section>${hasDatabase ? `\n <div class="ticks" aria-hidden="true"></div>\n${indent(getMessagesDemo(), 2)}` : ""}
449
+ <div class="ticks" aria-hidden="true"></div>
450
+ <section id="next-steps" aria-label="Resources">
451
+ <div id="docs">
452
+ <svg class="icon" role="presentation" aria-hidden="true">
453
+ <use href="/icons.svg#documentation-icon"></use>
454
+ </svg>
455
+ <h2>Documentation</h2>
456
+ <p>Your questions, answered</p>
457
+ <ul>
458
+ <li>
459
+ <a href="https://void.cloud/guide/quickstart" target="_blank" rel="noreferrer">
460
+ Quickstart
461
+ </a>
462
+ </li>
463
+ <li>
464
+ <a href="${docsUrl}" target="_blank" rel="noreferrer">
465
+ <img class="button-icon" src="/${framework}.svg" alt="" />
466
+ Learn more
467
+ </a>
468
+ </li>
469
+ </ul>
470
+ </div>
471
+ <div id="social">
472
+ <svg class="icon" role="presentation" aria-hidden="true">
473
+ <use href="/icons.svg#social-icon"></use>
474
+ </svg>
475
+ <h2>Connect with us</h2>
476
+ <p>Join the bwf community</p>
477
+ <ul>
478
+ <li>
479
+ <a href="https://github.com/builtbyfriends/platform" target="_blank" rel="noreferrer">
480
+ <svg class="button-icon" role="presentation" aria-hidden="true">
481
+ <use href="/icons.svg#github-icon"></use>
482
+ </svg>
483
+ GitHub
484
+ </a>
485
+ </li>
486
+ <li>
487
+ <a href="https://discord.gg/cC6TEVFKSx" target="_blank" rel="noreferrer">
488
+ <svg class="button-icon" role="presentation" aria-hidden="true">
489
+ <use href="/icons.svg#discord-icon"></use>
490
+ </svg>
491
+ Discord
492
+ </a>
493
+ </li>
494
+ <li>
495
+ <a href="https://x.com/deploytovoid" target="_blank" rel="noreferrer">
496
+ <svg class="button-icon" role="presentation" aria-hidden="true">
497
+ <use href="/icons.svg#x-icon"></use>
498
+ </svg>
499
+ X.com
500
+ </a>
501
+ </li>
502
+ <li>
503
+ <a href="https://bsky.app/profile/voidzero.dev" target="_blank" rel="noreferrer">
504
+ <svg class="button-icon" role="presentation" aria-hidden="true">
505
+ <use href="/icons.svg#bluesky-icon"></use>
506
+ </svg>
507
+ Bluesky
508
+ </a>
509
+ </li>
510
+ </ul>
511
+ </div>
512
+ </section>
513
+ <div class="ticks" aria-hidden="true"></div>
514
+ <div id="spacer" aria-hidden="true"></div>
515
+ </main>`.replaceAll("class=", "className=");
516
+ if (!hasDatabase) return `export default function App() {
517
+ return (
518
+ ${indent(jsx, 4)}
519
+ );
520
+ }
521
+ `;
522
+ return `import { useEffect, useState, type FormEvent } from "react";
523
+ import { fetch } from "@builtbyfriends/bwf/client";
524
+
525
+ const loadMessages = () => fetch("/api/messages");
526
+
527
+ export default function App() {
528
+ const [messages, setMessages] = useState<Awaited<ReturnType<typeof loadMessages>>>([]);
529
+ const [text, setText] = useState("");
530
+ const [pending, setPending] = useState(false);
531
+
532
+ useEffect(() => {
533
+ loadMessages().then(setMessages);
534
+ }, []);
535
+
536
+ async function addMessage(event: FormEvent) {
537
+ event.preventDefault();
538
+ setPending(true);
539
+ try {
540
+ await fetch("/api/messages", { method: "POST", body: { text } });
541
+ setText("");
542
+ setMessages(await loadMessages());
543
+ } finally {
544
+ setPending(false);
545
+ }
546
+ }
547
+
548
+ return (
549
+ ${indent(jsx, 4)}
550
+ );
551
+ }
552
+ `;
553
+ }
554
+ function getMessagesDemo() {
555
+ return `<section class="starter-demo" aria-labelledby="messages-title">
556
+ <div class="demo-content">
557
+ <h2 id="messages-title">Messages</h2>
558
+ {messages.length === 0 ? (
559
+ <p class="empty-state">
560
+ No messages yet. Run <code>bwf db seed</code> to load the sample row from <code>db/seed.ts</code>.
561
+ </p>
562
+ ) : (
563
+ <ul class="messages">
564
+ {messages.map((message) => (
565
+ <li key={message.id}>
566
+ <strong>{message.text}</strong>
567
+ <small>{String(message.createdAt)}</small>
568
+ </li>
569
+ ))}
570
+ </ul>
571
+ )}
572
+ <form onSubmit={addMessage} class="message-form">
573
+ <label htmlFor="message-text">Message</label>
574
+ <div class="message-fields">
575
+ <input id="message-text" name="text" value={text} onChange={(event) => setText(event.target.value)} required maxLength={1000} />
576
+ <button type="submit" disabled={pending}>Add message</button>
577
+ </div>
578
+ </form>
579
+ </div>
580
+ </section>`;
581
+ }
582
+ function indent(source, spaces) {
583
+ return source.split("\n").map((line) => " ".repeat(spaces) + line).join("\n");
584
+ }
585
+ // src/cli/init-vite-plus.ts
586
+ /** Keep every Vite consumer on the core used by the selected Vite+ toolchain. */
587
+ function configureVitePlusScaffold(root, packageManager, pkg) {
588
+ const core = SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES.vite;
589
+ if (packageManager === "pnpm") editYaml(root, "pnpm-workspace.yaml", (document) => {
590
+ if (document.hasIn(["overrides", "vite"])) document.deleteIn(["overrides", "vite"]);
591
+ document.setIn(["overrides", "vite@*"], core);
592
+ document.setIn([
593
+ "peerDependencyRules",
594
+ "allowedVersions",
595
+ "vite"
596
+ ], "*");
597
+ });
598
+ else if (packageManager === "yarn") {
599
+ pkg.resolutions = {
600
+ ...pkg.resolutions,
601
+ vite: core
602
+ };
603
+ editYaml(root, ".yarnrc.yml", (document) => {
604
+ document.set("nodeLinker", "node-modules");
605
+ });
606
+ } else pkg.overrides = {
607
+ ...pkg.overrides,
608
+ vite: packageManager === "npm" ? "$vite" : core
609
+ };
610
+ }
611
+ function editYaml(root, name, edit) {
612
+ const path = join(root, name);
613
+ const before = existsSync(path) ? readFileSync(path, "utf8") : "";
614
+ const document = parseDocument(before);
615
+ if (document.errors.length) throw new Error(`Could not parse ${name}: ${document.errors[0].message}`);
616
+ edit(document);
617
+ writeFileSync(path, document.toString());
618
+ }
619
+ // src/cli/vite-config-patch.ts
620
+ function unwrap(node) {
621
+ while (node && [
622
+ "TSAsExpression",
623
+ "TSSatisfiesExpression",
624
+ "ParenthesizedExpression",
625
+ "TSTypeAssertion"
626
+ ].includes(node.type)) node = node.expression;
627
+ return node;
628
+ }
629
+ function configObject(program) {
630
+ const declaration = program.body?.find((node) => node.type === "ExportDefaultDeclaration")?.declaration;
631
+ const exported = unwrap(declaration);
632
+ if (exported?.type === "ObjectExpression") return exported;
633
+ if (exported?.type === "CallExpression" && exported.callee?.name === "defineConfig") {
634
+ const firstArgument = unwrap(exported.arguments?.[0]);
635
+ if (firstArgument?.type === "ObjectExpression") return firstArgument;
636
+ }
637
+ }
638
+ function propertyName(property) {
639
+ if (property.type !== "Property" || property.computed || property.kind !== "init") return;
640
+ return property.key?.name ?? (typeof property.key?.value === "string" ? property.key.value : void 0);
641
+ }
642
+ function nodeValue(node) {
643
+ const value = node?.value;
644
+ return value !== null && typeof value === "object" && "type" in value ? value : void 0;
645
+ }
646
+ function lineIndent(code, index) {
647
+ const lineStart = code.lastIndexOf("\n", index) + 1;
648
+ return code.slice(lineStart, index).match(/^\s*/)?.[0] ?? "";
649
+ }
650
+ /** Add the plugin only when the exported Vite configuration has an editable object and array. */
651
+ function patchViteConfigWithBwfPlugin(filePath, code) {
652
+ if (filePath.endsWith(".cjs") || filePath.endsWith(".cts")) return;
653
+ let program;
654
+ try {
655
+ program = parseSync(filePath, code).program;
656
+ } catch {
657
+ return;
658
+ }
659
+ const object = configObject(program);
660
+ if (!object) return;
661
+ const pluginProperties = object.properties?.filter((property) => propertyName(property) === "plugins") ?? [];
662
+ if (pluginProperties.length > 1 || nodeValue(pluginProperties[0])?.type !== "ArrayExpression") {
663
+ if (pluginProperties.length > 0) return;
664
+ }
665
+ const imports = program.body?.filter((node) => node.type === "ImportDeclaration") ?? [];
666
+ const importedName = imports.filter((node) => node.source?.value === "@builtbyfriends/bwf").flatMap((node) => node.specifiers ?? []).find((node) => node.type === "ImportSpecifier" && node.imported?.name === "bwfPlugin")?.local?.name;
667
+ const pluginName = importedName ?? "bwfPlugin";
668
+ const plugins = nodeValue(pluginProperties[0]);
669
+ if (plugins?.elements?.some((element) => element?.type === "CallExpression" && element.callee?.name === pluginName)) return code;
670
+ const ms = new MagicString(code);
671
+ if (plugins) {
672
+ const insertAt = plugins.start + 1;
673
+ if (code.slice(insertAt, plugins.end - 1).trim() === "") {
674
+ if (insertAt === plugins.end - 1) ms.appendLeft(insertAt, `${pluginName}()`);
675
+ else ms.overwrite(insertAt, plugins.end - 1, `${pluginName}()`);
676
+ } else {
677
+ const indent = lineIndent(code, pluginProperties[0].start);
678
+ const next = code[insertAt];
679
+ ms.appendLeft(insertAt, next === "\n" || next === "\r" ? `\n${indent} ${pluginName}(),` : `${pluginName}(), `);
680
+ }
681
+ } else {
682
+ if (object.properties?.some((property) => property.type === "SpreadElement")) return;
683
+ if (code.slice(object.start + 1, object.end - 1).trim() === "") {
684
+ const replacement = ` plugins: [${pluginName}()] `;
685
+ if (object.start + 1 === object.end - 1) ms.appendLeft(object.start + 1, replacement);
686
+ else ms.overwrite(object.start + 1, object.end - 1, replacement);
687
+ } else {
688
+ const indent = lineIndent(code, object.start);
689
+ const next = code[object.start + 1];
690
+ ms.appendLeft(object.start + 1, next === "\n" || next === "\r" ? `\n${indent} plugins: [${pluginName}()],` : ` plugins: [${pluginName}()],`);
691
+ }
692
+ }
693
+ if (!importedName) {
694
+ const insertAt = imports.length > 0 ? imports[imports.length - 1].end : code.startsWith("#!") ? code.indexOf("\n") + 1 : 0;
695
+ const prefix = insertAt > 0 && code[insertAt - 1] !== "\n" ? "\n" : "";
696
+ ms.appendLeft(insertAt, `${prefix}import { bwfPlugin } from "@builtbyfriends/bwf";\n`);
697
+ }
698
+ return ms.toString();
699
+ }
700
+ // src/cli/init.ts
701
+ const SCAFFOLD_STARTER_MODES = [
702
+ "sqlite",
703
+ "postgresql",
704
+ "mysql",
705
+ "spa"
706
+ ];
707
+ const DEPLOYMENT_PLATFORMS = [
708
+ "cloudflare",
709
+ "nosam",
710
+ "none"
711
+ ];
712
+ function parseChoice(flag, value, choices) {
713
+ if (value === void 0) return;
714
+ if (typeof value !== "string" || !choices.includes(value)) throw new Error(`init: --${flag} must be one of ${choices.join(", ")}.`);
715
+ return value;
716
+ }
717
+ function parseInitArgs(args) {
718
+ let parsed;
719
+ try {
720
+ parsed = parseArgs({
721
+ args,
722
+ options: {
723
+ tsconfig: { type: "boolean" },
724
+ github: { type: "boolean" },
725
+ git: { type: "boolean" },
726
+ toolchain: { type: "string" },
727
+ framework: { type: "string" },
728
+ starter: { type: "string" },
729
+ deploy: { type: "string" }
730
+ },
731
+ allowNegative: true,
732
+ strict: true
733
+ });
734
+ } catch (error) {
735
+ const message = error instanceof Error ? error.message : String(error);
736
+ throw new Error(`init: ${message}.`);
737
+ }
738
+ return {
739
+ tsconfig: parsed.values.tsconfig === true,
740
+ github: parsed.values.github === true,
741
+ git: parsed.values.git,
742
+ toolchain: parseChoice("toolchain", parsed.values.toolchain, SCAFFOLD_TOOLCHAIN_OPTIONS.map((option) => option.value)),
743
+ framework: parseChoice("framework", parsed.values.framework, SCAFFOLD_FRAMEWORK_OPTIONS.map((option) => option.value)),
744
+ starter: parseChoice("starter", parsed.values.starter, SCAFFOLD_STARTER_MODES),
745
+ deploy: parseChoice("deploy", parsed.values.deploy, DEPLOYMENT_PLATFORMS)
746
+ };
747
+ }
748
+ const EMPTY_PROJECT_ALLOWED_ENTRIES = /* @__PURE__ */ new Set([
749
+ ".git",
750
+ ".gitignore",
751
+ "AGENTS.md",
752
+ "CLAUDE.md",
753
+ ".node-version",
754
+ ".npmrc",
755
+ ".yarnrc.yml",
756
+ ".nvmrc",
757
+ ".editorconfig",
758
+ ".vscode",
759
+ ".idea",
760
+ ".DS_Store",
761
+ ".bwf",
762
+ ".wrangler",
763
+ ".cloudflare",
764
+ "node_modules",
765
+ "package.json",
766
+ "package-lock.json",
767
+ "pnpm-lock.yaml",
768
+ "yarn.lock",
769
+ "bun.lock",
770
+ "bun.lockb",
771
+ "tsconfig.json",
772
+ ".agents",
773
+ ".claude",
774
+ ".cline",
775
+ ".codex",
776
+ ".continue",
777
+ ".cursor",
778
+ ".gemini",
779
+ ".goose",
780
+ ".junie",
781
+ ".kilocode",
782
+ ".kiro",
783
+ ".opencode",
784
+ ".qwen",
785
+ ".roo",
786
+ ".trae",
787
+ ".windsurf",
788
+ ".zencoder"
789
+ ]);
790
+ const PNPM_BUILD_DEFAULTS = [
791
+ ["better-sqlite3", false],
792
+ ["esbuild", true],
793
+ ["sharp", true],
794
+ ["workerd", true]
795
+ ];
796
+ const PNPM_BUILD_PLACEHOLDER = "set this to true or false";
797
+ const EMPTY_PROJECT_ALLOWED_PACKAGES = /* @__PURE__ */ new Set([
798
+ "@builtbyfriends/bwf",
799
+ "hono",
800
+ "vite",
801
+ "vite-plus",
802
+ "typescript",
803
+ "@rolldown/plugin-babel",
804
+ "@vitejs/plugin-react",
805
+ "babel-plugin-react-compiler",
806
+ "oxc-transform-react",
807
+ "@types/react",
808
+ "@types/react-dom",
809
+ "react",
810
+ "react-dom"
811
+ ]);
812
+ const EMPTY_PROJECT_ALLOWED_SCRIPTS = {
813
+ test: void 0,
814
+ dev: /* @__PURE__ */ new Set(["vite", "vp dev"]),
815
+ build: /* @__PURE__ */ new Set(["vite build", "vp build"]),
816
+ preview: /* @__PURE__ */ new Set(["vite preview", "vp preview"]),
817
+ postinstall: /* @__PURE__ */ new Set(["bwf prepare"])
818
+ };
819
+ const EMPTY_PROJECT_STARTER_SCRIPT_COMMANDS = new Set(Object.values(EMPTY_PROJECT_ALLOWED_SCRIPTS).flatMap((commands) => commands ? Array.from(commands) : []));
820
+ function isStarterScriptCommand(value) {
821
+ return typeof value === "string" && EMPTY_PROJECT_STARTER_SCRIPT_COMMANDS.has(value);
822
+ }
823
+ const EMPTY_PROJECT_STARTER_MARKER = "@vitejs/plugin-react";
824
+ function hasOnlyBwfStarterDependencies(depNames) {
825
+ if (depNames.some((dep) => !EMPTY_PROJECT_ALLOWED_PACKAGES.has(dep))) return false;
826
+ return !depNames.some((dep) => dep !== "@builtbyfriends/bwf" && dep !== EMPTY_PROJECT_STARTER_MARKER) || depNames.includes(EMPTY_PROJECT_STARTER_MARKER);
827
+ }
828
+ const VITE_CONFIG_FILES = [
829
+ "vite.config.ts",
830
+ "vite.config.js",
831
+ "vite.config.mts",
832
+ "vite.config.mjs",
833
+ "vite.config.cts",
834
+ "vite.config.cjs"
835
+ ];
836
+ const BWF_CONFIG_FILE = "bwf.json";
837
+ function asRecord(value) {
838
+ return isRecord(value) ? value : null;
839
+ }
840
+ function parseJsoncFile(path) {
841
+ const errors = [];
842
+ const parsed = asRecord(parse(readFileSync(path, "utf-8"), errors));
843
+ return errors.length === 0 ? parsed : null;
844
+ }
845
+ function uniqueStrings(values) {
846
+ return Array.from(new Set(values));
847
+ }
848
+ function normalizeRelativePath(fromDir, toPath) {
849
+ const rel = relative(fromDir, toPath).replaceAll("\\", "/");
850
+ return rel === ".." || rel.startsWith("../") || rel.startsWith("./") ? rel : `./${rel}`;
851
+ }
852
+ function getOwnConfigBaseUrlDir(config, configDir) {
853
+ const compilerOptions = asRecord(config.compilerOptions);
854
+ return compilerOptions && typeof compilerOptions.baseUrl === "string" ? resolve(configDir, compilerOptions.baseUrl) : null;
855
+ }
856
+ function readExtends(config) {
857
+ return typeof config.extends === "string" ? [config.extends] : Array.isArray(config.extends) ? config.extends.filter((value) => typeof value === "string") : [];
858
+ }
859
+ function getEffectiveConfigBaseUrlDir(config, configPath, seen) {
860
+ if (seen.has(configPath)) return null;
861
+ seen.add(configPath);
862
+ const ownBaseUrl = getOwnConfigBaseUrlDir(config, dirname(configPath));
863
+ if (ownBaseUrl) return ownBaseUrl;
864
+ const extendsValues = readExtends(config);
865
+ let inheritedBaseUrl = null;
866
+ for (const extendsValue of extendsValues) {
867
+ const extendedPath = resolveExtendedTsconfig(configPath, extendsValue);
868
+ if (!extendedPath || !existsSync(extendedPath)) continue;
869
+ const extendedConfig = parseJsoncFile(extendedPath);
870
+ if (!extendedConfig) continue;
871
+ inheritedBaseUrl = getEffectiveConfigBaseUrlDir(extendedConfig, extendedPath, seen) ?? inheritedBaseUrl;
872
+ }
873
+ return inheritedBaseUrl;
874
+ }
875
+ function effectiveConfigPathBaseDir(config, configPath) {
876
+ return getEffectiveConfigBaseUrlDir(config, configPath, /* @__PURE__ */ new Set()) ?? dirname(configPath);
877
+ }
878
+ function convertConfigFileEntry(value, configDir, root) {
879
+ if (isAbsolute(value)) return normalizeRelativePath(root, value);
880
+ return normalizeRelativePath(root, resolve(configDir, value));
881
+ }
882
+ function convertPathTarget(value, fromBaseDir, toBaseDir) {
883
+ if (isAbsolute(value)) return normalizeRelativePath(toBaseDir, value);
884
+ return normalizeRelativePath(toBaseDir, resolve(fromBaseDir, value));
885
+ }
886
+ function mergePathMaps(target, source) {
887
+ for (const [key, values] of Object.entries(source)) target[key] = values;
888
+ }
889
+ function readStringArray(value) {
890
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
891
+ }
892
+ function readPaths(value) {
893
+ const paths = asRecord(value);
894
+ if (!paths) return {};
895
+ const result = {};
896
+ for (const [key, values] of Object.entries(paths)) {
897
+ const stringValues = readStringArray(values);
898
+ if (stringValues.length > 0) result[key] = stringValues;
899
+ }
900
+ return result;
901
+ }
902
+ function resolveExtendedTsconfig(fromConfigPath, specifier) {
903
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
904
+ const resolved = resolve(dirname(fromConfigPath), specifier);
905
+ return resolved.endsWith(".json") ? resolved : `${resolved}.json`;
906
+ }
907
+ try {
908
+ return createRequire(fromConfigPath).resolve(specifier);
909
+ } catch {
910
+ try {
911
+ return createRequire(fromConfigPath).resolve(`${specifier}.json`);
912
+ } catch {
913
+ return null;
914
+ }
915
+ }
916
+ }
917
+ function collectTsconfigPatchFromConfig(config, configPath, root, outputBaseDir, seen) {
918
+ const patch = {
919
+ files: [],
920
+ paths: {}
921
+ };
922
+ if (seen.has(configPath)) return patch;
923
+ seen.add(configPath);
924
+ const extendsValues = readExtends(config);
925
+ const hasOwnFiles = Array.isArray(config.files);
926
+ const compilerOptions = asRecord(config.compilerOptions);
927
+ const hasOwnPaths = asRecord(compilerOptions?.paths) !== null;
928
+ for (const extendsValue of extendsValues) {
929
+ const extendedPath = resolveExtendedTsconfig(configPath, extendsValue);
930
+ if (!extendedPath || !existsSync(extendedPath)) continue;
931
+ const extendedConfig = parseJsoncFile(extendedPath);
932
+ if (!extendedConfig) continue;
933
+ const extendedPatch = collectTsconfigPatchFromConfig(extendedConfig, extendedPath, root, outputBaseDir, seen);
934
+ if (!hasOwnFiles) patch.files.push(...extendedPatch.files);
935
+ if (!hasOwnPaths) mergePathMaps(patch.paths, extendedPatch.paths);
936
+ }
937
+ const configDir = dirname(configPath);
938
+ if (hasOwnFiles) patch.files.push(...readStringArray(config.files).map((entry) => convertConfigFileEntry(entry, configDir, root)));
939
+ if (hasOwnPaths) {
940
+ const paths = readPaths(compilerOptions?.paths);
941
+ const pathBaseDir = effectiveConfigPathBaseDir(config, configPath);
942
+ const convertedPaths = {};
943
+ for (const [key, values] of Object.entries(paths)) convertedPaths[key] = values.map((value) => convertPathTarget(value, pathBaseDir, outputBaseDir));
944
+ mergePathMaps(patch.paths, convertedPaths);
945
+ }
946
+ return patch;
947
+ }
948
+ function createBwfTsconfigPatch(root, outputBaseDir) {
949
+ const hasSchema = hasDrizzleSchema(root);
950
+ return collectTsconfigPatchFromConfig(createProjectTsconfig(root, void 0, hasSchema, hasSchema), join(root, ".bwf", "tsconfig.json"), root, outputBaseDir, /* @__PURE__ */ new Set());
951
+ }
952
+ function hasTopLevelYamlKey(yaml, key) {
953
+ const keyPattern = new RegExp(`^${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*:`);
954
+ return yaml.split(/\r?\n/).some((rawLine) => {
955
+ const line = stripYamlLineComment(rawLine);
956
+ return keyPattern.test(line);
957
+ });
958
+ }
959
+ function isEmptyProjectAllowedPnpmWorkspaceFile(root) {
960
+ try {
961
+ return !hasTopLevelYamlKey(readFileSync(join(root, "pnpm-workspace.yaml"), "utf-8"), "packages");
962
+ } catch {
963
+ return false;
964
+ }
965
+ }
966
+ function isScaffoldableEmptyProject(root) {
967
+ for (const dir of [
968
+ "src",
969
+ "routes",
970
+ "db",
971
+ "migrations",
972
+ "middleware",
973
+ "crons",
974
+ "queues"
975
+ ]) if (existsSync(join(root, dir))) return false;
976
+ if (existsSync(join(root, "index.html"))) return false;
977
+ for (const file of VITE_CONFIG_FILES) if (existsSync(join(root, file))) return false;
978
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
979
+ if (EMPTY_PROJECT_ALLOWED_ENTRIES.has(entry.name)) continue;
980
+ if (entry.name === "pnpm-workspace.yaml" && isEmptyProjectAllowedPnpmWorkspaceFile(root)) continue;
981
+ if (entry.name.startsWith("README")) continue;
982
+ return false;
983
+ }
984
+ const packageJsonPath = join(root, "package.json");
985
+ if (!existsSync(packageJsonPath)) return true;
986
+ let pkgRaw;
987
+ try {
988
+ pkgRaw = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
989
+ } catch {
990
+ return false;
991
+ }
992
+ const pkg = asRecord(pkgRaw);
993
+ if (!pkg) return false;
994
+ const deps = {
995
+ ...asRecord(pkg.dependencies) ?? {},
996
+ ...asRecord(pkg.devDependencies) ?? {}
997
+ };
998
+ if (!hasOnlyBwfStarterDependencies(Object.keys(deps))) return false;
999
+ const scripts = asRecord(pkg.scripts) ?? {};
1000
+ for (const [name, command] of Object.entries(scripts)) {
1001
+ if (!(name in EMPTY_PROJECT_ALLOWED_SCRIPTS)) return false;
1002
+ const allowed = EMPTY_PROJECT_ALLOWED_SCRIPTS[name];
1003
+ if (allowed === void 0) continue;
1004
+ if (typeof command !== "string" || !allowed.has(command)) return false;
1005
+ }
1006
+ return true;
1007
+ }
1008
+ function shouldPromptForInitLocation(root) {
1009
+ if (isScaffoldableEmptyProject(root)) return false;
1010
+ if (existsSync(join(root, "package.json"))) return false;
1011
+ if (existsSync(join(root, BWF_CONFIG_FILE)) || existsSync(join(root, "bwf.config.ts"))) return false;
1012
+ return findViteConfig(root) === void 0;
1013
+ }
1014
+ function validateSubfolderName(root, value) {
1015
+ const name = value?.trim() ?? "";
1016
+ if (!name) return "Enter a folder name.";
1017
+ if (name === "." || name === ".." || name.includes("/") || name.includes("\\")) return "Enter a single folder name, not a path.";
1018
+ if (existsSync(join(root, name))) return "That folder already exists.";
1019
+ }
1020
+ async function resolveInitRoot(root) {
1021
+ if (!shouldPromptForInitLocation(root)) return root;
1022
+ const choice = await select({
1023
+ message: "This folder is not empty. Where should bwf initialize?",
1024
+ initialValue: "subfolder",
1025
+ options: [{
1026
+ value: "subfolder",
1027
+ label: "Create a new subfolder",
1028
+ hint: "Scaffold a new app inside this directory."
1029
+ }, {
1030
+ value: "current",
1031
+ label: "Continue here",
1032
+ hint: "Add package.json, vite.config.ts, and bwf files to this directory."
1033
+ }]
1034
+ });
1035
+ if (isCancel(choice)) {
1036
+ cancel("Setup cancelled.");
1037
+ process.exit(0);
1038
+ }
1039
+ if (choice === "current") return root;
1040
+ const defaultFolder = "my-nosam-app";
1041
+ const folder = await text({
1042
+ message: "New project folder name:",
1043
+ placeholder: defaultFolder,
1044
+ defaultValue: defaultFolder,
1045
+ validate: (value) => validateSubfolderName(root, value || defaultFolder)
1046
+ });
1047
+ if (isCancel(folder) || typeof folder === "symbol") {
1048
+ cancel("Setup cancelled.");
1049
+ process.exit(0);
1050
+ }
1051
+ const nextRoot = join(root, folder.trim());
1052
+ mkdirSync(nextRoot, { recursive: true });
1053
+ log.info(`Scaffolding in ${nextRoot}`);
1054
+ return nextRoot;
1055
+ }
1056
+ function parsePackageManagerField(pkg) {
1057
+ if (!pkg || typeof pkg !== "object") return;
1058
+ const raw = pkg.packageManager;
1059
+ if (typeof raw !== "string") return;
1060
+ const name = raw.split("@", 1)[0]?.trim();
1061
+ if (name === "npm" || name === "pnpm" || name === "yarn" || name === "bun") return name;
1062
+ }
1063
+ /**
1064
+ * Whether pnpm manages `root`. pnpm keeps the lockfile and Corepack pin at the
1065
+ * workspace root, so a member without local markers inherits them, but a local
1066
+ * lockfile or pin for another manager always wins.
1067
+ */
1068
+ function isPnpmProject(root, pkg) {
1069
+ if (existsSync(join(root, "pnpm-lock.yaml"))) return true;
1070
+ if (existsSync(join(root, "pnpm-workspace.yaml"))) return true;
1071
+ const localPm = parsePackageManagerField(pkg);
1072
+ if (localPm === "pnpm") return true;
1073
+ if (localPm === "bun" || localPm === "yarn" || localPm === "npm") return false;
1074
+ if (hasLocalLockfile(root)) return false;
1075
+ return hasAncestorPnpmMarkers(root);
1076
+ }
1077
+ /**
1078
+ * Whether `start` is a declared member of a pnpm-managed ancestor workspace.
1079
+ * A scratch app outside the workspace globs is a separate project.
1080
+ */
1081
+ function hasAncestorPnpmMarkers(start) {
1082
+ const workspaceRoot = findWorkspaceRoot(start);
1083
+ if (workspaceRoot === void 0) return false;
1084
+ if (!isWorkspaceSubpackage(workspaceRoot, start)) return false;
1085
+ if (existsSync(join(workspaceRoot, "pnpm-workspace.yaml"))) return true;
1086
+ if (existsSync(join(workspaceRoot, "pnpm-lock.yaml"))) return true;
1087
+ const pkgPath = join(workspaceRoot, "package.json");
1088
+ if (existsSync(pkgPath)) try {
1089
+ if (parsePackageManagerField(JSON.parse(readFileSync(pkgPath, "utf-8"))) === "pnpm") return true;
1090
+ } catch {}
1091
+ return false;
1092
+ }
1093
+ /**
1094
+ * Whether `nosam` resolves from `start`, through an ancestor `node_modules`
1095
+ * (hoisted workspace installs) or an installed Yarn PnP runtime.
1096
+ */
1097
+ function isBwfResolvableFrom(start) {
1098
+ let dir = start;
1099
+ while (true) {
1100
+ if (existsSync(join(dir, "node_modules", "@builtbyfriends", "bwf", "package.json"))) return true;
1101
+ const parent = dirname(dir);
1102
+ if (parent === dir) break;
1103
+ dir = parent;
1104
+ }
1105
+ const installed = findInstalledYarnPnpRuntime(start);
1106
+ if (installed !== void 0) {
1107
+ const probeArgs = installed.pnpCjs ? ["-e", "require.resolve('@builtbyfriends/bwf')"] : [
1108
+ "--input-type=module",
1109
+ "-e",
1110
+ "import.meta.resolve('@builtbyfriends/bwf')"
1111
+ ];
1112
+ const probe = spawnSync(process.execPath, probeArgs, {
1113
+ cwd: start,
1114
+ stdio: "ignore",
1115
+ env: buildDrizzleKitSpawnEnv(start)
1116
+ });
1117
+ return !probe.error && probe.status === 0;
1118
+ }
1119
+ return false;
1120
+ }
1121
+ /**
1122
+ * Nearest ancestor of `start` (excluding `start`) with a `pnpm-workspace.yaml`
1123
+ * or a `package.json#workspaces` field.
1124
+ */
1125
+ function findWorkspaceRoot(start) {
1126
+ let dir = dirname(start);
1127
+ while (true) {
1128
+ const pkgPath = join(dir, "package.json");
1129
+ if (existsSync(pkgPath)) try {
1130
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1131
+ if (pkg && typeof pkg === "object" && "workspaces" in pkg) return dir;
1132
+ } catch {}
1133
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1134
+ const parent = dirname(dir);
1135
+ if (parent === dir) return;
1136
+ dir = parent;
1137
+ }
1138
+ }
1139
+ /**
1140
+ * Member globs from `pnpm-workspace.yaml#packages` or `package.json#workspaces`
1141
+ * (an array or `{ packages }`). Empty when none can be read.
1142
+ */
1143
+ function readWorkspacePatterns(workspaceRoot) {
1144
+ const pnpmWorkspacePath = join(workspaceRoot, "pnpm-workspace.yaml");
1145
+ if (existsSync(pnpmWorkspacePath)) try {
1146
+ return extractPnpmWorkspacePackages(readFileSync(pnpmWorkspacePath, "utf-8"));
1147
+ } catch {
1148
+ return [];
1149
+ }
1150
+ const pkgPath = join(workspaceRoot, "package.json");
1151
+ if (existsSync(pkgPath)) try {
1152
+ const workspaces = JSON.parse(readFileSync(pkgPath, "utf-8")).workspaces;
1153
+ if (Array.isArray(workspaces)) return workspaces.filter((x) => typeof x === "string");
1154
+ if (workspaces && typeof workspaces === "object") {
1155
+ const packages = workspaces.packages;
1156
+ if (Array.isArray(packages)) return packages.filter((x) => typeof x === "string");
1157
+ }
1158
+ } catch {
1159
+ return [];
1160
+ }
1161
+ return [];
1162
+ }
1163
+ /** Strip a trailing YAML comment, keeping `#` inside quotes (`- "path #hash/*"`). */
1164
+ function stripYamlLineComment(line) {
1165
+ let inSingle = false;
1166
+ let inDouble = false;
1167
+ for (let i = 0; i < line.length; i++) {
1168
+ const ch = line[i];
1169
+ if (inSingle) {
1170
+ if (ch === "'") inSingle = false;
1171
+ continue;
1172
+ }
1173
+ if (inDouble) {
1174
+ if (ch === "\"") inDouble = false;
1175
+ continue;
1176
+ }
1177
+ if (ch === "'") {
1178
+ inSingle = true;
1179
+ continue;
1180
+ }
1181
+ if (ch === "\"") {
1182
+ inDouble = true;
1183
+ continue;
1184
+ }
1185
+ if (ch === "#" && i > 0 && /\s/.test(line[i - 1])) return line.slice(0, i).replace(/\s+$/, "");
1186
+ }
1187
+ return line;
1188
+ }
1189
+ /**
1190
+ * Read the `packages:` list of a `pnpm-workspace.yaml` in block (`- 'apps/*'`)
1191
+ * or flow (`packages: ['apps/*']`) form.
1192
+ */
1193
+ function extractPnpmWorkspacePackages(yaml) {
1194
+ const lines = yaml.split(/\r?\n/);
1195
+ const patterns = [];
1196
+ let inPackages = false;
1197
+ for (const rawLine of lines) {
1198
+ const line = stripYamlLineComment(rawLine);
1199
+ const inlineMatch = line.match(/^\s*packages\s*:\s*\[(.*)\]\s*$/);
1200
+ if (inlineMatch) {
1201
+ const items = inlineMatch[1].match(/(['"])(?:(?!\1).)*\1|[^,\s]+/g) ?? [];
1202
+ for (const raw of items) {
1203
+ const unquoted = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
1204
+ if (unquoted) patterns.push(unquoted);
1205
+ }
1206
+ inPackages = false;
1207
+ continue;
1208
+ }
1209
+ if (/^\s*packages\s*:\s*$/.test(line)) {
1210
+ inPackages = true;
1211
+ continue;
1212
+ }
1213
+ if (!inPackages) continue;
1214
+ if (/^[A-Za-z_][\w-]*\s*:\s*(?:\S.*)?$/.test(line) && !/^\s/.test(line)) {
1215
+ inPackages = false;
1216
+ continue;
1217
+ }
1218
+ const m = line.match(/^\s*-\s*(['"]?)([^'"\s][^'"]*?)\1\s*$/);
1219
+ if (m) patterns.push(m[2]);
1220
+ }
1221
+ return patterns;
1222
+ }
1223
+ /** Expand `{a,b}` brace groups, including several groups in one pattern. */
1224
+ function expandBraces(pattern) {
1225
+ const match = pattern.match(/^([^{}]*)\{([^{}]*)\}(.*)$/);
1226
+ if (!match) return [pattern];
1227
+ const [, before, group, after] = match;
1228
+ const options = group.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
1229
+ if (options.length === 0) return [pattern];
1230
+ const results = [];
1231
+ for (const opt of options) for (const sub of expandBraces(before + opt + after)) results.push(sub);
1232
+ return results;
1233
+ }
1234
+ function matchesWorkspacePattern(relPath, pattern) {
1235
+ return expandBraces(pattern).some((p) => matchesSingleWorkspacePattern(relPath, p));
1236
+ }
1237
+ function matchesSingleWorkspacePattern(relPath, pattern) {
1238
+ const normalizedPattern = pattern.replace(/^\.\/+/, "");
1239
+ return matchSegments(relPath.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean), 0, normalizedPattern.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean).map(compilePatternSegment), 0);
1240
+ }
1241
+ function compilePatternSegment(seg) {
1242
+ if (seg === "**") return { kind: "globstar" };
1243
+ if (!seg.includes("*")) return {
1244
+ kind: "literal",
1245
+ value: seg
1246
+ };
1247
+ return {
1248
+ kind: "regex",
1249
+ re: new RegExp("^" + seg.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*") + "$")
1250
+ };
1251
+ }
1252
+ function matchSegments(path, pi, pat, qi) {
1253
+ while (qi < pat.length) {
1254
+ const seg = pat[qi];
1255
+ if (seg.kind === "globstar") {
1256
+ if (qi === pat.length - 1) return true;
1257
+ for (let k = pi; k <= path.length; k++) if (matchSegments(path, k, pat, qi + 1)) return true;
1258
+ return false;
1259
+ }
1260
+ if (pi >= path.length) return false;
1261
+ if (seg.kind === "literal") {
1262
+ if (seg.value !== path[pi]) return false;
1263
+ } else if (!seg.re.test(path[pi])) return false;
1264
+ pi++;
1265
+ qi++;
1266
+ }
1267
+ return pi === path.length;
1268
+ }
1269
+ /**
1270
+ * Whether `root` matches a workspace glob and no `!` glob. A nested app outside
1271
+ * the globs is a separate project.
1272
+ */
1273
+ function isWorkspaceSubpackage(workspaceRoot, root) {
1274
+ const relPath = relative(workspaceRoot, root);
1275
+ if (relPath === "" || relPath.startsWith("..")) return false;
1276
+ const normalized = relPath.split(/[\\/]/).join("/");
1277
+ const patterns = readWorkspacePatterns(workspaceRoot);
1278
+ if (patterns.length === 0) return false;
1279
+ let matched = false;
1280
+ for (const raw of patterns) {
1281
+ const isNegation = raw.startsWith("!");
1282
+ if (matchesWorkspacePattern(normalized, isNegation ? raw.slice(1) : raw)) {
1283
+ if (isNegation) return false;
1284
+ matched = true;
1285
+ }
1286
+ }
1287
+ return matched;
1288
+ }
1289
+ /** Workspace membership, even when the member manages its own install. */
1290
+ function isInsideWorkspaceSubpackage(root) {
1291
+ const workspaceRoot = findWorkspaceRoot(root);
1292
+ if (workspaceRoot === void 0) return false;
1293
+ return isWorkspaceSubpackage(workspaceRoot, root);
1294
+ }
1295
+ /**
1296
+ * The workspace root that should install for `root`: set when `root` is a
1297
+ * member without its own lockfile or non-pnpm Corepack pin, as in `isPnpmProject`.
1298
+ */
1299
+ function resolveWorkspaceDeferral(root, pkg) {
1300
+ const workspaceRoot = findWorkspaceRoot(root);
1301
+ if (workspaceRoot === void 0) return;
1302
+ if (!isWorkspaceSubpackage(workspaceRoot, root)) return;
1303
+ if (hasLocalLockfile(root)) return;
1304
+ const localPm = parsePackageManagerField(pkg);
1305
+ if (localPm === "bun" || localPm === "yarn" || localPm === "npm") return;
1306
+ return { workspaceRoot };
1307
+ }
1308
+ function detectProjectState(root) {
1309
+ let hasTypescript = false;
1310
+ let pkg;
1311
+ try {
1312
+ pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
1313
+ const pkgRecord = pkg ?? {};
1314
+ hasTypescript = "typescript" in {
1315
+ ...asRecord(pkgRecord.dependencies) ?? {},
1316
+ ...asRecord(pkgRecord.devDependencies) ?? {}
1317
+ };
1318
+ } catch {}
1319
+ let packageManager;
1320
+ if (existsSync(join(root, "pnpm-lock.yaml"))) packageManager = "pnpm";
1321
+ else if (existsSync(join(root, "yarn.lock"))) packageManager = "yarn";
1322
+ else if (existsSync(join(root, "bun.lock")) || existsSync(join(root, "bun.lockb"))) packageManager = "bun";
1323
+ else if (existsSync(join(root, "pnpm-workspace.yaml"))) packageManager = "pnpm";
1324
+ else {
1325
+ const field = parsePackageManagerField(pkg);
1326
+ if (field === "pnpm" || field === "yarn" || field === "bun") packageManager = field;
1327
+ else packageManager = "npm";
1328
+ }
1329
+ const paths = readProjectPaths(root);
1330
+ return {
1331
+ hasTypescript,
1332
+ hasTsconfig: existsSync(join(root, "tsconfig.json")),
1333
+ hasRoutes: existsSync(paths.routesDir),
1334
+ hasMigrations: existsSync(paths.migrationsDir) || existsSync(join(root, "migrations")),
1335
+ packageManager,
1336
+ typescriptWanted: hasTypescript
1337
+ };
1338
+ }
1339
+ function findViteConfig(root) {
1340
+ return VITE_CONFIG_FILES.find((file) => existsSync(join(root, file)));
1341
+ }
1342
+ function hasDrizzleSchema(root) {
1343
+ const paths = readProjectPaths(root);
1344
+ return existsSync(paths.schemaFile) || existsSync(paths.schemaDir);
1345
+ }
1346
+ function detectScaffoldFramework(root) {
1347
+ const pkg = readPackageJson(root);
1348
+ if (!pkg) return;
1349
+ return detectScaffoldFrameworkFromDependencies({
1350
+ ...asRecord(pkg.dependencies) ?? {},
1351
+ ...asRecord(pkg.devDependencies) ?? {}
1352
+ });
1353
+ }
1354
+ const DEPENDENCY_FIELDS = [
1355
+ "dependencies",
1356
+ "devDependencies",
1357
+ "peerDependencies",
1358
+ "optionalDependencies"
1359
+ ];
1360
+ /** The first declared spec for `packageName`, in `DEPENDENCY_FIELDS` order. */
1361
+ function resolveScaffoldDependencySpec(root, packageName, fallbackVersion) {
1362
+ const pkg = readPackageJson(root);
1363
+ for (const field of DEPENDENCY_FIELDS) {
1364
+ const spec = asRecord(pkg?.[field])?.[packageName];
1365
+ if (typeof spec === "string") return spec || fallbackVersion;
1366
+ }
1367
+ return fallbackVersion;
1368
+ }
1369
+ function defaultPackageName(root) {
1370
+ return basename(root).toLowerCase().replace(/[^a-z0-9-]/g, "-") || "my-app";
1371
+ }
1372
+ function setupTsconfig(root, state, framework) {
1373
+ const tsconfigPath = join(root, "tsconfig.json");
1374
+ if (state.hasTsconfig) {
1375
+ let tsconfig;
1376
+ try {
1377
+ const parsed = parseJsoncFile(tsconfigPath);
1378
+ if (!parsed) throw new SyntaxError("Failed to parse tsconfig.json");
1379
+ tsconfig = parsed;
1380
+ } catch {
1381
+ log.warn("Could not parse tsconfig.json, skipping");
1382
+ return;
1383
+ }
1384
+ let updated = false;
1385
+ const rootPathBaseDir = effectiveConfigPathBaseDir(tsconfig, tsconfigPath);
1386
+ const existingPatch = collectTsconfigPatchFromConfig(tsconfig, tsconfigPath, root, rootPathBaseDir, /* @__PURE__ */ new Set());
1387
+ const bwfPatch = createBwfTsconfigPatch(root, rootPathBaseDir);
1388
+ const extendsValue = tsconfig.extends;
1389
+ const target = "./.bwf/tsconfig.json";
1390
+ if (!(extendsValue === target || Array.isArray(extendsValue) && extendsValue.includes(target))) {
1391
+ if (typeof extendsValue === "string") tsconfig.extends = [extendsValue, target];
1392
+ else if (Array.isArray(extendsValue)) tsconfig.extends = [...extendsValue, target];
1393
+ else tsconfig.extends = target;
1394
+ updated = true;
1395
+ log.step("Updated tsconfig.json — added extends .bwf/tsconfig.json");
1396
+ }
1397
+ const compilerOptions = asRecord(tsconfig.compilerOptions) ?? {};
1398
+ tsconfig.compilerOptions = compilerOptions;
1399
+ const types = Array.isArray(compilerOptions.types) ? compilerOptions.types.filter((value) => typeof value === "string") : [];
1400
+ if (!types.includes("@builtbyfriends/bwf/env")) {
1401
+ types.push("@builtbyfriends/bwf/env");
1402
+ updated = true;
1403
+ log.step("Updated tsconfig.json — added bwf/env to types");
1404
+ }
1405
+ const cfIdx = types.indexOf("@cloudflare/workers-types");
1406
+ if (cfIdx !== -1) {
1407
+ types.splice(cfIdx, 1);
1408
+ updated = true;
1409
+ log.step("Removed @cloudflare/workers-types from tsconfig types (included in bwf/env)");
1410
+ }
1411
+ compilerOptions.types = types;
1412
+ const existingFiles = uniqueStrings(existingPatch.files);
1413
+ if (existingFiles.length > 0 || Array.isArray(tsconfig.files)) {
1414
+ const files = uniqueStrings([...existingFiles, ...bwfPatch.files]);
1415
+ if (JSON.stringify(tsconfig.files) !== JSON.stringify(files)) {
1416
+ tsconfig.files = files;
1417
+ updated = true;
1418
+ log.step("Updated tsconfig.json — merged generated bwf type files");
1419
+ }
1420
+ }
1421
+ if (Object.keys(existingPatch.paths).length > 0 || asRecord(compilerOptions.paths) !== null) {
1422
+ const paths = { ...existingPatch.paths };
1423
+ mergePathMaps(paths, bwfPatch.paths);
1424
+ const existingPaths = readPaths(compilerOptions.paths);
1425
+ if (JSON.stringify(existingPaths) !== JSON.stringify(paths)) {
1426
+ compilerOptions.paths = paths;
1427
+ updated = true;
1428
+ log.step("Updated tsconfig.json — merged generated bwf path aliases");
1429
+ }
1430
+ }
1431
+ if (updated) {
1432
+ const { extends: ext, ...rest } = tsconfig;
1433
+ const ordered = {
1434
+ extends: ext,
1435
+ ...rest
1436
+ };
1437
+ writeFileSync(tsconfigPath, JSON.stringify(ordered, null, 2) + "\n");
1438
+ } else log.step("tsconfig.json looks good");
1439
+ try {
1440
+ const pkgPath = join(root, "package.json");
1441
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1442
+ let pkgUpdated = false;
1443
+ if (pkg.dependencies?.["@cloudflare/workers-types"]) {
1444
+ delete pkg.dependencies["@cloudflare/workers-types"];
1445
+ pkgUpdated = true;
1446
+ }
1447
+ if (pkg.devDependencies?.["@cloudflare/workers-types"]) {
1448
+ delete pkg.devDependencies["@cloudflare/workers-types"];
1449
+ pkgUpdated = true;
1450
+ }
1451
+ if (pkgUpdated) {
1452
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
1453
+ log.step("Removed @cloudflare/workers-types from package.json (included in bwf/env)");
1454
+ log.info(`Re-run ${state.packageManager} install to update your lockfile`);
1455
+ }
1456
+ } catch {}
1457
+ } else {
1458
+ const tsconfig = {
1459
+ extends: "./.bwf/tsconfig.json",
1460
+ compilerOptions: {
1461
+ target: "ES2022",
1462
+ module: "ESNext",
1463
+ moduleResolution: "bundler",
1464
+ strict: true,
1465
+ esModuleInterop: true,
1466
+ skipLibCheck: true,
1467
+ types: ["@builtbyfriends/bwf/env"],
1468
+ ...getScaffoldTsconfigCompilerOptions(framework)
1469
+ },
1470
+ include: [
1471
+ "src",
1472
+ "routes",
1473
+ "middleware",
1474
+ "crons",
1475
+ "queues",
1476
+ "db"
1477
+ ]
1478
+ };
1479
+ writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + "\n");
1480
+ log.step("Created tsconfig.json");
1481
+ if (!state.hasTypescript) log.info("Don't forget to install typescript");
1482
+ }
1483
+ }
1484
+ function readProjectWranglerCompatDate(root) {
1485
+ const configPath = materializeCloudflareConfig(root);
1486
+ if (!existsSync(configPath)) return;
1487
+ try {
1488
+ const errors = [];
1489
+ const parsed = parse(readFileSync(configPath, "utf-8"), errors);
1490
+ if (errors.length === 0 && typeof parsed?.compatibility_date === "string") return parsed.compatibility_date;
1491
+ } catch {}
1492
+ }
1493
+ function ensureBwfWorkerCompatibilityDate(root) {
1494
+ const config = readConfig(root);
1495
+ const worker = asRecord(config.worker) ?? {};
1496
+ if (typeof worker.compatibility_date === "string" && worker.compatibility_date.length > 0) return;
1497
+ const compatibilityDate = readProjectWranglerCompatDate(root) ?? "2026-02-24";
1498
+ if (!canRewriteBwfProjectConfig(root)) {
1499
+ writeProvisionedWranglerConfig(root, { compatibilityDate });
1500
+ log.step("Pinned worker compatibility_date in bwf.lock.json");
1501
+ return;
1502
+ }
1503
+ config.worker = {
1504
+ ...worker,
1505
+ compatibility_date: compatibilityDate
1506
+ };
1507
+ writeBwfProjectConfig(root, config);
1508
+ log.step("Pinned worker compatibility_date in bwf.config.ts");
1509
+ }
1510
+ /** Write `dialect` to the config's `database`, keeping its casing. */
1511
+ function writeDatabaseDialect(root, config, dialect) {
1512
+ const next = { ...config };
1513
+ const database = databaseConfigValue(dialect, getDatabaseCasing(config));
1514
+ if (database === void 0) delete next.database;
1515
+ else next.database = database;
1516
+ writeBwfProjectConfig(root, next);
1517
+ }
1518
+ function clearConfiguredDatabase(root, messages) {
1519
+ const config = readConfig(root);
1520
+ if (getDatabaseDialect(config) === "sqlite") {
1521
+ log.info(messages.unchanged);
1522
+ return;
1523
+ }
1524
+ writeDatabaseDialect(root, config, "sqlite");
1525
+ log.step(messages.updated);
1526
+ }
1527
+ /** Remove `database` entirely: its casing alone still makes bwf serve `@builtbyfriends/bwf/db`. */
1528
+ function removeDatabaseConfig(root) {
1529
+ const config = readConfig(root);
1530
+ if (config.database === void 0) {
1531
+ log.info("No database configured yet");
1532
+ return;
1533
+ }
1534
+ const next = { ...config };
1535
+ delete next.database;
1536
+ writeBwfProjectConfig(root, next);
1537
+ log.step("Removed database config from bwf.config.ts");
1538
+ }
1539
+ function applyDatabaseDialect(root, dialect) {
1540
+ const config = readConfig(root);
1541
+ if (dialect === "postgresql") {
1542
+ if (getDatabaseDialect(config) === "postgresql") {
1543
+ log.info("PostgreSQL already configured in bwf.config.ts");
1544
+ return;
1545
+ }
1546
+ writeDatabaseDialect(root, config, "postgresql");
1547
+ log.step("Configured PostgreSQL in bwf.config.ts");
1548
+ return;
1549
+ }
1550
+ if (dialect === "mysql") {
1551
+ if (getDatabaseDialect(config) === "mysql") {
1552
+ log.info("MySQL already configured in bwf.config.ts");
1553
+ return;
1554
+ }
1555
+ writeDatabaseDialect(root, config, "mysql");
1556
+ log.step("Configured MySQL in bwf.config.ts");
1557
+ return;
1558
+ }
1559
+ clearConfiguredDatabase(root, {
1560
+ unchanged: "Using default D1 (SQLite) configuration",
1561
+ updated: "Updated bwf.config.ts to use the default D1 (SQLite) configuration"
1562
+ });
1563
+ }
1564
+ function detectDatabaseSetup(root) {
1565
+ const dialect = getDatabaseDialect(readConfig(root));
1566
+ if (dialect !== "sqlite") return dialect;
1567
+ if (hasDrizzleSchema(root) || existsSync(readProjectPaths(root).migrationsDir) || existsSync(join(root, "migrations"))) return "sqlite";
1568
+ return "none";
1569
+ }
1570
+ function applyDatabaseSetup(root, choice) {
1571
+ if (choice === "none") {
1572
+ removeDatabaseConfig(root);
1573
+ return;
1574
+ }
1575
+ applyDatabaseDialect(root, choice);
1576
+ }
1577
+ /**
1578
+ * A prompt cannot be answered when stdin is not a terminal, so fail with the
1579
+ * flag that answers it instead of exiting as if init succeeded.
1580
+ */
1581
+ function assertInteractive(flag, choices) {
1582
+ if (!process.stdin.isTTY) throw new Error(`init: Pass --${flag} (${choices.join(", ")}) when running without an interactive terminal.`);
1583
+ }
1584
+ async function promptStarterMode(starter) {
1585
+ if (starter) return starter;
1586
+ assertInteractive("starter", SCAFFOLD_STARTER_MODES);
1587
+ const choice = await select({
1588
+ message: "Choose a starter:",
1589
+ options: [
1590
+ {
1591
+ value: "sqlite",
1592
+ label: "D1 (SQLite)",
1593
+ hint: "Recommended starter. Scaffolds a React app with a DB-backed API route, schema, generated migration, and seed file."
1594
+ },
1595
+ {
1596
+ value: "postgresql",
1597
+ label: "PostgreSQL",
1598
+ hint: "Scaffolds the same starter with PostgreSQL, a generated migration, a seed file, and writes database: \"pg\" to bwf.config.ts."
1599
+ },
1600
+ {
1601
+ value: "mysql",
1602
+ label: "MySQL",
1603
+ hint: "Scaffolds the same starter with MySQL, a generated migration, a seed file, and writes database: \"mysql\" to bwf.config.ts."
1604
+ },
1605
+ {
1606
+ value: "spa",
1607
+ label: "React SPA only",
1608
+ hint: "No database or backend starter files yet; add routes/ and bwf features later."
1609
+ }
1610
+ ]
1611
+ });
1612
+ if (isCancel(choice) || typeof choice === "symbol") {
1613
+ cancel("Setup cancelled.");
1614
+ process.exit(0);
1615
+ }
1616
+ return choice;
1617
+ }
1618
+ async function promptScaffoldToolchain(toolchain) {
1619
+ if (toolchain) return toolchain;
1620
+ assertInteractive("toolchain", SCAFFOLD_TOOLCHAIN_OPTIONS.map((option) => option.value));
1621
+ const choice = await select({
1622
+ message: "Choose a scaffold toolchain:",
1623
+ initialValue: "vite-plus",
1624
+ options: [...SCAFFOLD_TOOLCHAIN_OPTIONS]
1625
+ });
1626
+ if (isCancel(choice)) {
1627
+ cancel("Setup cancelled.");
1628
+ process.exit(0);
1629
+ }
1630
+ return choice;
1631
+ }
1632
+ async function promptDatabaseSetup(root) {
1633
+ const currentSetup = detectDatabaseSetup(root);
1634
+ const choice = await select({
1635
+ message: "Choose a database setup for this project:",
1636
+ initialValue: currentSetup === "none" ? "sqlite" : currentSetup,
1637
+ options: [
1638
+ {
1639
+ value: "sqlite",
1640
+ label: currentSetup === "sqlite" ? "D1 (SQLite) [current]" : "D1 (SQLite)",
1641
+ hint: "Zero-config and fully managed by bwf; best for prototyping and read-heavy apps."
1642
+ },
1643
+ {
1644
+ value: "postgresql",
1645
+ label: currentSetup === "postgresql" ? "PostgreSQL [current]" : "PostgreSQL",
1646
+ hint: "Bring your own Postgres via Hyperdrive; best for write-heavy apps, complex queries, or existing infra."
1647
+ },
1648
+ {
1649
+ value: "mysql",
1650
+ label: currentSetup === "mysql" ? "MySQL [current]" : "MySQL",
1651
+ hint: "Bring your own MySQL via Hyperdrive; ideal for existing MySQL infrastructure and compatible providers."
1652
+ },
1653
+ {
1654
+ value: "none",
1655
+ label: "No Database Yet",
1656
+ hint: "Skip database setup for now. You can add D1, PostgreSQL, or MySQL later as your app grows."
1657
+ }
1658
+ ]
1659
+ });
1660
+ if (isCancel(choice)) {
1661
+ cancel("Setup cancelled.");
1662
+ process.exit(0);
1663
+ }
1664
+ return choice;
1665
+ }
1666
+ async function promptDeploymentPlatform(root, deploy) {
1667
+ if (deploy) {
1668
+ writeDeploymentPlatform(root, deploy);
1669
+ return deploy;
1670
+ }
1671
+ assertInteractive("deploy", DEPLOYMENT_PLATFORMS);
1672
+ const current = readDeploymentPlatform(root);
1673
+ const choice = await select({
1674
+ message: "Where should this project deploy?",
1675
+ initialValue: current ?? "cloudflare",
1676
+ options: [
1677
+ {
1678
+ value: "cloudflare",
1679
+ label: current === "cloudflare" ? "Cloudflare [current]" : "Cloudflare",
1680
+ hint: "Deploy to your own Cloudflare account. (default)"
1681
+ },
1682
+ {
1683
+ value: "nosam",
1684
+ label: current === "nosam" ? "bwf [current]" : "Nosam",
1685
+ hint: "Deploy to your company's bwf Platform."
1686
+ },
1687
+ {
1688
+ value: "none",
1689
+ label: current === "none" ? "Skip deployment setup [current]" : "Skip deployment setup",
1690
+ hint: "Use bwf locally or deploy another way."
1691
+ }
1692
+ ]
1693
+ });
1694
+ if (isCancel(choice) || typeof choice === "symbol") {
1695
+ cancel("Setup cancelled.");
1696
+ process.exit(0);
1697
+ }
1698
+ const platform = choice;
1699
+ writeDeploymentPlatform(root, platform);
1700
+ return platform;
1701
+ }
1702
+ async function ensureBwfPlatformConnection(root) {
1703
+ let selectedApiUrl = null;
1704
+ let promptedForPlatform = false;
1705
+ try {
1706
+ const { getApiUrl, getSiteDomain } = await import("./auth-aKyIWkdS.mjs");
1707
+ selectedApiUrl = getApiUrl(root);
1708
+ getSiteDomain(root);
1709
+ } catch (error) {
1710
+ if (!(error instanceof Error) || !error.message.includes("No bwf platform connected")) throw error;
1711
+ }
1712
+ if (!selectedApiUrl) {
1713
+ promptedForPlatform = true;
1714
+ const value = await text({
1715
+ message: "bwf platform API URL:",
1716
+ placeholder: "https://platform.example.com"
1717
+ });
1718
+ if (isCancel(value) || typeof value === "symbol") {
1719
+ cancel("Setup cancelled.");
1720
+ process.exit(0);
1721
+ }
1722
+ selectedApiUrl = String(value);
1723
+ }
1724
+ const discovery = await discoverPlatform(selectedApiUrl);
1725
+ saveDiscoveredPlatform(discovery);
1726
+ if (promptedForPlatform) log.step(`Connected to ${discovery.displayName} at ${formatUrl(discovery.apiUrl)}.`);
1727
+ return discovery;
1728
+ }
1729
+ async function setupCloudflareDeployment(root) {
1730
+ try {
1731
+ await connectCloudflare(root, true);
1732
+ } catch (error) {
1733
+ log.warn(error instanceof Error ? error.message : String(error));
1734
+ note("Run `bwf connect --platform cloudflare` when you want to finish Cloudflare setup.", "Cloudflare deployment");
1735
+ }
1736
+ }
1737
+ /** Get the dev command for the project. */
1738
+ function getDevCommand(root) {
1739
+ return formatProjectCommand(root, "vite dev");
1740
+ }
1741
+ function getNodeVersionLine(root) {
1742
+ return `${existsSync(join(root, ".node-version")) ? "node-version-file: .node-version" : "node-version: lts/*"}\n check-latest: true`;
1743
+ }
1744
+ function getWorkflowSetupSteps(root, pm) {
1745
+ const nodeVersion = getNodeVersionLine(root);
1746
+ switch (pm) {
1747
+ case "pnpm": return {
1748
+ setup: ` - uses: pnpm/action-setup@v5
1749
+ - uses: actions/setup-node@v6
1750
+ with:
1751
+ ${nodeVersion}
1752
+ cache: pnpm`,
1753
+ install: " - run: pnpm install --frozen-lockfile",
1754
+ runner: "pnpm exec bwf"
1755
+ };
1756
+ case "yarn": return {
1757
+ setup: ` - uses: actions/setup-node@v6
1758
+ with:
1759
+ ${nodeVersion}
1760
+ cache: yarn`,
1761
+ install: " - run: yarn install --immutable",
1762
+ runner: "yarn bwf"
1763
+ };
1764
+ case "bun": return {
1765
+ setup: ` - uses: oven-sh/setup-bun@v2
1766
+ - uses: actions/setup-node@v6
1767
+ with:
1768
+ ${nodeVersion}`,
1769
+ install: " - run: bun install --frozen-lockfile",
1770
+ runner: "bunx bwf"
1771
+ };
1772
+ default: return {
1773
+ setup: ` - uses: actions/setup-node@v6
1774
+ with:
1775
+ ${nodeVersion}
1776
+ cache: npm`,
1777
+ install: " - run: npm ci",
1778
+ runner: "npx bwf"
1779
+ };
1780
+ }
1781
+ }
1782
+ /**
1783
+ * The deploy workflow. bwf deploys exchange a GitHub OIDC token (`id-token: write`)
1784
+ * at deploy time, so no long-lived token is stored. Without a `slug`, the workflow
1785
+ * reads a `vars.BWF_PROJECT` repository variable.
1786
+ */
1787
+ function getWorkflowYaml(root, pm, slug, platform = "nosam", platformApiUrl) {
1788
+ const { setup, install, runner } = getWorkflowSetupSteps(root, pm);
1789
+ if (platform === "cloudflare") return `name: Deploy to Cloudflare
1790
+ on:
1791
+ push:
1792
+ branches: [main]
1793
+
1794
+ concurrency:
1795
+ group: nosam-cloudflare-deploy-\${{ github.repository }}-\${{ github.ref }}
1796
+ cancel-in-progress: true
1797
+
1798
+ permissions:
1799
+ contents: read
1800
+
1801
+ jobs:
1802
+ deploy:
1803
+ runs-on: ubuntu-latest
1804
+ steps:
1805
+ - uses: actions/checkout@v6
1806
+ ${setup}
1807
+ ${install}
1808
+ - name: Deploy
1809
+ env:
1810
+ # Add this scoped token at Settings → Secrets and variables → Actions.
1811
+ CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
1812
+ # Required only for PostgreSQL/MySQL provisioning and migrations.
1813
+ DATABASE_URL: \${{ secrets.DATABASE_URL }}
1814
+ # Account subdomain for workers.dev readiness when a version has no preview URL.
1815
+ CLOUDFLARE_WORKERS_SUBDOMAIN: \${{ vars.CLOUDFLARE_WORKERS_SUBDOMAIN }}
1816
+ # Required only when Cloudflare Access protects Worker readiness.
1817
+ CF_ACCESS_CLIENT_ID: \${{ secrets.CF_ACCESS_CLIENT_ID }}
1818
+ CF_ACCESS_CLIENT_SECRET: \${{ secrets.CF_ACCESS_CLIENT_SECRET }}
1819
+ run: ${runner} deploy --platform cloudflare
1820
+ `;
1821
+ if (!platformApiUrl) throw new Error("init: Connect to a bwf platform before generating a deployment workflow. Run `bwf connect <url>` first.");
1822
+ return `name: Deploy to bwf
1823
+ on:
1824
+ push:
1825
+ branches: [main]
1826
+
1827
+ # Latest push wins: cancel an in-flight deploy for the same repo+branch so a
1828
+ # newer commit is never overtaken by an older one. Keyed by repo + ref only —
1829
+ # workflow-level concurrency cannot read the \`env\` context, so BWF_PROJECT is
1830
+ # not used here (one repo+branch deploys to one project in this scaffold).
1831
+ concurrency:
1832
+ group: nosam-deploy-\${{ github.repository }}-\${{ github.ref }}
1833
+ cancel-in-progress: true
1834
+
1835
+ # id-token: write lets the job mint a GitHub OIDC token. No long-lived
1836
+ # BWF_TOKEN secret is stored — \`bwf deploy\` mints that OIDC token and
1837
+ # exchanges it for a short-lived, project-scoped deploy token at deploy time.
1838
+ permissions:
1839
+ id-token: write
1840
+ contents: read
1841
+
1842
+ env:
1843
+ # Override only when intentionally targeting another platform deployment.
1844
+ BWF_API_URL: \${{ vars.BWF_API_URL || '${platformApiUrl}' }}
1845
+ ${slug ? `BWF_PROJECT: ${slug}` : `# Set a BWF_PROJECT repository variable to your project slug
1846
+ # (Settings → Secrets and variables → Actions → Variables).
1847
+ BWF_PROJECT: \${{ vars.BWF_PROJECT }}`}
1848
+
1849
+ jobs:
1850
+ deploy:
1851
+ runs-on: ubuntu-latest
1852
+ steps:
1853
+ - uses: actions/checkout@v6
1854
+ ${setup}
1855
+ ${install}
1856
+ - name: Deploy
1857
+ run: |
1858
+ ${runner} connect "$BWF_API_URL" --no-login
1859
+ ${runner} deploy --platform bwf --project "$BWF_PROJECT"
1860
+ `;
1861
+ }
1862
+ function setupGithubActions(root, state, platform = "nosam", platformApiUrl) {
1863
+ const workflowDir = join(root, ".github", "workflows");
1864
+ const workflowPath = join(workflowDir, "bwf-deploy.yml");
1865
+ if (existsSync(workflowPath)) {
1866
+ log.warn("bwf-deploy.yml already exists, skipping");
1867
+ return;
1868
+ }
1869
+ const slug = readProjectConfig(root)?.slug ?? null;
1870
+ mkdirSync(workflowDir, { recursive: true });
1871
+ writeFileSync(workflowPath, getWorkflowYaml(root, state.packageManager, slug, platform, platformApiUrl));
1872
+ log.step("Created .github/workflows/bwf-deploy.yml");
1873
+ if (platform === "cloudflare") note("Pushes to main will deploy through the same readiness-gated Cloudflare path.\nAdd a scoped CLOUDFLARE_API_TOKEN repository secret; PostgreSQL/MySQL apps also need DATABASE_URL.\nKeep cloudflare.account_id in bwf.config.ts.", "GitHub Actions Cloudflare deploy");
1874
+ else if (slug) note(`Pushes to main will build and deploy "${slug}" via GitHub OIDC — no token to store.\nConnect the repo to your project in the bwf dashboard to authorize it.`, "GitHub Actions OIDC deploy");
1875
+ else note("Pushes to main will build and deploy via GitHub OIDC — no token to store.\nSet a BWF_PROJECT repository variable (Settings → Secrets and variables → Actions → Variables)\nto your project slug, and connect the repo to your project in the bwf dashboard.", "GitHub Actions OIDC deploy");
1876
+ }
1877
+ /**
1878
+ * Replace the `vars.BWF_PROJECT` placeholder in `bwf-deploy.yml` with a slug
1879
+ * linked after the workflow was written. Returns false when there is none.
1880
+ */
1881
+ function patchWorkflowProjectSlug(root, slug) {
1882
+ const workflowPath = join(root, ".github", "workflows", "bwf-deploy.yml");
1883
+ if (!existsSync(workflowPath)) return false;
1884
+ const yaml = readFileSync(workflowPath, "utf-8");
1885
+ const placeholderBlock = " # Set a BWF_PROJECT repository variable to your project slug\n # (Settings → Secrets and variables → Actions → Variables).\n BWF_PROJECT: ${{ vars.BWF_PROJECT }}";
1886
+ if (!yaml.includes(placeholderBlock)) return false;
1887
+ writeFileSync(workflowPath, yaml.replace(placeholderBlock, ` BWF_PROJECT: ${slug}`));
1888
+ log.step(`Set BWF_PROJECT: ${slug} in .github/workflows/bwf-deploy.yml`);
1889
+ return true;
1890
+ }
1891
+ function writeFileIfMissing(root, filePath, content) {
1892
+ const fullPath = join(root, filePath);
1893
+ if (existsSync(fullPath)) return;
1894
+ mkdirSync(dirname(fullPath), { recursive: true });
1895
+ writeFileSync(fullPath, content);
1896
+ log.step(`Created ${filePath}`);
1897
+ }
1898
+ function ensureGitignore(root) {
1899
+ const existed = existsSync(join(root, ".gitignore"));
1900
+ if (ensureGitignoreLines(root, SCAFFOLD_GITIGNORE_LINES).length > 0) log.step(existed ? "Updated .gitignore with bwf defaults" : "Created .gitignore");
1901
+ }
1902
+ /** Removes each block-style top-level `key:` block; `removed` holds its non-blank lines. */
1903
+ function removeTopLevelYamlBlock(yaml, key) {
1904
+ const lines = yaml.split(/\r?\n/);
1905
+ const next = [];
1906
+ const removed = [];
1907
+ for (let i = 0; i < lines.length; i += 1) {
1908
+ const line = lines[i];
1909
+ if (!new RegExp(`^${key}:\\s*(?:#.*)?$`).test(line)) {
1910
+ next.push(line);
1911
+ continue;
1912
+ }
1913
+ i += 1;
1914
+ while (i < lines.length && (lines[i].trim() === "" || /^(?:\s|-(?:\s|$))/.test(lines[i]))) {
1915
+ if (lines[i].trim() !== "") removed.push(lines[i]);
1916
+ i += 1;
1917
+ }
1918
+ i -= 1;
1919
+ }
1920
+ return {
1921
+ yaml: next.join("\n"),
1922
+ removed
1923
+ };
1924
+ }
1925
+ function pnpmAllowBuildsEntryName(line) {
1926
+ return /^\s+(?!#)(["']?)(.+?)\1\s*:(?:\s|$)/.exec(line)?.[2];
1927
+ }
1928
+ /**
1929
+ * Keeps the existing `allowBuilds` entries as written, approves the legacy
1930
+ * `onlyBuiltDependencies` list, and adds each bwf default that is missing.
1931
+ */
1932
+ function pnpmAllowBuildsYaml(entries, legacyList) {
1933
+ const legacy = legacyList.flatMap((line) => {
1934
+ const name = /^\s*-\s+(["']?)(.+?)\1\s*(?:#.*)?$/.exec(line)?.[2];
1935
+ return name === void 0 ? [] : [name];
1936
+ });
1937
+ const decided = /* @__PURE__ */ new Set([...legacy, ...PNPM_BUILD_DEFAULTS.map(([name]) => name)]);
1938
+ const lines = entries.filter((line) => {
1939
+ const name = pnpmAllowBuildsEntryName(line);
1940
+ return !(name !== void 0 && decided.has(name) && line.includes(PNPM_BUILD_PLACEHOLDER));
1941
+ });
1942
+ const names = new Set(lines.map((line) => pnpmAllowBuildsEntryName(line)));
1943
+ const firstEntry = lines.find((line) => pnpmAllowBuildsEntryName(line) !== void 0);
1944
+ const indent = /^\s+/.exec(firstEntry ?? "")?.[0] ?? " ";
1945
+ const additions = [...legacy.map((name) => [name, true]), ...PNPM_BUILD_DEFAULTS];
1946
+ for (const [name, value] of additions) if (!names.has(name)) {
1947
+ names.add(name);
1948
+ lines.push(`${indent}${/^[\w.-]+$/.test(name) ? name : JSON.stringify(name)}: ${value}`);
1949
+ }
1950
+ return ["allowBuilds:", ...lines].join("\n");
1951
+ }
1952
+ function insertPnpmAllowBuilds(yaml, allowBuilds) {
1953
+ const trimmed = yaml.trim();
1954
+ if (trimmed === "") return `${allowBuilds}\n`;
1955
+ const lines = trimmed.split(/\r?\n/);
1956
+ const packagesIndex = lines.findIndex((line) => /^packages:\s*(?:#.*)?$/.test(line));
1957
+ if (packagesIndex === -1) return `${trimmed}\n\n${allowBuilds}\n`;
1958
+ let insertIndex = packagesIndex + 1;
1959
+ while (insertIndex < lines.length && (lines[insertIndex].trim() === "" || /^\s/.test(lines[insertIndex]))) insertIndex += 1;
1960
+ lines.splice(insertIndex, 0, "", ...allowBuilds.split("\n"), "");
1961
+ return `${lines.join("\n").replace(/\n{3,}/g, "\n\n")}\n`;
1962
+ }
1963
+ function resolvePnpmConfigRoot(root, pkg) {
1964
+ if (existsSync(join(root, "pnpm-workspace.yaml")) || existsSync(join(root, "pnpm-lock.yaml")) || parsePackageManagerField(pkg) === "pnpm") return root;
1965
+ const workspaceRoot = findWorkspaceRoot(root);
1966
+ if (workspaceRoot !== void 0 && hasAncestorPnpmMarkers(root)) return workspaceRoot;
1967
+ return root;
1968
+ }
1969
+ function ensurePnpmAllowBuilds(root, pkg) {
1970
+ const configRoot = resolvePnpmConfigRoot(root, pkg);
1971
+ const workspacePath = join(configRoot, "pnpm-workspace.yaml");
1972
+ const displayPath = configRoot === root ? "pnpm-workspace.yaml" : relative(root, workspacePath);
1973
+ const before = existsSync(workspacePath) ? readFileSync(workspacePath, "utf-8") : "";
1974
+ const inline = /^allowBuilds:[ \t]*([^\s#].*)$/m.exec(before)?.[1];
1975
+ if (inline !== void 0) {
1976
+ const missing = PNPM_BUILD_DEFAULTS.filter(([name]) => !new RegExp(`[{,]\\s*["']?${name}["']?\\s*:`).test(inline));
1977
+ if (missing.length > 0) log.warn(`Add ${missing.map(([name, value]) => `${name}: ${value}`).join(", ")} to allowBuilds in ${displayPath}. bwf only edits allowBuilds when each entry is on its own line.`);
1978
+ return;
1979
+ }
1980
+ const legacy = removeTopLevelYamlBlock(before, "onlyBuiltDependencies");
1981
+ const current = removeTopLevelYamlBlock(legacy.yaml, "allowBuilds");
1982
+ const after = insertPnpmAllowBuilds(current.yaml, pnpmAllowBuildsYaml(current.removed, legacy.removed));
1983
+ if (after !== before) {
1984
+ writeFileSync(workspacePath, after);
1985
+ log.step(`Updated ${displayPath} with approved builds`);
1986
+ }
1987
+ }
1988
+ function installProjectDependencies(root, packageManager) {
1989
+ const pkg = readPackageJson(root);
1990
+ const useVitePlus = pkg !== null && hasPackageDependency(pkg, "vite-plus");
1991
+ const installer = useVitePlus ? "vp" : packageManager;
1992
+ log.step(`Installing dependencies with ${installer}`);
1993
+ let command = installer;
1994
+ let args = useVitePlus || packageManager === "pnpm" ? ["install", "--no-frozen-lockfile"] : ["install"];
1995
+ if (useVitePlus) {
1996
+ let localBin;
1997
+ try {
1998
+ const require = createRequire(join(root, "package.json"));
1999
+ localBin = join(dirname(require.resolve("vite-plus/package.json")), "bin/vp");
2000
+ } catch {}
2001
+ if (localBin) {
2002
+ command = process.execPath;
2003
+ args = [localBin, ...args];
2004
+ } else if (spawnSync("vp", ["--version"], {
2005
+ cwd: root,
2006
+ stdio: "ignore",
2007
+ shell: process.platform === "win32",
2008
+ timeout: 5e3
2009
+ }).status !== 0) {
2010
+ command = "npx";
2011
+ const packageArg = `--package=vite-plus@${SCAFFOLD_VITE_PLUS_DEV_DEPENDENCIES["vite-plus"]}`;
2012
+ args = [
2013
+ "--yes",
2014
+ process.platform === "win32" ? `"${packageArg}"` : packageArg,
2015
+ "vp",
2016
+ ...args
2017
+ ];
2018
+ }
2019
+ }
2020
+ const result = spawnSync(command, args, {
2021
+ cwd: root,
2022
+ stdio: "inherit",
2023
+ shell: command !== process.execPath && process.platform === "win32"
2024
+ });
2025
+ if (result.error) throw result.error;
2026
+ if (result.status !== 0) throw new Error(`${installer} install failed with exit code ${result.status ?? "unknown"}`);
2027
+ log.step(`Installed dependencies with ${installer}`);
2028
+ }
2029
+ function generateStarterMigration(root, starterMode) {
2030
+ const dialect = starterMode;
2031
+ const configPath = writeDrizzleConfig(root, PLACEHOLDER_DB_URL[dialect], dialect);
2032
+ const rollBack = snapshotDrizzleOutputs(readProjectPaths(root).migrationsDir);
2033
+ log.step("Generating initial Drizzle migration");
2034
+ const result = spawnSync(process.execPath, [
2035
+ drizzleKitBin,
2036
+ "generate",
2037
+ "--config",
2038
+ configPath
2039
+ ], {
2040
+ cwd: root,
2041
+ stdio: "pipe",
2042
+ encoding: "utf-8",
2043
+ env: buildDrizzleKitSpawnEnv(root)
2044
+ });
2045
+ if (result.error || result.status !== 0) rollBack();
2046
+ if (result.error) throw result.error;
2047
+ if (result.status !== 0) {
2048
+ const detail = [result.stderr, result.stdout].filter(Boolean).join("\n").trim();
2049
+ throw new Error(["Failed to generate the starter database migration.", ...detail ? [detail] : []].join("\n\n"));
2050
+ }
2051
+ log.step("Generated initial Drizzle migration");
2052
+ }
2053
+ function scaffoldSpaApp(root, packageManager, framework, starterMode, toolchain) {
2054
+ const packageJsonPath = join(root, "package.json");
2055
+ const template = createSpaStarterTemplate({
2056
+ framework,
2057
+ starterMode,
2058
+ toolchain,
2059
+ bwfPackageSpec: resolveScaffoldDependencySpec(root, "@builtbyfriends/bwf", getOwnVersion())
2060
+ });
2061
+ let pkg = {};
2062
+ if (existsSync(packageJsonPath)) try {
2063
+ pkg = asRecord(JSON.parse(readFileSync(packageJsonPath, "utf-8"))) ?? {};
2064
+ } catch {
2065
+ throw new Error("Could not parse package.json in empty project");
2066
+ }
2067
+ const fallbackName = defaultPackageName(root);
2068
+ if (!pkg.name || typeof pkg.name !== "string") pkg.name = fallbackName;
2069
+ if (pkg.private === void 0) pkg.private = true;
2070
+ if (!pkg.type) pkg.type = "module";
2071
+ const scripts = asRecord(pkg.scripts) ?? {};
2072
+ pkg.scripts = scripts;
2073
+ for (const [name, command] of Object.entries(template.scripts)) {
2074
+ const existing = scripts[name];
2075
+ if (typeof existing !== "string" || isStarterScriptCommand(existing)) scripts[name] = command;
2076
+ }
2077
+ const dependencies = asRecord(pkg.dependencies) ?? {};
2078
+ const devDependencies = asRecord(pkg.devDependencies) ?? {};
2079
+ pkg.dependencies = dependencies;
2080
+ pkg.devDependencies = devDependencies;
2081
+ let dependencyAdded = false;
2082
+ const ensureDependency = (group, name, fallbackVersion) => {
2083
+ const otherGroup = group === "dependencies" ? "devDependencies" : "dependencies";
2084
+ const targetGroup = group === "dependencies" ? dependencies : devDependencies;
2085
+ const sourceGroup = otherGroup === "dependencies" ? dependencies : devDependencies;
2086
+ const existing = targetGroup[name] ?? sourceGroup[name];
2087
+ const selectToolchainVersion = toolchain === "vite-plus" && (name === "vite" || name === "vite-plus");
2088
+ if (!targetGroup[name] || selectToolchainVersion && existing !== fallbackVersion) {
2089
+ targetGroup[name] = selectToolchainVersion ? fallbackVersion : existing ?? fallbackVersion;
2090
+ dependencyAdded = true;
2091
+ }
2092
+ if (sourceGroup[name]) {
2093
+ delete sourceGroup[name];
2094
+ dependencyAdded = true;
2095
+ }
2096
+ };
2097
+ for (const [name, version] of Object.entries(template.dependencies)) ensureDependency("dependencies", name, version);
2098
+ for (const [name, version] of Object.entries(template.devDependencies)) ensureDependency("devDependencies", name, version);
2099
+ if (packageManager === "pnpm" || isPnpmProject(root, pkg)) ensurePnpmAllowBuilds(root, pkg);
2100
+ if (toolchain === "vite-plus") configureVitePlusScaffold(packageManager === "pnpm" ? resolvePnpmConfigRoot(root, pkg) : root, packageManager, pkg);
2101
+ writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + "\n");
2102
+ log.step("Updated package.json with starter scripts and dependencies");
2103
+ for (const [filePath, content] of Object.entries(template.files)) writeFileIfMissing(root, filePath, content);
2104
+ ensureGitignore(root);
2105
+ if (starterMode !== "spa") applyDatabaseDialect(root, starterMode);
2106
+ if (starterMode === "postgresql") {
2107
+ const devCommand = getDevCommand(root);
2108
+ note(`Add DATABASE_URL to .env before running \`${devCommand}\`.\nbwf uses that direct connection for local PostgreSQL development.`, "PostgreSQL local dev");
2109
+ } else if (starterMode === "mysql") {
2110
+ const devCommand = getDevCommand(root);
2111
+ note(`Add DATABASE_URL to .env before running \`${devCommand}\`.\nbwf uses that direct connection for local MySQL development.`, "MySQL local dev");
2112
+ }
2113
+ return dependencyAdded;
2114
+ }
2115
+ /** Returns whether a dependency was added. */
2116
+ function ensureExistingProjectPackage(root, options = {}) {
2117
+ const packageJsonPath = join(root, "package.json");
2118
+ const bwfSpec = resolveScaffoldDependencySpec(root, "@builtbyfriends/bwf", getOwnVersion());
2119
+ const plainViteSetup = options.plainViteSetup ?? true;
2120
+ let pkg = {};
2121
+ let existedBefore = false;
2122
+ if (existsSync(packageJsonPath)) {
2123
+ existedBefore = true;
2124
+ try {
2125
+ pkg = asRecord(JSON.parse(readFileSync(packageJsonPath, "utf-8"))) ?? {};
2126
+ } catch {
2127
+ throw new Error("Could not parse package.json while configuring bwf");
2128
+ }
2129
+ }
2130
+ const fallbackName = defaultPackageName(root);
2131
+ let changed = !existedBefore;
2132
+ let dependencyAdded = false;
2133
+ if (!pkg.name || typeof pkg.name !== "string") {
2134
+ pkg.name = fallbackName;
2135
+ changed = true;
2136
+ }
2137
+ if (!existedBefore && pkg.private === void 0) {
2138
+ pkg.private = true;
2139
+ changed = true;
2140
+ }
2141
+ if (!existedBefore && !pkg.type) {
2142
+ pkg.type = "module";
2143
+ changed = true;
2144
+ }
2145
+ if (plainViteSetup) {
2146
+ const scripts = asRecord(pkg.scripts) ?? {};
2147
+ pkg.scripts = scripts;
2148
+ if (typeof scripts.dev !== "string") {
2149
+ scripts.dev = "vite";
2150
+ changed = true;
2151
+ }
2152
+ if (typeof scripts.build !== "string") {
2153
+ scripts.build = "vite build";
2154
+ changed = true;
2155
+ }
2156
+ }
2157
+ const devDependencies = asRecord(pkg.devDependencies) ?? {};
2158
+ pkg.devDependencies = devDependencies;
2159
+ if (!hasPackageDependency(pkg, "@builtbyfriends/bwf", DEPENDENCY_FIELDS)) {
2160
+ devDependencies["@builtbyfriends/bwf"] = bwfSpec;
2161
+ changed = true;
2162
+ dependencyAdded = true;
2163
+ }
2164
+ if (plainViteSetup && !hasPackageDependency(pkg, "vite", DEPENDENCY_FIELDS)) {
2165
+ devDependencies.vite = SCAFFOLD_BASE_DEV_DEPENDENCIES.vite;
2166
+ changed = true;
2167
+ dependencyAdded = true;
2168
+ }
2169
+ if (isPnpmProject(root, pkg)) ensurePnpmAllowBuilds(root, pkg);
2170
+ if (changed) {
2171
+ writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + "\n");
2172
+ log.step(existedBefore ? plainViteSetup ? "Updated package.json with bwf dependencies and Vite scripts" : "Updated package.json with bwf dependency" : plainViteSetup ? "Created package.json with bwf dependencies and Vite scripts" : "Created package.json with bwf dependency");
2173
+ }
2174
+ return dependencyAdded;
2175
+ }
2176
+ function getBasicBwfViteConfig() {
2177
+ return `import { defineConfig } from "vite";
2178
+ import { bwfPlugin } from "@builtbyfriends/bwf";
2179
+
2180
+ export default defineConfig({
2181
+ plugins: [bwfPlugin()],
2182
+ });
2183
+ `;
2184
+ }
2185
+ function getGeneratedViteConfigPath(root) {
2186
+ return readPackageJson(root)?.type === "module" ? "vite.config.ts" : "vite.config.mts";
2187
+ }
2188
+ function noteManualViteConfigSetup(configPath) {
2189
+ note(`Could not safely update ${configPath ?? "your Vite config"} automatically.\n\nAdd \`bwfPlugin()\` to the top-level Vite plugins array:\n\nimport { bwfPlugin } from "@builtbyfriends/bwf";\n\nexport default defineConfig({\n plugins: [bwfPlugin()],\n});`, "Manual Vite config step");
2190
+ }
2191
+ function ensureExistingProjectViteConfig(root) {
2192
+ const configPath = findViteConfig(root);
2193
+ if (!configPath) {
2194
+ writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicBwfViteConfig());
2195
+ return;
2196
+ }
2197
+ const fullPath = join(root, configPath);
2198
+ const original = readFileSync(fullPath, "utf-8");
2199
+ const updated = patchViteConfigWithBwfPlugin(configPath, original);
2200
+ if (updated === void 0) {
2201
+ noteManualViteConfigSetup(configPath);
2202
+ return;
2203
+ }
2204
+ if (updated === original) {
2205
+ log.info(`${configPath} already includes bwfPlugin()`);
2206
+ return;
2207
+ }
2208
+ writeFileSync(fullPath, updated);
2209
+ log.step(`Added bwfPlugin() to ${configPath}`);
2210
+ }
2211
+ /** Returns whether a dependency was added. */
2212
+ function setupExistingProject(root) {
2213
+ log.info("Existing project detected. Configuring bwf...");
2214
+ const dependencyAdded = ensureExistingProjectPackage(root, { plainViteSetup: true });
2215
+ ensureExistingProjectViteConfig(root);
2216
+ return dependencyAdded;
2217
+ }
2218
+ /** The demo `posts` table for the database dialect that init configured. */
2219
+ function demoSchemaSource(dialect) {
2220
+ if (dialect === "postgresql") return `import { pgTable, serial, text, timestamp } from "@builtbyfriends/bwf/schema-pg";
2221
+
2222
+ export const posts = pgTable("posts", {
2223
+ id: serial("id").primaryKey(),
2224
+ title: text("title").notNull(),
2225
+ body: text("body").notNull(),
2226
+ createdAt: timestamp("created_at").notNull().defaultNow(),
2227
+ });
2228
+ `;
2229
+ if (dialect === "mysql") return `import { int, mysqlTable, text, timestamp } from "@builtbyfriends/bwf/schema-mysql";
2230
+
2231
+ export const posts = mysqlTable("posts", {
2232
+ id: int("id").autoincrement().primaryKey(),
2233
+ title: text("title").notNull(),
2234
+ body: text("body").notNull(),
2235
+ createdAt: timestamp("created_at").notNull().defaultNow(),
2236
+ });
2237
+ `;
2238
+ return `import { sql } from "@builtbyfriends/bwf/db";
2239
+ import { integer, sqliteTable, text } from "@builtbyfriends/bwf/schema-d1";
2240
+
2241
+ export const posts = sqliteTable("posts", {
2242
+ id: integer("id").primaryKey({ autoIncrement: true }),
2243
+ title: text("title").notNull(),
2244
+ body: text("body").notNull(),
2245
+ createdAt: text("created_at").notNull().default(sql\`(datetime('now'))\`),
2246
+ });
2247
+ `;
2248
+ }
2249
+ function demoFiles(root) {
2250
+ const paths = readProjectPaths(root);
2251
+ return {
2252
+ schema: paths.schemaFile,
2253
+ route: join(paths.routesDir, "api", "posts.ts"),
2254
+ client: join(paths.sourceDir ? paths.sourceRoot : join(root, "src"), "demo.ts")
2255
+ };
2256
+ }
2257
+ /**
2258
+ * Scaffolds the "SQL → types → handler → fetch" demo into an existing project.
2259
+ * `setupExistingProject` has already declared `nosam` in `package.json`.
2260
+ * The caller skips the demo when any of its files exists, so these writes never replace user code.
2261
+ */
2262
+ function scaffoldDemo(root, dialect) {
2263
+ const devCommand = getDevCommand(root);
2264
+ const paths = readProjectPaths(root);
2265
+ const files = demoFiles(root);
2266
+ mkdirSync(paths.dbDir, { recursive: true });
2267
+ writeFileSync(files.schema, demoSchemaSource(dialect));
2268
+ log.step("Created db/schema.ts");
2269
+ mkdirSync(join(paths.routesDir, "api"), { recursive: true });
2270
+ writeFileSync(files.route, `import { defineHandler } from "@builtbyfriends/bwf";
2271
+ import { db } from "@builtbyfriends/bwf/db";
2272
+ import { posts } from "@schema";
2273
+
2274
+ // GET /api/posts — returns all posts, fully typed from migration schema
2275
+ export const GET = defineHandler(async () => {
2276
+ return db.select().from(posts);
2277
+ });
2278
+ `);
2279
+ log.step("Created routes/api/posts.ts");
2280
+ ensureProjectTsconfig(root, void 0, true, true, { paths });
2281
+ mkdirSync(dirname(files.client), { recursive: true });
2282
+ writeFileSync(files.client, `import { fetch } from "@builtbyfriends/bwf/client";
2283
+
2284
+ // Fully typed: response type is inferred from the GET handler's return type,
2285
+ // which is derived from the migration schema. No manual types needed.
2286
+ const posts = await fetch("/api/posts");
2287
+
2288
+ console.log(posts);
2289
+ // posts[0].title ← string (type-checked)
2290
+ // posts[0].body ← string (type-checked)
2291
+ // posts[0].nope ← TypeScript error
2292
+ `);
2293
+ log.step("Created src/demo.ts");
2294
+ note(`SQL migration → DB types → Route handler → Route types → Typed fetch
2295
+
2296
+ Run \`${devCommand}\` and open src/demo.ts to see the types in action.\nTry changing the migration or handler — types update automatically.`, "Type Safety Demo");
2297
+ }
2298
+ const MARKER_VERSION_SOURCE = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?` + String.raw`(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?`;
2299
+ const MARKER_CLOSE = "<!--/injected-by-nosam-->";
2300
+ const MARKER_BLOCK_RE = new RegExp(String.raw`^<!--injected-by-nosam-v${MARKER_VERSION_SOURCE}-->\r?\n[\s\S]*?^<!--\/injected-by-nosam-->\r?$`, "m");
2301
+ async function injectAgentBlock(root, newProject) {
2302
+ const filePath = "AGENTS.md";
2303
+ const fullPath = join(root, filePath);
2304
+ const version = getOwnVersion();
2305
+ const template = readFileSync(join(getPackageDir(), "AGENTS_TEMPLATE.md"), "utf-8");
2306
+ const block = `${`<!--injected-by-nosam-v${version}-->`}\n${template}\n${MARKER_CLOSE}`;
2307
+ const existing = existsSync(fullPath) ? readFileSync(fullPath, "utf-8") : null;
2308
+ const managedBlock = existing?.match(MARKER_BLOCK_RE);
2309
+ if (managedBlock?.[0] === block) {
2310
+ log.info(`${filePath} already has bwf instructions (v${version})`);
2311
+ return;
2312
+ }
2313
+ if (!newProject) {
2314
+ if (process.env.CI || !process.stdin.isTTY) {
2315
+ log.info(`Skipping ${filePath} setup without an interactive terminal; read node_modules/@builtbyfriends/bwf/docs/.`);
2316
+ return;
2317
+ }
2318
+ const accepted = await confirm({
2319
+ message: managedBlock ? "Update bwf instructions in AGENTS.md?" : existing !== null ? "Append bwf instructions to AGENTS.md?" : "Create AGENTS.md with bwf instructions?",
2320
+ initialValue: true
2321
+ });
2322
+ if (isCancel(accepted)) {
2323
+ cancel("Setup cancelled.");
2324
+ process.exit(0);
2325
+ }
2326
+ if (!accepted) return;
2327
+ }
2328
+ if (existing !== null) {
2329
+ if (managedBlock) {
2330
+ const updated = existing.replace(MARKER_BLOCK_RE, block);
2331
+ writeFileSync(fullPath, updated);
2332
+ log.step(`Updated bwf instructions in ${filePath}`);
2333
+ } else {
2334
+ const separator = existing.endsWith("\n") ? "\n" : "\n\n";
2335
+ writeFileSync(fullPath, existing + separator + block + "\n");
2336
+ log.step(`Added bwf instructions to ${filePath}`);
2337
+ }
2338
+ } else {
2339
+ writeFileSync(fullPath, block + "\n");
2340
+ log.step(`Created ${filePath} with bwf instructions`);
2341
+ }
2342
+ }
2343
+ async function runInitCommand(root, initArgs) {
2344
+ console.log();
2345
+ const targeted = Boolean(initArgs && (initArgs.tsconfig || initArgs.github));
2346
+ if (!targeted) root = await resolveInitRoot(root);
2347
+ const newProject = isScaffoldableEmptyProject(root) && !existsSync(join(root, "AGENTS.md"));
2348
+ if (migrateLegacyBwfConfig(root)) log.step("Migrated project configuration to bwf.config.ts. Commit bwf.config.ts and bwf.lock.json.");
2349
+ const workspaceSubpackage = isInsideWorkspaceSubpackage(root);
2350
+ if (workspaceSubpackage && initArgs?.git !== void 0) throw new Error("init: The --git/--no-git options are not available when adding a package to an existing monorepo.");
2351
+ const gitInitialized = !workspaceSubpackage && (!targeted || initArgs?.git !== void 0) ? await setupGit(root, initArgs?.git) : false;
2352
+ const preScaffoldState = detectProjectState(root);
2353
+ const detectedFramework = detectScaffoldFramework(root);
2354
+ let scaffoldedFramework;
2355
+ let scaffoldedStarterMode;
2356
+ let didScaffoldStarter = false;
2357
+ let scaffoldAddedDependencies = false;
2358
+ let workspaceSubpackageSkip = false;
2359
+ if (!targeted && isScaffoldableEmptyProject(root)) {
2360
+ log.info("Empty project detected. Scaffolding a React starter...");
2361
+ const scaffoldToolchain = await promptScaffoldToolchain(initArgs?.toolchain);
2362
+ if (detectedFramework) log.info(`Detected ${SCAFFOLD_FRAMEWORKS[detectedFramework].label} in package.json`);
2363
+ scaffoldedFramework = detectedFramework ?? initArgs?.framework ?? "react";
2364
+ const starterMode = await promptStarterMode(initArgs?.starter);
2365
+ if (initArgs?.deploy === void 0) assertInteractive("deploy", DEPLOYMENT_PLATFORMS);
2366
+ const existingPackageJson = readPackageJson(root);
2367
+ const hasPackageManager = hasLocalLockfile(root) || existsSync(join(root, "pnpm-workspace.yaml")) || parsePackageManagerField(existingPackageJson) !== void 0 || resolveWorkspaceDeferral(root, existingPackageJson) !== void 0;
2368
+ const scaffoldPackageManager = scaffoldToolchain === "vite-plus" && !hasPackageManager ? "pnpm" : preScaffoldState.packageManager;
2369
+ const scaffoldWroteDeps = scaffoldSpaApp(root, scaffoldPackageManager, scaffoldedFramework, starterMode, scaffoldToolchain);
2370
+ const deferral = resolveWorkspaceDeferral(root, readPackageJson(root));
2371
+ const bwfResolvable = isBwfResolvableFrom(root);
2372
+ if (deferral && (!bwfResolvable || scaffoldWroteDeps)) {
2373
+ workspaceSubpackageSkip = true;
2374
+ const relRoot = relative(deferral.workspaceRoot, root) || ".";
2375
+ const dbFollowUp = starterMode === "spa" ? "" : `\nthen run \`bwf db generate\` from ./${relRoot} to create the initial migration.`;
2376
+ note(`Scaffolded the starter in ./${relRoot}.\n\nRun your workspace install from ${deferral.workspaceRoot} to pick up the new dependencies.${dbFollowUp}`, "Workspace subpackage");
2377
+ } else if (scaffoldWroteDeps || !bwfResolvable) scaffoldAddedDependencies = true;
2378
+ if (starterMode !== "spa") scaffoldedStarterMode = starterMode;
2379
+ didScaffoldStarter = true;
2380
+ }
2381
+ const state = detectProjectState(root);
2382
+ const scaffoldFramework = scaffoldedFramework ?? detectScaffoldFramework(root);
2383
+ if (!targeted && !didScaffoldStarter) {
2384
+ const dependencyAdded = setupExistingProject(root);
2385
+ const bwfResolvable = isBwfResolvableFrom(root);
2386
+ if (dependencyAdded || !bwfResolvable) {
2387
+ const deferral = resolveWorkspaceDeferral(root, readPackageJson(root));
2388
+ if (deferral) {
2389
+ workspaceSubpackageSkip = true;
2390
+ const relRoot = relative(deferral.workspaceRoot, root) || ".";
2391
+ note(`Configured bwf in ./${relRoot}.\n\nRun your workspace install from ${deferral.workspaceRoot} to sync the lockfile and pick up the updated dependencies.\nIf this init flow scaffolds database files, then run \`bwf db generate\` from ./${relRoot}.`, "Workspace subpackage");
2392
+ } else scaffoldAddedDependencies = true;
2393
+ }
2394
+ }
2395
+ if (!targeted || initArgs?.tsconfig) {
2396
+ state.typescriptWanted = true;
2397
+ setupTsconfig(root, state, scaffoldFramework);
2398
+ }
2399
+ if (state.typescriptWanted) {
2400
+ const hasSchema = hasDrizzleSchema(root);
2401
+ ensureProjectTsconfig(root, void 0, hasSchema, hasSchema);
2402
+ }
2403
+ ensureGitignore(root);
2404
+ if (!targeted) ensureBwfWorkerCompatibilityDate(root);
2405
+ if (!targeted && !didScaffoldStarter) applyDatabaseSetup(root, await promptDatabaseSetup(root));
2406
+ await injectAgentBlock(root, newProject);
2407
+ const agents = detectAgents(root);
2408
+ if (agents.length > 0) {
2409
+ const { linkSkillsForSpecificAgents } = await import("./skills-Dr3AjuBF.mjs");
2410
+ linkSkillsForSpecificAgents(root, agents);
2411
+ } else log.info("Bundled bwf docs: node_modules/@builtbyfriends/bwf/docs/");
2412
+ if (!targeted) {
2413
+ const existingDemoFiles = Object.values(demoFiles(root)).filter((file) => existsSync(file));
2414
+ if (didScaffoldStarter || state.hasRoutes || state.hasMigrations) log.info("Project already has routes or migrations, skipping demo");
2415
+ else if (hasDrizzleSchema(root)) log.info("Project already has a database schema, skipping demo");
2416
+ else if (existingDemoFiles.length > 0) {
2417
+ const names = existingDemoFiles.map((file) => relative(root, file)).join(", ");
2418
+ log.info(`Project already has ${names}, skipping demo`);
2419
+ } else {
2420
+ const scaffold = await confirm({ message: "Scaffold demo code? (migration + API route + frontend fetch)" });
2421
+ if (isCancel(scaffold)) {
2422
+ cancel("Setup cancelled.");
2423
+ process.exit(0);
2424
+ }
2425
+ if (scaffold) {
2426
+ const demoDialect = getDatabaseDialect(readConfig(root));
2427
+ scaffoldDemo(root, demoDialect);
2428
+ const bwfResolvable = isBwfResolvableFrom(root);
2429
+ const deferral = resolveWorkspaceDeferral(root, readPackageJson(root));
2430
+ if (deferral && !bwfResolvable) {
2431
+ const relRoot = relative(deferral.workspaceRoot, root) || ".";
2432
+ note(`Scaffolded the starter demo in ./${relRoot}.\n\nRun your workspace install from ${deferral.workspaceRoot} to pick up the new \`bwf\` dep,\nthen run \`bwf db generate\` from ./${relRoot} to create the initial migration.`, "Workspace subpackage");
2433
+ }
2434
+ scaffoldedStarterMode = demoDialect;
2435
+ }
2436
+ }
2437
+ }
2438
+ const deploymentPlatform = !targeted ? await promptDeploymentPlatform(root, initArgs?.deploy) : readDeploymentPlatform(root);
2439
+ let bwfPlatformDiscovery = null;
2440
+ if (!targeted && deploymentPlatform === "cloudflare") await setupCloudflareDeployment(root);
2441
+ if (!targeted && deploymentPlatform === "nosam") bwfPlatformDiscovery = await ensureBwfPlatformConnection(root);
2442
+ let shouldSetupGithub = targeted ? initArgs?.github === true : deploymentPlatform !== "none";
2443
+ if (shouldSetupGithub && !workspaceSubpackage && deploymentPlatform !== "cloudflare" && deploymentPlatform !== "none") {
2444
+ if (!bwfPlatformDiscovery) {
2445
+ const { getApiUrl } = await import("./auth-aKyIWkdS.mjs");
2446
+ bwfPlatformDiscovery = await discoverPlatform(getApiUrl(root));
2447
+ }
2448
+ if (!bwfPlatformDiscovery.capabilities.githubActions) {
2449
+ const message = `${bwfPlatformDiscovery.displayName} does not support GitHub Actions deployments.`;
2450
+ if (targeted) throw new Error(`init: ${message}`);
2451
+ log.info(`${message} Skipping workflow setup.`);
2452
+ shouldSetupGithub = false;
2453
+ }
2454
+ }
2455
+ if (shouldSetupGithub && !workspaceSubpackage) {
2456
+ if (targeted) setupGithubActions(root, state, deploymentPlatform === "cloudflare" ? "cloudflare" : "nosam", bwfPlatformDiscovery?.apiUrl);
2457
+ else {
2458
+ const setupGha = await confirm({ message: "Create .github/workflows/bwf-deploy.yml to deploy on pushes to main?" });
2459
+ if (isCancel(setupGha)) {
2460
+ cancel("Setup cancelled.");
2461
+ process.exit(0);
2462
+ }
2463
+ if (setupGha) setupGithubActions(root, state, deploymentPlatform === "cloudflare" ? "cloudflare" : "nosam", bwfPlatformDiscovery?.apiUrl);
2464
+ }
2465
+ } else if (workspaceSubpackage && shouldSetupGithub) log.info("Skipping GitHub Actions setup: workflow files must live at the repo root, not in a workspace subpackage.");
2466
+ if (!targeted) {
2467
+ const scaffoldResult = maybeScaffoldEnvTs(root);
2468
+ if (scaffoldResult.written) {
2469
+ const rel = relative(root, scaffoldResult.written) || "env.ts";
2470
+ if (scaffoldResult.entries.length > 0) log.step(`Scaffolded ${rel} from .env — review inferred types before running dev.`);
2471
+ else log.step(`Created empty ${rel} — add your env keys with \`defineEnv({...})\`.`);
2472
+ }
2473
+ }
2474
+ if (scaffoldAddedDependencies) installProjectDependencies(root, state.packageManager);
2475
+ if (scaffoldedStarterMode && !workspaceSubpackageSkip) generateStarterMigration(root, scaffoldedStarterMode);
2476
+ if (!targeted && deploymentPlatform === "nosam") {
2477
+ const linked = await maybeSetupDeployProject(root);
2478
+ if (linked?.slug) patchWorkflowProjectSlug(root, linked.slug);
2479
+ }
2480
+ if (gitInitialized) log.info(`Git (optional): ${initialCommitCommand(root)}`);
2481
+ if (workspaceSubpackageSkip) {
2482
+ if (scaffoldedStarterMode) printSuccess("Project initialized. Run your workspace install, then `bwf db generate` to finish setup.");
2483
+ else printSuccess("Project initialized. Run your workspace install to finish setup.");
2484
+ } else printSuccess(`Project initialized. Run \`${getDevCommand(root)}\` to start developing.`);
2485
+ }
2486
+ export { parseInitArgs, runInitCommand };