@rebasepro/server-postgres 0.30.0 → 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 (248) hide show
  1. package/README.md +11 -8
  2. package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
  3. package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
  4. package/dist/PostgresBackendDriver.d.ts +99 -54
  5. package/dist/PostgresBootstrapper.d.ts +12 -27
  6. package/dist/auth/ensure-tables.d.ts +16 -5
  7. package/dist/auth/schema-version.d.ts +2 -2
  8. package/dist/auth/services.d.ts +2 -3
  9. package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
  10. package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
  11. package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
  12. package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
  13. package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
  14. package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
  15. package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
  16. package/dist/cli-console-DsRgGSBR.js.map +1 -0
  17. package/dist/cli-console.d.ts +16 -13
  18. package/dist/cli-flags.d.ts +8 -9
  19. package/dist/cli-helpers.d.ts +15 -11
  20. package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
  21. package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
  22. package/dist/cli-schema-dir.d.ts +64 -0
  23. package/dist/cli.js +192 -257
  24. package/dist/cli.js.map +1 -1
  25. package/dist/data-transformer.d.ts +50 -19
  26. package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
  27. package/dist/database-preflight-bfnIBnjM.js.map +1 -0
  28. package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
  29. package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
  30. package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
  31. package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
  33. package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
  34. package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
  35. package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
  36. package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
  37. package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
  38. package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
  39. package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
  40. package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
  41. package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
  42. package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
  43. package/dist/generate-files-tlJ9_lGI.js.map +1 -0
  44. package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
  45. package/dist/generate-next-step-CO09dovd.js.map +1 -0
  46. package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
  47. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
  48. package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
  49. package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
  50. package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
  51. package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
  52. package/dist/history/ensure-history-table.d.ts +22 -0
  53. package/dist/index.d.ts +8 -2
  54. package/dist/index.es.js +201 -25
  55. package/dist/index.es.js.map +1 -1
  56. package/dist/interfaces.d.ts +3 -4
  57. package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
  58. package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
  59. package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
  60. package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
  61. package/dist/load-tables-B1Re74ng.js +92 -0
  62. package/dist/load-tables-B1Re74ng.js.map +1 -0
  63. package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
  64. package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
  65. package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
  66. package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
  67. package/dist/model/PostgresTableRegistry.d.ts +159 -0
  68. package/dist/model/build-registry.d.ts +25 -0
  69. package/dist/model/refresh-relational-schema.d.ts +24 -0
  70. package/dist/model/runtime-table.d.ts +53 -0
  71. package/dist/{collections → model}/validate-relations.d.ts +15 -21
  72. package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
  73. package/dist/open-rebase-4kisUF_k.js.map +1 -0
  74. package/dist/open-rebase.d.ts +16 -15
  75. package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
  76. package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
  77. package/dist/plan-schema-Hbtjhge3.js +1633 -0
  78. package/dist/plan-schema-Hbtjhge3.js.map +1 -0
  79. package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
  80. package/dist/policy-drift-BVMyqHSa.js.map +1 -0
  81. package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
  82. package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
  83. package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
  84. package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
  85. package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
  86. package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
  87. package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
  88. package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
  89. package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
  90. package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
  91. package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
  92. package/dist/render-ddl-D4n86NHz.js.map +1 -0
  93. package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
  94. package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
  95. package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
  96. package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
  97. package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
  98. package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
  99. package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
  100. package/dist/rls-settings-CmGK2U0a.js.map +1 -0
  101. package/dist/schema/auth-users-columns.d.ts +1 -11
  102. package/dist/schema/catalogue-schema.d.ts +33 -29
  103. package/dist/schema/classify-change.d.ts +23 -16
  104. package/dist/schema/column-type-drift.d.ts +16 -0
  105. package/dist/schema/config-relations.d.ts +10 -9
  106. package/dist/schema/deferred-index-build.d.ts +1 -1
  107. package/dist/schema/doctor-cli.js +1544 -66
  108. package/dist/schema/doctor-cli.js.map +1 -1
  109. package/dist/schema/doctor-database.d.ts +7 -7
  110. package/dist/schema/doctor-policy-checks.d.ts +4 -4
  111. package/dist/schema/doctor-search-scale.d.ts +14 -14
  112. package/dist/schema/doctor.d.ts +27 -27
  113. package/dist/schema/dynamic-tables.d.ts +6 -5
  114. package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
  115. package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
  116. package/dist/schema/enum-labels-kept.d.ts +6 -6
  117. package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
  118. package/dist/schema/generate-drizzle-schema.js +1 -1
  119. package/dist/schema/generate-files.d.ts +6 -6
  120. package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
  121. package/dist/schema/generate-postgres-ddl.js +11 -11
  122. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  123. package/dist/schema/generate-schema-commit.d.ts +13 -8
  124. package/dist/schema/generated-schema-diff.d.ts +16 -16
  125. package/dist/schema/generated-schema-staleness.d.ts +11 -11
  126. package/dist/schema/index-adoption.d.ts +4 -4
  127. package/dist/schema/introspect-db-customization.d.ts +47 -0
  128. package/dist/schema/introspect-db-inference.d.ts +30 -9
  129. package/dist/schema/introspect-db-logic.d.ts +79 -110
  130. package/dist/schema/introspect-db-project.d.ts +15 -18
  131. package/dist/schema/introspect-db-queries.d.ts +1 -1
  132. package/dist/schema/introspect-db-search.d.ts +25 -4
  133. package/dist/schema/introspect-db-storage.d.ts +4 -74
  134. package/dist/schema/introspect-db.js +102 -90
  135. package/dist/schema/introspect-db.js.map +1 -1
  136. package/dist/schema/introspect-runtime.d.ts +47 -36
  137. package/dist/schema/introspect-tables.d.ts +182 -0
  138. package/dist/schema/load-tables.d.ts +55 -0
  139. package/dist/schema/migrate-policy-stamps.d.ts +4 -4
  140. package/dist/schema/migration-freshness.d.ts +13 -13
  141. package/dist/schema/plan/column-order.d.ts +82 -0
  142. package/dist/schema/plan/diff-plan.d.ts +9 -3
  143. package/dist/schema/plan/plan-schema.d.ts +55 -52
  144. package/dist/schema/plan/render-drizzle.d.ts +1 -1
  145. package/dist/schema/plan/types.d.ts +24 -15
  146. package/dist/schema/push-index-adoption.d.ts +3 -3
  147. package/dist/schema/push-index-prebuild.d.ts +3 -3
  148. package/dist/schema/push-kept-defaults.d.ts +7 -7
  149. package/dist/schema/push-legacy-renames.d.ts +3 -3
  150. package/dist/schema/push-policy-plan.d.ts +5 -5
  151. package/dist/schema/reconcile-schema.d.ts +5 -5
  152. package/dist/schema/relation-names.d.ts +15 -20
  153. package/dist/schema/render-outputs.d.ts +76 -0
  154. package/dist/schema/search-column.d.ts +11 -43
  155. package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
  156. package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
  157. package/dist/schema/vector-index.d.ts +24 -28
  158. package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
  159. package/dist/search-column-BO-WND-B.js.map +1 -0
  160. package/dist/security/caller-sql-columns.d.ts +9 -6
  161. package/dist/security/policy-drift.d.ts +14 -14
  162. package/dist/security/rls-enforcement.d.ts +19 -25
  163. package/dist/security/rls-settings.d.ts +2 -2
  164. package/dist/security/served-table-protection.d.ts +125 -0
  165. package/dist/services/FetchService.d.ts +22 -133
  166. package/dist/services/PersistService.d.ts +6 -17
  167. package/dist/services/RelationService.d.ts +57 -106
  168. package/dist/services/RelationWriteService.d.ts +59 -66
  169. package/dist/services/cdc/identity-columns.d.ts +7 -5
  170. package/dist/services/cdc/junction-tables.d.ts +14 -14
  171. package/dist/services/collection-helpers.d.ts +52 -95
  172. package/dist/services/dataService.d.ts +15 -12
  173. package/dist/services/field-op-sql.d.ts +11 -9
  174. package/dist/services/field-viewer.d.ts +12 -11
  175. package/dist/services/hidden-columns.d.ts +30 -0
  176. package/dist/services/index.d.ts +1 -1
  177. package/dist/services/junction-writes.d.ts +37 -18
  178. package/dist/services/nested-path.d.ts +18 -18
  179. package/dist/services/read-field-access.d.ts +23 -7
  180. package/dist/services/read-scope.d.ts +10 -9
  181. package/dist/services/realtimeService.d.ts +25 -10
  182. package/dist/services/relation-tables.d.ts +97 -0
  183. package/dist/services/row-pipeline.d.ts +50 -69
  184. package/dist/services/soft-delete.d.ts +25 -24
  185. package/dist/services/table-hooks.d.ts +146 -0
  186. package/dist/services/view-access.d.ts +7 -7
  187. package/dist/services/write-transaction-scope.d.ts +1 -1
  188. package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
  189. package/dist/source-VxbrQojV.js.map +1 -0
  190. package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
  191. package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
  192. package/dist/utils/drizzle-conditions.d.ts +70 -84
  193. package/dist/utils/pg-array-null-patch.d.ts +27 -10
  194. package/dist/utils/pg-error-utils.d.ts +4 -4
  195. package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
  196. package/dist/vector-index-VSh3ufTd.js.map +1 -0
  197. package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
  198. package/dist/websocket-BevXvwfo.js.map +1 -0
  199. package/dist/websocket.d.ts +2 -2
  200. package/package.json +7 -7
  201. package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
  202. package/dist/cli-collections-path.d.ts +0 -31
  203. package/dist/cli-console-DBPw-oAz.js.map +0 -1
  204. package/dist/cli-errors-DYTxnLbW.js.map +0 -1
  205. package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
  206. package/dist/collections/buildRegistry.d.ts +0 -27
  207. package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
  208. package/dist/column-plan-helpers-BeSztMor.js +0 -161
  209. package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
  210. package/dist/database-preflight-iBpT7-vv.js.map +0 -1
  211. package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
  212. package/dist/doctor-Kg1oUK0Q.js +0 -1458
  213. package/dist/doctor-Kg1oUK0Q.js.map +0 -1
  214. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
  215. package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
  216. package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
  217. package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
  218. package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
  219. package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
  220. package/dist/generate-files-CsaVzatS.js.map +0 -1
  221. package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
  222. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
  223. package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
  224. package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
  225. package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
  226. package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
  227. package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
  228. package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
  229. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
  230. package/dist/open-rebase-40paQfVW.js.map +0 -1
  231. package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
  232. package/dist/plan-schema-vJd3UEmT.js +0 -1604
  233. package/dist/plan-schema-vJd3UEmT.js.map +0 -1
  234. package/dist/policy-drift-C-m0uWHH.js.map +0 -1
  235. package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
  236. package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
  237. package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
  238. package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
  239. package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
  240. package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
  241. package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
  242. package/dist/rls-settings-BCGMIig3.js.map +0 -1
  243. package/dist/schema/column-plan-helpers.d.ts +0 -161
  244. package/dist/schema/introspect-db-naming.d.ts +0 -10
  245. package/dist/search-column-BM-GV6vH.js.map +0 -1
  246. package/dist/source-fZb92pN8.js.map +0 -1
  247. package/dist/vector-index-DsQ3V2d2.js.map +0 -1
  248. package/dist/websocket-B7ex6AQM.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { n as extractPgError } from "./pg-error-utils-DJHjCF7-.js";
4
+ import { n as extractPgError } from "./pg-error-utils-BT5NzGFZ.js";
5
5
  //#region src/schema/boot-ddl.ts
6
6
  /**
7
7
  * How boot DDL waits for a table lock, and how it applies several statements as
@@ -102,4 +102,4 @@ var sleep = (ms) => ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) :
102
102
  //#endregion
103
103
  export { isLockTimeout as a, resolveBootLockOptions as c, boot_ddl_exports as i, sleep as l, BOOT_LOCK_TIMEOUT_MS as n, isMultiStatementRefusal as o, atomicBatch as r, joinStatements as s, BOOT_LOCK_RETRY_BUDGET_MS as t };
104
104
 
105
- //# sourceMappingURL=boot-ddl-CqGIwSYx.js.map
105
+ //# sourceMappingURL=boot-ddl-5H2bL_80.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"boot-ddl-CqGIwSYx.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}
1
+ {"version":3,"file":"boot-ddl-5H2bL_80.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}
@@ -2,10 +2,10 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as require_arg, o as __toESM } from "./cli-prompt-DXG0yk-h.js";
4
4
  import { d as poolMaxCeiling } from "./connection-C1zXTPJq.js";
5
- import { t as openRebase } from "./open-rebase-40paQfVW.js";
6
- import { a as diagnoseDbError } from "./cli-errors-DYTxnLbW.js";
7
- import { i as outError, n as describeFailure, r as out } from "./source-fZb92pN8.js";
8
- import { h as RELAYED_FLAGS } from "./migrate-baseline-CmWXL7qx.js";
5
+ import { t as openRebase } from "./open-rebase-4kisUF_k.js";
6
+ import { c as diagnoseDbError } from "./cli-schema-dir-CiN0ephV.js";
7
+ import { i as outError, n as describeFailure, r as out } from "./source-VxbrQojV.js";
8
+ import { h as RELAYED_FLAGS } from "./migrate-baseline-DZmekgpD.js";
9
9
  import { setLogOutput } from "@rebasepro/server";
10
10
  import path from "path";
11
11
  import fs from "fs";
@@ -22,8 +22,7 @@ var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
22
22
  * keeps the REPL's history (`.rebase/console_history` in the project).
23
23
  */
24
24
  var CONSOLE_FLAGS = {
25
- "--collections": String,
26
- "-c": "--collections",
25
+ "--schema-dir": String,
27
26
  "--eval": String,
28
27
  "-e": "--eval",
29
28
  "--history": String
@@ -31,7 +30,7 @@ var CONSOLE_FLAGS = {
31
30
  /** The constructor of `async function` — what `new Function` is for a body that awaits. */
32
31
  var AsyncFunction = Object.getPrototypeOf(async () => void 0).constructor;
33
32
  /**
34
- * Run `code` with `rebase` and `collections` in scope and resolve with its
33
+ * Run `code` with `rebase` and `tables` in scope and resolve with its
35
34
  * value.
36
35
  *
37
36
  * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own
@@ -41,12 +40,12 @@ var AsyncFunction = Object.getPrototypeOf(async () => void 0).constructor;
41
40
  async function evaluateInConsole(code, scope) {
42
41
  let run;
43
42
  try {
44
- run = new AsyncFunction("rebase", "collections", `return (${code}\n);`);
43
+ run = new AsyncFunction("rebase", "tables", `return (${code}\n);`);
45
44
  } catch (error) {
46
45
  if (!(error instanceof SyntaxError)) throw error;
47
- run = new AsyncFunction("rebase", "collections", code);
46
+ run = new AsyncFunction("rebase", "tables", code);
48
47
  }
49
- return run(scope.rebase, scope.collections);
48
+ return run(scope.rebase, scope.tables);
50
49
  }
51
50
  /** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */
52
51
  function consoleJson(value) {
@@ -62,7 +61,7 @@ function describeDatabase(databaseUrl) {
62
61
  }
63
62
  }
64
63
  /**
65
- * `rebase console [--eval <code>] [--collections <dir>]`, from the driver
64
+ * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver
66
65
  * line `["console", …flags]`. Resolves with the exit code.
67
66
  */
68
67
  async function consoleCommand(args, streams = {}) {
@@ -84,7 +83,7 @@ async function consoleCommand(args, streams = {}) {
84
83
  try {
85
84
  return await openAndRun({
86
85
  databaseUrl,
87
- collections: flags["--collections"],
86
+ schemaDir: flags["--schema-dir"],
88
87
  eval: flags["--eval"],
89
88
  history: flags["--history"]
90
89
  }, streams);
@@ -120,50 +119,77 @@ function describeOpenFailure(error, databaseUrl, managed) {
120
119
  if (managed && (connectionCutOff(error) || noFreeConnection(error))) return "✗ The managed development database has no free connection: it accepts only a few at a time, and other clients hold them — a running `rebase dev` holds some.\n Close another `rebase console`, psql or database GUI and run this again, or stop `rebase dev` while you use the console.";
121
120
  return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);
122
121
  }
122
+ /** The names a table hook can have; anything else on a `hooks` export is not one. */
123
+ var TABLE_HOOK_NAMES = [
124
+ "beforeQuery",
125
+ "afterRead",
126
+ "beforeSave",
127
+ "afterSave",
128
+ "afterSaveError",
129
+ "beforeDelete",
130
+ "afterDelete"
131
+ ];
132
+ /** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */
133
+ function isTableHooks(value) {
134
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
135
+ return Object.entries(value).every(([key, hook]) => TABLE_HOOK_NAMES.includes(key) && (hook === void 0 || typeof hook === "function"));
136
+ }
123
137
  /**
124
- * The project's global callbacks: the `callbacks` its `config/index.ts`
125
- * exports, which the server runs ahead of every collection's own hooks.
138
+ * The project's global table hooks: the `hooks` its `backend/hooks.ts`
139
+ * exports, which the server runs for every table ahead of each table's own.
126
140
  *
127
- * The config package is the directory the collections live in
128
- * (`<config>/collections`), or `../config` beside the backend for a
129
- * collections directory named otherwise. No `index` there means no global
130
- * callbacks, as it does for the server.
141
+ * `backend/` is the schema directory's parent. No module there means no global
142
+ * hooks, as it does for the server.
131
143
  *
132
144
  * One that is there and cannot be imported — an import that needs an
133
145
  * environment variable the console was not given, say — does not stop the
134
146
  * console, which can still read and write. It says so, once, and runs without
135
147
  * them: writes from this session then skip the global tier, and the reader
136
148
  * knows it.
149
+ *
150
+ * They are handed on as declared: the driver calls each with the descriptor
151
+ * of the table it runs for.
152
+ *
153
+ * @param schemaDir the schema directory, absolute.
137
154
  */
138
- async function loadProjectCallbacks(collectionsPath) {
139
- const configDir = path.basename(collectionsPath) === "collections" ? path.dirname(collectionsPath) : path.resolve("..", "config");
140
- const indexPath = [".js", ".ts"].map((ext) => path.join(configDir, `index${ext}`)).find((candidate) => fs.existsSync(candidate));
141
- if (!indexPath) return void 0;
155
+ async function loadProjectHooks(schemaDir) {
156
+ const backendDir = path.dirname(schemaDir);
157
+ const modulePath = [
158
+ ".js",
159
+ ".mjs",
160
+ ".ts",
161
+ ".mts"
162
+ ].map((ext) => path.join(backendDir, `hooks${ext}`)).find((candidate) => fs.existsSync(candidate));
163
+ if (!modulePath) return void 0;
142
164
  let mod;
143
165
  try {
144
- mod = await import(pathToFileURL(indexPath).href);
166
+ mod = await import(pathToFileURL(modulePath).href);
145
167
  } catch (error) {
146
168
  const reason = (error instanceof Error ? error.message : String(error)).split("\n")[0];
147
- outError(`⚠ Global callbacks are off in this session: ${indexPath} could not be loaded (${reason}). Collection callbacks still run.`);
169
+ outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);
170
+ return;
171
+ }
172
+ if (mod.hooks === void 0) return void 0;
173
+ if (!isTableHooks(mod.hooks)) {
174
+ outError(`⚠ Global hooks are off in this session: the \`hooks\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(", ")}).`);
148
175
  return;
149
176
  }
150
- const callbacks = mod.callbacks;
151
- return callbacks && typeof callbacks === "object" ? callbacks : void 0;
177
+ return mod.hooks;
152
178
  }
153
179
  /** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */
154
180
  async function openAndRun(options, streams) {
155
181
  const { databaseUrl } = options;
156
- const collectionsPath = path.resolve(options.collections || path.join("..", "config", "collections"));
157
- const { loadCollections } = await import("./doctor-Kg1oUK0Q.js").then((n) => n.t);
158
- const collections = fs.existsSync(collectionsPath) ? await loadCollections(collectionsPath) : [];
159
- const callbacks = await loadProjectCallbacks(collectionsPath);
182
+ const { loadTableSchema } = await import("./load-tables-B1Re74ng.js").then((n) => n.i);
183
+ const schemaDir = path.resolve(options.schemaDir || "schema");
184
+ const { tables } = await loadTableSchema(schemaDir);
185
+ const hooks = await loadProjectHooks(schemaDir);
160
186
  const ceiling = poolMaxCeiling();
161
187
  let rebase;
162
188
  try {
163
189
  rebase = await openRebase({
164
190
  databaseUrl,
165
- collections,
166
- ...callbacks ? { callbacks } : {},
191
+ tables,
192
+ ...hooks ? { hooks } : {},
167
193
  ...ceiling !== null ? { pool: { max: ceiling } } : {}
168
194
  });
169
195
  } catch (error) {
@@ -175,7 +201,7 @@ async function openAndRun(options, streams) {
175
201
  if (code !== void 0) try {
176
202
  const result = await evaluateInConsole(code, {
177
203
  rebase,
178
- collections: rebase.collections
204
+ tables: rebase.tables
179
205
  });
180
206
  if (result !== void 0) out(consoleJson(result));
181
207
  return 0;
@@ -185,7 +211,7 @@ async function openAndRun(options, streams) {
185
211
  }
186
212
  await startRepl({
187
213
  rebase,
188
- collections: rebase.collections
214
+ tables: rebase.tables
189
215
  }, {
190
216
  history: options.history,
191
217
  database: describeDatabase(databaseUrl),
@@ -203,9 +229,9 @@ async function startRepl(scope, options) {
203
229
  const typed = input instanceof tty.ReadStream && input.isTTY;
204
230
  const say = typed ? out : outError;
205
231
  say("");
206
- say(` rebase console — ${options.database}, ${scope.collections.length} collection(s)`);
207
- say(" In scope: rebase (dataAsAdmin, sql, withAuth, close) and collections. Top-level await works.");
208
- say(" Try: await rebase.dataAsAdmin.<collection>.find({ limit: 5 })");
232
+ say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);
233
+ say(" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.");
234
+ say(" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })");
209
235
  say("");
210
236
  const feed = typed ? void 0 : new PassThrough();
211
237
  const colors = output instanceof tty.WriteStream && output.isTTY;
@@ -226,7 +252,7 @@ async function startRepl(scope, options) {
226
252
  })
227
253
  });
228
254
  server.context.rebase = scope.rebase;
229
- server.context.collections = scope.collections;
255
+ server.context.tables = scope.tables;
230
256
  server.setPrompt("rebase> ");
231
257
  const history = options.history;
232
258
  if (history) {
@@ -291,4 +317,4 @@ async function feedLineByLine(source, server, feed, exited) {
291
317
  //#endregion
292
318
  export { consoleCommand };
293
319
 
294
- //# sourceMappingURL=cli-console-DBPw-oAz.js.map
320
+ //# sourceMappingURL=cli-console-DsRgGSBR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-console-DsRgGSBR.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's tables (`backend/schema`) the way `rebase db push` does,\n * and the global table hooks `backend/hooks.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `tables` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { TableDescriptor, TableHooks } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { DEFAULT_SCHEMA_DIR } from \"./cli-schema-dir\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--schema-dir\": String,\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n /** The descriptors of the tables the project serves. */\n tables: TableDescriptor[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, tables: TableDescriptor[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `tables` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"tables\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"tables\", code);\n }\n return run(scope.rebase, scope.tables);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n schemaDir: flags[\"--schema-dir\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/** The names a table hook can have; anything else on a `hooks` export is not one. */\nconst TABLE_HOOK_NAMES = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */\nfunction isTableHooks(value: unknown): value is TableHooks {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return Object.entries(value).every(([key, hook]) =>\n (TABLE_HOOK_NAMES as readonly string[]).includes(key) && (hook === undefined || typeof hook === \"function\"));\n}\n\n/**\n * The project's global table hooks: the `hooks` its `backend/hooks.ts`\n * exports, which the server runs for every table ahead of each table's own.\n *\n * `backend/` is the schema directory's parent. No module there means no global\n * hooks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n *\n * They are handed on as declared: the driver calls each with the descriptor\n * of the table it runs for.\n *\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined> {\n const backendDir = path.dirname(schemaDir);\n // `.js` first, as the server's own loader reads a built module.\n const modulePath = [\".js\", \".mjs\", \".ts\", \".mts\"]\n .map(ext => path.join(backendDir, `hooks${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!modulePath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(modulePath).href);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);\n return undefined;\n }\n if (mod.hooks === undefined) return undefined;\n if (!isTableHooks(mod.hooks)) {\n outError(`⚠ Global hooks are off in this session: the \\`hooks\\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(\", \")}).`);\n return undefined;\n }\n return mod.hooks;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; schemaDir?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n // The tables the way every other driver command reads them: a schema that\n // does not compile stops the console too, rather than opening it over a\n // subset of the tables.\n const { loadTableSchema } = await import(\"./schema/load-tables\");\n const schemaDir = path.resolve(options.schemaDir || DEFAULT_SCHEMA_DIR);\n const { tables } = await loadTableSchema(schemaDir);\n // Writes from the console run the same hook tiers as a server write.\n const hooks = await loadProjectHooks(schemaDir);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n tables,\n ...(hooks ? { hooks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, tables: rebase.tables });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, tables: rebase.tables }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.tables = scope.tables;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,gBAAgB;CACzB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAaA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,cAAc,UAAU,UAAU,WAAW,KAAK,KAAK;CACrE,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,cAAc,MAAM;EAC3C,MAAM,IAAI,cAAc,UAAU,UAAU,IAAI;CACpD;CACA,OAAO,IAAI,MAAM,QAAQ,MAAM,MAAM;AACzC;;AAGA,SAAgB,YAAY,OAAwB;CAChD,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAkB,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK;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Z,UAAU;CACd;CAGA,OAAO,gBAAgB,cAAc;EACjC,IAAI,CAAC,OAAO,YAAY,OAAO,MAAM;CACzC,CAAC;CAED,OAAO,GAAG,cAAc;EACpB,IAAI,CAAC,OAAO,YAAY;EACxB,OAAO,OAAO;EACd,MAAM;CACV,CAAC;CACD,OAAO,GAAG,UAAU,KAAK;CAEzB,MAAM,SAAS,OAAO,WAAW,QAAiB;CAClD,MAAM,QAAQ,SAAS,gBAAgB;EAAE,OAAO;EAAQ,WAAW;CAAS,CAAC;CAC7E,WAAW,MAAM,QAAQ,OAAO;EAC5B,MAAM,OAAO,IAAI,SAAiB,YAAY;GAAE,kBAAkB,QAAQ,MAAM;EAAG,CAAC;EACpF,KAAK,MAAM,GAAG,KAAK,GAAG;EAEtB,IAAI,MAAM,QAAQ,KAAK,CAAC,MAAM,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
@@ -1,12 +1,11 @@
1
- import type { CollectionCallbacks, CollectionConfig } from "@rebasepro/types";
1
+ import type { TableDescriptor, TableHooks } from "@rebasepro/types";
2
2
  import { type OpenedRebase } from "./open-rebase.js";
3
3
  /**
4
4
  * The flags `rebase console` takes. `--history` is the CLI's own: where it
5
5
  * keeps the REPL's history (`.rebase/console_history` in the project).
6
6
  */
7
7
  export declare const CONSOLE_FLAGS: {
8
- "--collections": StringConstructor;
9
- "-c": string;
8
+ "--schema-dir": StringConstructor;
10
9
  "--eval": StringConstructor;
11
10
  "-e": string;
12
11
  "--history": StringConstructor;
@@ -14,10 +13,11 @@ export declare const CONSOLE_FLAGS: {
14
13
  /** What the code the console runs can name. */
15
14
  export interface ConsoleScope {
16
15
  rebase: OpenedRebase;
17
- collections: CollectionConfig[];
16
+ /** The descriptors of the tables the project serves. */
17
+ tables: TableDescriptor[];
18
18
  }
19
19
  /**
20
- * Run `code` with `rebase` and `collections` in scope and resolve with its
20
+ * Run `code` with `rebase` and `tables` in scope and resolve with its
21
21
  * value.
22
22
  *
23
23
  * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own
@@ -33,7 +33,7 @@ export interface ConsoleStreams {
33
33
  output?: NodeJS.WritableStream;
34
34
  }
35
35
  /**
36
- * `rebase console [--eval <code>] [--collections <dir>]`, from the driver
36
+ * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver
37
37
  * line `["console", …flags]`. Resolves with the exit code.
38
38
  */
39
39
  export declare function consoleCommand(args: string[], streams?: ConsoleStreams): Promise<number>;
@@ -49,18 +49,21 @@ export declare function consoleCommand(args: string[], streams?: ConsoleStreams)
49
49
  */
50
50
  export declare function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string;
51
51
  /**
52
- * The project's global callbacks: the `callbacks` its `config/index.ts`
53
- * exports, which the server runs ahead of every collection's own hooks.
52
+ * The project's global table hooks: the `hooks` its `backend/hooks.ts`
53
+ * exports, which the server runs for every table ahead of each table's own.
54
54
  *
55
- * The config package is the directory the collections live in
56
- * (`<config>/collections`), or `../config` beside the backend for a
57
- * collections directory named otherwise. No `index` there means no global
58
- * callbacks, as it does for the server.
55
+ * `backend/` is the schema directory's parent. No module there means no global
56
+ * hooks, as it does for the server.
59
57
  *
60
58
  * One that is there and cannot be imported — an import that needs an
61
59
  * environment variable the console was not given, say — does not stop the
62
60
  * console, which can still read and write. It says so, once, and runs without
63
61
  * them: writes from this session then skip the global tier, and the reader
64
62
  * knows it.
63
+ *
64
+ * They are handed on as declared: the driver calls each with the descriptor
65
+ * of the table it runs for.
66
+ *
67
+ * @param schemaDir the schema directory, absolute.
65
68
  */
66
- export declare function loadProjectCallbacks(collectionsPath: string): Promise<CollectionCallbacks | undefined>;
69
+ export declare function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined>;
@@ -73,22 +73,21 @@ export declare const OUTPUT_FLAG_ALIASES: readonly ["--out", "--output"];
73
73
  */
74
74
  export declare function assertOutputAliasesPaired(specs: Record<string, arg.Spec>): string[];
75
75
  /**
76
- * The `--collections` path the user typed, or `null` if they typed none.
76
+ * The `--schema-dir` the user typed, or `null` if they typed none.
77
77
  *
78
78
  * Read once, at the entry point, because every command that takes it re-enters
79
- * the generators with the same line and each of them resolved it again — which
80
- * is how "Collections path not found" came to be printed four times before the
81
- * real output, and how a path that does not exist got as far as *writing* an
82
- * empty schema.
79
+ * the generators with the same line and each of them would resolve it again —
80
+ * which is how a missing directory came to be reported four times before the
81
+ * real output, and how one got as far as *writing* an empty schema.
83
82
  *
84
83
  * Permissive, and it has to be: {@link assertKnownFlags} has already judged the
85
- * line, and `db push` carries flags the `--collections` spec does not name.
84
+ * line, and `db push` carries flags this one-flag spec does not name.
86
85
  */
87
- export declare function collectionsPathIn(args: string[]): string | null;
86
+ export declare function schemaDirIn(args: string[]): string | null;
88
87
  /**
89
88
  * The long flags a `--help` usage line documents.
90
89
  *
91
- * `"rebase db push [--collections <dir>] [--dry-run] …"` → `["--collections",
90
+ * `"rebase db push [--schema-dir <dir>] [--dry-run] …"` → `["--schema-dir",
92
91
  * "--dry-run"]`. Placeholders (`<dir>`) and the alternation inside a positional
93
92
  * (`<create|list|switch>`) are not flags and are not returned.
94
93
  */
@@ -111,7 +110,7 @@ export declare function flagsInUsage(usage: string): string[];
111
110
  * help covers commands that parse their own lines (`db branch`, `db backup`),
112
111
  * and an absent spec entry means "not checked here".
113
112
  *
114
- * Aliases (`"-c": "--collections"`, `"--out": "--output"`) need no line of their
113
+ * Aliases (`"-y": "--yes"`, `"--out": "--output"`) need no line of their
115
114
  * own: they are spellings of a documented flag. Neither do {@link RELAYED_FLAGS},
116
115
  * which every driver command accepts because the CLI relays them.
117
116
  */
@@ -1,7 +1,7 @@
1
1
  import type { GeneratedColumnDependency } from "./schema/generated-column-conflicts.js";
2
2
  import { type ExistingColumnType } from "./schema/destructive-sql.js";
3
3
  import { type ExistingConstraint } from "./schema/undeclarable-constraints.js";
4
- import type { CollectionConfig } from "@rebasepro/types";
4
+ import type { TableDescriptor } from "@rebasepro/types";
5
5
  /**
6
6
  * Why is a dependency's binary missing — never installed, or installed with its
7
7
  * build script blocked?
@@ -97,9 +97,13 @@ export type MissingBinDiagnosis = "not-installed" | "build-script-blocked" | "bi
97
97
  export declare function declaredBinaries(manifestPath: string): string[];
98
98
  export declare function diagnoseMissingBin(packageName: string): MissingBinDiagnosis;
99
99
  export declare function resolveLocalBin(binName: string): string | null;
100
- export declare function getTableIncludesFromCollections(allCollections: CollectionConfig[]): Promise<string[]>;
101
- export declare function getTableIncludes(collectionsPath: string): Promise<string[]>;
102
- export declare function loadCollectionsForCli(collectionsPath: string): Promise<CollectionConfig[]>;
100
+ /**
101
+ * The tables Atlas may manage: every declared table (a view is Rebase's to
102
+ * create and drop, `views.sql`, never Atlas's) and every junction, as
103
+ * `schema.table`.
104
+ */
105
+ export declare function getTableIncludesFromTables(descriptors: readonly TableDescriptor[]): string[];
106
+ export declare function getTableIncludes(schemaDir: string): Promise<string[]>;
103
107
  type PgClient = import("pg").Client;
104
108
  /**
105
109
  * Run one step on this process's connection to the app database.
@@ -206,7 +210,7 @@ export declare function applySearchDdl(databaseUrl: string, sqlDir?: string): Pr
206
210
  * Returns an empty list — and so changes nothing — for a project with no
207
211
  * `search` block, which is every project that has not opted in.
208
212
  */
209
- export declare function getSearchExcludes(collectionsPath: string): Promise<string[]>;
213
+ export declare function getSearchExcludes(schemaDir: string): Promise<string[]>;
210
214
  /**
211
215
  * Every `generated column → column it reads` edge in the database.
212
216
  *
@@ -262,7 +266,7 @@ export declare function applyVectorDdl(databaseUrl: string, sqlDir?: string): Pr
262
266
  * Returns an empty list — and so changes nothing — for a project with no
263
267
  * `vector` property, which is every project that has not opted in.
264
268
  */
265
- export declare function getVectorExcludes(collectionsPath: string): Promise<string[]>;
269
+ export declare function getVectorExcludes(schemaDir: string): Promise<string[]>;
266
270
  /**
267
271
  * The generated SQL for the project's `autoValue: "on_update"` properties, if
268
272
  * it has any.
@@ -297,7 +301,7 @@ export declare function readViewsDdl(sqlDir?: string): string;
297
301
  */
298
302
  export declare function applyViewsDdl(databaseUrl: string, sqlDir?: string): Promise<void>;
299
303
  /** @see getSearchExcludes */
300
- export declare function getTriggerExcludes(collectionsPath: string): Promise<string[]>;
304
+ export declare function getTriggerExcludes(schemaDir: string): Promise<string[]>;
301
305
  /**
302
306
  * Query the live database for every user table/view outside the system
303
307
  * catalogs. Separated from {@link getTableExcludes} so its failure mode can
@@ -348,9 +352,9 @@ export declare function queryExistingIndexes(databaseUrl: string): Promise<Exist
348
352
  * spelled by `atlasExcludePattern`: a raw `orders_idx[v1]` is a glob that
349
353
  * matches `orders_idxv`, so that index was dropped with no prompt.
350
354
  */
351
- export declare function getForeignIndexExcludes(databaseUrl: string, collectionsPath: string, deps?: {
355
+ export declare function getForeignIndexExcludes(databaseUrl: string, schemaDir: string, deps?: {
352
356
  queryExistingIndexes?: (databaseUrl: string) => Promise<ExistingIndex[]>;
353
- getManagedIndexNames?: (collectionsPath: string) => Promise<Set<string>>;
357
+ getManagedIndexNames?: (schemaDir: string) => Promise<Set<string>>;
354
358
  }): Promise<string[]>;
355
359
  /** Every CHECK and EXCLUDE constraint the database holds. @see UNDECLARABLE_CONSTRAINTS_SQL */
356
360
  export declare function queryUndeclarableConstraints(databaseUrl: string): Promise<ExistingConstraint[]>;
@@ -396,8 +400,8 @@ export declare class ExcludeIntrospectionError extends Error {
396
400
  *
397
401
  * `deps` is injectable for tests; production uses the real pg-backed queries.
398
402
  */
399
- export declare function getTableExcludes(databaseUrl: string, collectionsPath: string, deps?: {
403
+ export declare function getTableExcludes(databaseUrl: string, schemaDir: string, deps?: {
400
404
  queryExistingTables?: (databaseUrl: string) => Promise<ExistingTable[]>;
401
- getIncludes?: (collectionsPath: string) => Promise<string[]>;
405
+ getIncludes?: (schemaDir: string) => Promise<string[]>;
402
406
  }): Promise<string[]>;
403
407
  export {};