@rebasepro/cli 0.30.1 → 0.31.0-canary.g59cd6fd

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 (284) hide show
  1. package/README.md +8 -7
  2. package/dist/{agent-setup-0uyfC7VX.js → agent-setup-DqAcoDcn.js} +10 -5
  3. package/dist/{agent-setup-0uyfC7VX.js.map → agent-setup-DqAcoDcn.js.map} +1 -1
  4. package/dist/{api-keys-Dfw5-9s1.js → api-keys-eIUjMqWn.js} +8 -7
  5. package/dist/api-keys-eIUjMqWn.js.map +1 -0
  6. package/dist/{apps-MKQbgDtN.js → apps-DExO4PEl.js} +8 -7
  7. package/dist/apps-DExO4PEl.js.map +1 -0
  8. package/dist/{project-CasK56vN.js → args-CaCcrYE1.js} +2 -351
  9. package/dist/args-CaCcrYE1.js.map +1 -0
  10. package/dist/{atlas-dev-database-BODqdCWt.js → atlas-dev-database-DOCKk6ht.js} +2 -2
  11. package/dist/{atlas-dev-database-BODqdCWt.js.map → atlas-dev-database-DOCKk6ht.js.map} +1 -1
  12. package/dist/{auth-Bv0rTbQX.js → auth-D96QYgFR.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-D96QYgFR.js.map} +1 -1
  14. package/dist/backend-guard-C0mVkXBw.js +162 -0
  15. package/dist/backend-guard-C0mVkXBw.js.map +1 -0
  16. package/dist/{branch-pointer-BQUF6lYa.js → branch-pointer-DMPyvZoK.js} +1 -1
  17. package/dist/{build-BuKTnec8.js → build-CA5R07tw.js} +29 -9
  18. package/dist/build-CA5R07tw.js.map +1 -0
  19. package/dist/{bundle-BAH4FCju.js → bundle-DgILeA5b.js} +112 -138
  20. package/dist/bundle-DgILeA5b.js.map +1 -0
  21. package/dist/bundle.d.ts +35 -12
  22. package/dist/cli.d.ts +2 -2
  23. package/dist/{cloud-DtADfWwn.js → cloud-CYMk92iG.js} +72 -71
  24. package/dist/cloud-CYMk92iG.js.map +1 -0
  25. package/dist/cms-directories-BK3vcswg.js +33 -0
  26. package/dist/cms-directories-BK3vcswg.js.map +1 -0
  27. package/dist/codemod/collections-to-tables/ast.d.ts +135 -0
  28. package/dist/codemod/collections-to-tables/backend.d.ts +38 -0
  29. package/dist/codemod/collections-to-tables/command.d.ts +35 -0
  30. package/dist/codemod/collections-to-tables/comments.d.ts +45 -0
  31. package/dist/codemod/collections-to-tables/customization.d.ts +47 -0
  32. package/dist/codemod/collections-to-tables/dynamic-props.d.ts +34 -0
  33. package/dist/codemod/collections-to-tables/export-changes.d.ts +83 -0
  34. package/dist/codemod/collections-to-tables/firestore.d.ts +11 -0
  35. package/dist/codemod/collections-to-tables/helper-hooks.d.ts +41 -0
  36. package/dist/codemod/collections-to-tables/hooks.d.ts +44 -0
  37. package/dist/codemod/collections-to-tables/journal.d.ts +10 -0
  38. package/dist/codemod/collections-to-tables/legacy-shims.d.ts +52 -0
  39. package/dist/codemod/collections-to-tables/load-legacy.d.ts +81 -0
  40. package/dist/codemod/collections-to-tables/migrate.d.ts +20 -0
  41. package/dist/codemod/collections-to-tables/modules.d.ts +127 -0
  42. package/dist/codemod/collections-to-tables/moved-imports.d.ts +70 -0
  43. package/dist/codemod/collections-to-tables/moved-symbols.generated.d.ts +12 -0
  44. package/dist/codemod/collections-to-tables/own.d.ts +10 -0
  45. package/dist/codemod/collections-to-tables/path-aliases.d.ts +26 -0
  46. package/dist/codemod/collections-to-tables/plan-context.d.ts +49 -0
  47. package/dist/codemod/collections-to-tables/print-js.d.ts +44 -0
  48. package/dist/codemod/collections-to-tables/project-files.d.ts +144 -0
  49. package/dist/codemod/collections-to-tables/repoint.d.ts +50 -0
  50. package/dist/codemod/collections-to-tables/row-hands.d.ts +7 -0
  51. package/dist/codemod/collections-to-tables/sdk-calls.d.ts +88 -0
  52. package/dist/codemod/collections-to-tables/skills-step.d.ts +13 -0
  53. package/dist/codemod/collections-to-tables/split-constants.d.ts +42 -0
  54. package/dist/codemod/collections-to-tables/storage-paths.d.ts +28 -0
  55. package/dist/codemod/collections-to-tables/types.d.ts +164 -0
  56. package/dist/codemod/collections-to-tables/verify.d.ts +27 -0
  57. package/dist/codemod/collections-to-tables/vocabulary.d.ts +40 -0
  58. package/dist/command-D5lhW_-B.js +9984 -0
  59. package/dist/command-D5lhW_-B.js.map +1 -0
  60. package/dist/commands/agent-setup.d.ts +6 -2
  61. package/dist/commands/cloud/context.d.ts +1 -1
  62. package/dist/commands/cloud/init.d.ts +2 -2
  63. package/dist/commands/console.d.ts +1 -2
  64. package/dist/commands/db.d.ts +5 -6
  65. package/dist/commands/dev.d.ts +18 -17
  66. package/dist/commands/doctor.d.ts +4 -5
  67. package/dist/commands/eject.d.ts +17 -13
  68. package/dist/commands/generate-view.d.ts +20 -9
  69. package/dist/commands/generate_sdk.d.ts +27 -27
  70. package/dist/commands/init.d.ts +21 -8
  71. package/dist/commands/migrate.d.ts +24 -0
  72. package/dist/commands/schema-reconcile.d.ts +1 -1
  73. package/dist/commands/skills.d.ts +8 -0
  74. package/dist/commands/verify-cms.d.ts +28 -0
  75. package/dist/commands/verify.d.ts +14 -9
  76. package/dist/{consent-BD7F29T3.js → consent-BXLIrMl8.js} +2 -2
  77. package/dist/{consent-BD7F29T3.js.map → consent-BXLIrMl8.js.map} +1 -1
  78. package/dist/{console-CdwIYOMV.js → console-C1d3LwB7.js} +14 -14
  79. package/dist/console-C1d3LwB7.js.map +1 -0
  80. package/dist/{context-AXdAh-q8.js → context--JwaHaZp.js} +6 -5
  81. package/dist/context--JwaHaZp.js.map +1 -0
  82. package/dist/{daemon-Cp7oNXth.js → daemon-w30PsdwV.js} +2 -2
  83. package/dist/{daemon-Cp7oNXth.js.map → daemon-w30PsdwV.js.map} +1 -1
  84. package/dist/{db-DBbKpjYX.js → db-DQZK9n9c.js} +52 -51
  85. package/dist/db-DQZK9n9c.js.map +1 -0
  86. package/dist/{derive-ae9UOoOB.js → derive-C3ezmY-p.js} +105 -133
  87. package/dist/derive-C3ezmY-p.js.map +1 -0
  88. package/dist/{dev-C93d4QIv.js → dev-PY5h4O6u.js} +142 -84
  89. package/dist/dev-PY5h4O6u.js.map +1 -0
  90. package/dist/dev-db/attver.d.ts +32 -0
  91. package/dist/dev-db/pull.d.ts +15 -1
  92. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  93. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  94. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  95. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  96. package/dist/{doctor-BBPQUO2g.js → doctor-CnUu8kpM.js} +39 -62
  97. package/dist/doctor-CnUu8kpM.js.map +1 -0
  98. package/dist/doctor-environment.d.ts +6 -6
  99. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  100. package/dist/eject-Bhzd6hgb.js.map +1 -0
  101. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  102. package/dist/fold-static-CKewnAPX.js.map +1 -0
  103. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  104. package/dist/generate-view-CTOluXvH.js.map +1 -0
  105. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  106. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  107. package/dist/import-schema-module-Df67TIWj.js +51 -0
  108. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  109. package/dist/index.es.js +64 -51
  110. package/dist/index.es.js.map +1 -1
  111. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  112. package/dist/init-Dtl-IcXf.js.map +1 -0
  113. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  114. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  115. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  116. package/dist/manifest.d.ts +79 -24
  117. package/dist/migrate-VrKoi3nB.js +138 -0
  118. package/dist/migrate-VrKoi3nB.js.map +1 -0
  119. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  120. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  121. package/dist/path-flags-7O5uPBcQ.js +139 -0
  122. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  123. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  124. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  125. package/dist/project-CLcF5i8c.js +360 -0
  126. package/dist/project-CLcF5i8c.js.map +1 -0
  127. package/dist/project-schema-CsSOG2gE.js +30 -0
  128. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  129. package/dist/{pull-DDMpsZ5r.js → pull-DRWqBZp5.js} +327 -4
  130. package/dist/pull-DRWqBZp5.js.map +1 -0
  131. package/dist/resolve-BY7bSFRT.js +2 -0
  132. package/dist/resources/derive.d.ts +19 -13
  133. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  134. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  135. package/dist/{schema-DtLPsXbT.js → schema-CdDjv5zI.js} +41 -39
  136. package/dist/schema-CdDjv5zI.js.map +1 -0
  137. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  138. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  139. package/dist/schema-reconcile-BAupXfkd.js +2 -0
  140. package/dist/schema-text-CpNrsuMe.js +73 -0
  141. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  142. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  143. package/dist/skills-CXjA9TWw.js.map +1 -0
  144. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  145. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  146. package/dist/{status-BREvtzJm.js → status-D7XCGHu2.js} +12 -12
  147. package/dist/status-D7XCGHu2.js.map +1 -0
  148. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  149. package/dist/storage-iTqj5-Av.js.map +1 -0
  150. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  151. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  152. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  153. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  154. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  155. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  156. package/dist/utils/backend-guard.d.ts +47 -0
  157. package/dist/utils/cms-directories.d.ts +6 -0
  158. package/dist/utils/dev-preflight.d.ts +2 -2
  159. package/dist/utils/import-schema-module.d.ts +16 -0
  160. package/dist/utils/path-flags.d.ts +35 -16
  161. package/dist/utils/project-schema.d.ts +40 -0
  162. package/dist/utils/project.d.ts +8 -2
  163. package/dist/utils/schema-dir.d.ts +32 -0
  164. package/dist/utils/schema-drift.d.ts +6 -0
  165. package/dist/utils/schema-text.d.ts +24 -0
  166. package/dist/verify-5p_vaUG2.js +1160 -0
  167. package/dist/verify-5p_vaUG2.js.map +1 -0
  168. package/package.json +11 -8
  169. package/runtime/dev-server.mjs +5 -1
  170. package/templates/eject/Dockerfile +1 -4
  171. package/templates/eject/backend/src/env.ts +1 -1
  172. package/templates/eject/backend/src/index.ts +53 -40
  173. package/templates/eject/docker-compose.custom.yml +1 -1
  174. package/templates/overlays/baas/README.md +39 -12
  175. package/templates/overlays/baas/ai-instructions.md +8 -8
  176. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  177. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  178. package/templates/overlays/baas/package.json +1 -2
  179. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  180. package/templates/presets/blank/backend/schema/index.ts +19 -0
  181. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  182. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  183. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  184. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  185. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  186. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  187. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  188. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  189. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  190. package/templates/resource-graphs/blank.json +2 -2
  191. package/templates/resource-graphs/blog.json +5 -5
  192. package/templates/resource-graphs/ecommerce.json +5 -5
  193. package/templates/resource-graphs/headless.json +1 -1
  194. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  195. package/templates/template/.cursorrules +2 -2
  196. package/templates/template/.env.example +6 -17
  197. package/templates/template/.github/copilot-instructions.md +2 -2
  198. package/templates/template/.windsurfrules +2 -2
  199. package/templates/template/AGENTS.md +2 -2
  200. package/templates/template/CLAUDE.md +2 -2
  201. package/templates/template/README.md +47 -13
  202. package/templates/template/ai-instructions.md +15 -14
  203. package/templates/template/backend/functions/hello.ts +1 -1
  204. package/templates/template/backend/package.json +0 -2
  205. package/templates/template/{config → backend}/resources.ts +3 -3
  206. package/templates/template/backend/schema/authors.ts +11 -0
  207. package/templates/template/backend/schema/index.ts +29 -0
  208. package/templates/template/backend/schema/posts.ts +29 -0
  209. package/templates/template/backend/schema/tags.ts +9 -0
  210. package/templates/template/backend/schema/users.ts +32 -0
  211. package/templates/template/{config → backend}/storage.ts +4 -4
  212. package/templates/template/backend/tsconfig.json +15 -20
  213. package/templates/template/docker-compose.yml +3 -3
  214. package/templates/template/frontend/package.json +0 -2
  215. package/templates/template/frontend/src/App.tsx +10 -4
  216. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  217. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  218. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  219. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  220. package/templates/template/frontend/src/cms/users.tsx +54 -0
  221. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  222. package/templates/template/frontend/vite.config.ts +6 -2
  223. package/templates/template/gitignore +1 -1
  224. package/templates/template/package.json +1 -2
  225. package/templates/template/pnpm-workspace.yaml +0 -1
  226. package/templates/template/scripts/example.ts +3 -3
  227. package/templates/template/tsconfig.json +1 -1
  228. package/templates/views/AppView.tsx.tmpl +4 -4
  229. package/templates/views/EntityView.tsx.tmpl +3 -4
  230. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  231. package/dist/apps-MKQbgDtN.js.map +0 -1
  232. package/dist/build-BuKTnec8.js.map +0 -1
  233. package/dist/bundle-BAH4FCju.js.map +0 -1
  234. package/dist/cloud-DtADfWwn.js.map +0 -1
  235. package/dist/collection-drift-BKj_BoMq.js +0 -106
  236. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  237. package/dist/collections-dir-DlvDhime.js +0 -69
  238. package/dist/collections-dir-DlvDhime.js.map +0 -1
  239. package/dist/console-CdwIYOMV.js.map +0 -1
  240. package/dist/context-AXdAh-q8.js.map +0 -1
  241. package/dist/db-DBbKpjYX.js.map +0 -1
  242. package/dist/derive-ae9UOoOB.js.map +0 -1
  243. package/dist/dev-C93d4QIv.js.map +0 -1
  244. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  245. package/dist/doctor-BBPQUO2g.js.map +0 -1
  246. package/dist/eject-DABcDnPN.js.map +0 -1
  247. package/dist/fold-static-BWzxNn06.js.map +0 -1
  248. package/dist/generate-view-IFwCADvb.js.map +0 -1
  249. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  250. package/dist/init-vL1DWOeC.js.map +0 -1
  251. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  252. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  253. package/dist/path-flags-DNvtEi2-.js +0 -92
  254. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  255. package/dist/project-CasK56vN.js.map +0 -1
  256. package/dist/pull-DDMpsZ5r.js.map +0 -1
  257. package/dist/resolve-D647F1LA.js +0 -2
  258. package/dist/schema-DtLPsXbT.js.map +0 -1
  259. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  260. package/dist/skills-CbwV6vw_.js.map +0 -1
  261. package/dist/status-BREvtzJm.js.map +0 -1
  262. package/dist/storage-CO9ouK76.js.map +0 -1
  263. package/dist/utils/collection-drift.d.ts +0 -27
  264. package/dist/utils/collections-dir.d.ts +0 -14
  265. package/dist/verify-Y3rWSgfA.js +0 -730
  266. package/dist/verify-Y3rWSgfA.js.map +0 -1
  267. package/templates/overlays/baas/config/index.ts +0 -24
  268. package/templates/overlays/baas/config/package.json +0 -30
  269. package/templates/template/config/cms.d.ts +0 -15
  270. package/templates/template/config/collections/authors.ts +0 -47
  271. package/templates/template/config/collections/index.ts +0 -44
  272. package/templates/template/config/collections/posts.ts +0 -94
  273. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  274. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  275. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  276. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  277. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  278. package/templates/template/config/collections/tags.ts +0 -27
  279. package/templates/template/config/collections/users.ts +0 -149
  280. package/templates/template/config/frontend-assets.d.ts +0 -17
  281. package/templates/template/config/index.ts +0 -12
  282. package/templates/template/config/package.json +0 -30
  283. package/templates/template/config/tsconfig.json +0 -35
  284. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"init-vL1DWOeC.js","names":[],"sources":["../src/commands/init.ts"],"sourcesContent":["import inquirer from \"inquirer\";\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport { promisify } from \"util\";\nimport { execa } from \"execa\";\nimport { cp } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\nimport crypto from \"crypto\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { cliVersion } from \"../utils/version\";\nimport { invokedRebaseCommand } from \"../utils/invoked-command\";\nimport { dockerClaimedPorts } from \"../utils/dev-preflight\";\nimport { Refusal } from \"../utils/refusal\";\nimport type arg from \"arg\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { resolveCloudUrl, writeLink } from \"./cloud/context\";\nimport type { PackageManager, PMCommands } from \"../utils/package-manager\";\nimport { promptForConsent } from \"../telemetry/consent\";\nimport { durationBucket, recordEvent } from \"../telemetry\";\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { AGENT_KEYS, AGENTS, type AgentKey, reportRootPointers, resolveAgentNames } from \"./skills\";\nimport { writeRootPointers } from \"../utils/root-pointer\";\nimport { configureAgents, printAgentSetup, promptForAgents, retargetScaffoldMcpConfig } from \"./agent-setup\";\n\nconst access = promisify(fs.access);\n\n\n// Resolve template path relative to this file\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nfunction findParentDir(currentDir: string, targetName: string): string | null {\n const root = path.parse(currentDir).root;\n while (currentDir && currentDir !== root) {\n if (path.basename(currentDir) === targetName) {\n return currentDir;\n }\n currentDir = path.dirname(currentDir);\n }\n return null;\n}\n\nconst cliRoot = findParentDir(__dirname, \"cli\");\n\nconst PROJECT_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/**\n * Every scaffolded file that carries a `{{PLACEHOLDER}}`.\n *\n * Exported because it is the single source of truth: `init.test.ts` reads it and\n * asserts that every template file containing `{{` appears here. It used to be a\n * local, with the test harness keeping a *second* copy — so the two drifted, and\n * a test built on the copy could not observe the production list at all.\n *\n * The drift shipped: `docker-compose.yml` arrived with the self-host work\n * (26fd5259c) and was added to neither, so every scaffolded project got a literal\n * `name: {{PROJECT_NAME}}`. In YAML `{{...}}` is a map, not a string, so the\n * documented `docker compose up` path failed on the file before doing anything:\n *\n * yaml: unmarshal errors: line 28: cannot unmarshal !!map into string\n */\nexport const TEMPLATE_PLACEHOLDER_FILES = [\n \"package.json\",\n \"frontend/package.json\",\n \"backend/package.json\",\n \"config/package.json\",\n \"frontend/index.html\",\n \"pnpm-workspace.yaml\",\n \"docker-compose.yml\",\n \"README.md\"\n];\n\n/** Returns an error message, or null when the name is a valid package name. */\nexport function validateProjectName(name: string): string | null {\n if (!name.trim()) return \"Project name is required\";\n if (!PROJECT_NAME_RE.test(name)) {\n return \"Project name must start with a lowercase letter or number and contain only lowercase letters, numbers, hyphens, dots, or underscores\";\n }\n return null;\n}\n\nexport type TemplatePreset = \"blog\" | \"ecommerce\" | \"blank\";\n\n/**\n * Whether to scaffold the admin panel alongside the backend.\n *\n * A boolean, not a named pair. It was `--flavor cms|baas`, and neither word\n * survived what they described: \"cms\" is a product category rather than a thing\n * this tool builds, and \"baas\" was the same value that used to appear as\n * `backend.mode` — which is now derived from whether collections are declared.\n * What is left is one question: does this project get an admin UI?\n */\nconst HEADLESS_CHOICES: Array<{ name: string; value: boolean; short: string }> = [\n { name: \"Backend + admin — API plus an admin UI, driven by collections you define (like Payload/Directus)\",\nvalue: false,\nshort: \"Backend + admin\" },\n { name: \"Backend only — headless API over your database. No collections, no UI (like Supabase)\",\nvalue: true,\nshort: \"Backend only\" }\n];\n\nconst PRESET_CHOICES: Array<{ name: string; value: TemplatePreset; short: string }> = [\n { name: \"Blog — Posts, Authors, Tags (with markdown editor)\",\nvalue: \"blog\",\nshort: \"Blog\" },\n { name: \"E-commerce — Products, Categories, Orders\",\nvalue: \"ecommerce\",\nshort: \"E-commerce\" },\n { name: \"Blank — Empty project, just authentication\",\nvalue: \"blank\",\nshort: \"Blank\" }\n];\n\nexport interface InitOptions {\n projectName: string;\n git: boolean;\n installDeps: boolean;\n targetDirectory: string;\n templateDirectory: string;\n databaseUrl?: string;\n introspect?: boolean;\n /** Starter template preset. */\n preset: TemplatePreset;\n /** Whether `preset` came from an explicit --template rather than the default. */\n explicitPreset?: boolean;\n /** Scaffold the backend alone, with no admin panel and no collections. */\n headless: boolean;\n /** Detected package manager (pnpm or npm). */\n pm: PackageManager;\n /** Command helpers for the detected PM. */\n pmCommands: PMCommands;\n /** Cloud project slug (its subdomain) to link the scaffold to. */\n cloudProject?: string;\n /** One-time setup key that authenticates the cloud link. */\n setupKey?: string;\n /** Control-plane URL the setup key is redeemed against. */\n cloudUrl?: string;\n /** AI coding agents to install skills and the MCP server for. */\n agents: AgentKey[];\n /** Whoever reads the closing steps can answer a prompt (a TTY, not --yes). */\n interactive?: boolean;\n}\n\nexport interface BuildQuestionsParams {\n nameArg?: string;\n templateArg?: TemplatePreset;\n headlessArg?: boolean;\n hasGitFlag: boolean;\n hasInstallFlag: boolean;\n pm: PackageManager;\n}\n\n/**\n * Builds the interactive prompt questions for `rebase init`.\n * Exported for testability — all prompt `type` values must match\n * types registered by the installed version of inquirer.\n */\n/**\n * The questions this command asks, as inquirer types them.\n *\n * Declared, rather than left as `Record<string, unknown>` and asserted into\n * `Parameters<typeof inquirer.prompt>[0]` at the call. Inquirer infers the\n * answer shape from the array it is handed, so an array of open records matches\n * none of its overloads — which is the refusal that assertion was there to get\n * past, at the cost of every question in this file being unchecked: a\n * misspelled `mesage`, a `choices` on a `confirm`, a `default` of the wrong\n * type for its question kind all compiled.\n */\nexport type InitQuestion =\n | { type: \"input\"; name: string; message: string; default: string; validate?: (input: string) => string | true }\n | { type: \"confirm\"; name: string; message: string; default: boolean; when?: (answers: Record<string, unknown>) => boolean }\n | { type: \"select\"; name: string; message: string; choices: ReadonlyArray<{ name: string; value: unknown; short: string }>; default: unknown; when?: (answers: Record<string, unknown>) => boolean };\n\n/**\n * Why `input` cannot be this project's `DATABASE_URL`, or null when it can.\n *\n * The runtime refuses anything that is not a URL, and only a Postgres one can\n * work, so `init` refuses the same — before the scaffold is written around it.\n * The value itself is never repeated back: it may hold a password.\n */\nexport function databaseUrlProblem(input: string): string | null {\n const expected = \"(expected postgresql://user:password@host:5432/database)\";\n let parsed: URL;\n try {\n parsed = new URL(input.trim());\n } catch {\n return `not a PostgreSQL connection string ${expected}`;\n }\n if (parsed.protocol !== \"postgresql:\" && parsed.protocol !== \"postgres:\") {\n return `not a PostgreSQL connection string: it starts with ${parsed.protocol}// ${expected}`;\n }\n return null;\n}\n\n/** One line saying `dir` already holds files, or null when it may be scaffolded into. */\nfunction scaffoldConflictLine(dir: string): string | null {\n const conflicts = scaffoldDirectoryConflicts(dir);\n if (conflicts.length === 0) return null;\n const shown = conflicts.slice(0, 4).join(\", \") + (conflicts.length > 4 ? `, and ${conflicts.length - 4} more` : \"\");\n return `\"${path.basename(dir)}\" already holds files a new project would overwrite or mix with (${shown}). Choose another name.`;\n}\n\nexport function buildInitQuestions(params: BuildQuestionsParams): InitQuestion[] {\n const { nameArg, templateArg, headlessArg, hasGitFlag, hasInstallFlag, pm } = params;\n const questions: InitQuestion[] = [];\n\n if (!nameArg) {\n questions.push({\n type: \"input\",\n name: \"projectName\",\n message: \"Project name:\",\n default: \"my-app\",\n // The directory is checked here, while the name can still be\n // changed, rather than after every other question is answered.\n validate: (input: string) => validateProjectName(input)\n ?? scaffoldConflictLine(path.resolve(process.cwd(), input))\n ?? true\n });\n }\n\n if (headlessArg === undefined) {\n questions.push({\n type: \"select\",\n name: \"headless\",\n message: \"What do you want to build?\",\n choices: HEADLESS_CHOICES,\n default: false\n });\n }\n\n if (!templateArg) {\n questions.push({\n type: \"select\",\n name: \"preset\",\n message: \"Choose a starter template:\",\n choices: PRESET_CHOICES,\n default: \"blog\",\n // A headless project has no collection files, so a preset is moot.\n when: (answers: Record<string, unknown>) => !(headlessArg ?? answers.headless)\n });\n }\n\n if (!hasGitFlag) {\n questions.push({\n type: \"confirm\",\n name: \"git\",\n message: \"Initialize a git repository?\",\n default: true\n });\n }\n\n if (!hasInstallFlag) {\n questions.push({\n type: \"confirm\",\n name: \"installDeps\",\n message: `Install dependencies with ${pm}?`,\n default: true\n });\n }\n\n questions.push({\n type: \"input\",\n name: \"databaseUrl\",\n message: \"PostgreSQL connection string (blank = a managed database for this project, no setup):\",\n default: \"\",\n validate: (input: string) => {\n if (!input.trim()) return true;\n if (/[\\r\\n]/.test(input)) {\n return \"Database URL cannot contain newline characters.\";\n }\n // `n` here was an answer to the yes/no question the reader thought\n // this was, and it became DATABASE_URL=n.\n const problem = databaseUrlProblem(input);\n return problem ? `That is ${problem}. Leave it blank for the managed database.` : true;\n }\n });\n\n questions.push({\n type: \"confirm\",\n name: \"introspect\",\n message: \"Would you like to introspect this database to automatically generate collections?\",\n default: true,\n when: (answers: Record<string, unknown>) => !!(answers.databaseUrl as string)?.trim()\n });\n\n return questions;\n}\n\n/**\n * The `cd` a user must type to enter the new project.\n *\n * Not the project's basename: `init apps/my-app` has to say `cd apps/my-app`,\n * and `init .` returns \"\" because they are already in the project.\n */\nexport function formatCdTarget(cwd: string, targetDirectory: string): string {\n return path.relative(cwd, targetDirectory);\n}\n\n/** Help for `rebase init` — the flags were previously only discoverable by\n * triggering the non-TTY error. */\nexport function printInitHelp(): void {\n console.log(`\n${chalk.bold(\"rebase init\")} — Create a new Rebase project\n\n${chalk.bold(\"Usage\")}\n rebase init ${chalk.blue(\"[name]\")} [options]\n\n ${chalk.gray(\"The name may be a nested path (apps/my-app) or \\\".\\\" for the current directory.\")}\n ${chalk.gray(\"Asks when omitted; defaults to \\\"my-app\\\", and takes it without asking under --yes.\")}\n\n${chalk.bold(\"Options\")}\n ${chalk.blue(\"-t, --template\")} ${chalk.gray(\"<preset>\")} blog | ecommerce | blank ${chalk.gray(\"(default: blog)\")}\n ${chalk.blue(\"--headless\")} Backend only — no admin panel, no collections\n ${chalk.blue(\"-y, --yes\")} Never prompt ${chalk.gray(\"(required for CI / non-TTY)\")}: take every default,\n ${chalk.gray(\"except that git init and the install are skipped unless\")}\n ${chalk.gray(\"--git / --install is passed\")}\n ${chalk.blue(\"-i, --install\")} Install dependencies after scaffolding.\n ${chalk.gray(\"Without it, init asks (default yes); under --yes, no install\")}\n ${chalk.blue(\"--no-install\")} Install nothing, and do not ask\n ${chalk.blue(\"-g, --git\")} Initialize a git repository and make an initial commit.\n ${chalk.gray(\"Without it, init asks (default yes); under --yes, no repository\")}\n ${chalk.blue(\"--database-url\")} ${chalk.gray(\"<url>\")} Use an existing database instead of the generated one\n ${chalk.blue(\"--introspect\")} Generate collections from that database ${chalk.gray(\"(implies --template blank; needs --install)\")}\n ${chalk.blue(\"--project\")} ${chalk.gray(\"<slug>\")} Link the scaffold to a Rebase Cloud project\n ${chalk.blue(\"--setup-key\")} ${chalk.gray(\"<key>\")} One-time key authenticating the cloud link ${chalk.gray(\"(use with --project)\")}\n ${chalk.blue(\"-a, --agent\")} ${chalk.gray(\"<name>\")} Set up an AI coding agent: Rebase skills + the MCP server.\n ${chalk.gray(`Repeatable or comma-separated: ${AGENT_KEYS.join(\" | \")} | all`)}\n ${chalk.gray(\"Asks when omitted, pre-ticking the agents installed on this\")}\n ${chalk.gray(\"machine; under --yes, none unless named.\")}\n\n${chalk.bold(\"What gets scaffolded\")}\n ${chalk.gray(\"default\")} Backend + an admin UI, driven by collections you define ${chalk.gray(\"(like Payload/Directus)\")}\n ${chalk.blue(\"--headless\")} Backend only, over your existing database ${chalk.gray(\"(like Supabase)\")}\n ${chalk.gray(\"--template has no effect: there are no collections to seed.\")}\n\n${chalk.bold(\"Examples\")}\n ${chalk.gray(\"$\")} rebase init my-shop --template ecommerce --install\n ${chalk.gray(\"$\")} rebase init my-api --headless --yes\n ${chalk.gray(\"$\")} rebase init . --yes --git\n ${chalk.gray(\"$\")} rebase init my-app --yes --agent claude,cursor\n`);\n}\n\nexport async function createRebaseApp(rawArgs: string[]) {\n if (wantsHelp(rawArgs)) {\n printInitHelp();\n return;\n }\n\n console.log(`\n${chalk.bold(\"Rebase\")} — Create a new project 🚀\n`);\n\n const pm = detectPackageManager();\n const options = await promptForOptions(rawArgs, pm).catch((error: unknown) => {\n // Ctrl-C at a question. Nothing went wrong and nothing was written, so\n // it is not reported as a failure: no `✗ User force closed the prompt`,\n // no --debug hint — the exit a shell gives Ctrl-C, 130.\n if (isPromptCancel(error)) {\n console.log(\"\");\n process.exit(130);\n }\n throw error;\n });\n await createProject(options);\n}\n\n/** Whether `error` is inquirer's answer to Ctrl-C at a prompt (`ExitPromptError`). */\nfunction isPromptCancel(error: unknown): boolean {\n return error instanceof Error && error.name === \"ExitPromptError\";\n}\n\n/** The flags `rebase init` takes. */\nexport const INIT_FLAGS = {\n \"--git\": Boolean,\n \"--install\": Boolean,\n // The default, spelled out. `arg` has no negation, so without this entry a\n // CI script that writes what reads naturally — `rebase init app --yes\n // --no-install` — died on \"Unknown or unexpected option\", and both the\n // README and the Quickstart documented a flag the parser rejected. When\n // both are passed, the explicit \"no\" wins.\n \"--no-install\": Boolean,\n \"--database-url\": String,\n \"--introspect\": Boolean,\n \"--template\": String,\n \"--headless\": Boolean,\n \"--project\": String,\n \"--setup-key\": String,\n \"--agent\": [String],\n \"--yes\": Boolean,\n \"-a\": \"--agent\",\n \"-g\": \"--git\",\n \"-i\": \"--install\",\n \"-t\": \"--template\",\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\nasync function promptForOptions(rawArgs: string[], pm: PackageManager): Promise<InitOptions> {\n const { flags: args, positionals } = parseCommandArgs({\n spec: INIT_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"init\",\n maxPositionals: 1\n });\n\n // The first positional arg after \"init\" is the project name. Under the old\n // permissive parse a mistyped flag took that slot — `rebase init --headles\n // shop` scaffolded a directory called `--headles` — and the misspelling that\n // caused it was accepted in silence.\n const nameArg = positionals[0];\n const isNonInteractive = args[\"--yes\"] || false;\n\n // The interactive prompt validates typed names; a name passed as an\n // argument must pass the same check or it becomes an invalid package.json\n // \"name\" that only fails later, at install time. Validate the basename so\n // nested paths (\"apps/my-app\") and \".\" still work.\n if (nameArg) {\n const resolvedName = path.basename(path.resolve(process.cwd(), nameArg));\n const nameError = validateProjectName(resolvedName);\n if (nameError) {\n console.error(chalk.red(`Invalid project name \"${resolvedName}\": ${nameError}`));\n process.exit(1);\n }\n // Before any question: the answer cannot change, so asking first only\n // wastes every answer the reader gives.\n const targetDirectory = path.resolve(process.cwd(), nameArg);\n const conflicts = scaffoldDirectoryConflicts(targetDirectory);\n if (conflicts.length > 0) {\n for (const line of scaffoldConflictMessage(resolvedName, formatCdTarget(process.cwd(), targetDirectory), conflicts)) {\n console.error(line);\n }\n process.exit(1);\n }\n }\n\n const databaseUrlArg = args[\"--database-url\"]?.trim();\n if (databaseUrlArg) {\n const problem = databaseUrlProblem(databaseUrlArg);\n if (problem) {\n console.error(chalk.red(`✗ --database-url is ${problem}.`));\n console.error(chalk.gray(\" Leave the flag out to use a managed database for this project, with no setup.\"));\n process.exit(1);\n }\n }\n\n const templateArg = args[\"--template\"] as TemplatePreset | undefined;\n if (templateArg && !PRESET_CHOICES.some(p => p.value === templateArg)) {\n console.error(chalk.red(`Unknown template \"${templateArg}\". Available: ${PRESET_CHOICES.map(p => p.value).join(\", \")}`));\n process.exit(1);\n }\n\n const headlessArg = args[\"--headless\"] === true ? true : undefined;\n\n // Resolved before any question, so a misspelt agent costs nothing.\n const namedAgents = resolveAgentNames(args[\"--agent\"] ?? []);\n\n // `--no-install` is an explicit \"no\", not merely the absence of a \"yes\": it\n // suppresses the interactive question too, so `rebase init app --no-install`\n // asks one fewer thing rather than asking and ignoring the answer.\n const noInstall = args[\"--no-install\"] === true;\n const installFlag = noInstall ? false : (args[\"--install\"] ?? false);\n const hasInstallFlag = noInstall || args[\"--install\"] === true;\n\n if (isNonInteractive) {\n // Non-interactive: nothing to ask, so the prompt's default stands in.\n const projectName = nameArg || \"my-app\";\n const targetDirectory = path.resolve(process.cwd(), projectName);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName: path.basename(targetDirectory),\n git: args[\"--git\"] ?? false,\n installDeps: installFlag,\n targetDirectory,\n templateDirectory,\n databaseUrl: args[\"--database-url\"] || undefined,\n introspect: args[\"--introspect\"] || false,\n preset: templateArg || \"blog\",\n explicitPreset: !!templateArg,\n headless: headlessArg ?? false,\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs),\n // Nothing is guessed without a person to confirm it: the machine's\n // agents are only ever a pre-ticked default in the prompt.\n agents: namedAgents ?? [],\n interactive: false\n };\n }\n\n // A non-interactive stdin (CI, a pipe, no TTY) can't answer prompts:\n // inquirer either blocks forever waiting for input or aborts with a raw\n // ExitPromptError stack trace. Fail fast with actionable guidance instead.\n if (!process.stdin.isTTY) {\n const rerun = initRerunCommand(rawArgs, invokedRebaseCommand());\n console.error(chalk.red(\"Cannot prompt: this is a non-interactive terminal (no TTY).\"));\n console.error(chalk.yellow(\" Re-run it with --yes, which takes the default for anything not passed as a flag:\"));\n console.error(chalk.yellow(` ${rerun.command}`));\n if (rerun.redacted.length > 0) {\n console.error(chalk.gray(` ${capitalize(joinWords(rerun.redacted))} ${rerun.redacted.length === 1 ? \"is\" : \"are\"} left out above; put yours back in.`));\n }\n console.error(chalk.gray(\" Options: --template <blog|ecommerce|blank> --headless --database-url <url> --install --git --agent <name>\"));\n process.exit(1);\n }\n\n const questions = buildInitQuestions({\n nameArg,\n templateArg,\n headlessArg,\n hasGitFlag: !!args[\"--git\"],\n hasInstallFlag,\n pm\n });\n\n\n const answers = await inquirer.prompt(questions);\n const agents = namedAgents ?? await promptForAgents();\n\n const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);\n const projectName = path.basename(targetDirectory);\n const templateDirectory = path.resolve(cliRoot!, \"templates\", \"template\");\n const pmCommands = getPMCommands(pm);\n\n return {\n projectName,\n git: args[\"--git\"] || answers.git || false,\n installDeps: noInstall ? false : (args[\"--install\"] || answers.installDeps || false),\n targetDirectory,\n templateDirectory,\n databaseUrl: (answers.databaseUrl as string)?.trim() || undefined,\n introspect: answers.introspect || false,\n preset: templateArg || (answers.preset as TemplatePreset) || \"blog\",\n // Only a flag is \"explicit\" here: the interactive path never asks for a\n // preset once baas is chosen, so it can't produce a conflicting answer.\n explicitPreset: !!templateArg,\n headless: headlessArg ?? Boolean(answers.headless),\n pm,\n pmCommands,\n cloudProject: args[\"--project\"] || undefined,\n setupKey: args[\"--setup-key\"] || undefined,\n cloudUrl: resolveCloudUrl(rawArgs),\n agents,\n interactive: true\n };\n}\n\n/**\n * The command a reader with no terminal is told to run instead: the one they\n * typed, as they typed it, with `--yes`.\n *\n * It used to be one fixed example, `rebase init <name> --yes --template blog`,\n * whatever had been passed — so `init intro-app --headless --database-url …\n * --introspect --install` was told to scaffold a blog. Every word after `init`\n * is repeated in its place, and `invocation` is `rebase` as the reader started\n * it (see `invokedRebaseCommand`).\n *\n * Two values are never repeated, because a hint is printed to logs: the\n * password in `--database-url` (`databaseUrlProblem` keeps the same rule) and\n * the `--setup-key`. Each is replaced with a placeholder and named in\n * `redacted`, so the caller can say the copy is not runnable as printed.\n *\n * Exported for its test.\n */\nexport function initRerunCommand(\n rawArgs: readonly string[],\n invocation: readonly string[]\n): { command: string; redacted: string[] } {\n const rest = rawArgs.slice(2);\n const commandWord = rest.indexOf(\"init\");\n const redacted = new Set<string>();\n\n const hide = (flag: string, value: string): string => {\n if (flag === \"--setup-key\") {\n redacted.add(\"the setup key\");\n return \"<setup-key>\";\n }\n if (flag === \"--database-url\") {\n return value.replace(/^([a-z][a-z0-9+.-]*:\\/\\/[^:@/?#]*):([^@/?#]+)@/i, (_all, before: string) => {\n redacted.add(\"the password in --database-url\");\n return `${before}:<password>@`;\n });\n }\n return value;\n };\n\n const words: string[] = [];\n for (let i = 0; i < rest.length; i++) {\n if (i === commandWord) continue;\n const word = rest[i];\n const inline = /^(--[a-z-]+)=([\\s\\S]*)$/.exec(word);\n if (inline) {\n words.push(`${inline[1]}=${shellWord(hide(inline[1], inline[2]))}`);\n continue;\n }\n const previous = i > 0 && i - 1 !== commandWord ? rest[i - 1] : \"\";\n words.push(shellWord(previous.startsWith(\"--\") ? hide(previous, word) : word));\n }\n\n return {\n command: [...invocation, \"init\", ...words, \"--yes\"].join(\" \"),\n redacted: [...redacted]\n };\n}\n\n/** One word for a POSIX shell: bare when nothing in it is special, else single-quoted. */\nfunction shellWord(word: string): string {\n return /^[\\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction joinWords(items: readonly string[]): string {\n return items.length <= 1 ? items.join(\"\") : `${items.slice(0, -1).join(\", \")} and ${items[items.length - 1]}`;\n}\n\nfunction capitalize(text: string): string {\n return text.charAt(0).toUpperCase() + text.slice(1);\n}\n\n/**\n * Redeem the one-time setup key from the console's setup page and write the\n * `.rebase/cloud.json` link into the scaffold, so `rebase cloud deploy` etc.\n * work in the new directory with no further flags. `--project` carries the\n * project's slug (its subdomain, as shown in console URLs); the control plane\n * also accepts a raw id for old copies of the command.\n *\n * Best-effort by design: a failed link must never fail the scaffold, so every\n * exit path other than success is a warning plus instructions to link later.\n */\nasync function linkScaffoldToCloud(options: InitOptions): Promise<void> {\n if (!options.cloudProject && !options.setupKey) return;\n\n const linkLater = `Link it later with ${chalk.bold(\"rebase cloud login\")} then ${chalk.bold(\"rebase cloud link\")}.`;\n if (!options.cloudProject || !options.setupKey) {\n console.warn(chalk.yellow(\" --project and --setup-key go together; skipping the cloud link.\"));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n\n try {\n const res = await fetch(`${options.cloudUrl}/api/functions/setup-key/validate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectId: options.cloudProject,\nsetupKey: options.setupKey })\n });\n const body = (await res.json().catch(() => ({}))) as {\n error?: { message?: string };\n project?: { id?: string | number; subdomain?: string; name?: string };\n };\n if (!res.ok || body.project?.id === undefined) {\n console.warn(chalk.yellow(` Could not verify the setup key: ${body.error?.message || res.statusText}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n return;\n }\n writeLink(\n {\n url: String(options.cloudUrl),\n projectId: String(body.project.id),\n slug: body.project.subdomain,\n projectName: body.project.name\n },\n options.targetDirectory\n );\n console.log(\"\");\n console.log(` ${chalk.green(\"✓\")} Linked to cloud project ${chalk.bold(body.project.subdomain ?? options.cloudProject)}`);\n } catch (e) {\n console.warn(chalk.yellow(` Could not reach the control plane: ${e instanceof Error ? e.message : String(e)}`));\n console.warn(chalk.yellow(` ${linkLater}`));\n }\n}\n\n/**\n * Make the initial commit, after everything that writes into the project has run.\n *\n * It used to happen immediately after `git init`, which is before dependency\n * installation and before introspection — so `init --git --install` ended on a\n * dirty tree whose only untracked file was `pnpm-lock.yaml`. A lockfile is\n * precisely the thing that should be in a project's first commit, and a brand\n * new scaffold whose first `git status` is dirty invites the reader to conclude\n * the lockfile is deliberately ignored and never commit it at all.\n *\n * Introspection has the same shape: it generates `config/collections` and\n * `schema.generated.ts`, which belong in the commit describing the scaffold that\n * produced them.\n *\n * `git init` stays where it was. Creating the repository early costs nothing and\n * means a failed install still leaves the user a repository to commit into.\n */\nasync function commitScaffold(targetDirectory: string): Promise<void> {\n try {\n // Leaving the tree uncommitted makes the very first `git diff`\n // useless and hides the scaffold in a wall of untracked files.\n // .gitignore is already in place, so .env is never committed.\n await execa(\"git\", [\"add\", \"-A\"], { cwd: targetDirectory });\n // A machine with no user.email configured cannot commit at all.\n // Supply an identity only in that case, so a configured user still\n // authors their own initial commit.\n let identity: Record<string, string> = {};\n try {\n await execa(\"git\", [\"config\", \"user.email\"], { cwd: targetDirectory });\n } catch {\n identity = {\n GIT_AUTHOR_NAME: \"Rebase\",\n GIT_AUTHOR_EMAIL: \"noreply@rebase.pro\",\n GIT_COMMITTER_NAME: \"Rebase\",\n GIT_COMMITTER_EMAIL: \"noreply@rebase.pro\"\n };\n }\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit from Rebase\"], {\n cwd: targetDirectory,\n env: identity\n });\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to create the initial commit\"));\n }\n}\n\n/** What the closing \"Next steps\" depend on: the project's shape, and what `init` managed to do. */\nexport interface InitNextStepsInput {\n headless: boolean;\n /** `--database-url` was given, so `.env` names the user's own database. */\n ownDatabase: boolean;\n /** Introspection was asked for. */\n introspect: boolean;\n /** Introspection ran and produced collections. */\n introspected: boolean;\n /** Dependencies were installed. */\n installed: boolean;\n /** What the reader types to enter the project; \"\" when they are in it. */\n cdTarget: string;\n pm: PMCommands;\n}\n\n/**\n * The \"Next steps\" `init` closes on, every command one that works as printed.\n *\n * Each flavour has its own steps, and the branch for one flavour must not run\n * for another. The `--database-url` branch was checked before the headless one,\n * so `init --headless --database-url` — the documented BaaS path — opened on\n * `pnpm run db:push`: a script the headless scaffold does not have, for a\n * schema it does not declare (its tables are the developer's own), with an\n * Atlas it does not install. `init-next-steps.test.ts` holds every script\n * named here to the scaffold it is printed for.\n */\nexport function initNextSteps(input: InitNextStepsInput): string[] {\n const { headless, ownDatabase, introspect, introspected, installed, cdTarget, pm } = input;\n const cmd = (parts: string[]): string => ` ${chalk.cyan(parts.join(\" \"))}`;\n const note = (text: string): string => chalk.gray(` # ${text}`);\n const runDev = cmd(pm.run(\"dev\"));\n const lines: string[] = [];\n\n if (cdTarget) lines.push(` ${chalk.cyan(\"cd\")} ${cdTarget}`);\n if (!installed) lines.push(cmd(pm.install));\n lines.push(\"\");\n\n if (introspected) {\n lines.push(note(\"Database has been introspected & collections generated!\"));\n lines.push(note(headless\n ? \"Start the API over it:\"\n : \"Start the development server (frontend + backend):\"));\n lines.push(runDev);\n } else if (introspect) {\n // Introspection was requested but did not run. Point at the steps that\n // finish the job rather than claiming collections exist.\n lines.push(note(\"Introspection did not run — finish it with:\"));\n lines.push(cmd(pm.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"])));\n lines.push(cmd(pm.exec(\"rebase\", [\"schema\", \"generate\"])));\n lines.push(\"\");\n lines.push(note(\"Then start the development server:\"));\n lines.push(runDev);\n } else if (headless) {\n // One step, then the thing that is actually this mode's job. `dev`\n // starts the database itself when none is named; a headless project has\n // no collections, so there is no schema to push and the tables are the\n // developer's to create — on their own database or the managed one.\n lines.push(note(ownDatabase\n ? \"Your database is configured in .env (DATABASE_URL).\"\n : \"A local database configuration has been generated in .env.\"));\n lines.push(note(ownDatabase\n ? \"1. Start the API over it:\"\n : \"1. Start everything — the database comes up with it:\"));\n lines.push(runDev);\n lines.push(\"\");\n lines.push(note(ownDatabase\n ? \"2. Serve your tables.\"\n : \"2. Create your tables (migrations, SQL, any tool you like).\"));\n lines.push(note(\" A table is served once row-level security is enabled on it, and a\"));\n lines.push(note(\" policy is what opens its rows:\"));\n lines.push(cmd([\"ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;\"]));\n // The column side is cast, as the policies Rebase generates cast it:\n // `rebase.uid()` is text, so `user_id = rebase.uid()` on a uuid column\n // failed with \"operator does not exist: uuid = text\".\n lines.push(cmd([\"-- rebase.uid() is text: the cast makes this work for a uuid or integer column too.\"]));\n lines.push(cmd([\"CREATE POLICY your_table_owner ON your_table FOR ALL USING (user_id::text = rebase.uid());\"]));\n lines.push(note(\" The API logs any table it skips, and why.\"));\n } else if (ownDatabase) {\n lines.push(note(\"Your custom database is configured in .env.\"));\n lines.push(note(\"If the database is empty, push the Rebase schema to initialize it:\"));\n lines.push(cmd(pm.run(\"db:push\")));\n lines.push(\"\");\n lines.push(note(\"Then start the development server:\"));\n lines.push(runDev);\n } else {\n // The whole first run, in one command.\n //\n // Deliberately does NOT say \"container\". This branch is the one a new\n // project takes, and it is precisely the branch with no container in it:\n // `.env` ships DATABASE_URL commented out, so `dev` starts the managed\n // PGlite database rather than Docker. Saying otherwise sent a reader who\n // had no Docker installed off to install it, to satisfy a step that was\n // never going to run — and made the whole quickstart look like it\n // required a daemon it does not.\n //\n // \"schema\" covers two things `dev` does before serving: generating the\n // Drizzle schema from the collections, and applying the collections to\n // the database. The push-and-Docker steps are documented under\n // `rebase dev --help`.\n lines.push(note(\"A local database configuration has been generated in .env.\"));\n lines.push(note(\"Start everything — the database and schema are set up for you,\"));\n lines.push(note(\"with no Docker and nothing else to install:\"));\n lines.push(runDev);\n lines.push(\"\");\n lines.push(note(\"To use a Postgres of your own instead, uncomment DATABASE_URL in .env.\"));\n }\n\n lines.push(\"\");\n // Both halves of the first-admin rule, once, here.\n //\n // `init` has just written REBASE_ADMIN_EMAIL and a generated password into\n // `.env`, and they belong to the *production* boot — the compose stack, where\n // the first-registration window is shut. `rebase dev` reads the same file, so\n // without this line the honest reading of that `.env` is \"these are my\n // credentials\", and the first documented step (register, become the admin)\n // reads as broken.\n lines.push(note(\"Sign in: the first account you register becomes the admin.\"));\n lines.push(note(\"In production (docker compose) that window is shut and the account named by\"));\n lines.push(note(\"REBASE_ADMIN_EMAIL in .env is created at boot instead.\"));\n\n lines.push(\"\");\n // `--headless --introspect` had these two claims fighting: the step above\n // announced \"collections generated!\" and this line then said there are none.\n // Both were reachable at once, and the reader has to believe one of them.\n lines.push(headless\n ? introspected\n ? chalk.gray(\"This starts a headless API (Hono + PostgreSQL) over the collections just \")\n + chalk.gray(\"generated from your database in config/collections. Edit them to change what the \")\n + chalk.gray(\"API exposes; docs are at /api/swagger.\")\n : chalk.gray(\"This starts a headless API (Hono + PostgreSQL). There are no collection files: \")\n + chalk.gray(\"the API is derived from your database schema. Once it serves a table, docs are at /api/swagger.\")\n : chalk.gray(\"This starts both the backend (Hono + PostgreSQL)\")\n + chalk.gray(\" and the frontend (Vite + React) concurrently.\"));\n return lines;\n}\n\n/**\n * The closing \"AI Agent Skills\" lines, each command one its reader can run.\n *\n * `rebase skills install` with no `--agent` prompts, and refuses without a\n * TTY — so printing it bare at the end of `rebase init --yes`, the agent and\n * CI path, told that reader to run a command that answers \"Cannot prompt\".\n * Named agents are spelled out (a refresh must not depend on detection, which\n * never finds Copilot); otherwise a TTY reader gets the prompt, anyone else\n * the `--agent` form.\n */\nexport function agentNextSteps(agents: readonly AgentKey[], interactive: boolean, pm: PMCommands): string[] {\n const both = (args: string[]): string =>\n ` ${chalk.cyan([\"rebase\", ...args].join(\" \"))} ${chalk.gray(\"or\")} ${chalk.cyan(pm.exec(\"rebase\", args).join(\" \"))}`;\n if (agents.length > 0) {\n return [\n chalk.gray(` Set up for ${agents.map(a => AGENTS[a].label).join(\", \")}. Commit the files to share them;`),\n chalk.gray(\" after a Rebase upgrade, refresh the skills with:\"),\n \"\",\n both([\"skills\", \"install\", \"--agent\", agents.join(\",\")])\n ];\n }\n if (interactive) {\n return [\n chalk.gray(\" Install Rebase agent skills, and the Rebase MCP server, for your AI coding assistant:\"),\n \"\",\n both([\"skills\", \"install\", \"--mcp\"])\n ];\n }\n return [\n chalk.gray(\" Install Rebase agent skills, and the Rebase MCP server, for your AI coding assistant —\"),\n chalk.gray(` name it: ${AGENT_KEYS.join(\", \")}, or all.`),\n \"\",\n both([\"skills\", \"install\", \"--agent\", \"<agent>\", \"--mcp\"])\n ];\n}\n\n/**\n * What a directory may already hold for `rebase init` to scaffold into it.\n *\n * `git clone` of an empty repository, or `git init`, leaves exactly `.git` —\n * and `rebase init . --yes --git` is the help's own example. Counting every\n * entry as \"not empty\" refused the one directory that example is most likely\n * to be typed in. The entries here are a repository's metadata, the files\n * operating systems drop into any folder, and a licence: none of them is\n * something the scaffold writes (`init.test.ts` holds the template to that),\n * so tolerating them can never overwrite anything. Everything else is a\n * conflict and is named, never merged into.\n */\nexport const SCAFFOLD_TOLERATED_ENTRIES: ReadonlySet<string> = new Set([\n \".git\", \".hg\", \".svn\", \".gitattributes\",\n \".DS_Store\", \"Thumbs.db\", \"desktop.ini\",\n \"LICENSE\", \"LICENSE.md\", \"LICENSE.txt\"\n]);\n\n/** Entries in `dir` the scaffold would overwrite or mix with — `[]` when it may proceed. */\nexport function scaffoldDirectoryConflicts(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir, { withFileTypes: true })\n .filter(entry => !SCAFFOLD_TOLERATED_ENTRIES.has(entry.name))\n .map(entry => entry.isDirectory() ? `${entry.name}/` : entry.name)\n .sort();\n}\n\n/**\n * The refusal for a directory that already holds files, with the two ways forward.\n *\n * `invocation` is `rebase` as the reader started it, so the command offered is\n * one they can run.\n */\nexport function scaffoldConflictMessage(\n projectName: string,\n displayPath: string,\n conflicts: string[],\n invocation: readonly string[] = invokedRebaseCommand()\n): string[] {\n const shown = conflicts.slice(0, 8).join(\", \") + (conflicts.length > 8 ? `, and ${conflicts.length - 8} more` : \"\");\n return [\n `${chalk.red.bold(\"ERROR\")} Directory \"${projectName}\" already holds files a new project would overwrite or mix with: ${shown}`,\n chalk.yellow(` Scaffold somewhere new — ${chalk.cyan([...invocation, \"init\", \"<new-directory>\"].join(\" \"))} — or move those out of ${displayPath || \"this directory\"} and run this again.`),\n chalk.gray(` A repository's own metadata (.git) and a LICENSE are fine to leave in place.`)\n ];\n}\n\n/**\n * `git init`, or nothing when the directory is already a repository.\n *\n * A cloned repository keeps its branch, its remote and its history: the\n * scaffold is committed on top of what is there. Only a repository this\n * function created is pointed at `main`.\n */\nexport async function initGitRepository(targetDirectory: string): Promise<boolean> {\n if (fs.existsSync(path.join(targetDirectory, \".git\"))) {\n console.log(chalk.gray(\" Using the existing git repository...\"));\n return true;\n }\n console.log(chalk.gray(\" Initializing git repository...\"));\n try {\n await execa(\"git\", [\"init\"], { cwd: targetDirectory });\n // Name the branch `main` rather than inheriting whatever\n // `init.defaultBranch` is (often still `master`). `git init -b` would\n // be the obvious way, but it needs git >= 2.28; rewriting HEAD works\n // on every version and is safe before the first commit.\n try {\n await execa(\"git\", [\"symbolic-ref\", \"HEAD\", \"refs/heads/main\"], { cwd: targetDirectory });\n } catch {\n // Leave the default branch name; not worth failing the scaffold.\n }\n return true;\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to initialize git repository\"));\n return false;\n }\n}\n\nasync function createProject(options: InitOptions) {\n const startedAt = Date.now();\n const conflicts = scaffoldDirectoryConflicts(options.targetDirectory);\n if (conflicts.length > 0) {\n for (const line of scaffoldConflictMessage(options.projectName, formatCdTarget(process.cwd(), options.targetDirectory), conflicts)) {\n console.error(line);\n }\n process.exit(1);\n }\n fs.mkdirSync(options.targetDirectory, { recursive: true });\n\n // Verify template exists\n try {\n await access(options.templateDirectory, fs.constants.R_OK);\n } catch {\n console.error(`${chalk.red.bold(\"ERROR\")} Template not found at ${options.templateDirectory}`);\n process.exit(1);\n }\n\n // Copy template files\n console.log(chalk.gray(\" Copying project files...\"));\n try {\n await cp(options.templateDirectory, options.targetDirectory, {\n recursive: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n // Skip node_modules and .DS_Store\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n } catch (err: unknown) {\n console.error(`${chalk.red.bold(\"ERROR\")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n\n // npm/pnpm always strip files named .gitignore and .npmrc from published\n // tarballs, so the template ships them un-dotted and we restore the real\n // names here.\n for (const [from, to] of [[\"gitignore\", \".gitignore\"], [\"npmrc\", \".npmrc\"]] as const) {\n const shipped = path.join(options.targetDirectory, from);\n if (fs.existsSync(shipped)) {\n fs.renameSync(shipped, path.join(options.targetDirectory, to));\n }\n }\n\n // Apply the selected template preset (swap collection files)\n if (options.headless && options.explicitPreset) {\n // baas has no collections, so there is nothing for a preset to swap.\n // Say so rather than accepting the flag and silently dropping it.\n console.log(chalk.yellow(` Ignoring --template ${options.preset}: a headless project declares no collections.`));\n }\n let applied: TemplatePreset | null = null;\n if (!options.headless) {\n // When introspecting, the database is the source of truth: start from\n // the blank preset so example collections never register on top of\n // tables the database doesn't have.\n if (options.introspect && options.preset !== \"blank\") {\n console.log(chalk.gray(\" Using the blank template: collections will come from your database.\"));\n }\n applied = await applyPreset(options.targetDirectory, options.introspect ? \"blank\" : options.preset);\n writeShippedSchema(options.targetDirectory, applied);\n }\n\n // Reduce the project to the selected shape\n await applyHeadless(options.targetDirectory, options.headless);\n\n // Not when introspecting: the collections are about to come from the\n // database, and `rebase build` writes the graph they declare.\n if (!options.introspect) {\n writeShippedResourceGraph(options.targetDirectory, options.headless ? \"headless\" : applied ?? \"blog\");\n }\n\n // Replace placeholder project name in package.json files\n await replacePlaceholders(options);\n\n // Rename .env.example to .env if it exists and randomize secrets\n await configureEnvFile(options.targetDirectory, options.databaseUrl);\n\n // The manifest's build command is the project's package manager, not npm.\n // The template has to spell one of them, and `npm run build --workspace\n // frontend` in a pnpm project is a second package manager reading a\n // lockfile it did not write.\n await writeProjectPackageManagerIntoManifest(options.targetDirectory, options.pmCommands);\n // The scaffold's `.mcp.json` runs the project's own `@rebasepro/mcp`\n // through the package manager, and it ships spelled for pnpm.\n retargetScaffoldMcpConfig(options.targetDirectory, options.pm);\n\n // Before git, so the skills and MCP configs are in the initial commit.\n if (options.agents.length > 0) {\n console.log(chalk.gray(\" Setting up AI coding agents...\"));\n printAgentSetup(configureAgents(options.agents, options.targetDirectory, undefined, options.pm), options.pm);\n }\n\n // Inside a larger repository, an assistant started at its root loads none of\n // the project's agent files: write the rules there too (utils/root-pointer).\n // Before git init, which would make the project its own repository root.\n reportRootPointers(writeRootPointers(options.targetDirectory, options.templateDirectory));\n\n // Create the repository now, but commit at the very end — see\n // commitScaffold below for why the two halves are separated.\n const gitInitialized = options.git ? await initGitRepository(options.targetDirectory) : false;\n\n const { pm, pmCommands } = options;\n const installCmd = pmCommands.install;\n const execCmd = pmCommands.exec(\"rebase\", [\"schema\", \"introspect\", \"--force\"]);\n // No --collections: config/collections is the default, and a path written\n // here is resolved from where the reader runs it — the project root.\n const generateCmd = pmCommands.exec(\"rebase\", [\"schema\", \"generate\"]);\n\n // Whether the install succeeded, so a failed one is printed as a step still to take.\n let installed = false;\n if (options.installDeps) {\n console.log(\"\");\n console.log(chalk.gray(` Installing dependencies with ${pm}...`));\n console.log(\"\");\n try {\n await execa(installCmd[0], installCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n installed = true;\n } catch {\n console.warn(chalk.yellow(` Warning: Failed to install dependencies. You may need to run \\`${installCmd.join(\" \")}\\` manually.`));\n }\n }\n\n // Whether introspection actually ran and produced collections. The next\n // steps below report what really happened, so a skipped or failed\n // introspection is never announced as a success.\n let introspected = false;\n\n if (options.introspect) {\n console.log(\"\");\n if (options.installDeps) {\n console.log(chalk.gray(\" Introspecting database and generating collections...\"));\n console.log(\"\");\n try {\n // --force overwrites template example collections with real ones\n await execa(execCmd[0], execCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n // The scaffold holds the blank preset's schema.generated.ts;\n // regenerate it from the introspected collections or the\n // backend serves a schema that doesn't match the database.\n await execa(generateCmd[0], generateCmd.slice(1), {\n cwd: options.targetDirectory,\n stdio: \"inherit\"\n });\n console.log(chalk.green(\" Database successfully introspected!\"));\n introspected = true;\n } catch {\n console.warn(chalk.yellow(\" Warning: Failed to introspect database automatically.\"));\n console.warn(chalk.yellow(` You can run \\`${execCmd.join(\" \")}\\` then \\`${generateCmd.join(\" \")}\\` manually after setup.`));\n }\n } else {\n console.warn(chalk.yellow(\" Skipping introspection because dependencies were not installed.\"));\n console.warn(chalk.yellow(` Run \\`${installCmd.join(\" \")}\\` then \\`${execCmd.join(\" \")}\\` manually.`));\n }\n }\n\n if (gitInitialized) await commitScaffold(options.targetDirectory);\n\n await linkScaffoldToCloud(options);\n\n // Success message\n console.log(\"\");\n console.log(`${chalk.green.bold(\"✓\")} Project ${chalk.bold(options.projectName)} created successfully!`);\n console.log(\"\");\n console.log(chalk.bold(\"Next steps:\"));\n console.log(\"\");\n const nextSteps = initNextSteps({\n headless: options.headless,\n ownDatabase: Boolean(options.databaseUrl),\n introspect: Boolean(options.introspect),\n introspected,\n installed,\n // The path the user has to type, not the project's basename: `init\n // apps/my-app` must say `cd apps/my-app`, and `init .` needs no cd at all\n // because they are already standing in the project.\n cdTarget: formatCdTarget(process.cwd(), options.targetDirectory),\n pm: pmCommands\n });\n for (const line of nextSteps) console.log(line);\n console.log(\"\");\n console.log(chalk.gray(\"Docs: https://rebase.pro/docs\"));\n console.log(chalk.gray(\"GitHub: https://github.com/rebasepro/rebase\"));\n console.log(\"\");\n console.log(chalk.bold(\"🤖 AI Agent Skills\"));\n console.log(\"\");\n for (const line of agentNextSteps(options.agents, options.interactive === true, pmCommands)) console.log(line);\n console.log(\"\");\n\n // Asked here, at the very end, and never before: the project exists, it\n // worked, and the user has something to judge us on. Nothing has been\n // written or transmitted up to this line — declining leaves no id and no\n // file. See telemetry/consent.ts for why the order matters.\n //\n // `--yes` and non-TTY runs never reach the prompt, so CI behaviour is\n // unchanged.\n const initProperties = {\n preset: options.headless ? \"none\" : options.preset,\n headless: Boolean(options.headless),\n package_manager: options.pm,\n installed_deps: Boolean(options.installDeps),\n introspected,\n own_database: Boolean(options.databaseUrl),\n cloud_linked: Boolean(options.cloudProject),\n git: Boolean(options.git),\n duration: durationBucket(Date.now() - startedAt)\n };\n // `reAskDeclined`: scaffolding is the one moment where asking again is an\n // offer rather than nagging. See PromptOptions.\n if (await promptForConsent({ reAskDeclined: true })) {\n await recordEvent(\"cli.init\", initProperties, { projectRoot: options.targetDirectory });\n }\n}\n\n/**\n * Apply a template preset by replacing the default collection files.\n *\n * The template ships with blog collections at the top level and\n * preset alternatives under `config/collections/presets/<name>/`.\n * This function swaps the active collection files and removes the\n * presets directory so the final project is clean.\n */\n/**\n * Reduce the scaffolded project to the chosen shape.\n *\n * The base template is the full triad. `--headless` drops the frontend and the\n * declared collections — there is nothing to define, since the server derives\n * its API from the database — and overlays the files that differ.\n *\n * The config *package* stays, holding only `storageAuthorize`. Storage is not\n * under row-level security, so a deployment with file storage enabled and no\n * access model serves every user's files to every signed-in user; the server\n * refuses to boot in that state. Deleting the package outright would leave a\n * headless project with nowhere to put the hook, and the scaffold's own\n * docker-compose.yml enables storage — so the first `docker compose up` would\n * crash-loop.\n */\nasync function applyHeadless(targetDirectory: string, headless: boolean): Promise<void> {\n if (!headless) return;\n\n fs.rmSync(path.join(targetDirectory, \"frontend\"), { recursive: true,\nforce: true });\n // Collections only. `rebase build` reads the absence of this directory as\n // \"introspect from the database\", and the overlay replaces config/index.ts\n // with one that exports the storage hook alone.\n fs.rmSync(path.join(targetDirectory, \"config\", \"collections\"), { recursive: true,\nforce: true });\n for (const stray of [\"cms.d.ts\", \"frontend-assets.d.ts\"]) {\n fs.rmSync(path.join(targetDirectory, \"config\", stray), { force: true });\n }\n // Generated from collection files; a headless project reads the live schema.\n fs.rmSync(path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\"), { force: true });\n\n const overlayDir = path.resolve(cliRoot!, \"templates\", \"overlays\", \"baas\");\n if (!fs.existsSync(overlayDir)) {\n console.error(`${chalk.red.bold(\"ERROR\")} BaaS template overlay not found at ${overlayDir}`);\n process.exit(1);\n }\n\n await cp(overlayDir, targetDirectory, {\n recursive: true,\n force: true,\n filter: (source: string) => {\n const basename = path.basename(source);\n return basename !== \"node_modules\" && basename !== \".DS_Store\";\n }\n });\n}\n\n/**\n * Rewrite `rebase.json`'s static-app build command for this project's package manager.\n *\n * The template must spell one of them, and it spells npm. In a pnpm project\n * that is a second package manager invoked against a lockfile it did not\n * write — `rebase build` then either installs a second tree or fails on a\n * workspace flag npm and pnpm spell differently.\n */\nasync function writeProjectPackageManagerIntoManifest(\n targetDirectory: string,\n pmCommands: PMCommands\n): Promise<void> {\n const manifestPath = path.join(targetDirectory, \"rebase.json\");\n if (!fs.existsSync(manifestPath)) return;\n\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as {\n apps?: Record<string, { type?: string; root?: string; build?: string }>;\n };\n let changed = false;\n for (const app of Object.values(manifest.apps ?? {})) {\n if (app.type !== \"static\" || !app.root || !app.build) continue;\n const rewritten = pmCommands.runWorkspace(app.root, \"build\").join(\" \");\n if (rewritten !== app.build) {\n app.build = rewritten;\n changed = true;\n }\n }\n if (changed) {\n fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 4)}\\n`, \"utf8\");\n }\n } catch {\n // A manifest that will not parse is `rebase build`'s problem to report,\n // and scaffolding must not fail on a cosmetic rewrite.\n }\n}\n\n/** Swap in the preset's collection files. Returns the preset actually applied. */\nasync function applyPreset(targetDirectory: string, preset: TemplatePreset): Promise<TemplatePreset> {\n const collectionsDir = path.join(targetDirectory, \"config\", \"collections\");\n const presetsDir = path.join(collectionsDir, \"presets\");\n\n if (preset !== \"blog\") {\n const presetDir = path.join(presetsDir, preset);\n if (!fs.existsSync(presetDir)) {\n console.warn(chalk.yellow(` Warning: Preset \"${preset}\" not found, falling back to blog template.`));\n cleanupPresets(presetsDir);\n return \"blog\";\n }\n\n // Remove the default blog collection files (keep users.ts — it's shared)\n const blogFiles = [\"posts.ts\", \"authors.ts\", \"tags.ts\", \"index.ts\"];\n for (const file of blogFiles) {\n const filePath = path.join(collectionsDir, file);\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n }\n }\n\n // Copy preset files into the collections directory\n const presetFiles = fs.readdirSync(presetDir).filter(f => f.endsWith(\".ts\"));\n for (const file of presetFiles) {\n fs.copyFileSync(\n path.join(presetDir, file),\n path.join(collectionsDir, file)\n );\n }\n }\n\n // Always clean up the presets directory — it shouldn't ship with the final project\n cleanupPresets(presetsDir);\n return preset;\n}\n\n/**\n * Where the generated Drizzle schema for each preset ships, beside the template.\n *\n * `rebase dev` regenerates `backend/src/schema.generated.ts` on every start, and\n * the Studio's schema editor refuses to commit over a dirty copy of it — a\n * schema change must not sweep up somebody's work in progress. So whatever\n * `init` writes there, and commits under `--git`, has to be byte-for-byte what\n * that first regeneration produces. A stub (`export const tables = {}`) was\n * rewritten on the first `rebase dev`, and every new project's first Studio\n * edit was refused with `SCHEMA_EDIT_DIRTY_TREE` before its owner had changed\n * a thing.\n *\n * The file cannot be generated here: generation loads the collection files,\n * and they import `@rebasepro/cms-types`, which the project does not have\n * until it is installed — `init --git` without `--install` commits first. So\n * each preset's output is generated in this repository and shipped, and\n * `init-generated-schema.test.ts` fails the moment one of them differs from\n * what the generator writes for that preset's collections.\n *\n * Outside `templates/template` on purpose: a preset's schema must not be\n * copied into a project that chose another preset.\n */\nexport function shippedSchemaPath(preset: TemplatePreset): string {\n return path.resolve(cliRoot!, \"templates\", \"generated-schemas\", `${preset}.ts`);\n}\n\n/** Write the preset's generated schema to `backend/src/schema.generated.ts`. */\nfunction writeShippedSchema(targetDirectory: string, preset: TemplatePreset): void {\n const destination = path.join(targetDirectory, \"backend\", \"src\", \"schema.generated.ts\");\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.copyFileSync(shippedSchemaPath(preset), destination);\n}\n\n/** A scaffold's shape, for the resource graph it ships with: a preset, or headless. */\nexport type ScaffoldShape = TemplatePreset | \"headless\";\n\n/**\n * Where each scaffold shape's `rebase.resources.json` ships, beside the template.\n *\n * `rebase resources --check` is the CI gate for that file, and a fresh\n * scaffold failed it before anything had changed: `config/resources.ts`\n * declares `main = database()`, `backend/functions/hello.ts` is a function,\n * and nothing had written the graph — `rebase build` does, on its first run.\n * So `init` writes it, and a fresh project starts consistent with its own\n * gate, with the file in its first commit.\n *\n * It cannot be derived here for the reason the schema cannot (see\n * `shippedSchemaPath`): deriving evaluates the collection files, which import\n * `@rebasepro/cms-types`, and the project has none until it is installed. So\n * each shape's graph is derived in this repository and shipped, and\n * `init-resource-graph.test.ts` fails the moment one differs from what\n * `rebase resources --write` writes for that shape.\n */\nexport function shippedResourceGraphPath(shape: ScaffoldShape): string {\n return path.resolve(cliRoot!, \"templates\", \"resource-graphs\", `${shape}.json`);\n}\n\n/** Write the shape's resource graph to `rebase.resources.json`. */\nfunction writeShippedResourceGraph(targetDirectory: string, shape: ScaffoldShape): void {\n fs.copyFileSync(shippedResourceGraphPath(shape), path.join(targetDirectory, \"rebase.resources.json\"));\n}\n\nfunction cleanupPresets(presetsDir: string): void {\n if (fs.existsSync(presetsDir)) {\n fs.rmSync(presetsDir, { recursive: true,\nforce: true });\n }\n}\n\n/**\n * The one registry call `init` makes, and what it is for.\n *\n * Every `@rebasepro/*` package in this repository carries the same version —\n * `check:publishable-set` fails the build on the first PR after a bump if any\n * of them drifts — so the version to pin is known before the network is\n * touched: it is this CLI's own. Asking npm eleven times, once per package,\n * bought nothing but eleven chances to hang. On a slow connection that was the\n * slowest part of `init`; on no connection it was eleven timeouts before a\n * fallback to `\"latest\"`, which is the one answer that produces a project\n * mixing framework eras.\n *\n * One call remains, and it asks a different question. Lockstep is enforced in\n * the repository, not on the registry: a release can still ship the CLI and\n * leave a package behind, which is exactly what happened to\n * `@rebasepro/agent-skills` across three releases. So this probes a single\n * package — `@rebasepro/server`, the one a project cannot run without — to see\n * whether this version really made it out. A gap is a refusal, because the\n * alternative is scaffolding a project that cannot install.\n *\n * Unreachable is NOT a refusal. `init` offline is a legitimate thing to do,\n * and the pin it would write is the same pin the probe would have confirmed.\n * It says so and carries on.\n */\ntype ReleaseProbe =\n | { kind: \"published\" }\n | { kind: \"gap\"; found: string }\n | { kind: \"unreachable\"; reason: string };\n\n/** The package the probe asks about. Not the CLI: the CLI is what is running. */\nconst RELEASE_PROBE_PACKAGE = \"@rebasepro/server\";\n\nasync function probeRelease(version: string): Promise<ReleaseProbe> {\n try {\n const { stdout } = await execa(\"npm\", [\"view\", `${RELEASE_PROBE_PACKAGE}@${version}`, \"version\"]);\n if (stdout.trim() === version) return { kind: \"published\" };\n // npm answers an unpublished version with empty output rather than an\n // error on some registries. Empty is a gap, not a success.\n return { kind: \"gap\", found: stdout.trim() || \"nothing\" };\n } catch (error) {\n const text = `${(error as { stderr?: string }).stderr ?? \"\"}${(error as Error).message ?? \"\"}`;\n if (/E404|404 Not Found|No match(ing)? version/i.test(text)) {\n return { kind: \"gap\", found: \"nothing\" };\n }\n return { kind: \"unreachable\", reason: firstLine(text) || \"the registry could not be reached\" };\n }\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\").map(l => l.trim()).filter(Boolean)[0] ?? \"\";\n}\n\nasync function replacePlaceholders(options: InitOptions) {\n const filesToProcess = TEMPLATE_PLACEHOLDER_FILES;\n\n // `unknown` only when the manifest could not be read at all, which is the\n // same \"nothing to pin, nothing to confirm\" case `latest` used to stand for.\n const version = cliVersion();\n\n const fileContents = new Map<string, string>();\n const allPackages = new Set<string>();\n\n for (const file of filesToProcess) {\n const fullPath = path.resolve(options.targetDirectory, file);\n if (!fs.existsSync(fullPath)) continue;\n const content = fs.readFileSync(fullPath, \"utf-8\");\n fileContents.set(fullPath, content);\n\n const matches = [...content.matchAll(/\"(@rebasepro\\/[^\"]+)\":\\s*\"workspace:\\*\"/g)];\n for (const match of matches) allPackages.add(match[1]);\n }\n\n // `latest` means this CLI could not read its own manifest — there is no\n // version to confirm, and nothing to gain from asking.\n const skipProbe = parseEnvBoolean(process.env.REBASE_E2E) === true || version === \"unknown\";\n const probe: ReleaseProbe = skipProbe ? { kind: \"published\" } : await probeRelease(version);\n\n if (probe.kind === \"gap\") {\n throw new Refusal(\n `Rebase ${version} is not fully published to npm.\\n\\n` +\n `${RELEASE_PROBE_PACKAGE} has no ${version} release — the registry has ${probe.found}.\\n` +\n `Every @rebasepro package ships at one version, so scaffolding would pin ${allPackages.size}\\n` +\n `dependencies at a version that is not there, and the install would fail.\\n\\n` +\n \"That is a release gap in Rebase itself — not a problem with your machine,\\n\" +\n \"your network, or your package manager.\\n\\n\" +\n \"Stopped before writing dependency versions or installing anything. The\\n\" +\n `project directory ${path.basename(options.targetDirectory)}/ was created and is safe to delete.\\n` +\n \"Please report this.\"\n );\n }\n\n if (probe.kind === \"published\") {\n console.log(chalk.gray(` Pinning ${allPackages.size} @rebasepro package(s) to ${version}...`));\n }\n\n if (probe.kind === \"unreachable\") {\n console.log(chalk.gray(` Pinning @rebasepro packages to ${version} (this CLI's version).`));\n console.log(chalk.yellow(` Could not reach npm to confirm the release: ${probe.reason}`));\n console.log(chalk.gray(\" The pin is right either way — install will say so if the version is missing.\"));\n }\n\n for (const [fullPath, originalContent] of fileContents.entries()) {\n let content = originalContent.replace(/\\{\\{PROJECT_NAME\\}\\}/g, options.projectName);\n for (const pkgName of allPackages) {\n content = content.replace(\n new RegExp(`\"${pkgName}\":\\\\s*\"workspace:\\\\*\"`, \"g\"),\n `\"${pkgName}\": \"${version}\"`\n );\n }\n fs.writeFileSync(fullPath, content, \"utf-8\");\n }\n}\n\n\n/** `undefined` binds the wildcard address, which is a different question — see isPortAvailable. */\nfunction canBind(port: number, host?: string): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", (err: NodeJS.ErrnoException) => {\n // The host has no such address family at all — a v4-only machine\n // asked about `::1`. Nothing can be listening on an address that\n // cannot exist, so this is free rather than taken.\n resolve(err.code === \"EAFNOSUPPORT\" || err.code === \"EADDRNOTAVAIL\");\n });\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n if (host === undefined) server.listen(port);\n else server.listen(port, host);\n });\n}\n\n/**\n * Whether `port` is free — on the wildcard address *and* on both loopback addresses.\n *\n * All three, because on macOS/BSD a successful bind does not mean the port is\n * unused. Sockets carry `SO_REUSEADDR` (Node sets it), under which a wildcard\n * bind and a specific-address bind on the same port do not conflict — in either\n * direction. So each probe alone has a blind spot, and they are different ones:\n *\n * - **Wildcard only** (what this used to do) misses a server bound to\n * `127.0.0.1` and `[::1]` — a Homebrew or Postgres.app install, i.e. most\n * developer machines. 5432 was reported free while it was already serving\n * another project's database. Docker then published `*:5432` for the same\n * reason and the container started cleanly, with no \"port already allocated\"\n * error anywhere to hint at the collision. `DATABASE_URL` pointed at\n * `localhost:5432`, `localhost` resolves to `::1` first, and every command\n * reported success while reading and writing the *pre-existing* database — a\n * `db push` would have created tables, roles and RLS policies inside it.\n *\n * - **Loopback only** misses the opposite case: Docker Desktop publishes a\n * container's port on `*`, and a specific-address bind succeeds right past it.\n * That port is free to probe and unusable to publish, so `docker compose up -d\n * db` fails on \"Bind for 0.0.0.0:PORT failed: port is already allocated\" —\n * loudly, but only after the project has been generated around the bad port.\n *\n * Requiring all three costs three sockets and leaves neither gap. The wildcard\n * bind is the one the container itself has to make; the loopback binds are the\n * addresses `DATABASE_URL` will actually name.\n */\nexport async function isPortAvailable(port: number): Promise<boolean> {\n return (await canBind(port)) && (await canBind(port, \"127.0.0.1\")) && (await canBind(port, \"::1\"));\n}\n\n/** The range a project's compose port search starts in: 5433–5632. */\nconst COMPOSE_DB_PORT_FIRST = 5433;\nconst COMPOSE_DB_PORT_SPAN = 200;\n\n/**\n * Where this project's compose port search starts: a port derived from its path.\n *\n * Every project used to start at 5432 and take the first free port. Nothing a\n * scaffold does claims that port — its container does not exist yet — so\n * projects scaffolded side by side all landed on the same one: blog, ecommerce\n * and blank all got 5433. `rebase dev --docker` in the second one then found\n * the first one's database answering there.\n *\n * Not 5432 at all: it is the port a Postgres installed on this machine later\n * will take, and on macOS a container publishing `*:5432` and a server bound to\n * loopback do not even collide loudly (see {@link isPortAvailable}).\n */\nexport function composeDbPortStart(targetDirectory: string): number {\n const digest = crypto.createHash(\"sha256\").update(path.resolve(targetDirectory)).digest();\n return COMPOSE_DB_PORT_FIRST + (digest.readUInt32BE(0) % COMPOSE_DB_PORT_SPAN);\n}\n\n/**\n * The host port this project's compose `db` service publishes.\n *\n * From {@link composeDbPortStart} upwards, the first port nothing listens on\n * ({@link isPortAvailable}) and no container on this machine is bound to,\n * running or stopped: a stopped project's `db` container takes its port back\n * the moment it starts, and a TCP probe cannot see it. Docker that cannot be\n * asked claims nothing. `probes` stands in for both in the tests.\n */\nexport async function chooseComposeDbPort(\n targetDirectory: string,\n probes: {\n isFree?: (port: number) => Promise<boolean>;\n claimed?: () => Promise<Set<number> | null>;\n } = {}\n): Promise<number> {\n const isFree = probes.isFree ?? isPortAvailable;\n const claimed = (await (probes.claimed ?? dockerClaimedPorts)()) ?? new Set<number>();\n let port = composeDbPortStart(targetDirectory);\n while (claimed.has(port) || !(await isFree(port))) {\n port++;\n }\n return port;\n}\n\n/**\n * The CLI's own version, which is the runtime image tag a scaffolded project\n * pins. They move together: the CLI, the packages and the runtime image are cut\n * from one release, so the version that installed the project is the version\n * whose runtime can boot its bundle.\n *\n * Falls back to `latest` only when the CLI cannot read its own manifest — a\n * floating tag is worse than a pinned one, but better than a compose file that\n * names a version that was never published.\n */\nfunction readCliVersion(): string {\n const version = cliVersion();\n return version === \"unknown\" ? \"latest\" : version;\n}\n\n/**\n * The runtime image tag to pin, given the version of the CLI doing the scaffolding.\n *\n * Only a stable release publishes `rebasepro/server` — a multi-arch build on\n * every push to main would cost minutes per commit for an image nobody pulls.\n * So pinning a prerelease CLI's own version writes a tag that cannot exist, and\n * `docker compose up` fails on `manifest unknown`, which is the same dead end\n * as the missing-repository bug this pinning was added to prevent.\n *\n * A prerelease therefore falls back to `latest`, which is correct rather than\n * merely available: a bundle's manifest declares the runtime range it needs\n * (`^1`), the image supplies only `@rebasepro/server`, and the framework a\n * bundle runs is installed from its own `deps.declared` at boot. The current\n * stable runtime boots a canary bundle by design.\n *\n * A floating tag is a real cost — it is what pinning exists to avoid — so say\n * so in the file rather than leaving a reader to discover it.\n */\nexport function resolveRuntimeImageTag(cliVersion: string): { tag: string; note?: string } {\n // Semver prerelease: everything after the first `-`. `0.13.1-canary.gcd6689e`.\n if (/^\\d+\\.\\d+\\.\\d+-/.test(cliVersion)) {\n return {\n tag: \"latest\",\n note: `# Scaffolded by a prerelease CLI (${cliVersion}), which publishes no runtime image,\\n` +\n \"# so this floats to the newest stable runtime. Pin an exact version once you\\n\" +\n \"# deploy: a moving tag changes what you are running with no version changing.\"\n };\n }\n return { tag: cliVersion };\n}\n\n/**\n * Set `KEY=value` in a .env body, whether the key ships set, commented out or\n * missing entirely.\n *\n * The missing case is not hypothetical: `configureEnvFile` runs against\n * whatever `.env.example` is in the target directory, which for a project\n * scaffolded from an older template — or from one somebody edited — may not\n * carry a key this version of `init` is expected to write. Silently skipping it\n * produces a `.env` that satisfies no `${VAR:?…}` in the compose file, which\n * surfaces as a stack that refuses to interpolate rather than as anything\n * pointing back here.\n */\nfunction setEnvValue(content: string, key: string, value: string, header?: string): string {\n const line = new RegExp(`^#?\\\\s*${key}=.*$`, \"m\");\n if (line.test(content)) return content.replace(line, `${key}=${value}`);\n return `${content.trimEnd()}\\n\\n${header ? `${header}\\n` : \"\"}${key}=${value}\\n`;\n}\n\n/**\n * `sslmode=disable` on a URL that names a database on this machine and says\n * nothing about TLS.\n *\n * A local Postgres — Homebrew, Postgres.app, a container — serves no TLS, and\n * Atlas, which `rebase db push`, `db generate` and `db migrate` run, requires it\n * unless the URL says otherwise: `pq: SSL is not enabled on the server`. The URL\n * `init` writes when it picks the database has always carried the parameter; a\n * URL passed with `--database-url` reached `.env` without it, so the app\n * connected and the first push failed.\n *\n * Only a loopback address, and only when the URL names no `sslmode` or `ssl` of\n * its own: another machine's TLS is not ours to turn off, and a choice the\n * developer wrote down is theirs. A `host` or `hostaddr` parameter is the real\n * address (a socket directory, say), so that URL is left as given too, and so\n * is anything this cannot parse.\n */\nexport function disableSslOnLoopback(connectionString: string): string {\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n if ([\"sslmode\", \"ssl\", \"host\", \"hostaddr\"].some(param => url.searchParams.has(param))) return connectionString;\n\n // `hostname` keeps an IPv6 literal's brackets.\n const host = url.hostname.replace(/^\\[(.+)\\]$/, \"$1\");\n const loopback = host === \"localhost\" || host === \"::1\" || host === \"0.0.0.0\" || /^127(?:\\.\\d{1,3}){3}$/.test(host);\n if (!loopback) return connectionString;\n\n // Appended to the query as it stands, so the percent-encoding `pinSearchPath`\n // chose for `options` — the form libpq accepts — is kept byte for byte.\n url.search = url.search ? `${url.search}&sslmode=disable` : \"?sslmode=disable\";\n return url.toString();\n}\n\nexport async function configureEnvFile(targetDirectory: string, databaseUrl?: string) {\n const envExamplePath = path.join(targetDirectory, \".env.example\");\n const envPath = path.join(targetDirectory, \".env\");\n if (fs.existsSync(envExamplePath) && !fs.existsSync(envPath)) {\n // Copy .env.example → .env (keep .env.example as a reference in the repo)\n fs.copyFileSync(envExamplePath, envPath);\n // Owner-only from the first byte. `copyFileSync` copies the *source's*\n // permissions and the packaged `.env.example` is 0644, so the file that\n // is about to receive a generated JWT_SECRET, the database password and\n // REBASE_SERVICE_KEY was world-readable for the whole of `init` — on a\n // shared build box or a multi-user machine, any local account could read\n // another project's service key, which the API treats as a full admin\n // credential. `.rebase/state.json` (dev-port.ts) and `telemetry.json`\n // are both 0600 for the same reason; this file holds strictly more.\n fs.chmodSync(envPath, 0o600);\n\n // Generate secure random strings\n const jwtSecret = crypto.randomBytes(32).toString(\"hex\");\n const dbPassword = crypto.randomBytes(16).toString(\"hex\");\n const serviceKey = crypto.randomBytes(48).toString(\"base64\");\n // base64url rather than base64 or hex: 24 characters, comfortably past\n // the runtime's 12-character floor, and every character it can produce\n // is one dotenv and Compose interpolation read back unchanged. `+`, `/`\n // and `=` are fine in a .env value but not obviously so to a reader\n // about to paste one into a shell, and `#` — which hex cannot produce\n // but a passphrase generator might — would truncate the line.\n const adminPassword = crypto.randomBytes(18).toString(\"base64url\");\n\n let envContent = fs.readFileSync(envPath, \"utf-8\");\n\n // The banner is written for the file being read as a template. This\n // copy *is* the filled-in one — it already carries a generated\n // JWT_SECRET, service key and database password — and telling its\n // reader to \"copy this file to .env and fill in the values\" invites\n // exactly the overwrite the README warns against two paragraphs later.\n envContent = envContent.replace(\n /^(# ║ {2})(Copy this file to \\.env and fill in the values)( +║)$/m,\n (_match, open: string, old: string, close: string) => {\n const replacement = \"Generated by `rebase init` — the secrets below are already set\";\n // Keep the box drawn: pad or clip to the width the line had.\n const width = old.length + close.length - 1;\n return open + replacement.slice(0, width).padEnd(width, \" \") + \"║\";\n }\n );\n\n envContent = envContent.replace(\n /^JWT_SECRET=.*$/m,\n `JWT_SECRET=${jwtSecret}`\n );\n\n // Ships commented out in .env.example. Left unset, the server generates\n // one on every boot and silently invalidates the previous run's tokens,\n // so write a stable one now rather than making each restart a logout.\n envContent = envContent.replace(\n /^#\\s*REBASE_SERVICE_KEY=.*$/m,\n `REBASE_SERVICE_KEY=${serviceKey}`\n );\n\n // Read back rather than hardcoded, so this tracks whatever PORT the\n // generated .env ends up carrying. `docker-compose.yml` publishes the\n // api as `${PORT:-3001}:3001`.\n const composeApiPort = /^PORT=(\\d+)/m.exec(envContent)?.[1] ?? \"3001\";\n\n // Also ships commented out, and left that way the very first command\n // this project tells you to run does not work.\n //\n // `docker-compose.yml` declares `CORS_ORIGINS: ${CORS_ORIGINS:?…}` on\n // the `api` service — deliberately required, because an API that\n // guesses its allowed origins eventually allows the wrong one. But\n // Compose interpolates the WHOLE file before selecting services, so\n // `docker compose up -d db` — step 1 of the \"Next steps\" printed at the\n // end of `rebase init` — failed on a variable the `db` service does not\n // use. So did `docker compose config`: the file could not be read at all.\n //\n // The guard is right; a generated project should satisfy it. The compose\n // stack serves the bundled admin from the `api` container on ${PORT},\n // so that is the origin a browser loads it from. A deployment still has\n // to set its own, and gets a visible CORS failure rather than a silent\n // one if it forgets.\n envContent = envContent.replace(\n /^#\\s*CORS_ORIGINS=.*$/m,\n `CORS_ORIGINS=http://localhost:${composeApiPort}`\n );\n\n // The first admin, named rather than raced for.\n //\n // `docker-compose.yml` runs the api service with NODE_ENV=production,\n // and in production the first-registration-becomes-admin window is\n // shut — deliberately, because the compose stack is serving before its\n // operator has typed anything and whoever found the sign-up form first\n // would own it. A closed window needs a way in that is not a race, and\n // this is it: the account is named in the same file that already holds\n // the JWT secret and the database password.\n //\n // Written by `init` rather than left for the reader, because the\n // compose file declares both with `${VAR:?…}`: unset, `docker compose\n // up` does not produce a deployment without an admin, it produces a\n // file that refuses to interpolate — and it refuses for `docker compose\n // up -d db` too, which is step 1 of the \"Next steps\" printed below.\n //\n // The address is a placeholder the login route accepts. Not\n // `admin@localhost`: `POST /auth/login` parses its body with\n // `z.string().email()`, which rejects a domain with no dot, so that\n // address seeds an account and then 400s on every attempt to use it.\n // The runtime now refuses it at boot; this default is one it accepts.\n envContent = setEnvValue(\n envContent,\n \"REBASE_ADMIN_EMAIL\",\n \"admin@example.com\",\n \"# ── The first admin account, in production only ──────────────────────\\n\" +\n \"# `rebase dev` ignores both of these: on a laptop the first account to\\n\" +\n \"# register becomes the admin, and it says so at boot. In production —\\n\" +\n \"# `docker compose up`, or anything with NODE_ENV=production — that\\n\" +\n \"# window is shut, because the server answers on a hostname before you\\n\" +\n \"# have typed anything. So the operator names the account here instead.\\n\" +\n \"# Created once, while the user table is empty. Change the email to\\n\" +\n \"# yours, sign in, and change the password below.\"\n );\n envContent = setEnvValue(envContent, \"REBASE_ADMIN_PASSWORD\", adminPassword);\n\n // Blank the build-time API URL rather than shipping `http://localhost:3001`.\n //\n // This is the one environment-specific value `init` used to leave alone,\n // and the chain that made it dangerous is fully closed: `.env.example`\n // ships the literal, `frontend/vite.config.ts` sets `envDir: \"..\"` so\n // `vite build` reads *this* file, and the managed bundle is built on the\n // developer's own machine — so `.env` being gitignored does not save\n // anyone. A stock scaffold deployed with `rebase cloud deploy` served\n // HTML that passed every health check while every XHR from the live site\n // went to the developer's laptop. `rebase cloud env set VITE_API_URL=…`\n // refuses build-time variables, so there was no recovery from the\n // platform side either.\n //\n // Empty is not a missing value, it is the correct one: the client falls\n // back to `window.location.origin`, which is the right shape for a\n // single-origin bundle and the only one that keeps working when a custom\n // domain is added. `rebase dev` injects the port it actually bound, so\n // local development is unaffected.\n // The template ships it blank, so this is belt-and-braces for a project\n // whose .env.example was edited or predates that change.\n envContent = envContent.replace(/^#?\\s*VITE_API_URL=.*$/m, \"VITE_API_URL=\");\n\n // Pin the runtime image `docker-compose.yml` pulls.\n //\n // The compose file reads `rebasepro/server:${REBASE_VERSION:-latest}`,\n // and unset it resolves to `latest` — a tag that moves under a running\n // deployment. That is precisely the hazard `cloudbuild-runtime.yaml`\n // designed away for the managed fleet, which pins releases by digest\n // because \"re-pushing a tag silently changes what the fleet is running\n // with no version anywhere changing\". A self-hoster deserves the same\n // guarantee, and it costs one line here.\n //\n // It also makes the compose header's upgrade instruction true: \"To\n // upgrade Rebase, change REBASE_VERSION and restart\" is a no-op while\n // the value is unset and the tag floats.\n const { tag: runtimeVersion, note } = resolveRuntimeImageTag(readCliVersion());\n const pinned = `${note ? `${note}\\n` : \"\"}REBASE_VERSION=${runtimeVersion}`;\n envContent = /^#?\\s*REBASE_VERSION=.*$/m.test(envContent)\n ? envContent.replace(/^#?\\s*REBASE_VERSION=.*$/m, pinned)\n : `${envContent.trimEnd()}\\n\\n# The Rebase runtime image tag docker-compose.yml pulls.\\n# Change this and restart to upgrade; your project bundle is untouched.\\n${pinned}\\n`;\n\n if (databaseUrl) {\n if (/[\\r\\n]/.test(databaseUrl)) {\n throw new Refusal(\"Invalid DATABASE_URL: multiline values are not allowed.\");\n }\n // A supplied URL used to be written through verbatim, which quietly\n // dropped the `search_path=public` pin the generated URL below has\n // always carried. Postgres defaults `search_path` to `\"$user\",\n // public`, and this project creates a `rebase` schema — so on any\n // database whose role happens to be named `rebase` (the name every\n // template, compose file and deployment doc uses), unqualified SQL\n // resolves to `$user` and the project's tables get created in\n // `rebase` instead of `public`. Pinning here makes the two branches\n // agree; a URL that already pins something keeps it.\n // Imported lazily: this is the only line in `init` that needs the\n // Postgres package, and a static import would load pg + drizzle on\n // every CLI invocation.\n const { pinSearchPath } = await import(\"@rebasepro/server-postgres\");\n const pinnedUrl = disableSslOnLoopback(pinSearchPath(databaseUrl));\n // DATABASE_PASSWORD is still written even though the URL points\n // elsewhere: docker-compose.yml interpolates it into both\n // POSTGRES_PASSWORD and the backend's own DATABASE_URL, defaulting\n // to `${DATABASE_PASSWORD:-changeme}`. Omitting it here shipped a\n // compose stack whose database password was literally \"changeme\",\n // on a service that publishes a host port by default.\n //\n // A replacer function, not a replacement string: in a string, `$$`,\n // `$&` and `$'` are patterns, and a password is free to contain\n // them — `pa$$w0rd` reached .env as `pa$w0rd`.\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n () => `DATABASE_URL=${pinnedUrl}\\nDATABASE_PASSWORD=${dbPassword}`\n );\n } else {\n const dbPort = await chooseComposeDbPort(targetDirectory);\n envContent = envContent.replace(\n /^DATABASE_URL=.*$/m,\n // sslmode=disable: the paired docker-compose Postgres has no TLS,\n // and Go-based tooling (atlas, via `rebase db push`) defaults to\n // requiring SSL when the URL doesn't say otherwise.\n //\n // 127.0.0.1 rather than `localhost`: the name resolves to `::1`\n // first on macOS, so on a machine that already runs Postgres on\n // loopback the two addresses can reach two different servers.\n // An address cannot be ambiguous the way a name can.\n //\n // `%3D`, not a literal `=`, inside the `options` value. libpq\n // splits a URI query parameter on the FIRST `=` and rejects any\n // further one outright:\n // extra key/value separator \"=\" in URI query parameter: \"options\"\n // That is every libpq caller — `pg_dump`/`pg_restore` behind\n // `rebase db backup|restore`, and a plain `psql \"$DATABASE_URL\"`\n // copied out of this very file. It is not a version quirk; 15\n // through 18 all refuse it. node-postgres parses URLs itself and\n // accepts the literal form, which is why `rebase dev` and\n // `rebase db push` worked and this shipped broken for so long.\n // `pinSearchPath` (the --database-url branch above) has always\n // emitted the encoded form; this line is what disagreed.\n // Commented out, not omitted. `rebase dev` starts a managed\n // PostgreSQL when nothing names a database, which is what makes\n // a fresh project one command rather than four. The compose URL\n // stays here, one `#` away, because the alternative — a project\n // that mentions Docker nowhere — makes switching to it a\n // documentation lookup instead of an edit.\n // Deliberately short: the header copied from `.env.example`\n // sits directly above and already says what unset means. Saying\n // it twice, in the first section of the first file a new\n // developer opens, is how a generated file starts reading like\n // boilerplate nobody wrote on purpose.\n [\n \"# Commented out on purpose — that is what selects the managed database.\",\n \"# To use the docker-compose Postgres this project ships instead:\",\n \"# docker compose up -d db, then uncomment the line below.\",\n `# DATABASE_URL=postgresql://rebase_app:${dbPassword}@127.0.0.1:${dbPort}/rebase?options=-c%20search_path%3Dpublic&sslmode=disable`,\n `DATABASE_PASSWORD=${dbPassword}`\n ].join(\"\\n\")\n );\n // The SSL note further down illustrates `sslmode=disable` with a\n // full URL, and this file was copied from `.env.example` before the\n // rewrite below gives that one this project's port.\n envContent = envContent.replaceAll(\"@localhost:5432/rebase\", `@127.0.0.1:${dbPort}/rebase`);\n\n // `.env.example` is copied to `.env` and then kept, as the reference\n // that gets committed — so it is the one file in the project that\n // still carries the template's defaults after everything else has\n // been rewritten. Two of them are actively dangerous once the port\n // is derived per project:\n //\n // - its `DATABASE_URL` is UNCOMMENTED, contradicting the rule the\n // rest of the scaffold now states (\"unset means the managed\n // database\"), and\n // - it names `localhost:5432`, while this project's compose\n // publishes ${dbPort}.\n //\n // Copying `.env.example` to `.env` is a near-universal habit, and on\n // a machine that already runs Postgres on 5432 — most developer\n // machines — the result is not a connection failure. It is a\n // successful connection to somebody else's database, which boot will\n // then provision. Comment it out and give it this project's port.\n const envExampleReference = path.join(targetDirectory, \".env.example\");\n if (fs.existsSync(envExampleReference)) {\n let exampleContent = fs.readFileSync(envExampleReference, \"utf-8\");\n exampleContent = exampleContent.replace(\n /^DATABASE_URL=postgresql:\\/\\/[^\\n]*$/m,\n [\n \"# Commented out on purpose — that is what selects the managed database.\",\n \"# To use the docker-compose Postgres this project ships instead:\",\n \"# docker compose up -d db, then uncomment the line below in .env\",\n \"# (with DATABASE_PASSWORD from that file, not the placeholder here).\",\n `# DATABASE_URL=postgresql://rebase_app:changeme@127.0.0.1:${dbPort}/rebase?options=-c%20search_path%3Dpublic&sslmode=disable`\n ].join(\"\\n\")\n );\n // The prose further down illustrates `sslmode=disable` with a\n // full DSN. It is commented and not meant to be copied whole,\n // but a file that names two different ports for one database\n // teaches the reader to distrust both.\n exampleContent = exampleContent.replaceAll(\n \"@localhost:5432/rebase\",\n `@127.0.0.1:${dbPort}/rebase`\n );\n fs.writeFileSync(envExampleReference, exampleContent, \"utf-8\");\n }\n\n // Also update docker-compose.yml with the dynamic host port if it has the default 5432 port mapping\n const dockerComposePath = path.join(targetDirectory, \"docker-compose.yml\");\n if (fs.existsSync(dockerComposePath)) {\n let dockerComposeContent = fs.readFileSync(dockerComposePath, \"utf-8\");\n dockerComposeContent = dockerComposeContent.replace(\n /-\\s*\"5432:5432\"/g,\n `- \"${dbPort}:5432\"`\n );\n fs.writeFileSync(dockerComposePath, dockerComposeContent, \"utf-8\");\n }\n }\n\n // `mode` only applies when the file is created, and this one exists\n // already — so chmod as well, exactly as `writeStateFile` does.\n fs.writeFileSync(envPath, envContent, {\n encoding: \"utf-8\",\n mode: 0o600\n });\n fs.chmodSync(envPath, 0o600);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAM,SAAS,UAAU,GAAG,MAAM;AAIlC,IAAM,aAAa,cAAc,OAAO,KAAK,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAEzC,SAAS,cAAc,YAAoB,YAAmC;CAC1E,MAAM,OAAO,KAAK,MAAM,UAAU,CAAC,CAAC;CACpC,OAAO,cAAc,eAAe,MAAM;EACtC,IAAI,KAAK,SAAS,UAAU,MAAM,YAC9B,OAAO;EAEX,aAAa,KAAK,QAAQ,UAAU;CACxC;CACA,OAAO;AACX;AAEA,IAAM,UAAU,cAAc,WAAW,KAAK;AAE9C,IAAM,kBAAkB;;;;;;;;;;;;;;;;AAiBxB,IAAa,6BAA6B;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;AAGA,SAAgB,oBAAoB,MAA6B;CAC7D,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;CACzB,IAAI,CAAC,gBAAgB,KAAK,IAAI,GAC1B,OAAO;CAEX,OAAO;AACX;;;;;;;;;;AAaA,IAAM,mBAA2E,CAC7E;CAAE,MAAM;CACZ,OAAO;CACP,OAAO;AAAkB,GACrB;CAAE,MAAM;CACZ,OAAO;CACP,OAAO;AAAe,CACtB;AAEA,IAAM,iBAAg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C,KAAK,IAAI,CACf;GAIA,aAAa,WAAW,WAAW,0BAA0B,cAAc,OAAO,QAAQ;GAmB1F,MAAM,sBAAsB,KAAK,KAAK,iBAAiB,cAAc;GACrE,IAAI,GAAG,WAAW,mBAAmB,GAAG;IACpC,IAAI,iBAAiB,GAAG,aAAa,qBAAqB,OAAO;IACjE,iBAAiB,eAAe,QAC5B,yCACA;KACI;KACA;KACA;KACA;KACA,6DAA6D,OAAO;IACxE,CAAC,CAAC,KAAK,IAAI,CACf;IAKA,iBAAiB,eAAe,WAC5B,0BACA,cAAc,OAAO,QACzB;IACA,GAAG,cAAc,qBAAqB,gBAAgB,OAAO;GACjE;GAGA,MAAM,oBAAoB,KAAK,KAAK,iBAAiB,oBAAoB;GACzE,IAAI,GAAG,WAAW,iBAAiB,GAAG;IAClC,IAAI,uBAAuB,GAAG,aAAa,mBAAmB,OAAO;IACrE,uBAAuB,qBAAqB,QACxC,oBACA,MAAM,OAAO,OACjB;IACA,GAAG,cAAc,mBAAmB,sBAAsB,OAAO;GACrE;EACJ;EAIA,GAAG,cAAc,SAAS,YAAY;GAClC,UAAU;GACV,MAAM;EACV,CAAC;EACD,GAAG,UAAU,SAAS,GAAK;CAC/B;AACJ"}
@@ -1,2 +0,0 @@
1
- import { o as readLastDevDocker } from "./prepare-CTw9NEkh.js";
2
- export { readLastDevDocker };
@@ -1 +0,0 @@
1
- {"version":3,"file":"manifest-BtzDy7KQ.js","names":[],"sources":["../src/manifest.ts"],"sourcesContent":["/**\n * Loading, validating and synthesizing `rebase.json`.\n *\n * The manifest declares *topology*: which runtime major a project targets and\n * which apps this repository contributes. It is deliberately small — schema,\n * security rules, hooks and functions stay in TypeScript, where a type system\n * can check them.\n *\n * Two properties matter more than the file format itself:\n *\n * - **A missing manifest is never an error.** Every project that exists today\n * predates this file. One is synthesized from the conventions the template\n * already follows, so nothing breaks and nobody is forced to migrate.\n * - **Validation reports every problem at once**, with the path to each. A\n * config file that surfaces its mistakes one run at a time is a bad config\n * file.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n findStorageSuffixCollision,\n parseAppAddress,\n reservedPrefixFor,\n type AppAddress,\n type ManagedCompatibility,\n type RebaseAppConfig,\n type RebaseBackendAppConfig,\n type RebaseProjectManifest,\n type RebaseStaticAppConfig\n} from \"@rebasepro/types\";\nimport { MANIFEST_FILENAME } from \"./utils/project\";\nimport { detectPackageManager, getPMCommands } from \"./utils/package-manager\";\n\n/** Runtime range written into new manifests. */\nexport const CURRENT_RUNTIME_RANGE = \"^1\";\n\n/** Conventional locations, matching what `rebase init` scaffolds. */\nexport const DEFAULT_CONFIG_DIR = \"config\";\nexport const DEFAULT_FUNCTIONS_DIR = \"backend/functions\";\nexport const DEFAULT_CRONS_DIR = \"backend/crons\";\nexport const DEFAULT_SCHEMA_FILE = \"backend/src/schema.generated.ts\";\n\nexport interface ManifestValidationIssue {\n /** Dotted path to the offending value, e.g. `apps.web.output`. */\n path: string;\n message: string;\n}\n\nexport interface LoadedManifest {\n manifest: RebaseProjectManifest;\n /** Where it came from — a real file, or inferred from the directory layout. */\n source: \"file\" | \"synthesized\";\n /** Absolute path to `rebase.json`, when one exists. */\n filePath?: string;\n}\n\nexport class ManifestError extends Error {\n constructor(message: string, readonly issues: ManifestValidationIssue[] = []) {\n super(message);\n this.name = \"ManifestError\";\n }\n}\n\nconst APP_TYPES = [\"backend\", \"static\"] as const;\n\n/**\n * App types that used to exist, and what replaced each one.\n *\n * Kept so a manifest written against the old vocabulary fails with the fix in\n * hand rather than with `must be one of: backend, static`, which tells a reader\n * what is wrong but not what to write instead.\n */\nconst REMOVED_APP_TYPES: Record<string, string> = {\n admin:\n \"the admin panel is an ordinary static app now — declare it as \" +\n '{ \"type\": \"static\", \"root\": \"frontend\", \"output\": \"frontend/dist\", \"path\": \"/admin\" }',\n custom:\n \"who owns the server is a property of the backend now — declare \" +\n '{ \"type\": \"backend\", \"runtime\": \"custom\" } instead of a separate app',\n mobile:\n \"mobile apps are no longer declared in the manifest — nothing consumed this type. \" +\n \"Remove the entry\"\n};\n\n/** Reserved because they name things in URLs and CLI output. */\nconst RESERVED_APP_NAMES = new Set([\"api\", \"health\", \"metrics\", \"livez\", \"_rebase\"]);\n\n/**\n * Validate a URL path an app is served at: a static app's `path`, or the path\n * part of it when `path` is a URL, and `cms`.\n *\n * Normalizes to \"no trailing slash, except for the root\" so that mounting and\n * the `REBASE_APP_BASE` build variable have one shape to reason about.\n *\n * `origin` is `https://<host>` when the path came out of a URL, and is only\n * used to phrase the fix in the form the author wrote: telling someone who\n * wrote `\"https://admin.example.com/cms/\"` to write `\"/cms\"` would be telling\n * them to drop the hostname.\n */\nfunction checkAppPath(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[],\n origin = \"\"\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !value.startsWith(\"/\")) {\n issues.push({\n path: fieldPath,\n message: 'must be an absolute path like \"/admin\"'\n });\n return undefined;\n }\n // Before the `..` and empty-segment rules, which it would otherwise trip\n // with a message about paths. `//admin.example.com` is a URL with the\n // scheme left off, and mounting it as a path is not what was meant.\n if (!origin && value.startsWith(\"//\")) {\n issues.push({\n path: fieldPath,\n message: `looks like a URL without its scheme — write \"https:${value}\" to give this app its own hostname`\n });\n return undefined;\n }\n if (value.includes(\"..\") || value.includes(\"//\")) {\n issues.push({\n path: fieldPath,\n message: origin\n ? `must have a plain path after the hostname, with no \"..\" and no empty segment — like \"${origin}/admin\"`\n : 'must be an absolute path like \"/admin\", with no \"..\" and no empty segment'\n });\n return undefined;\n }\n if (value !== \"/\" && value.endsWith(\"/\")) {\n issues.push({\n path: fieldPath,\n message: `must not end with a slash — write \"${origin}${value.slice(0, -1)}\", not \"${origin}${value}\"`\n });\n return undefined;\n }\n // Mounting is longest-path-first, so an app at `/api` outranks the API and\n // every request to it is answered with that app's index.html — a 200 of HTML\n // where the caller wanted JSON, from a deployment that looks healthy. A\n // hostname does not change that: the backend's routes are registered before\n // any app's, on every hostname the project answers on.\n const reserved = reservedPrefixFor(value);\n if (reserved) {\n issues.push({\n path: fieldPath,\n message: `cannot be \"${reserved}\" or nest under it — the backend serves that path` +\n (origin ? \" on every hostname, this one included\" : \"\") +\n \", and an app mounted there would answer the API's requests with its own index.html\"\n });\n return undefined;\n }\n return value;\n}\n\n/**\n * Validate a static app's `path`, which is either a path or an https URL that\n * also gives the app a hostname of its own.\n *\n * The split is {@link parseAppAddress}, shared with the control plane and the\n * runtime so that all three read one value the same way. What it leaves to the\n * caller — the path rules — are {@link checkAppPath}'s, applied to the path\n * part of either form.\n */\nfunction checkAppAddress(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[]\n): AppAddress | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n issues.push({\n path: fieldPath,\n message: 'must be an absolute path like \"/admin\", or a URL like \"https://admin.example.com\"'\n });\n return undefined;\n }\n const parsed = parseAppAddress(value);\n if (!parsed.ok) {\n issues.push({ path: fieldPath, message: parsed.reason });\n return undefined;\n }\n const { host } = parsed.address;\n const appPath = checkAppPath(parsed.address.path, fieldPath, issues, host ? `https://${host}` : \"\");\n if (appPath === undefined) return undefined;\n return host ? { host, path: appPath } : { path: appPath };\n}\n\n/**\n * Where a validated static app answers: its hostname, if its `path` names one,\n * and the path under it.\n *\n * The manifest keeps `path` as it was written, URL and all, because it is also\n * what `writeManifest` puts back: storing the split pieces instead would have\n * `rebase eject` rewrite `\"https://admin.example.com\"` to `\"/\"` and drop the\n * hostname from a file the developer never asked it to touch. Everything that\n * mounts, builds or prints an app reads it through here instead, so there is\n * one reading of the field.\n *\n * Throws on a value `validateManifest` would have refused. Every caller holds a\n * manifest that came through it, so reaching the throw means one did not — and\n * guessing an address for it would build or mount the app somewhere it was\n * never declared.\n */\nexport function staticAppAddress(name: string, app: { path?: string }): AppAddress {\n if (app.path === undefined) return { path: \"/\" };\n const parsed = parseAppAddress(app.path);\n if (!parsed.ok) {\n throw new ManifestError(`apps.${name}.path ${parsed.reason}`, [{ path: `apps.${name}.path`, message: parsed.reason }]);\n }\n return parsed.address;\n}\n\n/**\n * An address as a developer would type it: the path alone for an app on every\n * hostname, the https URL for one on its own. The root of a hostname prints as\n * the bare origin — `https://admin.example.com`, which is how it is declared.\n */\nexport function formatAppAddress(address: AppAddress): string {\n if (!address.host) return address.path;\n return `https://${address.host}${address.path === \"/\" ? \"\" : address.path}`;\n}\n\n/**\n * The order static apps are mounted in, and the order a bundle lists them.\n *\n * Longest path first, so an app at `/` is registered after the apps beneath it\n * and its catch-all cannot claim their URLs. At an equal path, the app bound to\n * a hostname goes first: on that hostname it is the one that answers, and the\n * app on every hostname answers the rest. That is the runtime's matching rule,\n * restated as a sort so a bundle reads in the order it is served.\n */\nexport function compareMountOrder(a: AppAddress, b: AppAddress): number {\n if (a.path.length !== b.path.length) return b.path.length - a.path.length;\n return (a.host ? 0 : 1) - (b.host ? 0 : 1);\n}\n\n/**\n * Is `candidate` the path `parent`, or something beneath it?\n *\n * Segment-aware for the same reason `isForbiddenStaticPath` is: a plain\n * `startsWith` reads `/admin` as living under `/adm`.\n */\nfunction isUnderPath(candidate: string, parent: string): boolean {\n if (parent === \"/\") return true;\n return candidate === parent || candidate.startsWith(`${parent}/`);\n}\n\n/**\n * Validate where an app says it mounts the Rebase CMS.\n *\n * The same shape as {@link checkAppPath} — it is a URL path and ends up in the\n * same places — plus one rule of its own: it has to be inside the app declaring\n * it. The app's SPA fallback is what answers that URL, so a `cms` outside its\n * `path` names an address this app will never serve. That is a link the console\n * would then offer to a 404, which is worse than the missing link it replaces.\n *\n * Always a path, even on an app whose `path` is a URL. The app's address\n * already says which hostname it answers on, and a second hostname here could\n * only disagree with it; `cms` says where on that hostname the CMS is.\n */\nfunction checkCmsPath(\n value: unknown,\n app: AppAddress,\n fieldPath: string,\n issues: ManifestValidationIssue[]\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value === \"string\" && (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith(\"//\"))) {\n const parsed = parseAppAddress(value.startsWith(\"//\") ? `https:${value}` : value);\n issues.push({\n path: fieldPath,\n message: \"must be a path, not a URL — the CMS is a route of this app, which is served where its \" +\n \"`path` says\" + (parsed.ok ? `. Write \"${parsed.address.path}\"` : \"\")\n });\n return undefined;\n }\n const cms = checkAppPath(value, fieldPath, issues);\n if (cms === undefined) return undefined;\n if (!isUnderPath(cms, app.path)) {\n issues.push({\n path: fieldPath,\n message: `must be inside this app's path — it is at \"${formatAppAddress(app)}\", so it cannot serve \"${cms}\". ` +\n \"The CMS is a route of this app, not a separate deployment; if it really lives elsewhere, \" +\n \"declare that app and put `cms` on it instead\"\n });\n return undefined;\n }\n return cms;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reject paths that escape the repository.\n *\n * A manifest is committed and reviewed, so this is not a security boundary so\n * much as a guard against `../../` typos that would otherwise have `rebase build`\n * writing outside the project.\n *\n * `mayEscape` is for `context`, and only for `context`. Every other path here\n * names something Rebase *reads* — collections, functions, the generated\n * schema, the built assets to serve — and those have to be inside the project\n * or the bundle cannot carry them. A Docker build context is the one field that\n * names something Rebase never opens: it is handed to `docker build`, and in\n * any workspace repository the thing it has to name is the workspace root,\n * above the app. That is not exotic. It is what pnpm, turbo and nx layouts all\n * look like, and it is what this repository's own reference project needs — its\n * Dockerfile's first instruction copies `pnpm-lock.yaml`, which does not exist\n * beside `rebase.json` and never will.\n *\n * Refusing it did not prevent the escape; it only stopped anyone declaring it.\n * `app/rebase.json` built from the monorepo root the whole time — via\n * `infra/cloudbuild.yaml`, which says `-f app/backend/Dockerfile .` — while the\n * manifest said the context was `app/` and `rebase build` printed a command\n * that dies on its first `COPY`.\n */\nfunction checkRelativePath(\n value: unknown,\n fieldPath: string,\n issues: ManifestValidationIssue[],\n { required, mayEscape = false }: { required: boolean; mayEscape?: boolean }\n): string | undefined {\n if (value === undefined) {\n if (required) issues.push({ path: fieldPath,\nmessage: \"is required\" });\n return undefined;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") {\n issues.push({ path: fieldPath,\nmessage: \"must be a non-empty string\" });\n return undefined;\n }\n if (path.isAbsolute(value)) {\n issues.push({ path: fieldPath,\nmessage: \"must be a relative path, not absolute\" });\n return undefined;\n }\n const normalized = path.normalize(value);\n if (!mayEscape && (normalized === \"..\" || normalized.startsWith(`..${path.sep}`))) {\n issues.push({ path: fieldPath,\nmessage: \"must stay inside the project directory\" });\n return undefined;\n }\n return value;\n}\n\n/** Fields each app type understands. Anything else is a typo or a newer CLI. */\nconst KNOWN_APP_FIELDS: Record<string, readonly string[]> = {\n backend: [\"type\", \"runtime\", \"config\", \"functions\", \"crons\", \"schema\",\n \"usersCollection\", \"registerDatabase\", \"dockerfile\", \"context\", \"port\"],\n static: [\"type\", \"root\", \"build\", \"output\", \"path\", \"spa\", \"cms\"]\n};\n\n/**\n * Fields people reach for to give a static app a hostname, which is spelled as\n * a URL in `path` instead. Named so the warning says that, rather than \"your\n * CLI may be older than this manifest\" — which is false here and sends the\n * reader to upgrade a CLI that already does what they wanted.\n */\nconst HOSTNAME_FIELDS = new Set([\"host\", \"hostname\", \"domain\"]);\n\n/**\n * Report a field this CLI does not recognise.\n *\n * A warning rather than an error, and the distinction matters in both\n * directions. `\"pathh\": \"/admin\"` is a typo that would otherwise be silently\n * dropped — the app builds for `/`, mounts at `/`, and the only symptom is that\n * it is not where you put it. But an unknown field is also what an *older* CLI\n * sees when it opens a manifest written for a newer one, and refusing to build\n * over a field that is simply from the future would make every manifest addition\n * a breaking change.\n *\n * So: name it, suggest the near-miss, and carry on.\n */\nfunction warnUnknownFields(name: string, raw: Record<string, unknown>, type: string): void {\n const known = KNOWN_APP_FIELDS[type];\n if (!known) return;\n\n for (const field of Object.keys(raw)) {\n if (known.includes(field)) continue;\n if (type === \"static\" && HOSTNAME_FIELDS.has(field)) {\n const value = raw[field];\n const host = typeof value === \"string\" && value.trim() !== \"\"\n ? value.trim().replace(/^[a-z]+:\\/\\//i, \"\").replace(/\\/+$/, \"\")\n : \"admin.example.com\";\n const under = typeof raw.path === \"string\" && raw.path.startsWith(\"/\") && raw.path !== \"/\" ? raw.path : \"\";\n console.warn(\n `⚠ rebase.json: apps.${name}.${field} is not a field — it is ignored. To serve this app on its ` +\n `own hostname, write its path as a URL: \"path\": \"https://${host}${under}\"`\n );\n continue;\n }\n const suggestion = known.find(candidate => isNearMiss(candidate, field));\n console.warn(\n `⚠ rebase.json: apps.${name}.${field} is not a field this CLI knows.` +\n (suggestion ? ` Did you mean \"${suggestion}\"?` : \" It is ignored — your CLI may be older than this manifest.\")\n );\n }\n}\n\n/**\n * One edit apart, ignoring case: enough for a typo, tight enough to stay quiet.\n *\n * The same rule as `isNearMiss` in `@rebasepro/utils`, which the collection\n * validator uses for unknown `admin` keys. It is a copy rather than an import\n * because the CLI does not depend on `@rebasepro/utils`, and adding the\n * dependency is a lockfile change; collapsing the two is worth doing the next\n * time this package's dependencies are touched.\n */\nfunction isNearMiss(a: string, b: string): boolean {\n const x = a.toLowerCase();\n const y = b.toLowerCase();\n if (x === y) return true;\n if (Math.abs(x.length - y.length) > 1) return false;\n\n const [shorter, longer] = x.length <= y.length ? [x, y] : [y, x];\n let i = 0;\n let j = 0;\n let edits = 0;\n while (i < shorter.length && j < longer.length) {\n if (shorter[i] === longer[j]) { i++; j++; continue; }\n if (++edits > 1) return false;\n if (shorter.length === longer.length) i++;\n j++;\n }\n return edits + (longer.length - j) + (shorter.length - i) <= 1;\n}\n\nfunction validateApp(\n name: string,\n raw: unknown,\n issues: ManifestValidationIssue[]\n): RebaseAppConfig | undefined {\n const base = `apps.${name}`;\n\n if (!isRecord(raw)) {\n issues.push({ path: base,\nmessage: \"must be an object\" });\n return undefined;\n }\n\n const type = raw.type;\n if (typeof type === \"string\" && REMOVED_APP_TYPES[type]) {\n issues.push({ path: `${base}.type`,\nmessage: `\"${type}\" is no longer an app type — ${REMOVED_APP_TYPES[type]}` });\n return undefined;\n }\n if (typeof type !== \"string\" || !(APP_TYPES as readonly string[]).includes(type)) {\n issues.push({\n path: `${base}.type`,\n message: `must be one of: ${APP_TYPES.join(\", \")}`\n });\n return undefined;\n }\n\n warnUnknownFields(name, raw, type);\n\n switch (type) {\n case \"backend\": {\n checkRelativePath(raw.config, `${base}.config`, issues, { required: false });\n checkRelativePath(raw.functions, `${base}.functions`, issues, { required: false });\n checkRelativePath(raw.crons, `${base}.crons`, issues, { required: false });\n checkRelativePath(raw.schema, `${base}.schema`, issues, { required: false });\n checkRelativePath(raw.usersCollection, `${base}.usersCollection`, issues, { required: false });\n\n if (raw.mode !== undefined) {\n issues.push({\n path: `${base}.mode`,\n message:\n \"is no longer a field — collections come from the config directory when \" +\n \"it exists, and are introspected from the database when it does not\"\n });\n }\n\n const custom = raw.runtime === \"custom\";\n if (raw.runtime !== \"managed\" && !custom) {\n issues.push({\n path: `${base}.runtime`,\n message: 'is required, and must be \"managed\" or \"custom\"'\n });\n }\n\n // The image fields describe an image this repository builds. Under a\n // managed backend there is no such image, so accepting them silently\n // would be accepting a Dockerfile that never gets built.\n for (const field of [\"dockerfile\", \"context\", \"port\"] as const) {\n if (raw[field] !== undefined && !custom) {\n issues.push({\n path: `${base}.${field}`,\n message: 'only applies to a custom runtime — set \"runtime\": \"custom\" to build your own image'\n });\n }\n }\n checkRelativePath(raw.dockerfile, `${base}.dockerfile`, issues, { required: false });\n // `dockerfile` stays project-relative even when the context is\n // above the project: it names a file in THIS repository, and moving\n // the context should not rewrite it. `rebase build` re-expresses it\n // against the context when it prints the command.\n checkRelativePath(raw.context, `${base}.context`, issues, { required: false, mayEscape: true });\n if (raw.port !== undefined && (typeof raw.port !== \"number\" || !Number.isInteger(raw.port))) {\n issues.push({ path: `${base}.port`,\nmessage: \"must be an integer\" });\n }\n if (raw.registerDatabase !== undefined && typeof raw.registerDatabase !== \"boolean\") {\n issues.push({ path: `${base}.registerDatabase`,\nmessage: \"must be a boolean\" });\n }\n // Constructed, not asserted. Everything above pushes an issue for a\n // field it does not like and then leaves the field alone, so\n // double-casting `raw` to `RebaseAppConfig` handed the caller the *whole\n // parsed object* under a type describing only these fields — an\n // unknown key that `warnUnknownFields` merely warned about travelled\n // on as if it were part of the config, and a field that failed its\n // check above travelled on with the type saying it had passed.\n // Naming them is also what keeps this list and the interface in step:\n // a field added to `RebaseBackendAppConfig` and not validated here\n // now fails to compile instead of silently arriving unchecked.\n return {\n type: \"backend\",\n runtime: custom ? \"custom\" : \"managed\",\n config: raw.config as string | undefined,\n functions: raw.functions as string | undefined,\n crons: raw.crons as string | undefined,\n schema: raw.schema as string | undefined,\n usersCollection: raw.usersCollection as string | undefined,\n registerDatabase: raw.registerDatabase as boolean | undefined,\n dockerfile: raw.dockerfile as string | undefined,\n context: raw.context as string | undefined,\n port: raw.port as number | undefined\n };\n }\n case \"static\": {\n checkRelativePath(raw.root, `${base}.root`, issues, { required: true });\n checkRelativePath(raw.output, `${base}.output`, issues, { required: true });\n if (raw.build !== undefined && typeof raw.build !== \"string\") {\n issues.push({ path: `${base}.build`,\nmessage: \"must be a string command\" });\n }\n if (raw.spa !== undefined && typeof raw.spa !== \"boolean\") {\n issues.push({ path: `${base}.spa`,\nmessage: \"must be a boolean\" });\n }\n const address = checkAppAddress(raw.path, `${base}.path`, issues);\n checkCmsPath(raw.cms, address ?? { path: \"/\" }, `${base}.cms`, issues);\n // See the backend branch: constructed for the same reasons. `path`\n // is kept as written — see `staticAppAddress` for why the split\n // pieces are not what the manifest stores.\n return {\n type: \"static\",\n root: raw.root as string,\n build: raw.build as string | undefined,\n output: raw.output as string,\n path: address ? raw.path as string : undefined,\n spa: raw.spa as boolean | undefined,\n cms: raw.cms as string | undefined\n };\n }\n default:\n return undefined;\n }\n}\n\n/**\n * Validate a parsed manifest, collecting every problem.\n */\nexport function validateManifest(raw: unknown): {\n manifest?: RebaseProjectManifest;\n issues: ManifestValidationIssue[];\n} {\n const issues: ManifestValidationIssue[] = [];\n\n if (!isRecord(raw)) {\n return { issues: [{ path: \"\",\nmessage: `${MANIFEST_FILENAME} must contain a JSON object` }] };\n }\n\n if (typeof raw.rebase !== \"string\" || raw.rebase.trim() === \"\") {\n // `runtime` used to be this key. It now means who owns the backend\n // process, so a manifest still using it at the top level is naming the\n // wrong thing rather than merely missing a field.\n const message = typeof raw.runtime === \"string\"\n ? `is required, e.g. \"${CURRENT_RUNTIME_RANGE}\" — this is the top-level \"runtime\" key renamed, ` +\n 'because \"runtime\" now means \"managed\" or \"custom\" on the backend app'\n : `is required, e.g. \"${CURRENT_RUNTIME_RANGE}\"`;\n issues.push({ path: \"rebase\",\nmessage });\n }\n\n if (!isRecord(raw.apps)) {\n issues.push({ path: \"apps\",\nmessage: \"is required and must be an object\" });\n return { issues };\n }\n\n const apps: Record<string, RebaseAppConfig> = {};\n let backendCount = 0;\n\n for (const [name, value] of Object.entries(raw.apps)) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {\n issues.push({\n path: `apps.${name}`,\n message: \"name must be lowercase alphanumeric with dashes (it appears in URLs)\"\n });\n continue;\n }\n if (RESERVED_APP_NAMES.has(name)) {\n issues.push({ path: `apps.${name}`,\nmessage: \"name is reserved\" });\n continue;\n }\n\n const app = validateApp(name, value, issues);\n if (!app) continue;\n if (app.type === \"backend\") backendCount++;\n apps[name] = app;\n }\n\n // One backend per *project*. A repository declaring two would have two sets\n // of collections claiming the same database and the same API surface.\n if (backendCount > 1) {\n issues.push({\n path: \"apps\",\n message: \"a project may declare at most one backend app\"\n });\n }\n\n // Two apps at one address is not a preference conflict — the first one\n // mounted swallows the other's URLs, and the loser looks like it deployed\n // fine. The address is the hostname and the path together: an app at \"/\" on\n // admin.example.com and one at \"/\" everywhere else are two different\n // addresses, and that pair is the point of giving an app a hostname. An app\n // with no hostname is its own value here, not a wildcard that collides with\n // every hostname — at an equal path the one naming the hostname wins there.\n const byAddress = new Map<string, string>();\n for (const [name, app] of Object.entries(apps)) {\n if (app.type !== \"static\") continue;\n const address = staticAppAddress(name, app);\n const key = `${address.host ?? \"\"} ${address.path}`;\n const owner = byAddress.get(key);\n if (owner) {\n issues.push({\n path: `apps.${name}.path`,\n message: `two apps cannot serve the same path — \"${owner}\" is already at \"${formatAppAddress(address)}\"`\n });\n continue;\n }\n byAddress.set(key, name);\n }\n\n // One CMS per project. Not a taste ruling: everything downstream — the\n // console's button, `rebase apps list`, the app row that records it — talks\n // about \"the project's CMS\", and two of them would make every one of those\n // pick arbitrarily. A repository that genuinely wants a second admin surface\n // has two apps and can say so by name.\n const withCms = Object.entries(apps).filter(\n ([, app]) => app.type === \"static\" && typeof app.cms === \"string\"\n );\n if (withCms.length > 1) {\n for (const [name] of withCms.slice(1)) {\n issues.push({\n path: `apps.${name}.cms`,\n message: `a project has one CMS — \"${withCms[0][0]}\" already declares one`\n });\n }\n }\n\n refuseStorageBlock(raw.storage, issues);\n\n // Carried rather than dropped. This key is the only repository-wide privacy\n // control the CLI honours, and a key that does not survive a parse does not\n // survive a rewrite either: `writeManifest` builds its output from what this\n // returned, so `rebase eject` deleted a committed `\"telemetry\": false` and\n // every developer who had ever opted in silently resumed sending events.\n //\n // Only a boolean is a value here — `true` is ignored elsewhere, loudly, but\n // it is still valid. A string `\"false\"` is the mistake that would leave\n // sharing on while looking like it was off, so it is named rather than\n // quietly discarded.\n let telemetry: boolean | undefined;\n if (raw.telemetry !== undefined) {\n if (typeof raw.telemetry === \"boolean\") {\n telemetry = raw.telemetry;\n } else {\n issues.push({\n path: \"telemetry\",\n message: \"must be a boolean — only `false` does anything, and it opts this repository out of usage sharing\"\n });\n }\n }\n\n if (issues.length > 0) return { issues };\n\n return {\n manifest: {\n $schema: typeof raw.$schema === \"string\" ? raw.$schema : undefined,\n rebase: raw.rebase as string,\n apps,\n ...(telemetry !== undefined ? { telemetry } : {})\n },\n issues\n };\n}\n\n/**\n * Refuse a hand-written `storage` block.\n *\n * Buckets are declared in config code now — `bucket(\"media\")` — and the graph\n * is generated from those declarations into `rebase.resources.json`. Two homes\n * for one concept is what this replaced, and the reason it had to go is that\n * the runtime *merged* them: a bucket declared in both had one engine kept and\n * the other silently discarded.\n *\n * Refused rather than ignored. A key that still parses and no longer does\n * anything is the same failure wearing a nicer hat — the author sees valid\n * JSON, the platform sees a bucket, and the runtime has neither.\n */\nfunction refuseStorageBlock(raw: unknown, issues: ManifestValidationIssue[]): undefined {\n if (raw === undefined) return undefined;\n issues.push({\n path: \"storage\",\n message:\n \"is no longer read. Declare each bucket in your config's resources.ts — \" +\n 'bucket(\"media\", { engine: \"s3\" }) — then run `rebase resources --write`, ' +\n \"which generates rebase.resources.json. Refused rather than ignored: this \" +\n \"block used to be merged with the code's declarations and silently win.\"\n });\n return undefined;\n}\n\n/**\n * Infer a manifest from a directory that does not have one.\n *\n * This mirrors what the template scaffolds, which is what makes adopting the\n * manifest a no-op for existing projects: the synthesized result is what they\n * would have written by hand. A field is written only when it says something\n * its default does not, as the scaffold's own `rebase.json` does — `spa`,\n * `functions` and `crons` restate their defaults, so they are left out.\n *\n * The static app's build command is the project's package manager, spelled the\n * way `rebase init` spells it, so a pnpm project is never built with npm.\n *\n * The static app is named `web`, where the scaffold says `admin`. The name is an\n * app's identity on a deployed project: Rebase Cloud registered `web` for every\n * project that deployed without a manifest, and its next deploy has to name the\n * same app. Nor can an inference know where an app mounts the CMS (`cms`), which\n * is a client-side route. `rebase apps init --force` therefore keeps the name,\n * `path` and `cms` a manifest already declares for the app it infers again.\n *\n * The backend's `runtime` is inferred from whether the repository declares a\n * **Dockerfile** — the thing that actually builds an image — and from nothing\n * else. It used to be inferred from the presence of `backend/src/index.ts`,\n * which every scaffolded project had whether or not it wanted its own server, so\n * projects predating the manifest silently landed on the custom runtime and paid\n * for it.\n */\nexport function synthesizeManifest(projectRoot: string): RebaseProjectManifest {\n const exists = (relative: string): boolean => fs.existsSync(path.join(projectRoot, relative));\n const apps: Record<string, RebaseAppConfig> = {};\n\n const hasConfig = exists(DEFAULT_CONFIG_DIR);\n const hasBackend = exists(\"backend\");\n const dockerfile = [\"Dockerfile\", \"backend/Dockerfile\"].find(exists);\n\n if (hasBackend || hasConfig) {\n const backend: RebaseBackendAppConfig = dockerfile\n ? { type: \"backend\",\nruntime: \"custom\",\ndockerfile,\ncontext: \".\" }\n : { type: \"backend\",\nruntime: \"managed\" };\n apps.backend = backend;\n\n // Say it out loud. The file looks exactly like the server and is never\n // loaded, which used to be discovered only after a deploy answered 404\n // on every route defined in it.\n if (!dockerfile && exists(\"backend/src/index.ts\")) {\n console.warn(\n \"⚠ backend/src/index.ts exists but this project's backend is managed — it is\\n\" +\n \" never loaded. Delete it, or move it aside and run `rebase eject`, which\\n\" +\n \" writes an entrypoint of its own and owns the image. Eject does not adopt\\n\" +\n \" this file: it refuses to replace it unless you pass --force.\"\n );\n }\n }\n\n if (exists(\"frontend\")) {\n apps.web = {\n type: \"static\",\n root: \"frontend\",\n build: getPMCommands(detectPackageManager(projectRoot)).runWorkspace(\"frontend\", \"build\").join(\" \"),\n output: \"frontend/dist\",\n path: \"/\"\n };\n }\n\n return { rebase: CURRENT_RUNTIME_RANGE,\napps };\n}\n\nexport function manifestPath(projectRoot: string): string {\n return path.join(projectRoot, MANIFEST_FILENAME);\n}\n\nexport function manifestExists(projectRoot: string): boolean {\n return fs.existsSync(manifestPath(projectRoot));\n}\n\n/**\n * Read the manifest, falling back to a synthesized one.\n *\n * A malformed manifest throws — unlike a missing one. Silently ignoring a file\n * the developer wrote, and building something else instead, is the worst\n * available behaviour.\n */\nexport function loadManifest(projectRoot: string): LoadedManifest {\n const filePath = manifestPath(projectRoot);\n\n if (!fs.existsSync(filePath)) {\n return { manifest: synthesizeManifest(projectRoot),\nsource: \"synthesized\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf8\"));\n } catch (err) {\n throw new ManifestError(\n `${MANIFEST_FILENAME} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n const { manifest, issues } = validateManifest(parsed);\n if (!manifest) {\n throw new ManifestError(`${MANIFEST_FILENAME} is invalid`, issues);\n }\n\n return { manifest,\nsource: \"file\",\nfilePath };\n}\n\n/** The keys `writeManifest` knows how to write. Everything else is carried through. */\nconst MODELLED_MANIFEST_KEYS = [\"$schema\", \"rebase\", \"apps\", \"storage\", \"telemetry\"];\n\n/**\n * What is on disk right now, or `{}` — this is a *rewrite*, so the file that is\n * about to be replaced is the only record of the keys the caller did not model.\n * Unparseable is treated as absent: `loadManifest` refuses malformed JSON long\n * before anything gets here, and a writer is not the place to fail on it.\n */\nfunction readManifestObject(filePath: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(filePath, \"utf8\"));\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\n/**\n * Each app as the caller wrote it, plus the fields the file has on that app\n * that this CLI does not model.\n *\n * Apps are validated by construction (`validateApp` names every field it\n * returns), so a manifest loaded and written back had lost every app field\n * this CLI does not know: a typo it had only warned about (`\"pathh\"`), or a\n * field from a newer CLI or the cloud running ahead — the case\n * `warnUnknownFields` exists not to break. `rebase generate-sdk --register`\n * said \"Remembered in rebase.json\" and deleted them.\n *\n * Only unmodelled fields, only onto an app of the same name and type: a\n * modelled field the caller left out was removed on purpose, and an app the\n * caller dropped or retyped is not this one any more.\n */\nfunction carryUnmodelledAppFields(\n apps: RebaseProjectManifest[\"apps\"],\n existingApps: unknown\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [name, app] of Object.entries(apps)) {\n const raw = isRecord(existingApps) ? existingApps[name] : undefined;\n const known = KNOWN_APP_FIELDS[app.type];\n if (!isRecord(raw) || raw.type !== app.type || !known) {\n result[name] = app;\n continue;\n }\n const carried: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(raw)) {\n if (!known.includes(field)) carried[field] = value;\n }\n result[name] = { ...app, ...carried };\n }\n return result;\n}\n\n/**\n * Write a manifest, with a trailing newline so it plays well with other tools.\n *\n * **Every key on disk survives.** This used to emit exactly `$schema`, `rebase`\n * and `apps`, so a rewrite deleted the rest of the file — and two commands with\n * no visible relationship to either key rewrite it: `rebase eject` and\n * `rebase apps init --force`. A repository that had committed\n * `\"telemetry\": false` lost its opt-out, and a multi-bucket project lost its\n * whole `storage` block, in a commit whose stated change was `runtime: custom`.\n *\n * So: the caller's manifest wins for what it models, the file supplies the rest.\n * `storage` and `telemetry` fall back to the file because the callers that\n * synthesize a manifest (`apps init --force`) cannot know them — they are\n * authored, not inferred — and unknown top-level keys are copied verbatim\n * rather than listed, since a hand-listed set loses the next key too.\n */\nexport function writeManifest(projectRoot: string, manifest: RebaseProjectManifest): string {\n const filePath = manifestPath(projectRoot);\n const existing = readManifestObject(filePath);\n\n const carried: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(existing)) {\n if (!MODELLED_MANIFEST_KEYS.includes(key)) carried[key] = value;\n }\n\n const schema = manifest.$schema\n ?? (typeof existing.$schema === \"string\" ? existing.$schema : undefined)\n ?? \"https://rebase.pro/schemas/rebase.json\";\n const telemetry = manifest.telemetry ?? (typeof existing.telemetry === \"boolean\" ? existing.telemetry : undefined);\n\n const ordered = {\n $schema: schema,\n rebase: manifest.rebase,\n apps: carryUnmodelledAppFields(manifest.apps, existing.apps),\n ...(telemetry !== undefined ? { telemetry } : {}),\n ...carried\n };\n fs.writeFileSync(filePath, `${JSON.stringify(ordered, null, 4)}\\n`, \"utf8\");\n return filePath;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Queries\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Find the single backend app, if this repository declares one. */\nexport function findBackendApp(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseBackendAppConfig } | undefined {\n for (const [name, app] of Object.entries(manifest.apps)) {\n if (app.type === \"backend\") return { name,\napp: app as RebaseBackendAppConfig };\n }\n return undefined;\n}\n\n/**\n * Where this project mounts the Rebase CMS, if it says.\n *\n * The CMS is a component inside a developer's own app, so its address is a\n * client-side route: no build artifact, no running server and no control plane\n * can observe it. {@link RebaseStaticAppConfig.cms} is the only place that fact\n * is ever written down, and this is the one reader of it — so that \"the\n * project's CMS\" means the same thing to `rebase dev`, `rebase apps list`, the\n * bundle it builds and the console that shows it.\n *\n * Returns the *serving* app alongside the path, because a caller with a base URL\n * needs to know which app answers there — and because the path alone cannot say\n * whether the CMS is the whole of an app or one route of it.\n *\n * `path` is always a path. `host` is the serving app's hostname, when its `path`\n * gives it one: the CMS is then at `https://<host><path>` and nowhere else, and\n * a caller holding a local or project base URL must not put the path on that.\n */\nexport function cmsMountOf(\n manifest: RebaseProjectManifest\n): { appName: string; app: RebaseStaticAppConfig; path: string; host?: string } | undefined {\n for (const [name, app] of Object.entries(manifest.apps)) {\n if (app.type !== \"static\" || typeof app.cms !== \"string\") continue;\n const { host } = staticAppAddress(name, app);\n return { appName: name, app: app as RebaseStaticAppConfig, path: app.cms, ...(host ? { host } : {}) };\n }\n return undefined;\n}\n\n/**\n * The app a deploy targets: the one named, or the obvious one.\n *\n * A repository declares apps; a project owns them. So \"which app\" is a question\n * a multi-repo setup asks routinely and a single-app repository should never\n * have to answer — hence the fallbacks, in the order that makes each of them\n * unambiguous:\n *\n * - A name, when one is given. Wrong names fail loudly, listing what is there;\n * guessing past a typo would deploy the wrong app to a live project.\n * - The backend, when this repository declares one. It is the app whose deploy\n * people mean when they do not say, and it is what every existing invocation\n * already did.\n * - The only app, when there is exactly one. This is what makes a static-only\n * repository — an admin panel, a marketing site — deploy with no argument.\n * - Otherwise a refusal that lists the choices. A repository with two static\n * apps and no backend has no obvious default, and picking one would publish\n * somebody's admin panel at their marketing domain.\n */\nexport function selectDeployApp(\n manifest: RebaseProjectManifest,\n requested?: string\n): { name: string; app: RebaseAppConfig } {\n const entries = Object.entries(manifest.apps).map(([name, app]) => ({ name,\napp }));\n\n if (requested) {\n const match = entries.find(entry => entry.name === requested);\n if (!match) {\n const known = entries.map(e => e.name).join(\", \") || \"none\";\n throw new ManifestError(\n `This repository declares no app named \"${requested}\". It declares: ${known}.`\n );\n }\n return match;\n }\n\n const backend = findBackendApp(manifest);\n if (backend) return { name: backend.name,\napp: backend.app };\n\n if (entries.length === 1) return entries[0];\n\n if (entries.length === 0) {\n throw new ManifestError(\n `${MANIFEST_FILENAME} declares no apps, so there is nothing to deploy.`\n );\n }\n\n throw new ManifestError(\n \"This repository declares several apps and no backend, so there is no obvious one to deploy. \" +\n `Name one: ${entries.map(e => e.name).join(\", \")}.`\n );\n}\n\n/** Apps that produce build output, in the order they should be built. */\nexport function buildableApps(\n manifest: RebaseProjectManifest\n): { name: string; app: RebaseAppConfig }[] {\n // Backend first: a static app's build may consume an SDK generated from the\n // backend's collections, so building it second is the order that works.\n const entries = Object.entries(manifest.apps).map(([name, app]) => ({ name,\napp }));\n const rank = (app: RebaseAppConfig): number => (app.type === \"backend\" ? 0 : 1);\n return entries.sort((a, b) => rank(a.app) - rank(b.app));\n}\n\n/**\n * Decide whether a project can run on the managed runtime, and say why not.\n *\n * \"Not eligible\" is never a dead end — it selects the custom-runtime path, which\n * still deploys. The reasons exist so the answer is actionable rather than a\n * verdict.\n */\nexport function assessManagedCompatibility(\n manifest: RebaseProjectManifest\n): ManagedCompatibility {\n const backend = findBackendApp(manifest);\n\n if (!backend) {\n return {\n eligible: false,\n reasons: [\n \"No backend app is declared in this repository. Only the repository that \" +\n \"declares the backend selects the runtime.\"\n ]\n };\n }\n\n // Declared, not deduced. A project on the custom runtime is there because\n // somebody wrote it down, which is the whole point of the field.\n if (backend.app.runtime === \"custom\") {\n return {\n eligible: false,\n reasons: [\n `App \"${backend.name}\" declares runtime: \"custom\", so it builds and runs its ` +\n \"own image. The managed runtime boots the platform image with your bundle; \" +\n \"the custom runtime deploys exactly the same way, from your Dockerfile.\"\n ]\n };\n }\n\n return { eligible: true,\nreasons: [] };\n}\n\n/**\n * Resolve a backend app's directories against the conventions it omits.\n *\n * `hasCollections` replaces the old `mode: \"cms\" | \"baas\"` field. Where the\n * collections come from was never an independent choice: either they are\n * declared in code and the bundle ships them, or they are not and the runtime\n * introspects the live database at boot. Declaring it separately only created\n * the contradictory state — code-first declared, no collections anywhere.\n *\n * `hasConfig` is deliberately a **separate** question. A headless project has no\n * `config/collections`, but it may still ship a config package — that is where\n * the `storageAuthorize` hook lives, and storage is not under row-level\n * security, so without one the server refuses to boot with storage enabled.\n * Collapsing the two would leave a headless project nowhere to put it.\n */\nexport function resolveBackendPaths(\n app: RebaseBackendAppConfig,\n projectRoot: string\n): {\n config: string;\n functions: string;\n crons: string;\n schema: string;\n usersCollection: string;\n /** Whether a config package exists — hooks, storage authorization. */\n hasConfig: boolean;\n /** Whether collections are declared in code, under `<config>/collections`. */\n hasCollections: boolean;\n} {\n const config = app.config ?? DEFAULT_CONFIG_DIR;\n return {\n config,\n functions: app.functions ?? DEFAULT_FUNCTIONS_DIR,\n crons: app.crons ?? DEFAULT_CRONS_DIR,\n schema: app.schema ?? DEFAULT_SCHEMA_FILE,\n usersCollection: app.usersCollection ?? \"collections/users\",\n hasConfig: fs.existsSync(path.join(projectRoot, config)),\n hasCollections: fs.existsSync(path.join(projectRoot, config, \"collections\"))\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,wBAAwB;;AAGrC,IAAa,qBAAqB;AAClC,IAAa,wBAAwB;AACrC,IAAa,oBAAoB;AACjC,IAAa,sBAAsB;AAgBnC,IAAa,gBAAb,cAAmC,MAAM;CACC;CAAtC,YAAY,SAAiB,SAA6C,CAAC,GAAG;EAC1E,MAAM,OAAO;EADqB,KAAA,SAAA;EAElC,KAAK,OAAO;CAChB;AACJ;AAEA,IAAM,YAAY,CAAC,WAAW,QAAQ;;;;;;;;AAStC,IAAM,oBAA4C;CAC9C,OACI;CAEJ,QACI;CAEJ,QACI;AAER;;AAGA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAO;CAAU;CAAW;CAAS;AAAS,CAAC;;;;;;;;;;;;;AAcnF,SAAS,aACL,OACA,WACA,QACA,SAAS,IACS;CAClB,IAAI,UAAU,KAAA,GAAW,OA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ACnB,OAAO;EACH;EACA,WAAW,IAAI,aAAA;EACf,OAAO,IAAI,SAAA;EACX,QAAQ,IAAI,UAAA;EACZ,iBAAiB,IAAI,mBAAmB;EACxC,WAAW,GAAG,WAAW,KAAK,KAAK,aAAa,MAAM,CAAC;EACvD,gBAAgB,GAAG,WAAW,KAAK,KAAK,aAAa,QAAQ,aAAa,CAAC;CAC/E;AACJ"}
@@ -1,92 +0,0 @@
1
- import chalk from "chalk";
2
- import fs from "fs";
3
- import path from "path";
4
- //#region src/utils/path-flags.ts
5
- /**
6
- * Where a path typed on a `rebase` command line resolves: one rule, one sentence.
7
- *
8
- * The driver CLI runs with `cwd: backend/` — that is where it and its
9
- * dependencies resolve from — while people type commands from the project root
10
- * (or anywhere else in it). So every relative path on the line is resolved by
11
- * the CLI, from the directory the command was run in, before the driver is
12
- * handed a different one (`absolutizeLocalPathArgs` in `commands/db.ts`).
13
- * `generate-sdk` and `db backup --out` already worked that way; `--collections`
14
- * was resolved from `backend/` and was the odd one out.
15
- *
16
- * The sentence below is printed by every help page that takes `--collections`,
17
- * and by the refusal when the path is not there, so the rule is stated in one
18
- * set of words wherever a reader meets it.
19
- */
20
- /** The rule, as every help page and error states it. */
21
- var COLLECTIONS_PATH_RULE = "relative paths are resolved from where you run the command";
22
- /** The `--collections` line of a help page. */
23
- var COLLECTIONS_FLAG_HELP = `Collections directory (default: config/collections, or <config>/collections when rebase.json moves the backend's config); ${COLLECTIONS_PATH_RULE}`;
24
- /** The flags that carry a collections path, in every spelling the driver accepts. */
25
- var COLLECTIONS_FLAGS = ["--collections", "-c"];
26
- /** The `--collections` value on a line, as typed, or `null` when there is none. */
27
- function typedCollectionsPath(args) {
28
- for (let i = 0; i < args.length; i++) {
29
- const token = args[i];
30
- const eq = token.indexOf("=");
31
- if (eq > 0 && COLLECTIONS_FLAGS.includes(token.slice(0, eq))) return token.slice(eq + 1) || null;
32
- if (COLLECTIONS_FLAGS.includes(token)) {
33
- const value = args[i + 1];
34
- return value && !value.startsWith("-") ? value : null;
35
- }
36
- }
37
- return null;
38
- }
39
- /**
40
- * What a refusal over a missing `--collections` path spared, by what the command
41
- * would have done with it. Only a schema writer drops tables; a console or a
42
- * doctor run over nothing does something else wrong, and says so.
43
- */
44
- var MISSING_COLLECTIONS_CONSEQUENCE = {
45
- schema: [
46
- "Nothing was generated and nothing was applied — a schema generated from a",
47
- "directory that is not there is an empty one, and applying it would drop",
48
- "every table it does not describe."
49
- ],
50
- console: ["Nothing was started — a console over a directory that is not there would", "load none of this project's collections."],
51
- doctor: ["Nothing was checked — a directory that is not there has no collections, so", "every collection check would pass over it."],
52
- verify: ["Nothing was verified — a directory that is not there has no collections, so", "every step would pass over it and report 0 errors."]
53
- };
54
- /**
55
- * The refusal for a `--collections` path that does not exist, or `null`.
56
- *
57
- * Checked by the CLI, in the reader's terms, before the driver is spawned: the
58
- * driver's own check runs in `backend/` and can only describe the path it was
59
- * handed. A generator pointed at a directory that is not there writes an empty
60
- * schema, and a push of an empty schema drops every table — so nothing runs.
61
- *
62
- * Scripts written for the old rule (`--collections ../config/collections`,
63
- * run from the root) land here, and the message says exactly what to change.
64
- */
65
- function missingCollectionsPath(args, cwd, backendDir, use = "schema") {
66
- const typed = typedCollectionsPath(args);
67
- if (typed === null) return null;
68
- const resolved = path.resolve(cwd, typed);
69
- if (fs.existsSync(resolved)) return null;
70
- const lines = [
71
- chalk.red(`✗ Collections path not found: "${typed}"`),
72
- chalk.gray(` Resolved to: ${resolved}`),
73
- chalk.gray(` (${COLLECTIONS_PATH_RULE}: ${cwd})`)
74
- ];
75
- const fromBackend = path.resolve(backendDir, typed);
76
- if (!path.isAbsolute(typed) && fs.existsSync(fromBackend)) lines.push("", chalk.yellow(` From backend/ it would be ${fromBackend} — the driver used to resolve paths from there.`), chalk.yellow(` Leave the flag out (config/collections is the default), or write it from here: ${path.relative(cwd, fromBackend) || "."}`));
77
- lines.push("", ...MISSING_COLLECTIONS_CONSEQUENCE[use].map((line) => chalk.gray(` ${line}`)));
78
- return lines;
79
- }
80
- /** Print {@link missingCollectionsPath}'s refusal and exit 1, or return. */
81
- function refuseMissingCollectionsPath(args, cwd, backendDir, use = "schema") {
82
- const lines = missingCollectionsPath(args, cwd, backendDir, use);
83
- if (!lines) return;
84
- console.error("");
85
- for (const line of lines) console.error(line);
86
- console.error("");
87
- process.exit(1);
88
- }
89
- //#endregion
90
- export { refuseMissingCollectionsPath as i, COLLECTIONS_PATH_RULE as n, missingCollectionsPath as r, COLLECTIONS_FLAG_HELP as t };
91
-
92
- //# sourceMappingURL=path-flags-DNvtEi2-.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"path-flags-DNvtEi2-.js","names":[],"sources":["../src/utils/path-flags.ts"],"sourcesContent":["/**\n * Where a path typed on a `rebase` command line resolves: one rule, one sentence.\n *\n * The driver CLI runs with `cwd: backend/` — that is where it and its\n * dependencies resolve from — while people type commands from the project root\n * (or anywhere else in it). So every relative path on the line is resolved by\n * the CLI, from the directory the command was run in, before the driver is\n * handed a different one (`absolutizeLocalPathArgs` in `commands/db.ts`).\n * `generate-sdk` and `db backup --out` already worked that way; `--collections`\n * was resolved from `backend/` and was the odd one out.\n *\n * The sentence below is printed by every help page that takes `--collections`,\n * and by the refusal when the path is not there, so the rule is stated in one\n * set of words wherever a reader meets it.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\n\n/** The rule, as every help page and error states it. */\nexport const COLLECTIONS_PATH_RULE = \"relative paths are resolved from where you run the command\";\n\n/** The `--collections` line of a help page. */\nexport const COLLECTIONS_FLAG_HELP = `Collections directory (default: config/collections, or <config>/collections when rebase.json moves the backend's config); ${COLLECTIONS_PATH_RULE}`;\n\n/** The flags that carry a collections path, in every spelling the driver accepts. */\nconst COLLECTIONS_FLAGS = [\"--collections\", \"-c\"];\n\n/** The `--collections` value on a line, as typed, or `null` when there is none. */\nfunction typedCollectionsPath(args: readonly string[]): string | null {\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n const eq = token.indexOf(\"=\");\n if (eq > 0 && COLLECTIONS_FLAGS.includes(token.slice(0, eq))) return token.slice(eq + 1) || null;\n if (COLLECTIONS_FLAGS.includes(token)) {\n const value = args[i + 1];\n return value && !value.startsWith(\"-\") ? value : null;\n }\n }\n return null;\n}\n\n/**\n * What a refusal over a missing `--collections` path spared, by what the command\n * would have done with it. Only a schema writer drops tables; a console or a\n * doctor run over nothing does something else wrong, and says so.\n */\nconst MISSING_COLLECTIONS_CONSEQUENCE = {\n schema: [\n \"Nothing was generated and nothing was applied — a schema generated from a\",\n \"directory that is not there is an empty one, and applying it would drop\",\n \"every table it does not describe.\"\n ],\n console: [\n \"Nothing was started — a console over a directory that is not there would\",\n \"load none of this project's collections.\"\n ],\n doctor: [\n \"Nothing was checked — a directory that is not there has no collections, so\",\n \"every collection check would pass over it.\"\n ],\n verify: [\n \"Nothing was verified — a directory that is not there has no collections, so\",\n \"every step would pass over it and report 0 errors.\"\n ]\n} as const;\n\n/** What a command does with its `--collections` path. */\nexport type CollectionsPathUse = keyof typeof MISSING_COLLECTIONS_CONSEQUENCE;\n\n/**\n * The refusal for a `--collections` path that does not exist, or `null`.\n *\n * Checked by the CLI, in the reader's terms, before the driver is spawned: the\n * driver's own check runs in `backend/` and can only describe the path it was\n * handed. A generator pointed at a directory that is not there writes an empty\n * schema, and a push of an empty schema drops every table — so nothing runs.\n *\n * Scripts written for the old rule (`--collections ../config/collections`,\n * run from the root) land here, and the message says exactly what to change.\n */\nexport function missingCollectionsPath(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: CollectionsPathUse = \"schema\"\n): string[] | null {\n const typed = typedCollectionsPath(args);\n if (typed === null) return null;\n const resolved = path.resolve(cwd, typed);\n if (fs.existsSync(resolved)) return null;\n\n const lines = [\n chalk.red(`✗ Collections path not found: \"${typed}\"`),\n chalk.gray(` Resolved to: ${resolved}`),\n chalk.gray(` (${COLLECTIONS_PATH_RULE}: ${cwd})`)\n ];\n const fromBackend = path.resolve(backendDir, typed);\n if (!path.isAbsolute(typed) && fs.existsSync(fromBackend)) {\n lines.push(\n \"\",\n chalk.yellow(` From backend/ it would be ${fromBackend} — the driver used to resolve paths from there.`),\n chalk.yellow(` Leave the flag out (config/collections is the default), or write it from here: ${path.relative(cwd, fromBackend) || \".\"}`)\n );\n }\n lines.push(\"\", ...MISSING_COLLECTIONS_CONSEQUENCE[use].map(line => chalk.gray(` ${line}`)));\n return lines;\n}\n\n/** Print {@link missingCollectionsPath}'s refusal and exit 1, or return. */\nexport function refuseMissingCollectionsPath(\n args: readonly string[],\n cwd: string,\n backendDir: string,\n use: CollectionsPathUse = \"schema\"\n): void {\n const lines = missingCollectionsPath(args, cwd, backendDir, use);\n if (!lines) return;\n console.error(\"\");\n for (const line of lines) console.error(line);\n console.error(\"\");\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAGrC,IAAa,wBAAwB,6HAA6H;;AAGlK,IAAM,oBAAoB,CAAC,iBAAiB,IAAI;;AAGhD,SAAS,qBAAqB,MAAwC;CAClE,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EAClC,MAAM,QAAQ,KAAK;EACnB,MAAM,KAAK,MAAM,QAAQ,GAAG;EAC5B,IAAI,KAAK,KAAK,kBAAkB,SAAS,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,OAAO,MAAM,MAAM,KAAK,CAAC,KAAK;EAC5F,IAAI,kBAAkB,SAAS,KAAK,GAAG;GACnC,MAAM,QAAQ,KAAK,IAAI;GACvB,OAAO,SAAS,CAAC,MAAM,WAAW,GAAG,IAAI,QAAQ;EACrD;CACJ;CACA,OAAO;AACX;;;;;;AAOA,IAAM,kCAAkC;CACpC,QAAQ;EACJ;EACA;EACA;CACJ;CACA,SAAS,CACL,4EACA,0CACJ;CACA,QAAQ,CACJ,8EACA,4CACJ;CACA,QAAQ,CACJ,+EACA,oDACJ;AACJ;;;;;;;;;;;;AAgBA,SAAgB,u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