@rebasepro/cli 0.30.0 → 0.31.0-canary.g902a0ce

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 (285) 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-CyADghFQ.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-CyADghFQ.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-Cj5ey3l_.js → cloud-CYMk92iG.js} +217 -104
  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/auth.d.ts +2 -0
  62. package/dist/commands/cloud/context.d.ts +1 -1
  63. package/dist/commands/cloud/init.d.ts +2 -2
  64. package/dist/commands/cloud/login-flow.d.ts +30 -1
  65. package/dist/commands/console.d.ts +1 -2
  66. package/dist/commands/db.d.ts +5 -6
  67. package/dist/commands/dev.d.ts +18 -17
  68. package/dist/commands/doctor.d.ts +4 -5
  69. package/dist/commands/eject.d.ts +17 -13
  70. package/dist/commands/generate-view.d.ts +20 -9
  71. package/dist/commands/generate_sdk.d.ts +27 -27
  72. package/dist/commands/init.d.ts +21 -8
  73. package/dist/commands/migrate.d.ts +24 -0
  74. package/dist/commands/schema-reconcile.d.ts +1 -1
  75. package/dist/commands/skills.d.ts +8 -0
  76. package/dist/commands/verify-cms.d.ts +28 -0
  77. package/dist/commands/verify.d.ts +14 -9
  78. package/dist/{consent-BD7F29T3.js → consent-BXLIrMl8.js} +2 -2
  79. package/dist/{consent-BD7F29T3.js.map → consent-BXLIrMl8.js.map} +1 -1
  80. package/dist/{console-CdwIYOMV.js → console-CMjhgMUE.js} +14 -14
  81. package/dist/console-CMjhgMUE.js.map +1 -0
  82. package/dist/{context-AXdAh-q8.js → context--JwaHaZp.js} +6 -5
  83. package/dist/context--JwaHaZp.js.map +1 -0
  84. package/dist/{daemon-Cp7oNXth.js → daemon-w30PsdwV.js} +2 -2
  85. package/dist/{daemon-Cp7oNXth.js.map → daemon-w30PsdwV.js.map} +1 -1
  86. package/dist/{db-DBbKpjYX.js → db-A7XDCIIO.js} +51 -51
  87. package/dist/db-A7XDCIIO.js.map +1 -0
  88. package/dist/{derive-ae9UOoOB.js → derive-C3ezmY-p.js} +105 -133
  89. package/dist/derive-C3ezmY-p.js.map +1 -0
  90. package/dist/dev-db/attver.d.ts +11 -0
  91. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  92. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  93. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  94. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  95. package/dist/{dev-C93d4QIv.js → dev-tWwPyWkQ.js} +142 -84
  96. package/dist/dev-tWwPyWkQ.js.map +1 -0
  97. package/dist/{doctor-BBPQUO2g.js → doctor-BBM0dWvZ.js} +39 -62
  98. package/dist/doctor-BBM0dWvZ.js.map +1 -0
  99. package/dist/doctor-environment.d.ts +6 -6
  100. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  101. package/dist/eject-Bhzd6hgb.js.map +1 -0
  102. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  103. package/dist/fold-static-CKewnAPX.js.map +1 -0
  104. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  105. package/dist/generate-view-CTOluXvH.js.map +1 -0
  106. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  107. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  108. package/dist/import-schema-module-Df67TIWj.js +51 -0
  109. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  110. package/dist/index.es.js +64 -51
  111. package/dist/index.es.js.map +1 -1
  112. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  113. package/dist/init-Dtl-IcXf.js.map +1 -0
  114. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  115. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  116. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  117. package/dist/manifest.d.ts +79 -24
  118. package/dist/migrate-VrKoi3nB.js +138 -0
  119. package/dist/migrate-VrKoi3nB.js.map +1 -0
  120. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  121. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  122. package/dist/path-flags-7O5uPBcQ.js +139 -0
  123. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  124. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  125. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  126. package/dist/project-CLcF5i8c.js +360 -0
  127. package/dist/project-CLcF5i8c.js.map +1 -0
  128. package/dist/project-schema-CsSOG2gE.js +30 -0
  129. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  130. package/dist/{pull-DDMpsZ5r.js → pull-D9WvpDYY.js} +189 -1
  131. package/dist/pull-D9WvpDYY.js.map +1 -0
  132. package/dist/resolve-BY7bSFRT.js +2 -0
  133. package/dist/resources/derive.d.ts +19 -13
  134. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  135. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  136. package/dist/{schema-DtLPsXbT.js → schema-DwFDI1iU.js} +41 -39
  137. package/dist/schema-DwFDI1iU.js.map +1 -0
  138. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  139. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  140. package/dist/schema-reconcile-Tto54Qbv.js +2 -0
  141. package/dist/schema-text-CpNrsuMe.js +73 -0
  142. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  143. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  144. package/dist/skills-CXjA9TWw.js.map +1 -0
  145. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  146. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  147. package/dist/{status-BREvtzJm.js → status-DQ_PPz4C.js} +12 -12
  148. package/dist/status-DQ_PPz4C.js.map +1 -0
  149. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  150. package/dist/storage-iTqj5-Av.js.map +1 -0
  151. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  152. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  153. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  154. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  155. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  156. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  157. package/dist/utils/backend-guard.d.ts +47 -0
  158. package/dist/utils/cms-directories.d.ts +6 -0
  159. package/dist/utils/dev-preflight.d.ts +2 -2
  160. package/dist/utils/import-schema-module.d.ts +16 -0
  161. package/dist/utils/path-flags.d.ts +35 -16
  162. package/dist/utils/project-schema.d.ts +40 -0
  163. package/dist/utils/project.d.ts +8 -2
  164. package/dist/utils/schema-dir.d.ts +32 -0
  165. package/dist/utils/schema-drift.d.ts +6 -0
  166. package/dist/utils/schema-text.d.ts +24 -0
  167. package/dist/verify-DkJqhYPI.js +1160 -0
  168. package/dist/verify-DkJqhYPI.js.map +1 -0
  169. package/package.json +11 -8
  170. package/runtime/dev-server.mjs +5 -1
  171. package/templates/eject/Dockerfile +1 -4
  172. package/templates/eject/backend/src/env.ts +1 -1
  173. package/templates/eject/backend/src/index.ts +53 -40
  174. package/templates/eject/docker-compose.custom.yml +1 -1
  175. package/templates/overlays/baas/README.md +39 -12
  176. package/templates/overlays/baas/ai-instructions.md +8 -8
  177. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  178. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  179. package/templates/overlays/baas/package.json +1 -2
  180. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  181. package/templates/presets/blank/backend/schema/index.ts +19 -0
  182. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  183. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  184. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  185. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  186. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  187. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  188. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  189. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  190. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  191. package/templates/resource-graphs/blank.json +2 -2
  192. package/templates/resource-graphs/blog.json +5 -5
  193. package/templates/resource-graphs/ecommerce.json +5 -5
  194. package/templates/resource-graphs/headless.json +1 -1
  195. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  196. package/templates/template/.cursorrules +2 -2
  197. package/templates/template/.env.example +6 -17
  198. package/templates/template/.github/copilot-instructions.md +2 -2
  199. package/templates/template/.windsurfrules +2 -2
  200. package/templates/template/AGENTS.md +2 -2
  201. package/templates/template/CLAUDE.md +2 -2
  202. package/templates/template/README.md +47 -13
  203. package/templates/template/ai-instructions.md +15 -14
  204. package/templates/template/backend/functions/hello.ts +1 -1
  205. package/templates/template/backend/package.json +0 -2
  206. package/templates/template/{config → backend}/resources.ts +3 -3
  207. package/templates/template/backend/schema/authors.ts +11 -0
  208. package/templates/template/backend/schema/index.ts +29 -0
  209. package/templates/template/backend/schema/posts.ts +29 -0
  210. package/templates/template/backend/schema/tags.ts +9 -0
  211. package/templates/template/backend/schema/users.ts +32 -0
  212. package/templates/template/{config → backend}/storage.ts +4 -4
  213. package/templates/template/backend/tsconfig.json +15 -20
  214. package/templates/template/docker-compose.yml +3 -3
  215. package/templates/template/frontend/package.json +0 -2
  216. package/templates/template/frontend/src/App.tsx +10 -4
  217. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  218. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  219. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  220. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  221. package/templates/template/frontend/src/cms/users.tsx +54 -0
  222. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  223. package/templates/template/frontend/vite.config.ts +6 -2
  224. package/templates/template/gitignore +1 -1
  225. package/templates/template/package.json +1 -2
  226. package/templates/template/pnpm-workspace.yaml +0 -1
  227. package/templates/template/scripts/example.ts +3 -3
  228. package/templates/template/tsconfig.json +1 -1
  229. package/templates/views/AppView.tsx.tmpl +4 -4
  230. package/templates/views/EntityView.tsx.tmpl +3 -4
  231. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  232. package/dist/apps-MKQbgDtN.js.map +0 -1
  233. package/dist/build-BuKTnec8.js.map +0 -1
  234. package/dist/bundle-BAH4FCju.js.map +0 -1
  235. package/dist/cloud-Cj5ey3l_.js.map +0 -1
  236. package/dist/collection-drift-BKj_BoMq.js +0 -106
  237. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  238. package/dist/collections-dir-DlvDhime.js +0 -69
  239. package/dist/collections-dir-DlvDhime.js.map +0 -1
  240. package/dist/console-CdwIYOMV.js.map +0 -1
  241. package/dist/context-AXdAh-q8.js.map +0 -1
  242. package/dist/db-DBbKpjYX.js.map +0 -1
  243. package/dist/derive-ae9UOoOB.js.map +0 -1
  244. package/dist/dev-C93d4QIv.js.map +0 -1
  245. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  246. package/dist/doctor-BBPQUO2g.js.map +0 -1
  247. package/dist/eject-DABcDnPN.js.map +0 -1
  248. package/dist/fold-static-BWzxNn06.js.map +0 -1
  249. package/dist/generate-view-IFwCADvb.js.map +0 -1
  250. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  251. package/dist/init-vL1DWOeC.js.map +0 -1
  252. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  253. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  254. package/dist/path-flags-DNvtEi2-.js +0 -92
  255. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  256. package/dist/project-CasK56vN.js.map +0 -1
  257. package/dist/pull-DDMpsZ5r.js.map +0 -1
  258. package/dist/resolve-D647F1LA.js +0 -2
  259. package/dist/schema-DtLPsXbT.js.map +0 -1
  260. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  261. package/dist/skills-CbwV6vw_.js.map +0 -1
  262. package/dist/status-BREvtzJm.js.map +0 -1
  263. package/dist/storage-CO9ouK76.js.map +0 -1
  264. package/dist/utils/collection-drift.d.ts +0 -27
  265. package/dist/utils/collections-dir.d.ts +0 -14
  266. package/dist/verify-Y3rWSgfA.js +0 -730
  267. package/dist/verify-Y3rWSgfA.js.map +0 -1
  268. package/templates/overlays/baas/config/index.ts +0 -24
  269. package/templates/overlays/baas/config/package.json +0 -30
  270. package/templates/template/config/cms.d.ts +0 -15
  271. package/templates/template/config/collections/authors.ts +0 -47
  272. package/templates/template/config/collections/index.ts +0 -44
  273. package/templates/template/config/collections/posts.ts +0 -94
  274. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  275. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  276. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  277. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  278. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  279. package/templates/template/config/collections/tags.ts +0 -27
  280. package/templates/template/config/collections/users.ts +0 -149
  281. package/templates/template/config/frontend-assets.d.ts +0 -17
  282. package/templates/template/config/index.ts +0 -12
  283. package/templates/template/config/package.json +0 -30
  284. package/templates/template/config/tsconfig.json +0 -35
  285. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -1,25 +1,24 @@
1
- import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
2
- import { c as findProjectRoot, d as readEnvFile } from "./project-CasK56vN.js";
3
- import { d as findBackendApp, m as manifestExists, p as loadManifest, x as writeManifest } from "./manifest-BtzDy7KQ.js";
4
- import { t as DEV_BACKEND_URL_ENV } from "./dev-server-OJsUGZEB.js";
5
- import { V as readLink } from "./context-AXdAh-q8.js";
6
- import { n as COLLECTIONS_PATH_RULE, t as COLLECTIONS_FLAG_HELP } from "./path-flags-DNvtEi2-.js";
1
+ import { c as findProjectRoot, d as readEnvFile } from "./project-CLcF5i8c.js";
2
+ import { O as writeManifest, _ as findBackendApp, b as loadManifest, o as GENERATED_DIR, x as manifestExists } from "./manifest-C3uLDrrJ.js";
3
+ import { n as SCHEMA_DIR_FLAG_HELP, t as PATH_RESOLUTION_RULE } from "./path-flags-7O5uPBcQ.js";
4
+ import { t as loadProjectSchema } from "./project-schema-CsSOG2gE.js";
5
+ import { t as DEV_BACKEND_URL_ENV } from "./dev-server-BLxCbQEP.js";
6
+ import { V as readLink } from "./context--JwaHaZp.js";
7
7
  import { t as Refusal } from "./refusal-ReeeGP8a.js";
8
- import { n as isLoadedCollectionFile } from "./collection-drift-BKj_BoMq.js";
9
8
  import chalk from "chalk";
10
9
  import fs from "fs";
11
10
  import path from "path";
12
- import { computeSchemaVersion, deserializeCollections } from "@rebasepro/types";
13
- import { CodegenError, generateSDK, toCollectionAccessor } from "@rebasepro/codegen";
11
+ import { computeSchemaVersion } from "@rebasepro/types";
12
+ import { isSchemaDefinitionError } from "@rebasepro/common";
13
+ import { CodegenError, generateSDK, toTableAccessor } from "@rebasepro/codegen";
14
14
  //#region src/commands/generate_sdk.ts
15
15
  /**
16
16
  * CLI command: generate-sdk
17
17
  *
18
- * Reads every collection file in a directory (default: ./config/collections) —
19
- * the files the backend serves, not the barrel's list — generates a typed
20
- * TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).
21
- *
22
- * Uses jiti for dynamic TypeScript import of collection files.
18
+ * Reads the project's tables — `backend/schema`, through the loader the
19
+ * backend boots from, so the SDK describes exactly the tables served — or,
20
+ * with `--from`, a running project's contract, and writes a typed TypeScript
21
+ * SDK to the output directory (default: ./generated/sdk).
23
22
  */
24
23
  /** What `--register` writes, and what marks a project as having opted in. */
25
24
  var REGISTER_FILE = "register.ts";
@@ -28,7 +27,7 @@ var REGISTER_MARKER = "// Auto-generated by `rebase generate-sdk --register`. Do
28
27
  var REGISTER_SOURCE = `${REGISTER_MARKER}
29
28
  //
30
29
  // Registers this project's generated \`Database\` on \`@rebasepro/types\`, so
31
- // \`context.data\` in collection callbacks, \`rebase.dataAsAdmin\`, and the
30
+ // \`context.data\` in table hooks, \`rebase.dataAsAdmin\`, and the
32
31
  // \`rebase\` a function or a cron receives are typed from it. Every later
33
32
  // \`rebase generate-sdk\` (and \`rebase dev\`) refreshes this directory; delete
34
33
  // it to go back to untyped server-side data.
@@ -41,19 +40,15 @@ declare module "@rebasepro/types" {
41
40
  }
42
41
  `;
43
42
  /**
44
- * Where `--register` writes: `generated/` beside the collections directory,
45
- * which is `config/generated/` in a scaffolded project.
43
+ * Where `--register` writes: `backend/generated/` under the project root.
46
44
  *
47
- * Inside `config/` because that is the one directory both compiles of a
48
- * collection file include: the backend's program (it includes
49
- * `../config/**`) and the `config` package's own `tsc`. A registration
50
- * there that imported `../generated/sdk/database.types` pulled a file from
51
- * outside `config/` into that package's program, which TypeScript refuses
52
- * (the file is not under its `rootDir`) — so the types are copied in beside
53
- * the registration rather than imported from the SDK.
45
+ * Inside `backend/` because that is the program the hooks, functions and
46
+ * crons it types are compiled in. The types are copied in beside the
47
+ * registration rather than imported from `generated/sdk`, which is outside
48
+ * the backend's `rootDir`.
54
49
  */
55
- function registrationDir(collectionsDir) {
56
- return path.join(path.dirname(path.resolve(collectionsDir)), "generated");
50
+ function registrationDir(projectRoot) {
51
+ return path.join(projectRoot, GENERATED_DIR);
57
52
  }
58
53
  /** Whether this project opted in: the registration is there, and it is ours. */
59
54
  function hasRegistration(dir) {
@@ -83,31 +78,32 @@ function writeRegistration(dir, databaseTypes) {
83
78
  writeIfChanged(registerPath, REGISTER_SOURCE);
84
79
  }
85
80
  /**
86
- * Write the server-side registration from the collection files in
87
- * `collectionsDir`, exactly as `rebase generate-sdk` writes it, for a build.
81
+ * Write the server-side registration from the build's tables, exactly as
82
+ * `rebase generate-sdk` writes it.
88
83
  *
89
84
  * Only for a project that asked for it: `registerDatabase` in `rebase.json`,
90
85
  * or a registration an earlier `--register` left, which is kept current. The
91
- * registration lives in gitignored `config/generated/`, so a fresh clone (a CI
92
- * job) has none until something writes it, and a bundle compiled without it
93
- * types `context.data` as untyped rows: callbacks that read a typed column
94
- * fail to compile there while they compile locally.
86
+ * registration lives in gitignored `backend/generated/`, so a fresh clone (a
87
+ * CI job) has none until something writes it, and a bundle compiled without
88
+ * it types `context.data` as untyped rows: hooks that read a typed column fail
89
+ * to compile there while they compile locally.
95
90
  *
96
91
  * Returns the directory written, or null when there was nothing to do.
97
92
  * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.
98
93
  */
99
- async function writeRegistrationForBuild(collectionsDir, registerDatabase) {
100
- const dir = registrationDir(collectionsDir);
94
+ async function writeRegistrationForBuild(projectRoot, tables, registerDatabase) {
95
+ const dir = registrationDir(projectRoot);
101
96
  if (!registerDatabase && !hasRegistration(dir)) return null;
102
- if (!fs.existsSync(collectionsDir)) return null;
103
- const collections = await loadCollections(collectionsDir);
104
- if (collections.length === 0) return null;
105
- collections.sort((a, b) => a.slug.localeCompare(b.slug));
106
- const databaseTypes = generateSDK(collections, { includeReadme: false }).find((file) => file.path === "database.types.ts")?.content;
97
+ if (tables.length === 0) return null;
98
+ const databaseTypes = generateSDK(sortedBySlug(tables), { includeReadme: false }).find((file) => file.path === "database.types.ts")?.content;
107
99
  if (databaseTypes === void 0) return null;
108
100
  writeRegistration(dir, databaseTypes);
109
101
  return dir;
110
102
  }
103
+ /** Tables sorted by slug: the same schema generates the same bytes, whatever order the index lists it in. */
104
+ function sortedBySlug(tables) {
105
+ return [...tables].sort((a, b) => a.slug.localeCompare(b.slug));
106
+ }
111
107
  /**
112
108
  * Whether `rebase.json` asks for the registration (`registerDatabase: true` on
113
109
  * the backend app). That is what survives a clone: `generated/` is gitignored,
@@ -153,69 +149,21 @@ function rememberRegistration(projectRoot) {
153
149
  }) };
154
150
  }
155
151
  /**
156
- * Load the collections the backend serves, the way it finds them.
157
- *
158
- * A directory is read as `loadCollectionsFromDirectory` in @rebasepro/server
159
- * reads it: every top-level collection file, each default-exporting one
160
- * collection. The barrel (`index.ts`) is not a registry. The runtime, the admin
161
- * panel, `rebase build` and `rebase schema generate` all scan the directory, and
162
- * the barrel only orders the panel's navigation and declares
163
- * `defaultSecurityRules`. This command used to read the barrel instead, so a
164
- * collection file left out of it was created, served at `/api/data/<slug>` and
165
- * listed in the panel, and missing from the typed SDK alone.
166
- *
167
- * A file that does not load is fatal, as it is at boot: `rebase dev` runs this
168
- * on every save, and skipping the file would overwrite good types with a
169
- * `Database` that is silently short a collection.
152
+ * The tables the backend serves, read the way it reads them: the schema
153
+ * directory's index, through `loadBackendSchema`, compiled to descriptors.
170
154
  *
171
- * A path to a single module is read as the runtime reads one: its
172
- * `backendCollections`, or its `collections`.
173
- *
174
- * A missing directory, a missing jiti and a module that exports no collections
175
- * are `Refusal`s: the message says all there is. A collection file that throws
176
- * on import is not: that is the project's own code failing, and the stack
177
- * `--debug` prints points at the line, so `bin/rebase.js` keeps its hint.
155
+ * A definition the backend would refuse is fatal here too, as it is at boot:
156
+ * `rebase dev` runs this on every save, and skipping a table would overwrite
157
+ * good types with a `Database` that is silently short one. A missing
158
+ * directory is a `Refusal`: the message says all there is. A module that
159
+ * throws on import is not: that is the project's own code failing, and the
160
+ * stack `--debug` prints points at the line.
178
161
  */
179
- async function loadCollections(collectionsDir) {
180
- const absDir = path.resolve(collectionsDir);
181
- if (!fs.existsSync(absDir)) throw new Refusal(`Collections directory not found: ${absDir} (${COLLECTIONS_PATH_RULE})`);
182
- let jiti;
183
- try {
184
- const jitiModule = await import("jiti");
185
- jiti = jitiModule.default || jitiModule;
186
- } catch {
187
- throw new Refusal(`Could not load 'jiti'. Install it with: ${[
188
- ...getPMCommands(detectPackageManager()).install,
189
- "-D",
190
- "jiti"
191
- ].join(" ")}\njiti is required to dynamically import TypeScript collection definitions.`);
192
- }
193
- if (!fs.statSync(absDir).isDirectory()) {
194
- const mod = jiti(path.dirname(absDir), {
195
- interopDefault: true,
196
- esmResolve: true
197
- })(absDir);
198
- const listed = mod.backendCollections ?? mod.collections ?? mod.default;
199
- if (Array.isArray(listed)) return listed;
200
- throw new Refusal(`Could not extract collections from ${absDir}.\nA single collections module exports \`backendCollections\` or \`collections\`: an array of collections.`);
201
- }
202
- const jitiInstance = jiti(absDir, {
203
- interopDefault: true,
204
- esmResolve: true
205
- });
206
- const collections = [];
207
- const failures = [];
208
- const files = fs.readdirSync(absDir).filter(isLoadedCollectionFile).sort();
209
- for (const file of files) try {
210
- const mod = jitiInstance(path.join(absDir, file));
211
- const exported = mod.default ?? mod;
212
- if (exported && typeof exported === "object" && "slug" in exported) collections.push(exported);
213
- else failures.push(`${file}: no default export of a collection`);
214
- } catch (err) {
215
- failures.push(`${file}: ${err.message}`);
216
- }
217
- if (failures.length > 0) throw new Error(`Could not load ${failures.length} collection file(s) from ${absDir}:\n` + failures.map((failure) => ` • ${failure}`).join("\n") + "\n\nEvery collection file must import cleanly and default-export a collection — the backend refuses to boot on the same file.");
218
- return collections;
162
+ async function loadTables(projectRoot, schemaDir, aliases) {
163
+ const absDir = path.resolve(schemaDir);
164
+ if (!fs.existsSync(absDir)) throw new Refusal(`Schema directory not found: ${absDir} (${PATH_RESOLUTION_RULE})`);
165
+ const { compiled } = await loadProjectSchema(projectRoot, absDir, aliases);
166
+ return compiled.descriptors;
219
167
  }
220
168
  /**
221
169
  * Write generated files to the output directory.
@@ -238,8 +186,7 @@ ${chalk.bold("Usage")}
238
186
  rebase generate-sdk [options]
239
187
 
240
188
  ${chalk.bold("Options")}
241
- -c, --collections <dir> ${COLLECTIONS_FLAG_HELP}
242
- (--collections-dir is accepted too)
189
+ --schema-dir <dir> ${SCHEMA_DIR_FLAG_HELP}
243
190
  -o, --output <dir> Where to write the SDK (default: ./generated/sdk)
244
191
  (--out is accepted too, as on 'rebase build')
245
192
  --from <link|url> Fetch the schema from a running project instead of
@@ -247,12 +194,12 @@ ${chalk.bold("Options")}
247
194
  --token <token> Bearer token for the contract endpoint
248
195
  (default: $REBASE_SERVICE_KEY)
249
196
  --register Also type server-side data: write the types and the
250
- Register declaration to config/generated/, and
197
+ Register declaration to backend/generated/, and
251
198
  remember it in rebase.json so later runs keep it.
252
199
  -h, --help Show this help
253
200
 
254
201
  ${chalk.bold("Examples")}
255
- rebase generate-sdk From local collections
202
+ rebase generate-sdk From backend/schema
256
203
  rebase generate-sdk --from link From the linked project
257
204
  rebase generate-sdk --from https://api.acme.com From any Rebase backend
258
205
  rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too
@@ -274,7 +221,20 @@ function contractRefusalHint(credential) {
274
221
  if (credential.envFileKey) return ["REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.", "Pass the key with --token."];
275
222
  return ["Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project."];
276
223
  }
277
- async function fetchRemoteCollections(baseUrl, token, credential) {
224
+ /**
225
+ * Whether one entry of a contract's `tables` is a table descriptor, as far as
226
+ * the generator reads one: a slug, a SQL name, columns and relations.
227
+ */
228
+ function isTableDescriptor(value) {
229
+ return typeof value === "object" && value !== null && "slug" in value && typeof value.slug === "string" && "table" in value && typeof value.table === "string" && "columns" in value && Array.isArray(value.columns) && "relations" in value && Array.isArray(value.relations);
230
+ }
231
+ /**
232
+ * The tables a running project serves, from its contract endpoint
233
+ * (`{ schemaVersion, runtime, tables: TableDescriptor[] }`). The descriptors
234
+ * are plain data — no thunks to rehydrate — so they go to the generator as
235
+ * they arrive.
236
+ */
237
+ async function fetchRemoteTables(baseUrl, token, credential) {
278
238
  const url = `${baseUrl.replace(/\/+$/, "")}/api/meta/contract`;
279
239
  const headers = { accept: "application/json" };
280
240
  if (token) headers.authorization = `Bearer ${token}`;
@@ -302,13 +262,27 @@ async function fetchRemoteCollections(baseUrl, token, credential) {
302
262
  process.exit(1);
303
263
  }
304
264
  const contract = await response.json();
305
- if (!Array.isArray(contract.collections)) {
306
- console.log(chalk.red(" ✗ The contract response did not contain collections."));
265
+ const field = (key) => typeof contract === "object" && contract !== null && key in contract ? Object.entries(contract).find(([name]) => name === key)?.[1] : void 0;
266
+ const tables = field("tables");
267
+ const schemaVersion = field("schemaVersion");
268
+ if (!Array.isArray(tables)) {
269
+ if (Array.isArray(field("collections"))) {
270
+ console.log(chalk.red(" ✗ This server answers the contract with collections: it runs a Rebase release from before tables."));
271
+ console.log(chalk.gray(" Upgrade the server to a release that serves `tables`, or generate from this project's"));
272
+ console.log(chalk.gray(" own backend/schema by running `rebase generate-sdk` without --from."));
273
+ process.exit(1);
274
+ }
275
+ console.log(chalk.red(" ✗ The contract response did not contain tables."));
276
+ process.exit(1);
277
+ }
278
+ const invalid = tables.findIndex((entry) => !isTableDescriptor(entry));
279
+ if (invalid !== -1) {
280
+ console.log(chalk.red(` ✗ The contract's tables[${invalid}] is not a table descriptor (no slug, table, columns or relations).`));
307
281
  process.exit(1);
308
282
  }
309
283
  return {
310
- collections: deserializeCollections(contract.collections),
311
- schemaVersion: contract.schemaVersion ?? "unknown"
284
+ tables: tables.filter(isTableDescriptor),
285
+ schemaVersion: typeof schemaVersion === "string" ? schemaVersion : "unknown"
312
286
  };
313
287
  }
314
288
  /**
@@ -391,17 +365,18 @@ function resolveSchemaSource(from, cwd) {
391
365
  * Main entry point for the generate-sdk command.
392
366
  */
393
367
  async function generateSdkCommand(args) {
394
- const { collectionsDir, output, cwd } = args;
368
+ const { schemaDir, output, cwd } = args;
395
369
  if (args.help) {
396
370
  printSdkHelp();
397
371
  return;
398
372
  }
399
- const resolvedCollectionsDir = path.isAbsolute(collectionsDir) ? collectionsDir : path.join(cwd, collectionsDir);
373
+ const resolvedSchemaDir = path.isAbsolute(schemaDir) ? schemaDir : path.join(cwd, schemaDir);
374
+ const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? void 0;
400
375
  const resolvedOutput = path.isAbsolute(output) ? output : path.join(cwd, output);
401
376
  console.log("");
402
377
  console.log(chalk.bold(" 🔧 Rebase SDK Generator"));
403
378
  console.log("");
404
- let collections;
379
+ let tables;
405
380
  let remoteSchemaVersion;
406
381
  if (args.from) {
407
382
  const baseUrl = resolveSchemaSource(args.from, cwd);
@@ -411,37 +386,46 @@ async function generateSdkCommand(args) {
411
386
  console.log(chalk.cyan(" → Fetching the project contract..."));
412
387
  const ambient = mayUseAmbientKey(baseUrl, cwd) ? process.env.REBASE_SERVICE_KEY : void 0;
413
388
  if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) console.log(chalk.dim(" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)"));
414
- const remote = await fetchRemoteCollections(baseUrl, args.token || ambient, {
389
+ const remote = await fetchRemoteTables(baseUrl, args.token || ambient, {
415
390
  sent: args.token ? "token" : ambient ? "ambient" : null,
416
391
  shellKey: Boolean(process.env.REBASE_SERVICE_KEY),
417
392
  envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)
418
393
  });
419
- collections = remote.collections;
394
+ tables = remote.tables;
420
395
  remoteSchemaVersion = remote.schemaVersion;
421
396
  } else {
422
- if (!fs.existsSync(resolvedCollectionsDir)) {
423
- console.log(chalk.gray(" ○ This project derives its API from the database — run `rebase schema introspect` first."));
424
- console.log(chalk.gray(` Nothing to generate from: ${resolvedCollectionsDir} does not exist.`));
397
+ if (!fs.existsSync(resolvedSchemaDir)) {
398
+ console.log(chalk.gray(" ○ This project derives its API from the database — there is no backend/schema to generate a client from."));
399
+ console.log(chalk.gray(` Nothing to generate from: ${resolvedSchemaDir} does not exist.`));
425
400
  console.log("");
426
401
  return;
427
402
  }
428
- console.log(` ${chalk.gray("Collections:")} ${resolvedCollectionsDir}`);
403
+ console.log(` ${chalk.gray("Schema:")} ${resolvedSchemaDir}`);
429
404
  console.log(` ${chalk.gray("Output:")} ${resolvedOutput}`);
430
405
  console.log("");
431
- console.log(chalk.cyan(" → Loading collection definitions..."));
432
- collections = await loadCollections(resolvedCollectionsDir);
406
+ console.log(chalk.cyan(" → Loading the tables..."));
407
+ try {
408
+ tables = await loadTables(projectRoot ?? cwd, resolvedSchemaDir, args.moduleAliases);
409
+ } catch (err) {
410
+ if (isSchemaDefinitionError(err)) {
411
+ console.log("");
412
+ console.log(chalk.red(` ✗ ${err.message}`));
413
+ process.exit(1);
414
+ }
415
+ throw err;
416
+ }
433
417
  }
434
- collections.sort((a, b) => a.slug.localeCompare(b.slug));
435
- if (collections.length === 0) {
436
- console.log(chalk.red(" ✗ No collections found. Nothing to generate."));
418
+ tables = sortedBySlug(tables);
419
+ if (tables.length === 0) {
420
+ console.log(chalk.red(" ✗ No tables found. Nothing to generate."));
437
421
  process.exit(1);
438
422
  }
439
- console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map((c) => c.slug).join(", ")}`));
423
+ console.log(chalk.green(` ✓ Found ${tables.length} table(s): ${tables.map((table) => table.slug).join(", ")}`));
440
424
  console.log("");
441
425
  console.log(chalk.cyan(" → Generating SDK files..."));
442
426
  let files;
443
427
  try {
444
- files = generateSDK(collections, { baseUrl: resolveExampleBaseUrl(cwd) });
428
+ files = generateSDK(tables, { baseUrl: resolveExampleBaseUrl(cwd) });
445
429
  } catch (err) {
446
430
  if (err instanceof CodegenError) {
447
431
  console.log("");
@@ -450,7 +434,7 @@ async function generateSdkCommand(args) {
450
434
  }
451
435
  throw err;
452
436
  }
453
- const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);
437
+ const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(tables);
454
438
  files.push({
455
439
  path: "schema.meta.ts",
456
440
  content: `// Auto-generated by \`rebase generate-sdk\`. Do not edit.
@@ -470,12 +454,11 @@ export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
470
454
  console.log(chalk.gray(` schema ${schemaVersion}`));
471
455
  console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));
472
456
  writeFiles(resolvedOutput, files);
473
- const registerDir = registrationDir(resolvedCollectionsDir);
474
- const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? void 0;
475
- if (args.register || hasRegistration(registerDir) || manifestRegisters(projectRoot)) {
476
- if (!fs.existsSync(path.dirname(registerDir))) {
477
- console.log(chalk.red(` ✗ No ${path.dirname(registerDir)} to register the Database in.`));
478
- console.log(chalk.gray(" --register writes beside the collections directory; pass --collections."));
457
+ const registerDir = projectRoot ? registrationDir(projectRoot) : void 0;
458
+ if (args.register || registerDir && hasRegistration(registerDir) || manifestRegisters(projectRoot)) {
459
+ if (!registerDir || !fs.existsSync(path.dirname(registerDir))) {
460
+ console.log(chalk.red(` ✗ No backend/ directory to register the Database in${registerDir ? ` (${path.dirname(registerDir)})` : ""}.`));
461
+ console.log(chalk.gray(" --register writes backend/generated/register.ts; run it inside a project with a backend."));
479
462
  process.exit(1);
480
463
  return;
481
464
  }
@@ -501,20 +484,20 @@ export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
501
484
  console.log("");
502
485
  const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, "database.types"))}`;
503
486
  const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, "schema.meta"))}`;
504
- const exampleSlug = collections[0]?.slug || "my_collection";
487
+ const exampleSlug = tables[0]?.slug || "my_table";
505
488
  console.log(chalk.gray(" Usage:"));
506
489
  console.log(chalk.gray(" import { createRebaseClient } from '@rebasepro/client';"));
507
- console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));
490
+ console.log(chalk.gray(` import { tablesDictionary, type Database } from '${typesImport}';`));
508
491
  console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));
509
492
  console.log("");
510
493
  console.log(chalk.gray(" const rebase = createRebaseClient<Database>({"));
511
494
  console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));
512
495
  console.log(chalk.gray(" schemaVersion: SCHEMA_VERSION,"));
513
- console.log(chalk.gray(" collections: collectionsDictionary,"));
496
+ console.log(chalk.gray(" tables: tablesDictionary,"));
514
497
  console.log(chalk.gray(" // token: 'your-jwt-token',"));
515
498
  console.log(chalk.gray(" });"));
516
499
  console.log("");
517
- const exampleAccessor = toCollectionAccessor(exampleSlug);
500
+ const exampleAccessor = toTableAccessor(exampleSlug);
518
501
  const exampleAccess = isIdentifierLike(exampleAccessor) ? `rebase.data.${exampleAccessor}` : `rebase.data[${JSON.stringify(exampleAccessor)}]`;
519
502
  console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));
520
503
  console.log("");
@@ -522,4 +505,4 @@ export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
522
505
  //#endregion
523
506
  export { generateSdkCommand, writeRegistrationForBuild };
524
507
 
525
- //# sourceMappingURL=generate_sdk-DNmNuFuW.js.map
508
+ //# sourceMappingURL=generate_sdk-De-aLC1L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate_sdk-De-aLC1L.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads the project's tables — `backend/schema`, through the loader the\n * backend boots from, so the SDK describes exactly the tables served — or,\n * with `--from`, a running project's contract, and writes a typed TypeScript\n * SDK to the output directory (default: ./generated/sdk).\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { computeSchemaVersion, type TableDescriptor } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toTableAccessor } from \"@rebasepro/codegen\";\nimport { isSchemaDefinitionError } from \"@rebasepro/common\";\nimport { findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { DEV_BACKEND_URL_ENV } from \"../utils/dev-server\";\nimport { Refusal } from \"../utils/refusal\";\nimport { findBackendApp, GENERATED_DIR, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { SCHEMA_DIR_FLAG_HELP, PATH_RESOLUTION_RULE } from \"../utils/path-flags\";\nimport { loadProjectSchema, type ModuleAliases } from \"../utils/project-schema\";\n\ninterface GenerateSDKArgs {\n /** The schema directory: the one whose index exports the tables. */\n schemaDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no tables — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `backend/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered\n * and under which `backend/generated/` is. Found from `cwd` when not given.\n */\n projectRoot?: string;\n /** Module specifiers mapped to files when importing the schema (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in table hooks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `backend/generated/` under the project root.\n *\n * Inside `backend/` because that is the program the hooks, functions and\n * crons it types are compiled in. The types are copied in beside the\n * registration rather than imported from `generated/sdk`, which is outside\n * the backend's `rootDir`.\n */\nexport function registrationDir(projectRoot: string): string {\n return path.join(projectRoot, GENERATED_DIR);\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Write the server-side registration from the build's tables, exactly as\n * `rebase generate-sdk` writes it.\n *\n * Only for a project that asked for it: `registerDatabase` in `rebase.json`,\n * or a registration an earlier `--register` left, which is kept current. The\n * registration lives in gitignored `backend/generated/`, so a fresh clone (a\n * CI job) has none until something writes it, and a bundle compiled without\n * it types `context.data` as untyped rows: hooks that read a typed column fail\n * to compile there while they compile locally.\n *\n * Returns the directory written, or null when there was nothing to do.\n * Throws when a `register.ts` there is not ours, as `generate-sdk` refuses.\n */\nexport async function writeRegistrationForBuild(\n projectRoot: string,\n tables: readonly TableDescriptor[],\n registerDatabase: boolean\n): Promise<string | null> {\n const dir = registrationDir(projectRoot);\n if (!registerDatabase && !hasRegistration(dir)) return null;\n if (tables.length === 0) return null;\n const databaseTypes = generateSDK(sortedBySlug(tables), { includeReadme: false })\n .find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes === undefined) return null;\n writeRegistration(dir, databaseTypes);\n return dir;\n}\n\n/** Tables sorted by slug: the same schema generates the same bytes, whatever order the index lists it in. */\nfunction sortedBySlug(tables: readonly TableDescriptor[]): TableDescriptor[] {\n return [...tables].sort((a, b) => a.slug.localeCompare(b.slug));\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * The tables the backend serves, read the way it reads them: the schema\n * directory's index, through `loadBackendSchema`, compiled to descriptors.\n *\n * A definition the backend would refuse is fatal here too, as it is at boot:\n * `rebase dev` runs this on every save, and skipping a table would overwrite\n * good types with a `Database` that is silently short one. A missing\n * directory is a `Refusal`: the message says all there is. A module that\n * throws on import is not: that is the project's own code failing, and the\n * stack `--debug` prints points at the line.\n */\nasync function loadTables(projectRoot: string, schemaDir: string, aliases?: ModuleAliases): Promise<TableDescriptor[]> {\n const absDir = path.resolve(schemaDir);\n if (!fs.existsSync(absDir)) {\n throw new Refusal(`Schema directory not found: ${absDir} (${PATH_RESOLUTION_RULE})`);\n }\n const { compiled } = await loadProjectSchema(projectRoot, absDir, aliases);\n return compiled.descriptors;\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n --schema-dir <dir> ${SCHEMA_DIR_FLAG_HELP}\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to backend/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From backend/schema\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/** What `--from` sent to the contract endpoint, and which keys it left behind. */\ninterface ContractCredential {\n /** The bearer token sent: `--token`, the shell's key, or none. */\n sent: \"token\" | \"ambient\" | null;\n /** `REBASE_SERVICE_KEY` is in the shell environment. */\n shellKey: boolean;\n /** `REBASE_SERVICE_KEY` is in the project's `.env`. */\n envFileKey: boolean;\n}\n\n/**\n * What to say when the contract endpoint refuses, by what was and was not sent.\n *\n * \"Set REBASE_SERVICE_KEY\" is only right when no key exists. The shell's key is\n * withheld from every host but the linked project, and `.env`'s is never read\n * here — it is the local backend's key, and the linked project is usually a\n * deployed one — so telling a reader whose key is in `.env` to set it sends them\n * to fix something that is not broken.\n */\nfunction contractRefusalHint(credential: ContractCredential): string[] {\n if (credential.sent === \"token\") {\n return [\"The token passed with --token was refused: pass a service key, or an admin's token.\"];\n }\n if (credential.sent === \"ambient\") {\n return [\"REBASE_SERVICE_KEY was sent and refused: it is not this project's service key. Pass the right one with --token.\"];\n }\n if (credential.shellKey) {\n return [\n \"REBASE_SERVICE_KEY is set, but it is only sent to this checkout's linked project, and this host is not it.\",\n \"Pass the key with --token to send it here.\"\n ];\n }\n if (credential.envFileKey) {\n return [\n \"REBASE_SERVICE_KEY in .env is not sent: --from sends the shell's REBASE_SERVICE_KEY, and only to this checkout's linked project.\",\n \"Pass the key with --token.\"\n ];\n }\n return [\"Pass --token <key>, a service key or an admin's token. The shell's REBASE_SERVICE_KEY is sent only to this checkout's linked project.\"];\n}\n\n/**\n * Whether one entry of a contract's `tables` is a table descriptor, as far as\n * the generator reads one: a slug, a SQL name, columns and relations.\n */\nfunction isTableDescriptor(value: unknown): value is TableDescriptor {\n return typeof value === \"object\" && value !== null\n && \"slug\" in value && typeof value.slug === \"string\"\n && \"table\" in value && typeof value.table === \"string\"\n && \"columns\" in value && Array.isArray(value.columns)\n && \"relations\" in value && Array.isArray(value.relations);\n}\n\n/**\n * The tables a running project serves, from its contract endpoint\n * (`{ schemaVersion, runtime, tables: TableDescriptor[] }`). The descriptors\n * are plain data — no thunks to rehydrate — so they go to the generator as\n * they arrive.\n */\nasync function fetchRemoteTables(\n baseUrl: string,\n token: string | undefined,\n credential: ContractCredential\n): Promise<{ tables: TableDescriptor[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n for (const line of contractRefusalHint(credential)) console.log(chalk.gray(` ${line}`));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract: unknown = await response.json();\n const field = (key: string): unknown =>\n typeof contract === \"object\" && contract !== null && key in contract\n ? Object.entries(contract).find(([name]) => name === key)?.[1]\n : undefined;\n const tables = field(\"tables\");\n const schemaVersion = field(\"schemaVersion\");\n\n if (!Array.isArray(tables)) {\n if (Array.isArray(field(\"collections\"))) {\n // A server from before tables: its contract lists collections, a\n // shape this CLI no longer generates from.\n console.log(chalk.red(\" ✗ This server answers the contract with collections: it runs a Rebase release from before tables.\"));\n console.log(chalk.gray(\" Upgrade the server to a release that serves `tables`, or generate from this project's\"));\n console.log(chalk.gray(\" own backend/schema by running `rebase generate-sdk` without --from.\"));\n process.exit(1);\n }\n console.log(chalk.red(\" ✗ The contract response did not contain tables.\"));\n process.exit(1);\n }\n const invalid = tables.findIndex(entry => !isTableDescriptor(entry));\n if (invalid !== -1) {\n console.log(chalk.red(` ✗ The contract's tables[${invalid}] is not a table descriptor (no slug, table, columns or relations).`));\n process.exit(1);\n }\n\n return {\n tables: tables.filter(isTableDescriptor),\n schemaVersion: typeof schemaVersion === \"string\" ? schemaVersion : \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port `rebase dev` says it is starting the backend on (`DEV_BACKEND_URL_ENV`:\n * it regenerates the SDK before the backend binds), then the port this project\n * last ran on; fall back to the literal only when the project has never been\n * started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const fromDev = process.env[DEV_BACKEND_URL_ENV]?.trim();\n if (fromDev) return fromDev;\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { schemaDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedSchemaDir = path.isAbsolute(schemaDir)\n ? schemaDir\n : path.join(cwd, schemaDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let tables: TableDescriptor[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteTables(baseUrl, args.token || ambient, {\n sent: args.token ? \"token\" : ambient ? \"ambient\" : null,\n shellKey: Boolean(process.env.REBASE_SERVICE_KEY),\n envFileKey: Boolean(readEnvFile(findProjectRoot(cwd) ?? cwd).REBASE_SERVICE_KEY)\n });\n tables = remote.tables;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no schema directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedSchemaDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"there is no backend/schema to generate a client from.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedSchemaDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Schema:\")} ${resolvedSchemaDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading the tables...\"));\n try {\n tables = await loadTables(projectRoot ?? cwd, resolvedSchemaDir, args.moduleAliases);\n } catch (err) {\n // A definition the backend would refuse to boot on: every problem,\n // one per line, each naming its table.\n if (isSchemaDefinitionError(err)) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n }\n\n // Sorted by slug, so the same schema generates the same SDK.\n tables = sortedBySlug(tables);\n\n if (tables.length === 0) {\n console.log(chalk.red(\" ✗ No tables found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${tables.length} table(s): ${tables.map(table => table.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n let files: GeneratedFile[];\n try {\n files = generateSDK(tables, { baseUrl: resolveExampleBaseUrl(cwd) });\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a table's reads to another's.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Tables are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(tables);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = projectRoot ? registrationDir(projectRoot) : undefined;\n if (args.register || (registerDir && hasRegistration(registerDir)) || manifestRegisters(projectRoot)) {\n if (!registerDir || !fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No backend/ directory to register the Database in${registerDir ? ` (${path.dirname(registerDir)})` : \"\"}.`));\n console.log(chalk.gray(\" --register writes backend/generated/register.ts; run it inside a project with a backend.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = tables[0]?.slug || \"my_table\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { tablesDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" tables: tablesDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.table(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toTableAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;AAwB3C,SAAgB,gBA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QAAQ,IAAI,MAAM,KAAK,qBAAqB,sBAAsB,GAAG,EAAE,GAAG,CAAC;CAI3E,QAAQ,IAAI,MAAM,KAAK,wCAAwC,CAAC;CAGhE,QAAQ,IAAI,MAAM,KAAK,mCAAmC,CAAC;CAC3D,QAAQ,IAAI,MAAM,KAAK,qCAAqC,CAAC;CAC7D,QAAQ,IAAI,MAAM,KAAK,SAAS,CAAC;CACjC,QAAQ,IAAI,EAAE;CAMd,MAAM,kBAAkB,gBAAgB,WAAW;CACnD,MAAM,gBAAgB,iBAAiB,eAAe,IAChD,eAAe,oBACf,eAAe,KAAK,UAAU,eAAe,EAAE;CACrD,QAAQ,IAAI,MAAM,KAAK,8BAA8B,cAAc,SAAS,CAAC;CAC7E,QAAQ,IAAI,EAAE;AAClB"}
@@ -0,0 +1,51 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ //#region src/utils/import-schema-module.ts
5
+ /**
6
+ * Importing a project's TypeScript modules from a CLI process.
7
+ *
8
+ * The CLI runs as plain Node: no TypeScript loader is registered, and a
9
+ * project's schema modules import each other without extensions (`./users`),
10
+ * which Node's built-in type stripping cannot resolve. So every command that
11
+ * reads a project's `backend/schema` (or any other project module) imports it
12
+ * through jiti, with this one importer — handed to `loadBackendSchema(dir, {
13
+ * importModule })` from `@rebasepro/server`, so the CLI reads tables exactly
14
+ * as the server does.
15
+ */
16
+ /**
17
+ * An importer for the modules of the project at `root`.
18
+ *
19
+ * One importer evaluates each module once, so modules that import each other
20
+ * see the same objects (a relation's target is the exported table itself). A
21
+ * new importer sees the files as they are now: what an earlier importer
22
+ * evaluated under `root` is dropped from Node's shared module cache first —
23
+ * a command may write a module and read it back in one process.
24
+ *
25
+ * @param root the project root, absolute
26
+ * @param aliases module specifiers mapped to files. A user's project resolves
27
+ * through its own `node_modules` and passes none; tests and in-repo runs point
28
+ * `@rebasepro/*` at the workspace's source so they never read a stale `dist`.
29
+ */
30
+ async function createSchemaModuleImporter(root, aliases = {}) {
31
+ const cache = createRequire(import.meta.url).cache;
32
+ const prefix = path.resolve(root) + path.sep;
33
+ for (const key of Object.keys(cache)) if (key.startsWith(prefix)) delete cache[key];
34
+ const { createJiti } = await import("jiti");
35
+ const jiti = createJiti(pathToFileURL(path.join(root, "__rebase_import__.ts")).href, {
36
+ alias: aliases,
37
+ interopDefault: true,
38
+ moduleCache: true,
39
+ fsCache: false,
40
+ jsx: true
41
+ });
42
+ return async (file) => {
43
+ const loaded = await jiti.import(file);
44
+ if (typeof loaded !== "object" || loaded === null) return { default: loaded };
45
+ return Object.fromEntries(Object.entries(loaded));
46
+ };
47
+ }
48
+ //#endregion
49
+ export { createSchemaModuleImporter as t };
50
+
51
+ //# sourceMappingURL=import-schema-module-Df67TIWj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import-schema-module-Df67TIWj.js","names":[],"sources":["../src/utils/import-schema-module.ts"],"sourcesContent":["/**\n * Importing a project's TypeScript modules from a CLI process.\n *\n * The CLI runs as plain Node: no TypeScript loader is registered, and a\n * project's schema modules import each other without extensions (`./users`),\n * which Node's built-in type stripping cannot resolve. So every command that\n * reads a project's `backend/schema` (or any other project module) imports it\n * through jiti, with this one importer — handed to `loadBackendSchema(dir, {\n * importModule })` from `@rebasepro/server`, so the CLI reads tables exactly\n * as the server does.\n */\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { SchemaModuleImporter } from \"@rebasepro/server\";\n\n/**\n * An importer for the modules of the project at `root`.\n *\n * One importer evaluates each module once, so modules that import each other\n * see the same objects (a relation's target is the exported table itself). A\n * new importer sees the files as they are now: what an earlier importer\n * evaluated under `root` is dropped from Node's shared module cache first —\n * a command may write a module and read it back in one process.\n *\n * @param root the project root, absolute\n * @param aliases module specifiers mapped to files. A user's project resolves\n * through its own `node_modules` and passes none; tests and in-repo runs point\n * `@rebasepro/*` at the workspace's source so they never read a stale `dist`.\n */\nexport async function createSchemaModuleImporter(root: string, aliases: Record<string, string> = {}): Promise<SchemaModuleImporter> {\n const cache = createRequire(import.meta.url).cache;\n const prefix = path.resolve(root) + path.sep;\n for (const key of Object.keys(cache)) if (key.startsWith(prefix)) delete cache[key];\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(pathToFileURL(path.join(root, \"__rebase_import__.ts\")).href, {\n alias: aliases,\n interopDefault: true,\n moduleCache: true,\n fsCache: false,\n jsx: true\n });\n return async (file: string) => {\n const loaded: unknown = await jiti.import(file);\n if (typeof loaded !== \"object\" || loaded === null) return { default: loaded };\n return Object.fromEntries(Object.entries(loaded));\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,eAAsB,2BAA2B,MAAc,UAAkC,CAAC,GAAkC;CAChI,MAAM,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,CAAC;CAC7C,MAAM,SAAS,KAAK,QAAQ,IAAI,IAAI,KAAK;CACzC,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG,IAAI,IAAI,WAAW,MAAM,GAAG,OAAO,MAAM;CAC/E,MAAM,EAAE,eAAe,MAAM,OAAO;CACpC,MAAM,OAAO,WAAW,cAAc,KAAK,KAAK,MAAM,sBAAsB,CAAC,CAAC,CAAC,MAAM;EACjF,OAAO;EACP,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,KAAK;CACT,CAAC;CACD,OAAO,OAAO,SAAiB;EAC3B,MAAM,SAAkB,MAAM,KAAK,OAAO,IAAI;EAC9C,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,EAAE,SAAS,OAAO;EAC5E,OAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC;CACpD;AACJ"}