@rebasepro/server-postgres 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.
- package/README.md +11 -8
- package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
- package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +99 -54
- package/dist/PostgresBootstrapper.d.ts +12 -27
- package/dist/auth/ensure-tables.d.ts +16 -5
- package/dist/auth/schema-version.d.ts +2 -2
- package/dist/auth/services.d.ts +2 -3
- package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
- package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
- package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
- package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
- package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
- package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
- package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
- package/dist/cli-console-DsRgGSBR.js.map +1 -0
- package/dist/cli-console.d.ts +16 -13
- package/dist/cli-flags.d.ts +8 -9
- package/dist/cli-helpers.d.ts +15 -11
- package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
- package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
- package/dist/cli-schema-dir.d.ts +64 -0
- package/dist/cli.js +192 -257
- package/dist/cli.js.map +1 -1
- package/dist/data-transformer.d.ts +50 -19
- package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
- package/dist/database-preflight-bfnIBnjM.js.map +1 -0
- package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
- package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
- package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
- package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
- package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
- package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
- package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
- package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
- package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
- package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
- package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
- package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
- package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
- package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
- package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
- package/dist/generate-files-tlJ9_lGI.js.map +1 -0
- package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
- package/dist/generate-next-step-CO09dovd.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
- package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
- package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
- package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
- package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
- package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
- package/dist/history/ensure-history-table.d.ts +22 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.es.js +201 -25
- package/dist/index.es.js.map +1 -1
- package/dist/interfaces.d.ts +3 -4
- package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
- package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
- package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
- package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
- package/dist/load-tables-B1Re74ng.js +92 -0
- package/dist/load-tables-B1Re74ng.js.map +1 -0
- package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
- package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
- package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
- package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
- package/dist/model/PostgresTableRegistry.d.ts +159 -0
- package/dist/model/build-registry.d.ts +25 -0
- package/dist/model/refresh-relational-schema.d.ts +24 -0
- package/dist/model/runtime-table.d.ts +53 -0
- package/dist/{collections → model}/validate-relations.d.ts +15 -21
- package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
- package/dist/open-rebase-4kisUF_k.js.map +1 -0
- package/dist/open-rebase.d.ts +16 -15
- package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
- package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
- package/dist/plan-schema-Hbtjhge3.js +1633 -0
- package/dist/plan-schema-Hbtjhge3.js.map +1 -0
- package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
- package/dist/policy-drift-BVMyqHSa.js.map +1 -0
- package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
- package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
- package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
- package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
- package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
- package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
- package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
- package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
- package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
- package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
- package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
- package/dist/render-ddl-D4n86NHz.js.map +1 -0
- package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
- package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
- package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
- package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
- package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
- package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
- package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
- package/dist/rls-settings-CmGK2U0a.js.map +1 -0
- package/dist/schema/auth-users-columns.d.ts +1 -11
- package/dist/schema/catalogue-schema.d.ts +33 -29
- package/dist/schema/classify-change.d.ts +23 -16
- package/dist/schema/column-type-drift.d.ts +16 -0
- package/dist/schema/config-relations.d.ts +10 -9
- package/dist/schema/deferred-index-build.d.ts +1 -1
- package/dist/schema/doctor-cli.js +1544 -66
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +7 -7
- package/dist/schema/doctor-policy-checks.d.ts +4 -4
- package/dist/schema/doctor-search-scale.d.ts +14 -14
- package/dist/schema/doctor.d.ts +27 -27
- package/dist/schema/dynamic-tables.d.ts +6 -5
- package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
- package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
- package/dist/schema/enum-labels-kept.d.ts +6 -6
- package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-files.d.ts +6 -6
- package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
- package/dist/schema/generate-postgres-ddl.js +11 -11
- package/dist/schema/generate-postgres-ddl.js.map +1 -1
- package/dist/schema/generate-schema-commit.d.ts +13 -8
- package/dist/schema/generated-schema-diff.d.ts +16 -16
- package/dist/schema/generated-schema-staleness.d.ts +11 -11
- package/dist/schema/index-adoption.d.ts +4 -4
- package/dist/schema/introspect-db-customization.d.ts +47 -0
- package/dist/schema/introspect-db-inference.d.ts +30 -9
- package/dist/schema/introspect-db-logic.d.ts +79 -110
- package/dist/schema/introspect-db-project.d.ts +15 -18
- package/dist/schema/introspect-db-queries.d.ts +1 -1
- package/dist/schema/introspect-db-search.d.ts +25 -4
- package/dist/schema/introspect-db-storage.d.ts +4 -74
- package/dist/schema/introspect-db.js +102 -90
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/introspect-runtime.d.ts +47 -36
- package/dist/schema/introspect-tables.d.ts +182 -0
- package/dist/schema/load-tables.d.ts +55 -0
- package/dist/schema/migrate-policy-stamps.d.ts +4 -4
- package/dist/schema/migration-freshness.d.ts +13 -13
- package/dist/schema/plan/column-order.d.ts +82 -0
- package/dist/schema/plan/diff-plan.d.ts +9 -3
- package/dist/schema/plan/plan-schema.d.ts +55 -52
- package/dist/schema/plan/render-drizzle.d.ts +1 -1
- package/dist/schema/plan/types.d.ts +24 -15
- package/dist/schema/push-index-adoption.d.ts +3 -3
- package/dist/schema/push-index-prebuild.d.ts +3 -3
- package/dist/schema/push-kept-defaults.d.ts +7 -7
- package/dist/schema/push-legacy-renames.d.ts +3 -3
- package/dist/schema/push-policy-plan.d.ts +5 -5
- package/dist/schema/reconcile-schema.d.ts +5 -5
- package/dist/schema/relation-names.d.ts +15 -20
- package/dist/schema/render-outputs.d.ts +76 -0
- package/dist/schema/search-column.d.ts +11 -43
- package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
- package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
- package/dist/schema/vector-index.d.ts +24 -28
- package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
- package/dist/search-column-BO-WND-B.js.map +1 -0
- package/dist/security/caller-sql-columns.d.ts +9 -6
- package/dist/security/policy-drift.d.ts +14 -14
- package/dist/security/rls-enforcement.d.ts +19 -25
- package/dist/security/rls-settings.d.ts +2 -2
- package/dist/security/served-table-protection.d.ts +125 -0
- package/dist/services/FetchService.d.ts +22 -133
- package/dist/services/PersistService.d.ts +6 -17
- package/dist/services/RelationService.d.ts +57 -106
- package/dist/services/RelationWriteService.d.ts +59 -66
- package/dist/services/cdc/identity-columns.d.ts +7 -5
- package/dist/services/cdc/junction-tables.d.ts +14 -14
- package/dist/services/collection-helpers.d.ts +52 -95
- package/dist/services/dataService.d.ts +15 -12
- package/dist/services/field-op-sql.d.ts +11 -9
- package/dist/services/field-viewer.d.ts +12 -11
- package/dist/services/hidden-columns.d.ts +30 -0
- package/dist/services/index.d.ts +1 -1
- package/dist/services/junction-writes.d.ts +37 -18
- package/dist/services/nested-path.d.ts +18 -18
- package/dist/services/read-field-access.d.ts +23 -7
- package/dist/services/read-scope.d.ts +10 -9
- package/dist/services/realtimeService.d.ts +25 -10
- package/dist/services/relation-tables.d.ts +97 -0
- package/dist/services/row-pipeline.d.ts +50 -69
- package/dist/services/soft-delete.d.ts +25 -24
- package/dist/services/table-hooks.d.ts +146 -0
- package/dist/services/view-access.d.ts +7 -7
- package/dist/services/write-transaction-scope.d.ts +1 -1
- package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
- package/dist/source-VxbrQojV.js.map +1 -0
- package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
- package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +70 -84
- package/dist/utils/pg-array-null-patch.d.ts +27 -10
- package/dist/utils/pg-error-utils.d.ts +4 -4
- package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
- package/dist/vector-index-VSh3ufTd.js.map +1 -0
- package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
- package/dist/websocket-BevXvwfo.js.map +1 -0
- package/dist/websocket.d.ts +2 -2
- package/package.json +7 -7
- package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
- package/dist/cli-collections-path.d.ts +0 -31
- package/dist/cli-console-DBPw-oAz.js.map +0 -1
- package/dist/cli-errors-DYTxnLbW.js.map +0 -1
- package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
- package/dist/collections/buildRegistry.d.ts +0 -27
- package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
- package/dist/column-plan-helpers-BeSztMor.js +0 -161
- package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
- package/dist/database-preflight-iBpT7-vv.js.map +0 -1
- package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
- package/dist/doctor-Kg1oUK0Q.js +0 -1458
- package/dist/doctor-Kg1oUK0Q.js.map +0 -1
- package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
- package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
- package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
- package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
- package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
- package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
- package/dist/generate-files-CsaVzatS.js.map +0 -1
- package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
- package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
- package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
- package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
- package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
- package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
- package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
- package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
- package/dist/open-rebase-40paQfVW.js.map +0 -1
- package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
- package/dist/plan-schema-vJd3UEmT.js +0 -1604
- package/dist/plan-schema-vJd3UEmT.js.map +0 -1
- package/dist/policy-drift-C-m0uWHH.js.map +0 -1
- package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
- package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
- package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
- package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
- package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
- package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
- package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
- package/dist/rls-settings-BCGMIig3.js.map +0 -1
- package/dist/schema/column-plan-helpers.d.ts +0 -161
- package/dist/schema/introspect-db-naming.d.ts +0 -10
- package/dist/search-column-BM-GV6vH.js.map +0 -1
- package/dist/source-fZb92pN8.js.map +0 -1
- package/dist/vector-index-DsQ3V2d2.js.map +0 -1
- package/dist/websocket-B7ex6AQM.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-database.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections);\n\n // Where a boot on this database writes the server-or-admin policies:\n // `TO public` where its admin switch is not live, and that is no drift.\n const drift = await checkPolicyDrift(pool, collections, { adminRoleAvailable: \"detect\" });\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","/**\n * `rebase doctor --database`: whether this database can host Rebase's request\n * role(s) under the project's `rls` settings, read from the catalogue without\n * changing anything.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import; the rendering and the table list are tested here.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName, relationalCollections, resolveJunctionSpecs } from \"@rebasepro/common\";\nimport type { PreflightFinding } from \"../security/database-preflight\";\nimport type { ManagedTable, RawSqlRunner } from \"../security/rls-enforcement\";\nimport type { RlsSettings } from \"../security/rls-settings\";\nimport type { PolicyCheckStatus } from \"./doctor-policy-checks\";\n\n/**\n * The tables Rebase serves, as the server would list them: every relational\n * collection's table in its schema (`public` by default), and every junction\n * table a many-to-many declares.\n */\nexport function managedTablesOf(collections: CollectionConfig[]): ManagedTable[] {\n const relational = relationalCollections(collections);\n const tables = new Map<string, ManagedTable>();\n const add = (schema: string, table: string) => tables.set(`${schema}.${table}`, { schema, table });\n for (const collection of relational) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n add(schema, getTableName(collection));\n }\n for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);\n return [...tables.values()];\n}\n\n/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */\nexport function preflightSchemasOf(collections: CollectionConfig[]): string[] {\n return Array.from(new Set([\n \"public\",\n \"rebase\",\n ...relationalCollections(collections)\n .filter(isPostgresCollectionConfig)\n .map((c) => c.schema)\n .filter((s): s is string => !!s)\n ]));\n}\n\nconst LEVEL_ORDER: PreflightFinding[\"level\"][] = [\"fail\", \"warn\", \"ok\"];\nconst LEVEL_TITLE: Record<PreflightFinding[\"level\"], string> = {\n fail: \"Needs fixing before Rebase can serve requests here\",\n warn: \"Worth a look\",\n ok: \"Fine\"\n};\nconst LEVEL_MARK: Record<PreflightFinding[\"level\"], string> = {\n fail: chalk.red(\"✗\"),\n warn: chalk.yellow(\"⚠\"),\n ok: chalk.green(\"✓\")\n};\n\n/**\n * The report, grouped by level, failures first. Each finding that is not fine\n * shows the SQL to run as an administrator in gray, and the `rls` setting that\n * would fit Rebase to the database instead.\n */\nexport function renderPreflightFindings(\n findings: readonly PreflightFinding[],\n settings: Pick<RlsSettings, \"roles\" | \"nonDefaults\">\n): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold(\" Database preflight\"));\n lines.push(chalk.gray(\n ` Request role(s): ${settings.roles.join(\", \")}. ` +\n (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(\", \")}.` : \"The other rls settings are at their defaults.\")\n ));\n for (const level of LEVEL_ORDER) {\n const group = findings.filter((f) => f.level === level);\n if (group.length === 0) continue;\n lines.push(\"\");\n lines.push(` ${LEVEL_TITLE[level]}`);\n for (const finding of group) {\n lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);\n if (finding.sql) {\n for (const sqlLine of finding.sql.split(\"\\n\")) lines.push(chalk.gray(` ${sqlLine}`));\n }\n if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? \"or set\" : \"set\"}: ${finding.setting}`));\n }\n }\n return lines;\n}\n\n/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */\nexport function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus {\n return findings.some((f) => f.level === \"fail\") ? \"problems\" : \"ok\";\n}\n\n/**\n * Every table in `schemas` but `rebase`: what a project with no declared\n * collections serves, since its API is introspected from the database.\n */\nasync function everyTableIn(run: RawSqlRunner, schemas: readonly string[]): Promise<ManagedTable[]> {\n const names = schemas.filter((s) => s !== \"rebase\").map((s) => `'${s.replace(/'/g, \"''\")}'`);\n if (names.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${names.join(\", \")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n ORDER BY 1, 2\n `);\n return rows.map((r) => ({ schema: String(r.schema), table: String(r.name) }));\n}\n\n/**\n * Run the preflight against `databaseUrl` with the settings a command outside\n * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),\n * and print it. Never reports `ok` for a check it could not run.\n */\nexport async function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — the database preflight did NOT run\"));\n return \"unchecked\";\n }\n\n const { loadCollections } = await import(\"./doctor\");\n const { preflightDatabase } = await import(\"../security/database-preflight\");\n const { readRecordedRequestRoles } = await import(\"../security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"../security/rls-settings\");\n const { Pool } = await import(\"pg\");\n\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const run: RawSqlRunner = async (text) => (await pool.query(text)).rows as Record<string, unknown>[];\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n // Only the schemas that exist: the SQL a finding carries grants on each\n // one, and a GRANT on a missing schema fails the whole script. A boot\n // grants on the ones it creates itself.\n const existing = new Set((await run(\"SELECT nspname FROM pg_namespace\")).map((row) => String(row.nspname)));\n const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n\n let managedTables = managedTablesOf(collections);\n console.log(\"\");\n if (managedTables.length === 0) {\n managedTables = await everyTableIn(run, schemas);\n console.log(chalk.gray(\" No declared collections: every table in public is treated as served, as an introspected project serves them.\"));\n }\n\n const findings = await preflightDatabase(run, settings, { schemas, managedTables });\n for (const line of renderPreflightFindings(findings, settings)) console.log(line);\n console.log(\"\");\n return preflightStatus(findings);\n } catch (err) {\n console.error(chalk.red(\" ✗ Could not run the database preflight:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { runDatabasePreflight } from \"./doctor-database\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n // --database runs only the preflight of the database itself: whether the\n // request role(s) can be set up and used here under the project's `rls`\n // settings. Read-only, and a gate like --policies.\n const databaseOnly = process.argv.includes(\"--database\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly || databaseOnly) {\n // Non-zero so this can gate CI — the whole point of the flags, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n const statuses = [\n ...(databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : []),\n ...(policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : [])\n ];\n process.exit(statuses.some(status => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,sBAAsB,QAAkC;CACpE,OAAO,WAAW,OAAO,IAAI;AACjC;;;;;;;AAQA,eAAsB,gBAAgB,iBAAyB,aAAkD;CAC7G,IAAI,CAAC,aAAa;EACd,QAAQ,MAAM,MAAM,OAAO,qDAAqD,CAAC;EACjF,OAAO;CACX;CAEA,MAAM,eAAe,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe;CAChE,IAAI,WAAW;CACf,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,OAAO,IAAI,KAAK,EAAE,kBAAkB,YAAY,CAAC;CACvD,IAAI;EACA,MAAM,cAAkC,MAAM,gBAAgB,YAAY;EAM1E,IAAI,YAAY,WAAW,GAAG;GAC1B,QAAQ,MAAM,MAAM,IAAI,+BAA+B,cAAc,CAAC;GACtE,QAAQ,MAAM,MAAM,KAAK,iGAAiG,CAAC;GAC3H,OAAO;EACX;EAEA,MAAM,SAAS,OAAO,UAAkB,MAAM,KAAK,MAAM,IAAI,EAAA,CAAG;EAUhE,IAAI;GACA,MAAM,OAAO,UAAU;EAC3B,SAAS,KAAK;GACV,QAAQ,MAAM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.js","../../src/schema/doctor.ts","../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-database.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["import { isNumericColumnType, isTemporalColumnType } from \"@rebasepro/types\";\nimport { sortCollectionsBySlug, toCamelCase, toPascalCase, toSafeIdentifier, toTableAccessor } from \"@rebasepro/common\";\n//#region src/utils.ts\n/**\n* Indent a block of text by a given number of spaces\n*/\nfunction indent(text, spaces) {\n\tconst pad = \" \".repeat(spaces);\n\treturn text.split(\"\\n\").map((line) => line.trim() ? pad + line : line).join(\"\\n\");\n}\n//#endregion\n//#region src/generate-types.ts\n/**\n* A schema that cannot be expressed as a valid TypeScript file.\n*\n* Thrown rather than emitted. The generator used to concatenate whatever it was\n* given, so a slug that collided with another one, or that was not an\n* identifier, produced a file that either failed to compile or — worse —\n* compiled while quietly routing one table to another's slug.\n*\n* @group SDK generation\n*/\nvar CodegenError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"CodegenError\";\n\t}\n};\nvar IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n/**\n* A property name for the emitted TypeScript: verbatim when it is a valid\n* identifier, quoted otherwise.\n*\n* Every key that reaches the output goes through here. Column keys are not\n* required to be identifiers — `\"order\"`, `\"user id\"`, a quoted Postgres\n* identifier — and the previous behaviour of camel-casing them into shape\n* renamed the column in the type while the wire kept the original, so the\n* generated `Row` described fields that did not exist.\n*/\nfunction emitKey(key) {\n\treturn IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n/**\n* A string literal, escaped.\n*\n* `\"${value}\"` was the previous form. A value containing a quote closed the\n* literal early, which at best broke the file and at worst let a slug from a\n* remote schema inject top-level statements into a file the developer\n* compiles and bundles.\n*/\nfunction emitString(value) {\n\treturn JSON.stringify(value);\n}\nvar GEOPOINT_TYPE = \"{ latitude: number; longitude: number; }\";\n/** A closed value set as a union of literals: strings escaped, numbers only when every value is one. */\nfunction literalUnion(values, numeric) {\n\tif (values.length === 0) return void 0;\n\tif (numeric) {\n\t\tconst numbers = values.map(Number);\n\t\tif (numbers.some((n) => !Number.isFinite(n))) return void 0;\n\t\treturn numbers.map((n) => String(n)).join(\" | \");\n\t}\n\treturn values.map((v) => emitString(String(v))).join(\" | \");\n}\n/**\n* The TypeScript type of a value of one Postgres type, as the wire serves it.\n*\n* A Postgres enum and a `.oneOf()` set are literal unions; a timestamp, a date\n* and a time are ISO strings; `bytea` is base64; a vector is its numbers; a\n* type Rebase serves but does not create (`other`) is `unknown`.\n*/\nfunction scalarType(type, oneOf) {\n\tif (type.kind === \"enum\") return literalUnion(type.values, false) ?? \"string\";\n\tif (isNumericColumnType(type)) return (oneOf && literalUnion(oneOf, true)) ?? \"number\";\n\tswitch (type.kind) {\n\t\tcase \"text\":\n\t\tcase \"varchar\":\n\t\tcase \"char\":\n\t\tcase \"uuid\": return (oneOf && literalUnion(oneOf, false)) ?? \"string\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"timestamptz\":\n\t\tcase \"date\":\n\t\tcase \"time\": return \"string\";\n\t\tcase \"vector\": return \"number[]\";\n\t\tcase \"bytea\": return \"string\";\n\t\tcase \"json\":\n\t\tcase \"jsonb\": return \"Record<string, unknown>\";\n\t\tdefault: return \"unknown\";\n\t}\n}\n/**\n* The TypeScript type of a JSON document, from the shape the table declares.\n*\n* An object types its declared fields — a field the shape does not mark\n* `required` may be absent or null — and an open object (`additional`) with no\n* declared field is a record. A typed block list (`json.oneOf`) is the union of\n* its blocks, each a `{ <typeField>: \"<variant>\"; <valueField>: … }`.\n*/\nfunction jsonType(shape) {\n\tswitch (shape.kind) {\n\t\tcase \"string\": return (shape.oneOf && literalUnion(shape.oneOf, false)) ?? \"string\";\n\t\tcase \"number\": return (shape.oneOf && literalUnion(shape.oneOf, true)) ?? \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"date\": return \"string\";\n\t\tcase \"geopoint\": return GEOPOINT_TYPE;\n\t\tcase \"object\": {\n\t\t\tconst entries = Object.entries(shape.fields);\n\t\t\tif (entries.length === 0 && shape.additional) return \"Record<string, unknown>\";\n\t\t\treturn `{ ${entries.map(([key, field]) => {\n\t\t\t\tconst optional = !field.required;\n\t\t\t\tconst type = jsonType(field);\n\t\t\t\treturn `${emitKey(key)}${optional ? \"?\" : \"\"}: ${optional ? `${type} | null` : type};`;\n\t\t\t}).join(\" \")} }`;\n\t\t}\n\t\tcase \"array\": return `Array<${jsonType(shape.of)}>`;\n\t\tcase \"oneOf\": {\n\t\t\tconst variants = Object.entries(shape.variants);\n\t\t\tif (variants.length === 0 || shape.typeField === shape.valueField) return \"unknown\";\n\t\t\treturn variants.map(([name, variant]) => `{ ${emitKey(shape.typeField)}: ${emitString(name)}; ${emitKey(shape.valueField)}: ${jsonType(variant)}; }`).join(\" | \");\n\t\t}\n\t\tdefault: return \"unknown\";\n\t}\n}\n/** The TypeScript type of a column's value on a read. */\nfunction columnType(column) {\n\tif (column.semantic === \"geopoint\") return GEOPOINT_TYPE;\n\tif (column.json && (column.type.kind === \"json\" || column.type.kind === \"jsonb\")) return jsonType(column.json);\n\tif (column.type.kind === \"array\") return `Array<${scalarType(column.type.of, column.element?.oneOf)}>`;\n\treturn scalarType(column.type, column.oneOf);\n}\n/**\n* The TypeScript type of a key: `number` for a numeric column, `string` for\n* every other — what a foreign key, a link written by the relation's name and\n* a to-many membership hold.\n*/\nfunction keyType(column) {\n\tif (!column) return \"string | number\";\n\treturn isNumericColumnType(column.type) ? \"number\" : \"string\";\n}\n/**\n* A column's type on a write: its own type (a temporal column also as a\n* `Date`), or `null` too when it is nullable.\n*\n* `Row` has typed a nullable column `T | null` for a while; its write twins\n* did not, so the one way to clear a value — `update(id, { publishedAt: null })`,\n* `{ authorId: null }` to unassign, the edit-form round trip of a row that came\n* back with nulls in it — was a compile error the server would have accepted.\n* A primary key is never null.\n*/\nfunction writableType(column, tsType) {\n\tconst written = isTemporalColumnType(column.type) ? `${tsType} | Date` : tsType;\n\treturn column.nullable ? `${written} | null` : written;\n}\n/**\n* Whether a create may leave the column out: it may be null, or the database\n* or the server fills it — a default of any kind (a literal, SQL, a random\n* uuid, an identity, one the database owns), a serial, a stamp.\n*/\nfunction insertOptional(column) {\n\tif (column.nullable) return true;\n\tif (column.default !== void 0 || column.stamp !== void 0) return true;\n\tconst kind = column.type.kind;\n\treturn kind === \"smallserial\" || kind === \"serial\" || kind === \"bigserial\";\n}\n/** Nobody may read it: `.private()`, or `access({ read: [] })`. */\nfunction unreadable(column) {\n\treturn column.private === true || column.access?.read?.length === 0;\n}\n/** Nobody may write it: `.private()`, `.readOnly()`, generated, or `access({ write: [] })`. */\nfunction unwritable(column) {\n\treturn column.private === true || column.readOnly === true || column.generated !== void 0 || column.access?.write?.length === 0;\n}\n/** One emitted `key: type;` line, already indented. */\nfunction line(key, type, optional) {\n\treturn ` ${emitKey(key)}${optional ? \"?\" : \"\"}: ${type};`;\n}\n/**\n* Map every slug to the property name it is reachable under on `client.data`.\n*\n* The accessor is a safe identifier because `client.data.myNotes` is the point\n* of generating this at all, and `tablesDictionary` maps it back to the\n* slug the wire uses. Two slugs that safe down to the same identifier cannot\n* both have it: the interface would not compile, and the dictionary — an object\n* literal — would silently keep only the last, routing one table's reads to\n* the other's. There is no defensible way to pick, so this refuses.\n*/\nfunction buildAccessors(tables) {\n\tconst accessors = /* @__PURE__ */ new Map();\n\tconst bySafeName = /* @__PURE__ */ new Map();\n\tfor (const table of tables) {\n\t\tconst slug = table.slug;\n\t\tif (typeof slug !== \"string\" || slug.length === 0) throw new CodegenError(\"A table has no slug, so it has no name to generate a type for. Every table needs a unique `slug`.\");\n\t\tconst safe = toSafeIdentifier(slug);\n\t\tif (safe.length === 0) throw new CodegenError(`The slug ${emitString(slug)} has no characters that can form a property name, so it cannot be reached as \\`client.data.<name>\\`. Use a slug containing letters, digits, underscores or dashes.`);\n\t\tconst accessor = toTableAccessor(slug);\n\t\tif (accessor !== safe) console.warn(`[codegen] The table ${emitString(slug)} would be \\`client.data.${safe}\\`, a name the client reserves, so its typed accessor is \\`client.data.${accessor}\\`. \\`client.data.table(${emitString(slug)})\\` reaches it too.`);\n\t\tconst existing = bySafeName.get(accessor);\n\t\tif (existing !== void 0) throw new CodegenError(`The tables ${emitString(existing)} and ${emitString(slug)} both generate the accessor \"${accessor}\", so only one of them could be reached from the generated client and the other's reads would silently go to the wrong table. Rename one of the slugs.`);\n\t\tbySafeName.set(accessor, slug);\n\t\taccessors.set(slug, accessor);\n\t}\n\treturn accessors;\n}\n/** The single key column of a table, or its first, for the type a link to it holds. */\nfunction keyColumnOf(table) {\n\tif (!table) return void 0;\n\tconst key = table.primaryKey[0];\n\treturn key === void 0 ? void 0 : table.columns.find((column) => column.key === key);\n}\n/**\n* The type a link to a relation's target holds: whatever the target's key is —\n* or, for a target outside this run, whatever the `belongsTo`'s own foreign-key\n* column holds.\n*/\nfunction targetKeyType(relation, run, plan) {\n\tconst own = relation.kind === \"belongsTo\" ? plan.byKey.get(relation.localField) : void 0;\n\treturn keyType(keyColumnOf(run.bySlug.get(relation.target)) ?? own);\n}\n/** Two column types that a foreign key may hold between: identical, a serial read as its integer. */\nfunction sameKeyType(a, b) {\n\tconst plain = (type) => {\n\t\tswitch (type.kind) {\n\t\t\tcase \"smallserial\": return { kind: \"smallint\" };\n\t\t\tcase \"serial\": return { kind: \"integer\" };\n\t\t\tcase \"bigserial\": return { kind: \"bigint\" };\n\t\t\tdefault: return type;\n\t\t}\n\t};\n\treturn JSON.stringify(plain(a)) === JSON.stringify(plain(b));\n}\n/**\n* The key a foreign-key column is served under when a relation derives it:\n* `author_id` → `authorId`, each later segment keeping its own casing. The\n* same rule as `toWireKey` in `@rebasepro/utils` (which this package does not\n* depend on); used only to recognise such a column, never to name one.\n*/\nfunction derivedFieldKey(localKey) {\n\tconst segments = localKey.split(/[-_ ]+/).filter(Boolean);\n\tif (segments.length <= 1) return localKey;\n\treturn segments.map((segment, index) => index === 0 ? segment.charAt(0).toLowerCase() + segment.slice(1) : segment.charAt(0).toUpperCase() + segment.slice(1)).join(\"\");\n}\n/**\n* Whether a `belongsTo`'s column is nothing but the link: the column the\n* relation would derive (its key the derived key of `localKey`, the target's\n* key type, no rule, default or flag of its own), over a constraint.\n*\n* Such a column is listed with the relations, after the table's own columns —\n* where a derived foreign key always is, so declaring the column a relation\n* would derive does not move it in the generated types.\n*/\nfunction isLinkOnly(column, relation, run) {\n\tif (!relation.constraint) return false;\n\tif (column.derived) return true;\n\tif (derivedFieldKey(relation.localKey) !== column.key) return false;\n\tif (column.primaryKey || column.default !== void 0 || column.generated !== void 0 || column.readOnly || column.private) return false;\n\tif (column.access !== void 0 || column.stamp !== void 0 || column.validate !== void 0 || column.oneOf !== void 0) return false;\n\tif (column.description !== void 0 || column.storage !== void 0 || column.semantic !== void 0) return false;\n\tif (column.vectorIndex !== void 0 || column.json !== void 0 || column.element !== void 0 || column.transforms !== void 0) return false;\n\tconst targetKey = keyColumnOf(run.bySlug.get(relation.target));\n\treturn targetKey === void 0 || sameKeyType(column.type, targetKey.type);\n}\nfunction planTable(table, run) {\n\tconst byKey = new Map(table.columns.map((column) => [column.key, column]));\n\tconst linkColumns = /* @__PURE__ */ new Set();\n\tconst links = [];\n\tfor (const relation of table.relations) {\n\t\tif (relation.kind !== \"belongsTo\") continue;\n\t\tconst column = byKey.get(relation.localField);\n\t\tconst listedWithRelation = column !== void 0 && isLinkOnly(column, relation, run);\n\t\tif (listedWithRelation && column) linkColumns.add(column.key);\n\t\tlinks.push({\n\t\t\trelation,\n\t\t\tcolumn: listedWithRelation ? column : void 0\n\t\t});\n\t}\n\tconst excluded = /* @__PURE__ */ new Set();\n\tconst unwritableKeys = /* @__PURE__ */ new Set();\n\tfor (const column of table.columns) {\n\t\tconst closedWrite = unwritable(column);\n\t\tif (closedWrite) unwritableKeys.add(column.key);\n\t\tif (closedWrite && unreadable(column)) excluded.add(column.key);\n\t}\n\tfor (const relation of table.relations) {\n\t\tif (relation.kind !== \"belongsTo\") continue;\n\t\tif (excluded.has(relation.localField)) excluded.add(relation.name);\n\t\tif (unwritableKeys.has(relation.localField)) unwritableKeys.add(relation.name);\n\t}\n\tfor (const key of excluded) unwritableKeys.add(key);\n\treturn {\n\t\ttable,\n\t\tcolumns: table.columns.filter((column) => !linkColumns.has(column.key)),\n\t\tlinks,\n\t\texcluded,\n\t\tunwritable: unwritableKeys,\n\t\tbyKey\n\t};\n}\n/**\n* The type an *included* relation arrives as: the target's own row, inlined.\n*\n* This is what the read pipeline actually serves — the target's flat columns\n* where the relation was, through the SDK and the HTTP API alike. It is\n* deliberately *not* a `{ __type: \"relation\" }` envelope: that shape is the\n* panel's view-model and never reaches a developer's `find()`.\n*\n* Falls back to an open record when the target is not part of this generation\n* run, since there is no `Row` to point at.\n*/\nfunction includedRelationType(relation, run) {\n\tconst accessor = run.accessors.get(relation.target);\n\tconst rowType = accessor ? `Database[${emitString(accessor)}][\"Row\"]` : \"Record<string, unknown>\";\n\tconst pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.pivot, \"read\") : void 0;\n\tconst elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;\n\treturn relation.cardinality === \"many\" ? `Array<${elementType}>` : elementType;\n}\n/**\n* Generate the typed SDK's `database.types.ts` from table descriptors — what\n* `compileTables` produces, `GET /api/schema/tables` serves and introspection\n* reports.\n*\n* Emits `Database` (per table: `Row`, `Insert`, `Update`, `Relations`, `Slug`),\n* `TableName`, `tablesDictionary`, `TablesDictionary` and the\n* `include` helpers `RelationsOf`, `RelationKeys`, `RelationTarget`,\n* `IncludeOptionsFor`, `IncludeFor` and `RowWith`.\n*\n* Deterministic: tables are emitted in slug order whatever order they arrive\n* in, so `rebase doctor` can regenerate in memory and diff against the file.\n*\n* @throws {CodegenError} when two slugs produce one accessor, or a slug has\n* nothing an accessor can be built from.\n*\n* @group SDK generation\n*/\nfunction generateTypedefs(input) {\n\tconst tables = sortCollectionsBySlug(input);\n\tconst run = {\n\t\taccessors: buildAccessors(tables),\n\t\tbySlug: new Map(tables.map((table) => [table.slug, table]))\n\t};\n\tconst lines = [\n\t\t\"/**\",\n\t\t\" * This file was auto-generated by Rebase.\",\n\t\t\" * Do not make direct changes to the file.\",\n\t\t\" */\",\n\t\t\"\",\n\t\t\"export interface Database {\"\n\t];\n\tfor (const table of tables) {\n\t\tconst plan = planTable(table, run);\n\t\tlines.push(` ${emitKey(run.accessors.get(table.slug))}: {`);\n\t\temitRow(lines, plan, run);\n\t\tif (table.kind === \"view\") {\n\t\t\tlines.push(\" Insert: never;\");\n\t\t\tlines.push(\" Update: never;\");\n\t\t} else {\n\t\t\temitInsert(lines, plan, run);\n\t\t\temitUpdate(lines, plan, run);\n\t\t}\n\t\temitRelations(lines, plan, run);\n\t\tlines.push(` Slug: ${emitString(table.slug)};`);\n\t\tlines.push(\" };\");\n\t}\n\tlines.push(\"}\");\n\tlines.push(\"\");\n\tlines.push(\"export type TableName = keyof Database;\");\n\tlines.push(\"\");\n\tlines.push(\"export const tablesDictionary = {\");\n\tfor (const table of tables) lines.push(` ${emitKey(run.accessors.get(table.slug))}: ${emitString(table.slug)},`);\n\tlines.push(\"} as const;\");\n\tlines.push(\"\");\n\tlines.push(\"export type TablesDictionary = typeof tablesDictionary;\");\n\tlines.push(\"\");\n\tlines.push(...includeHelperLines());\n\treturn lines.join(\"\\n\");\n}\n/**\n* `Row` — what a read serves.\n*\n* ## A `belongsTo` has three shapes, and all three are typed\n*\n* 1. **Write** — `Insert`/`Update` accept *either* the foreign key under its\n* own wire name (`{ authorId: 5 }`) or the relation's name\n* (`{ author: 5 }`). Emitted by `emitWritableRelations`.\n* 2. **Read** — a row carries `authorId`. Always: it is a column.\n* 3. **Read with `include`** — the target's own row arrives under `author`.\n* Optional, because it is absent from every read that did not name it; the\n* generated `RowWith` makes it required for a read that did.\n*\n* `fields` narrows which columns a read returns, but a column is optional here\n* only because the value may be null, never because the caller might not have\n* asked for it: a projection is a choice made at one call site.\n*/\nfunction emitRow(lines, plan, run) {\n\tlines.push(\" Row: {\");\n\tconst emitted = new Set(plan.excluded);\n\tfor (const column of plan.columns) {\n\t\tif (emitted.has(column.key)) continue;\n\t\tconst type = columnType(column);\n\t\tlines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));\n\t\temitted.add(column.key);\n\t}\n\tfor (const { relation, column } of plan.links) {\n\t\tif (!column || emitted.has(column.key)) continue;\n\t\tconst type = targetKeyType(relation, run, plan);\n\t\tlines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));\n\t\temitted.add(column.key);\n\t}\n\tfor (const relation of plan.table.relations) {\n\t\tif (emitted.has(relation.name)) continue;\n\t\tlines.push(line(relation.name, includedRelationType(relation, run), true));\n\t\temitted.add(relation.name);\n\t}\n\tlines.push(\" };\");\n}\n/**\n* `Insert` — what `create()` accepts: no hidden column and nothing nobody may\n* write; a column the database or the server fills may be left out.\n*/\nfunction emitInsert(lines, plan, run) {\n\tlines.push(\" Insert: {\");\n\tconst emitted = new Set(plan.unwritable);\n\tfor (const column of plan.columns) {\n\t\tif (emitted.has(column.key)) continue;\n\t\tlines.push(line(column.key, writableType(column, columnType(column)), insertOptional(column)));\n\t\temitted.add(column.key);\n\t}\n\tconst eitherSpelling = emitWritableRelations(lines, plan, run, emitted, false);\n\tlines.push(eitherSpelling.length === 0 ? \" };\" : ` } & ${eitherSpelling.join(\" & \")};`);\n}\n/**\n* `Update` — everything optional, and the primary key left out: an update\n* addresses a row by its key, it does not reassign one.\n*/\nfunction emitUpdate(lines, plan, run) {\n\tlines.push(\" Update: {\");\n\tconst emitted = new Set(plan.unwritable);\n\tfor (const column of plan.columns) {\n\t\tif (column.primaryKey || emitted.has(column.key)) continue;\n\t\tlines.push(line(column.key, writableType(column, columnType(column)), true));\n\t\temitted.add(column.key);\n\t}\n\temitWritableRelations(lines, plan, run, emitted, true);\n\tlines.push(\" };\");\n}\n/**\n* `Relations` — which relations the table has, and which table each one\n* reaches. Not a shape a read returns: it is the *graph*, and `include` is the\n* one parameter that needs it. `IncludeFor` walks it to constrain an include's\n* keys at every level, and `RowWith` reads it to make an included relation\n* non-optional on the row that comes back.\n*\n* Emitted as the accessor NAME rather than the target's `Row`, so a\n* self-referencing relation is a finite string instead of a type that expands\n* forever. A table with no relations gets `Record<never, never>`, not `{}`,\n* which typescript-eslint's `no-empty-object-type` refuses in every project\n* that lints its generated SDK. A hidden relation is left out: the server\n* answers an include naming one as it answers a typo.\n*/\nfunction emitRelations(lines, plan, run) {\n\tconst includable = plan.table.relations.filter((relation) => !plan.excluded.has(relation.name));\n\tif (includable.length === 0) {\n\t\tlines.push(\" Relations: Record<never, never>;\");\n\t\treturn;\n\t}\n\tlines.push(\" Relations: {\");\n\tfor (const relation of includable) {\n\t\tconst accessor = run.accessors.get(relation.target);\n\t\tlines.push(` ${emitKey(relation.name)}: ${accessor ? emitString(accessor) : \"never\"};`);\n\t}\n\tlines.push(\" };\");\n}\n/**\n* The `include` type machinery, emitted into the generated file.\n*\n* It lives here rather than in `@rebasepro/types` because it is the *graph*\n* that makes it work, and the graph only exists once a project's tables have\n* been generated. `IncludeSpec` in `@rebasepro/types` is deliberately\n* unconstrained; these narrow it for a project that has relations.\n*\n* - `IncludeFor<\"posts\">` — an include whose keys are relations that exist,\n* recursively, so a typo is a compile error rather than a 400 at runtime.\n* - `RowWith<\"posts\", I>` — the row a read with that include returns, where\n* every included relation is **present** rather than optional.\n*\n* The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as\n* a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.\n*/\nfunction includeHelperLines() {\n\treturn [\n\t\t\"/** Which table each of `A`'s relations reaches. */\",\n\t\t\"export type RelationsOf<A extends TableName> =\",\n\t\t\" Database[A] extends { Relations: infer R } ? R : Record<string, never>;\",\n\t\t\"\",\n\t\t\"/** The names of `A`'s relations. */\",\n\t\t\"export type RelationKeys<A extends TableName> = keyof RelationsOf<A> & string;\",\n\t\t\"\",\n\t\t\"/** The table a relation reaches, or `never` when it left this project. */\",\n\t\t\"export type RelationTarget<A extends TableName, K extends RelationKeys<A>> =\",\n\t\t\" RelationsOf<A>[K] extends TableName ? RelationsOf<A>[K] : never;\",\n\t\t\"\",\n\t\t\"/** Counts `IncludeFor` down; TypeScript has no arithmetic. */\",\n\t\t\"type Prev = [never, 0, 1, 2, 3];\",\n\t\t\"\",\n\t\t\"/**\",\n\t\t\" * Per-relation options, minus `include` — which `IncludeFor` supplies at\",\n\t\t\" * the next depth so the nested keys are checked against the *target's*\",\n\t\t\" * relations rather than this table's.\",\n\t\t\" */\",\n\t\t\"export interface IncludeOptionsFor<A extends TableName, K extends RelationKeys<A>, D extends number> {\",\n\t\t\" limit?: number;\",\n\t\t\" where?: Record<string, unknown>;\",\n\t\t\" logical?: unknown;\",\n\t\t\" orderBy?: unknown;\",\n\t\t\" fields?: string[];\",\n\t\t\" include?: RelationTarget<A, K> extends TableName\",\n\t\t\" ? IncludeFor<RelationTarget<A, K>, Prev[D]>\",\n\t\t\" : never;\",\n\t\t\"}\",\n\t\t\"\",\n\t\t\"/**\",\n\t\t\" * An `include` for table `A`: its relation names, dotted paths, or the\",\n\t\t\" * parametrised tree — with every key checked against the relations that\",\n\t\t\" * actually exist, at every level.\",\n\t\t\" */\",\n\t\t\"export type IncludeFor<A extends TableName, D extends number = 3> =\",\n\t\t\" D extends 0\",\n\t\t\" ? never\",\n\t\t\" : | readonly (RelationKeys<A> | \\\"*\\\")[]\",\n\t\t\" | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };\",\n\t\t\"\",\n\t\t\"/** The relation names an include asks for at the top level. */\",\n\t\t\"type IncludedKeys<A extends TableName, I> =\",\n\t\t\" I extends readonly (infer K)[]\",\n\t\t\" ? Extract<K, RelationKeys<A>>\",\n\t\t\" : Extract<keyof I, RelationKeys<A>>;\",\n\t\t\"\",\n\t\t\"/**\",\n\t\t\" * The row a read with include `I` returns: `Row`, with every included\",\n\t\t\" * relation made **required**.\",\n\t\t\" *\",\n\t\t\" * `Row` types a relation as optional because it is absent from every read\",\n\t\t\" * that did not name it. Once a read has named it, it is there — and having\",\n\t\t\" * to write `row.author?.name` after asking for the author is the type\",\n\t\t\" * describing a possibility the query already ruled out.\",\n\t\t\" */\",\n\t\t\"export type RowWith<A extends TableName, I> =\",\n\t\t\" Database[A][\\\"Row\\\"] & Required<Pick<Database[A][\\\"Row\\\"], IncludedKeys<A, I> & keyof Database[A][\\\"Row\\\"]>>;\",\n\t\t\"\"\n\t];\n}\n/**\n* Every relation write the server performs, typed.\n*\n* - A `belongsTo` is written under either of two names: its foreign key's wire\n* key (`{ authorId: 5 }`) and the relation's name (`{ author: 5 }`), which\n* the server maps onto the column — the second only over a constraint\n* (`rel.belongsTo(…, { constraint: false })` keeps a bare column, written by\n* its key alone). A **required** `belongsTo` is satisfied by either: on an\n* `Insert` both names go in optional, and the requirement comes back as one\n* returned `({ authorId: T } | { author: T })` for the caller to intersect\n* with the object. Both stay in the object so `keyof Insert` names them.\n* - A `hasOne`, and a single-hop to-one `via`, is written by naming the target\n* row; `null` unlinks it.\n* - A to-many membership (`hasMany`, `manyToMany`, a single-hop to-many `via`)\n* is written as the targets' keys, or `{ id }`, or `{ id, _pivot }` where the\n* junction declares payload columns. A multi-hop `via` is read-only.\n*\n* The target's key type is the one `Row` uses for the link.\n*/\nfunction emitWritableRelations(lines, plan, run, emittedKeys, allOptional) {\n\tconst spellings = /* @__PURE__ */ new Map();\n\tconst addSpelling = (relation, key) => {\n\t\tif (emittedKeys.has(key)) return;\n\t\tconst keys = spellings.get(relation) ?? [];\n\t\tif (!keys.includes(key)) keys.push(key);\n\t\tspellings.set(relation, keys);\n\t};\n\tfor (const { relation } of plan.links) addSpelling(relation, relation.localField);\n\tfor (const { relation } of plan.links) if (relation.constraint) addSpelling(relation, relation.name);\n\tconst eitherSpelling = [];\n\tconst emit = (key, relation) => {\n\t\tif (emittedKeys.has(key)) return;\n\t\tconst required = plan.byKey.get(relation.localField)?.nullable === false;\n\t\tconst type = required ? targetKeyType(relation, run, plan) : `${targetKeyType(relation, run, plan)} | null`;\n\t\tconst names = spellings.get(relation) ?? [key];\n\t\tconst oneOfSeveral = required && !allOptional && names.length > 1;\n\t\tlines.push(line(key, type, allOptional || !required || oneOfSeveral));\n\t\temittedKeys.add(key);\n\t\tif (oneOfSeveral && names[0] === key) eitherSpelling.push(`(${names.map((name) => `{ ${emitKey(name)}: ${type} }`).join(\" | \")})`);\n\t};\n\tfor (const { relation } of plan.links) emit(relation.localField, relation);\n\tfor (const { relation } of plan.links) if (relation.constraint) emit(relation.name, relation);\n\tfor (const relation of plan.table.relations) {\n\t\tif (emittedKeys.has(relation.name)) continue;\n\t\tif (!(relation.kind === \"hasOne\" || relation.kind === \"via\" && relation.cardinality === \"one\" && relation.writable)) continue;\n\t\tlines.push(line(relation.name, `${targetKeyType(relation, run, plan)} | null`, true));\n\t\temittedKeys.add(relation.name);\n\t}\n\tfor (const relation of plan.table.relations) {\n\t\tif (relation.cardinality !== \"many\" || emittedKeys.has(relation.name)) continue;\n\t\tif (relation.kind === \"via\" && !relation.writable) continue;\n\t\tconst fk = targetKeyType(relation, run, plan);\n\t\tconst pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.pivot, \"write\") : void 0;\n\t\tconst element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : \"\"} }`;\n\t\tlines.push(line(relation.name, `Array<${element}>`, true));\n\t\temittedKeys.add(relation.name);\n\t}\n\treturn eitherSpelling;\n}\n/**\n* The `_pivot` a many-to-many link carries: the junction's payload columns,\n* typed as a row's columns are on a read and as a write's on a write.\n* `undefined` when the junction declares none, so there is no `_pivot` to name.\n*/\nfunction pivotType(pivot, direction) {\n\tif (pivot.length === 0) return void 0;\n\treturn `{ ${pivot.map((column) => {\n\t\tconst tsType = columnType(column);\n\t\tconst required = !column.nullable;\n\t\tconst type = direction === \"write\" ? writableType(column, tsType) : required ? tsType : `${tsType} | null`;\n\t\treturn `${emitKey(column.key)}${required && direction === \"read\" ? \"\" : \"?\"}: ${type};`;\n\t}).join(\" \")} }`;\n}\n//#endregion\n//#region src/index.ts\n/**\n* The typed SDK for a set of tables: `database.types.ts` (see\n* {@link generateTypedefs}) and, unless switched off, a README.\n*\n* @param tables The table descriptors, in any order.\n*\n* @group SDK generation\n*/\nfunction generateSDK(tables, options = {}) {\n\tconst files = [];\n\tfiles.push({\n\t\tpath: \"database.types.ts\",\n\t\tcontent: generateTypedefs(tables)\n\t});\n\tif (options.includeReadme !== false) files.push({\n\t\tpath: \"README.md\",\n\t\tcontent: `# Rebase SDK\n\n> Auto-generated by \\`rebase generate-sdk\\`. Do not edit manually.\n\n## Usage\n\n1. Install the client package:\n \\`\\`\\`bash\n npm install @rebasepro/client\n \\`\\`\\`\n\n2. Initialize with your generated types:\n \\`\\`\\`typescript\n import { createRebaseClient } from '@rebasepro/client';\n import { tablesDictionary, type Database } from './database.types';\n\n const rebase = createRebaseClient<Database>({\n baseUrl: '${options.baseUrl ?? \"http://localhost:3001\"}',\n // Maps each accessor back to the slug the wire uses. Without it a\n // hyphenated slug is not resolvable from the property name alone.\n tables: tablesDictionary,\n });\n\n // Property access is the typed surface: rows, filters and sorts are all\n // checked against the generated Database.\n const { data: users } = await rebase.data.users.find();\n console.log(users[0].email); // flat access — no .values wrapper\n \\`\\`\\`\n\n## Field names are the ones the API serves\n\nThe generated \\`Row\\` uses each field's **wire** name — the key it arrives under in\nJSON — and nothing here renames anything.\n\n- **A column is its key in \\`columns\\`.** A column keyed \\`createdAt\\` is\n \\`row.createdAt\\`, whatever \\`.column()\\` says. A column name is the name of a\n different thing: where the value lives, not what the API calls it.\n- **A foreign key derived from a relation is camelCase**, because that is what\n the wire carries. A \\`belongsTo\\` named \\`author\\` gives you \\`row.authorId\\`, not\n the column spelling.\n- **A table accessor is camelCase too** (\\`my-notes\\` → \\`rebase.data.myNotes\\`),\n which is what \\`tablesDictionary\\` maps back to the slug.\n A slug whose accessor the client reserves (\\`table\\`, \\`then\\`, \\`toJSON\\`)\n is generated as \\`<name>Table\\`: \\`rebase.data.tableTable\\`.\n\n\\`where\\` and \\`orderBy\\` are keyed off the same type, so what compiles is what the\nbackend answers to.\n\n## \\`Row\\` vs \\`Insert\\` vs \\`Update\\`\n\n| Type | What it describes |\n|---|---|\n| \\`Row\\` | What a read serves. Nullable columns are \\`T \\\\| null\\`; relations appear only when \\`include\\` names them. |\n| \\`Insert\\` | What \\`create()\\` accepts. A column with a default, an identity or a stamp is optional; a \\`belongsTo\\` target may be named either way (\\`{ author: 5 }\\` or \\`{ authorId: 5 }\\`). A view takes no writes: \\`never\\`. |\n| \\`Update\\` | What \\`update()\\` accepts. Everything optional, and the primary key is not settable. |\n\nA column marked \\`.private()\\` is absent from all three: the API surface does\nnot mention it, in either direction. The server holds the same line — a\nread never serves the column and a write naming it is refused — so this is a\nguarantee rather than a description, and nothing generated names a password\nhash.\n\nIf you need an untyped escape hatch, \\`rebase.data.table(slug)\\` still works —\nbut it is generic over \\`Record<string, unknown>\\` and gives up everything above.\n`\n\t});\n\treturn files;\n}\n//#endregion\nexport { CodegenError, generateSDK, generateTypedefs, indent, toCamelCase, toPascalCase, toSafeIdentifier, toTableAccessor };\n\n//# sourceMappingURL=index.es.js.map","/**\n * Rebase Schema Doctor — Three-way schema drift detection.\n *\n * Compares:\n * 1. Collection definitions → Generated Drizzle schema (staleness check)\n * 2. Collection definitions → Live PostgreSQL database (structural drift)\n *\n * Run via: rebase doctor\n */\nimport { promises as fsPromises } from \"fs\";\nimport * as fs from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport chalk from \"chalk\";\nimport { DEFAULT_DATA_SOURCE_KEY, LEGACY_SCHEMA_VERSION_PREFIX, type ColumnDescriptor, type ColumnType, type CompiledTable, type TableDescriptor } from \"@rebasepro/types\";\nimport { generateSchema } from \"./generate-drizzle-schema-logic\";\nimport { compareGeneratedDeclarations, describeDeclarationDifferences } from \"./generated-schema-staleness\";\nimport { describeSchemaDifference, readGeneratedSchemaDrift, type SchemaDifference } from \"./generated-schema-diff\";\nimport { pgTypeOf, planSchema } from \"./plan/plan-schema\";\nimport { renderPgType } from \"./plan/render-ddl\";\nimport type { PgType, SchemaPlan, TablePlan } from \"./plan/types\";\nimport { generateTypedefs } from \"@rebasepro/codegen\";\nimport { relationsOfKind, resolveTableJunctions, sortTablesBySlug } from \"@rebasepro/common\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\nimport { defaultDatabaseSchemaVersion, loadTableSchema } from \"./load-tables\";\nimport { describeMismatch } from \"@rebasepro/server\";\n// The report is CLI output, not application logging — see cli-output.ts.\nimport { out, outError } from \"../cli-output\";\nimport { deepestErrorMessage, diagnoseDbError, parseHostInfo } from \"../cli-errors\";\n\n// ── Types ────────────────────────────────────────────────────────────────\n\nexport type IssueSeverity = \"error\" | \"warning\" | \"info\";\n\nexport interface DoctorIssue {\n severity: IssueSeverity;\n category: \"missing_table\" | \"missing_column\" | \"type_mismatch\" | \"nullability_mismatch\" | \"extra_column\" | \"missing_constraint\" | \"primary_key_mismatch\" | \"schema_stale\" | \"missing_enum\" | \"enum_value_mismatch\" | \"missing_foreign_key\" | \"orphaned_junction\" | \"sdk_stale\" | \"sdk_not_generated\" | \"sdk_ungeneratable\";\n table?: string;\n column?: string;\n expected?: string;\n actual?: string;\n message: string;\n fix: string;\n}\n\nexport interface DoctorPhase {\n passed: boolean;\n issues: DoctorIssue[];\n /**\n * Why this phase never ran, when it did not.\n *\n * A check that did not happen is a third state, not a passing one. While a\n * skipped phase initialised to `{ passed: true, issues: [] }` it rendered as\n * `✅ Collections → Database: In sync` and counted towards\n * `✓ All schemas are in sync!` — so a project whose connection string was\n * spelled `POSTGRES_URL`, or a CI job that never exported one, got two green\n * ticks and exit 0 against a database with no tables in it.\n */\n skipped?: string;\n /**\n * Why this phase had nothing to compare against, when it had nothing.\n *\n * Distinct from `skipped`, which means \"the check could not run, and that\n * is probably worth fixing\". This one means \"the artifact is optional and\n * you have not asked for it\": no drift is possible, so the run is still a\n * clean bill of health.\n *\n * It exists because the alternative was a contradiction. The typed-SDK\n * phase returned `{ passed: true }` when `generated/sdk/database.types.ts`\n * did not exist, so a fresh project's report read\n * `✅ Collections → SDK Types: In sync` directly above\n * `ℹ Typed SDK not generated (optional).` — one line calling a file\n * synchronised and the next saying it is absent. \"In sync\" is a claim about\n * a comparison, and no comparison happened.\n */\n notApplicable?: string;\n /**\n * The phase was skipped by a fault rather than by a choice.\n *\n * `skipped` covers both: \"no DATABASE_URL, so nothing to compare against\"\n * is a local situation a developer may be perfectly happy with, and \"the\n * DATABASE_URL you set refuses connections\" is not. The report renders them\n * the same way — a check that did not run is a check that did not run — but\n * the exit code must not, or `rebase doctor` in CI goes green against a\n * database it never reached.\n */\n blocked?: boolean;\n}\n\nexport interface DoctorReport {\n collectionsToSchema: DoctorPhase;\n collectionsToSdk: DoctorPhase;\n schemaToDatabase: DoctorPhase;\n summary: { passed: number; skipped: number; notApplicable: number; warnings: number; errors: number };\n}\n\n// ── Column type mapping ──────────────────────────────────────────────────\n\n/**\n * How `information_schema.columns.data_type` spells a planned column type.\n *\n * The catalogue's names are its own — `character varying`, not `varchar`;\n * `ARRAY` for every array whatever its element; `USER-DEFINED` for an enum, a\n * `vector`, and anything else identified by name rather than by shape. So the\n * translation has to exist somewhere. What must *not* exist twice is the step\n * before it: which column a property compiles to.\n *\n * This function was that second step — a fourth copy of the property switch,\n * kept \"in sync\" with the generators by a comment, and already out of step\n * (`geopoint` answered `null` here, so the one type that was genuinely\n * unpersistable was the one the doctor never checked). It reads the schema plan\n * now.\n */\nconst INFORMATION_SCHEMA_NAMES: Record<Exclude<PgType[\"kind\"], \"custom\">, string> = {\n text: \"text\",\n varchar: \"character varying\",\n char: \"character\",\n uuid: \"uuid\",\n // A `CREATE TYPE … AS ENUM` is a name, not a shape.\n enum: \"USER-DEFINED\",\n smallint: \"smallint\",\n integer: \"integer\",\n bigint: \"bigint\",\n // A serial is an integer with a sequence default; the catalogue reports the\n // underlying width and nothing about the sequence.\n smallserial: \"smallint\",\n serial: \"integer\",\n bigserial: \"bigint\",\n real: \"real\",\n doublePrecision: \"double precision\",\n numeric: \"numeric\",\n boolean: \"boolean\",\n timestamptz: \"timestamp with time zone\",\n date: \"date\",\n time: \"time without time zone\",\n json: \"json\",\n jsonb: \"jsonb\",\n // pgvector's type, like every extension type.\n vector: \"USER-DEFINED\",\n bytea: \"bytea\",\n tsvector: \"USER-DEFINED\",\n array: \"ARRAY\"\n};\n\n/**\n * {@link INFORMATION_SCHEMA_NAMES} for any planned type, or `null` for a\n * `col.custom()` type: its `data_type` is whatever the catalogue calls that\n * type (`inet`, `int4range`, `USER-DEFINED` for PostGIS), so the boot diff\n * compares it against `format_type` instead, and the doctor has nothing to add.\n */\nconst informationSchemaName = (type: PgType): string | null =>\n type.kind === \"custom\" ? null : INFORMATION_SCHEMA_NAMES[type.kind];\n\n/**\n * The planned Postgres type of a column of `table`, through the planner's own\n * `pgTypeOf` — or `undefined` for a type the planner refuses (an array of\n * documents, an enum with no labels), which is a problem the doctor's other\n * phases report with a message, not a type mismatch to invent one for.\n */\nfunction plannedColumnType(table: Pick<TableDescriptor, \"schema\" | \"table\" | \"slug\">, column: Pick<ColumnDescriptor, \"key\" | \"column\" | \"type\">): PgType | undefined {\n try {\n return pgTypeOf(column.type, {\n schema: table.schema,\n table: table.table,\n owner: table.slug,\n propName: column.key,\n column: column.column\n });\n } catch {\n return undefined;\n }\n}\n\n/**\n * The `data_type` the database should report for a column of this type, or\n * `null` when there is nothing to compare: a `col.custom()` type (the boot diff\n * compares it by `format_type`), or a type the planner refuses outright.\n */\nexport function expectedDataType(type: ColumnType): string | null {\n // The site only names an enum's type, and `data_type` never says the name.\n const planned = plannedColumnType({ schema: \"public\", table: \"__doctor__\", slug: \"__doctor__\" }, { key: \"column\", column: \"column\", type });\n return planned ? informationSchemaName(planned) : null;\n}\n\n/**\n * `information_schema.columns.udt_name` of a native array of this element\n * type — the array's `data_type` is `ARRAY` whatever it holds, so the element\n * is told apart here. `undefined` for an element this does not name.\n */\nconst ARRAY_UDT_NAMES: Partial<Record<PgType[\"kind\"], string>> = {\n text: \"_text\",\n varchar: \"_varchar\",\n char: \"_bpchar\",\n uuid: \"_uuid\",\n smallint: \"_int2\",\n integer: \"_int4\",\n bigint: \"_int8\",\n real: \"_float4\",\n doublePrecision: \"_float8\",\n numeric: \"_numeric\",\n boolean: \"_bool\",\n timestamptz: \"_timestamptz\",\n date: \"_date\",\n time: \"_time\"\n};\n\n// ── Phase 1: Collections ↔ Generated Schema ─────────────────────────────\n\nexport async function checkTablesVsSchema(\n tables: readonly CompiledTable[],\n schemaFilePath: string\n): Promise<DoctorPhase> {\n const issues: DoctorIssue[] = [];\n\n // Check if schema file exists\n if (!fs.existsSync(schemaFilePath)) {\n issues.push({\n severity: \"error\",\n category: \"schema_stale\",\n message: \"Generated schema file does not exist.\",\n fix: \"Run `rebase schema generate`\"\n });\n return { passed: false,\nissues };\n }\n\n // Re-generate schema in-memory and compare with file on disk.\n if (tables.length === 0) {\n return { passed: true,\nissues };\n }\n\n try {\n // Declaration by declaration, not byte by byte. The generated file is a\n // flat list of `export const`s, each the rendering of one piece of the\n // schema plan, so comparing them says *which* table or enum moved —\n // which is what the reader is about to go looking for — and ignores the\n // formatting and commentary the renderer is free to vary on its own.\n const differences = compareGeneratedDeclarations(\n generateSchema(tables),\n await fsPromises.readFile(schemaFilePath, \"utf-8\")\n );\n\n if (differences.length > 0) {\n issues.push({\n severity: \"warning\",\n category: \"schema_stale\",\n message: \"Generated schema is out of date — table definitions have changed since last generation. \"\n + `Differs in: ${describeDeclarationDifferences(differences)}.`,\n fix: \"Run `rebase schema generate`\"\n });\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n issues.push({\n severity: \"warning\",\n category: \"schema_stale\",\n message: `Could not regenerate schema for comparison: ${message}`,\n fix: \"Run `rebase schema generate` to verify\"\n });\n }\n\n return { passed: issues.length === 0,\nissues };\n}\n\nexport async function checkTablesVsSdk(\n /** The tables' compiled descriptors — what `rebase generate-sdk` generates from. */\n descriptors: readonly TableDescriptor[],\n sdkFilePath: string\n): Promise<DoctorPhase> {\n const issues: DoctorIssue[] = [];\n\n // The typed SDK is opt-in — nothing in a scaffolded project imports it until\n // you choose to. A project that never generated one isn't drifting, so report\n // it as information rather than a warning; otherwise `doctor` can never come\n // back clean on a fresh project and users learn to ignore its output.\n if (!fs.existsSync(sdkFilePath)) {\n issues.push({\n severity: \"info\",\n category: \"sdk_not_generated\",\n message: \"Typed SDK not generated (optional).\",\n fix: \"Run `rebase generate-sdk` if you want typed table access\"\n });\n return { passed: true,\nissues,\nnotApplicable: \"not generated (optional)\" };\n }\n\n try {\n const expectedSdk = generateTypedefs(descriptors);\n const actualSdk = await fsPromises.readFile(sdkFilePath, \"utf-8\");\n\n // Normalize whitespace for comparison\n const normalize = (s: string) =>\n s\n .replace(/\\/\\/.*$/gm, \"\") // strip single-line comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\") // strip multi-line comments\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (normalize(expectedSdk) !== normalize(actualSdk)) {\n issues.push({\n severity: \"warning\",\n category: \"sdk_stale\",\n message: \"Generated SDK types are out of date — table definitions have changed since last SDK generation.\",\n fix: \"Run `rebase generate-sdk`\"\n });\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n\n // A `CodegenError` is not \"the comparison did not run\" — it is the\n // schema saying it cannot produce a valid typed client at all, most\n // often two slugs collapsing onto one accessor. Reporting that as a\n // warning about staleness described the wrong problem and pointed at a\n // command that would fail the same way.\n if (err instanceof Error && err.name === \"CodegenError\") {\n issues.push({\n severity: \"error\",\n category: \"sdk_ungeneratable\",\n message: `The typed SDK cannot be generated from these tables: ${message}`,\n fix: \"Fix the table definitions named above, then run `rebase generate-sdk`\"\n });\n } else {\n issues.push({\n severity: \"warning\",\n category: \"sdk_stale\",\n message: `Could not regenerate SDK types for comparison: ${message}`,\n fix: \"Run `rebase generate-sdk` to verify\"\n });\n }\n }\n\n return { passed: issues.length === 0,\nissues };\n}\n\n// ── Phase 2: Collections ↔ Database ──────────────────────────────────────\n\ninterface DbColumn {\n table_schema: string;\n table_name: string;\n column_name: string;\n data_type: string;\n is_nullable: string;\n udt_name: string;\n}\n\n\ninterface DbEnumValue {\n enum_schema: string;\n enum_name: string;\n enum_value: string;\n}\n\n/**\n * Extensions the tables need, that the database does not have installed.\n *\n * Only `vector` today, and only because a `col.vector()` column plans a\n * column of a type that will not exist. Rebase installs it only where a project\n * has said it may (`database({ extensions: [\"vector\"] })`), so the absence is\n * often correct configuration and a wrong deployment — which is exactly why the\n * report has to name it rather than the first failing INSERT.\n *\n * Exported for its test.\n */\nexport function missingExtensionIssues(\n tables: readonly TableDescriptor[],\n installed: ReadonlySet<string>\n): DoctorIssue[] {\n const usesVector = tables.some(table => table.columns.some(column => column.type.kind === \"vector\"));\n\n if (!usesVector || installed.has(\"vector\")) return [];\n\n return [{\n severity: \"error\",\n category: \"missing_table\",\n message: 'A table declares a vector column (`col.vector(...)`) and the pgvector extension is not installed on this database.',\n fix: 'Declare it — `database({ extensions: [\"vector\"] })` in config/resources.ts — and use an image that ships the library '\n + \"(the scaffold's pgvector/pgvector:pg18; a stock postgres:18 does not). Or install it once by hand: CREATE EXTENSION vector;\"\n }];\n}\n\n/**\n * The stamp the runtime wrote, against the tables on disk (their compiled\n * descriptors, which is what the stamp is computed over).\n *\n * A stamp that disagrees means this database was provisioned from a different\n * set of tables than the ones in this checkout — a colleague's branch, an\n * older deploy, a tenant somebody else migrated. Everything else in this report\n * is then describing a schema somebody else created, which is worth knowing\n * before acting on any of it.\n *\n * A warning, not an error, and never a direction: the stamp is a hash, so it\n * can say the two disagree and never which is ahead. `null` — never stamped —\n * is not a finding: every database provisioned before the stamp existed reads\n * that way, and so does every fresh one.\n */\nexport async function schemaStampIssues(\n pool: { query<T>(text: string): Promise<{ rows: T[] }> },\n /** The version this checkout computes — `defaultDatabaseSchemaVersion`, what a boot and a push stamp. */\n expected: string\n): Promise<DoctorIssue[]> {\n let stamped: string | null = null;\n try {\n // `to_regclass` so a missing schema or table is a null rather than a\n // thrown 42P01 — the commonest state on a fresh database is neither.\n const present = await pool.query<{ present: boolean }>(\n `SELECT to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL AS present`\n );\n if (!present.rows[0]?.present) return [];\n const row = await pool.query<{ value: string }>(\n `SELECT value FROM \"rebase\".\"schema_meta\" WHERE key = 'collections_schema_version' LIMIT 1`\n );\n stamped = row.rows[0]?.value ?? null;\n } catch {\n // The stamp is a diagnostic, not a gate. A database that will not\n // answer this question has bigger problems, and they are reported by\n // the checks around this one.\n return [];\n }\n\n if (!stamped) return [];\n if (stamped === expected) return [];\n\n // A stamp from a runtime before 0.31 hashed collections, never tables: it\n // differs from every version this release computes and says nothing about\n // drift. Explained in the server's own words, once, with the restamp.\n if (stamped.startsWith(LEGACY_SCHEMA_VERSION_PREFIX)) {\n return [{\n severity: \"warning\",\n category: \"schema_stale\",\n message: describeMismatch(stamped, expected),\n fix: \"Run `rebase db push` (or boot the process that owns the schema) once to restamp it.\"\n }];\n }\n\n return [{\n severity: \"warning\",\n category: \"schema_stale\",\n message: `This database was provisioned from a different set of tables (stamp ${stamped}, this checkout computes ${expected}).`,\n fix: \"A hash says the two disagree, never which is ahead. Check you are pointed at the database you think you are; then `rebase db push` to bring it to these tables.\"\n }];\n}\n\n/** `\"public\".\"posts\"` — quoted, for a statement the reader will paste. */\nconst quotedTable = (schema: string, table: string): string => `\"${schema}\".\"${table}\"`;\n\n/**\n * What to do about a column whose type is not the one the collection plans.\n *\n * Both ways out, because the doctor cannot know which side is right: the\n * property moved, or the database did. Putting the property back always clears\n * the finding; converting the column clears it when every value converts.\n */\nexport function typeMismatchFix(\n schema: string,\n table: string,\n column: string,\n actual: string,\n planned: PgType | undefined\n): string {\n const back = `Either put the property back to the column's type (${actual}), or`;\n if (!planned) return `${back} run a migration that converts the column.`;\n const type = renderPgType(planned);\n return `${back} convert the column when you can watch it (every value must convert): `\n + `ALTER TABLE ${quotedTable(schema, table)} ALTER COLUMN \"${column}\" TYPE ${type} USING \"${column}\"::${type};`;\n}\n\n/**\n * The table's primary key against the one the collection reads it by.\n *\n * Rebase addresses a row by the key the plan names — the `isId` property, or\n * the implicit `id` — so a table keyed on other columns, or on none, serves\n * reads and writes against a key that does not hold. An error, because that is\n * what it is at runtime.\n */\nexport function primaryKeyIssues(tablePlan: TablePlan, dbPk: string[], displayName: string): DoctorIssue[] {\n const expected = tablePlan.primaryKey;\n const same = dbPk.length === expected.length && [...dbPk].sort().join(\"\\u0000\") === [...expected].sort().join(\"\\u0000\");\n if (same) return [];\n const table = quotedTable(tablePlan.schema, tablePlan.table);\n const keyList = expected.map(c => `\"${c}\"`).join(\", \");\n if (dbPk.length === 0) {\n return [{\n severity: \"error\",\n category: \"primary_key_mismatch\",\n table: displayName,\n expected: expected.join(\", \"),\n actual: \"(none)\",\n message: `Table \"${displayName}\" has no primary key; the table definition reads its rows by ${keyList}.`,\n fix: `ALTER TABLE ${table} ADD PRIMARY KEY (${keyList});`\n }];\n }\n // Several `isId` properties are one composite key, so a table keyed on\n // several columns is matched by marking each of them — and only them.\n const only = expected.some(column => !dbPk.includes(column)) ? \"only \" : \"\";\n const fix = dbPk.length === 1\n ? `Mark ${only}the property for column \"${dbPk[0]}\" with \\`isId\\` — the table is keyed on it — or re-key the table on ${keyList}.`\n : `Mark ${only}the properties for columns ${dbPk.map(c => `\"${c}\"`).join(\", \")} with \\`isId\\` — together they are `\n + `the table's composite key — or re-key the table on ${keyList}.`;\n return [{\n severity: \"error\",\n category: \"primary_key_mismatch\",\n table: displayName,\n expected: expected.join(\", \"),\n actual: dbPk.join(\", \"),\n message: `Table \"${displayName}\" is keyed on (${dbPk.join(\", \")}), but the table definition reads its rows by ${keyList}.`,\n fix\n }];\n}\n\n/**\n * A junction's two key columns: present, typed like the keys they point at,\n * and the table keyed on the pair. Order is not compared — boot and `db push`\n * have built the key in both orders, and either one serves the same rows.\n */\nexport function junctionKeyIssues(\n junctionPlan: TablePlan,\n dbColumns: DbColumn[],\n dbPk: string[],\n displayName: string\n): DoctorIssue[] {\n const issues: DoctorIssue[] = [];\n const byName = new Map(dbColumns.map(c => [c.column_name, c]));\n for (const column of junctionPlan.columns) {\n const dbCol = byName.get(column.column);\n if (!dbCol) {\n issues.push({\n severity: \"error\",\n category: \"missing_column\",\n table: displayName,\n column: column.column,\n message: `Junction table \"${displayName}\" has no \"${column.column}\" column.`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n continue;\n }\n const expected = informationSchemaName(column.type);\n if (expected !== null && dbCol.data_type !== expected) {\n issues.push({\n severity: \"warning\",\n category: \"type_mismatch\",\n table: displayName,\n column: column.column,\n expected,\n actual: dbCol.data_type,\n message: `Junction column \"${column.column}\" in \"${displayName}\" is ${dbCol.data_type}, but the key it points at is ${expected}.`,\n fix: typeMismatchFix(junctionPlan.schema, junctionPlan.table, column.column, dbCol.data_type, column.type)\n });\n }\n }\n issues.push(...primaryKeyIssues(junctionPlan, dbPk, displayName));\n return issues;\n}\n\n/** A table as the other issues name it: bare in `public`, `schema.table` elsewhere. */\nfunction displayTableOf(difference: SchemaDifference, tables: readonly TableDescriptor[]): string {\n const schema = difference.slug ? tables.find(t => t.slug === difference.slug)?.schema : undefined;\n return schema && schema !== \"public\" ? `${schema}.${difference.table}` : difference.table;\n}\n\n/** Which of the doctor's own categories already says what a boot difference says. */\nconst COVERING_CATEGORY: Record<SchemaDifference[\"kind\"], DoctorIssue[\"category\"]> = {\n \"missing-table\": \"missing_table\",\n \"missing-column\": \"missing_column\",\n type: \"type_mismatch\",\n nullability: \"nullability_mismatch\",\n \"extra-column\": \"extra_column\"\n};\n\n/** What to do about one boot difference, said the way the boot warning says it. */\nfunction generatedDriftFix(difference: SchemaDifference): string {\n const regenerate = \" If backend/schema changed since schema.generated.ts was written, run `rebase schema generate` first.\";\n switch (difference.kind) {\n case \"nullability\":\n return difference.generated === \"NOT NULL\"\n ? \"`rebase db push` applies it; a NOT NULL needs every row filled first (UPDATE the empty ones, or give \"\n + \"the property a default). Boot adds one only with a new column on an empty table.\" + regenerate\n : \"`rebase db push` drops the NOT NULL, which boot never does. If the column should stay required, \"\n + \"mark the property `validation: { required: true }`.\" + regenerate;\n case \"extra-column\":\n return \"Boot never drops a column, so its data is still there. `rebase db push` removes it (it asks first, \"\n + \"since that deletes the data), or a migration does (`rebase db generate`). If a property should still \"\n + \"read it, declare it again.\" + regenerate;\n case \"type\":\n return \"`rebase db push` converts it (it asks first when values may not convert), or a migration does.\" + regenerate;\n case \"missing-column\":\n return \"`rebase db push` adds it.\" + regenerate;\n case \"missing-table\":\n return \"Run `rebase db push` or `rebase db generate && rebase db migrate`\";\n }\n}\n\n/**\n * Boot's drift warnings, as doctor issues — one per difference, in boot's own\n * words ({@link describeSchemaDifference}), and a warning, as boot raises them.\n *\n * Except where an issue the collections-side checks above already raised says\n * the same thing: a missing table, a missing column or a type mismatch on the\n * same column. Nullability and columns no collection declares are boot's alone;\n * the doctor never compared them, which is how it came to say \"In sync\" beside\n * a boot that had just warned about both.\n */\nexport function generatedSchemaDriftIssues(\n differences: SchemaDifference[],\n already: DoctorIssue[],\n tables: readonly TableDescriptor[]\n): DoctorIssue[] {\n const bare = (table: string | undefined) => table?.split(\".\").pop();\n const covered = (difference: SchemaDifference) => already.some(issue =>\n issue.category === COVERING_CATEGORY[difference.kind]\n && bare(issue.table) === difference.table\n && (difference.kind === \"missing-table\" || issue.column === difference.column));\n\n return differences.filter(difference => !covered(difference)).map(difference => ({\n severity: \"warning\",\n category: COVERING_CATEGORY[difference.kind],\n table: displayTableOf(difference, tables),\n ...(difference.column ? { column: difference.column } : {}),\n ...(difference.generated ? { expected: difference.generated } : {}),\n ...(difference.live ? { actual: difference.live } : {}),\n message: describeSchemaDifference(difference),\n fix: generatedDriftFix(difference)\n }));\n}\n\n/**\n * The tables the default database holds — the filter boot applies before it\n * reads the catalogue, for the same reason: a table routed to\n * `database(\"analytics\")` has no table here.\n */\nfunction defaultDatabaseTables(tables: readonly CompiledTable[]): CompiledTable[] {\n return tables.filter(t => !t.descriptor.database || t.descriptor.database === DEFAULT_DATA_SOURCE_KEY);\n}\n\nexport async function checkTablesVsDatabase(\n tables: readonly CompiledTable[],\n databaseUrl: string,\n options: {\n /**\n * The `tables` export of `schema.generated.ts`, for boot's own drift\n * comparison. Without it the doctor compares the collections alone.\n */\n generated?: Record<string, unknown>;\n /**\n * The schema version this checkout computes\n * (`defaultDatabaseSchemaVersion`), to compare against the stamp the\n * runtime or a push wrote. Without it that one check is not made.\n */\n schemaVersion?: string;\n } = {}\n): Promise<DoctorPhase> {\n const issues: DoctorIssue[] = [];\n const descriptors = tables.map(table => table.descriptor);\n const bySlug = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n\n // Dynamic import to avoid loading pg when not needed\n const pgModule = await import(\"pg\");\n const { Pool } = pgModule.default ?? pgModule;\n const pool = new Pool({ connectionString: databaseUrl });\n\n // Every schema a table is declared in, plus public and rebase\n const schemas = Array.from(new Set([\"public\", \"rebase\", ...descriptors.map(d => d.schema)]));\n\n try {\n // Fetch all tables in the defined schemas\n const tablesResult = await pool.query<{ table_schema: string; table_name: string }>(\n `SELECT table_schema, table_name \n FROM information_schema.tables \n WHERE table_schema = ANY($1) AND table_type = 'BASE TABLE'`,\n [schemas]\n );\n const existingTables = new Set(tablesResult.rows.map((r) =>\n r.table_schema === \"public\" ? r.table_name : `${r.table_schema}.${r.table_name}`\n ));\n // Views and materialized views, for the collections that serve one.\n const viewsResult = await pool.query<{ table_schema: string; table_name: string }>(\n `SELECT n.nspname AS table_schema, c.relname AS table_name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY($1) AND c.relkind IN ('v', 'm')`,\n [schemas]\n );\n const existingViews = new Set(viewsResult.rows.map((r) =>\n r.table_schema === \"public\" ? r.table_name : `${r.table_schema}.${r.table_name}`\n ));\n\n // An extension the collections need and the database does not have.\n //\n // The symptom without this is `type \"vector\" does not exist` on the\n // first write to a table that looks perfectly well-formed in the\n // report: the column is planned, the extension is not, and the two\n // facts live in different places. Extensions are opt-in by design —\n // installing one needs an image that ships the library and a role\n // allowed to install it — so this reports, it does not install.\n const extensionsResult = await pool.query<{ extname: string }>(\"SELECT extname FROM pg_extension\");\n const installedExtensions = new Set(extensionsResult.rows.map(r => r.extname));\n issues.push(...missingExtensionIssues(descriptors, installedExtensions));\n\n // A database provisioned from a different set of collections than the\n // ones on disk.\n //\n // The runtime stamps what it applied; nothing compared it outside boot,\n // and a stamp that disagrees is exactly the state where the rest of\n // this report is describing a schema somebody else's deploy created.\n if (options.schemaVersion !== undefined) issues.push(...await schemaStampIssues(pool, options.schemaVersion));\n\n // Fetch all columns in the defined schemas\n const columnsResult = await pool.query<DbColumn>(\n `SELECT table_schema, table_name, column_name, data_type, is_nullable, udt_name\n FROM information_schema.columns\n WHERE table_schema = ANY($1)\n ORDER BY table_schema, table_name, ordinal_position`,\n [schemas]\n );\n const columnsByTable = new Map<string, DbColumn[]>();\n for (const row of columnsResult.rows) {\n const tableSchema = row.table_schema;\n const tableName = row.table_name;\n const key = tableSchema === \"public\" ? tableName : `${tableSchema}.${tableName}`;\n if (!columnsByTable.has(key)) {\n columnsByTable.set(key, []);\n }\n columnsByTable.get(key)!.push(row);\n }\n\n // Fetch enums, keyed `schema.name`. A type is found in the schema the\n // planner put it in, and nowhere else — a same-named type in another\n // schema is somebody else's, and the column does not use it.\n const enumsResult = await pool.query<DbEnumValue>(\n `SELECT n.nspname AS enum_schema, t.typname AS enum_name, e.enumlabel AS enum_value\n FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace\n JOIN pg_enum e ON t.oid = e.enumtypid\n ORDER BY n.nspname, t.typname, e.enumsortorder`\n );\n const enumsByName = new Map<string, string[]>();\n for (const row of enumsResult.rows) {\n const key = `${row.enum_schema}.${row.enum_name}`;\n if (!enumsByName.has(key)) {\n enumsByName.set(key, []);\n }\n enumsByName.get(key)!.push(row.enum_value);\n }\n\n // Every table's primary key, its columns in key order.\n const pksResult = await pool.query<{ table_schema: string; table_name: string; columns: string[] }>(\n `SELECT n.nspname AS table_schema, c.relname AS table_name,\n array_agg(a.attname::text ORDER BY array_position(i.indkey::int2[], a.attnum)) AS columns\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey::int2[])\n WHERE i.indisprimary AND n.nspname = ANY($1)\n GROUP BY n.nspname, c.relname`,\n [schemas]\n );\n const pksByTable = new Map<string, string[]>();\n for (const row of pksResult.rows) {\n pksByTable.set(row.table_schema === \"public\" ? row.table_name : `${row.table_schema}.${row.table_name}`, row.columns);\n }\n\n // Fetch foreign key constraints in the defined schemas\n const fksResult = await pool.query<{\n constraint_name: string;\n table_schema: string;\n table_name: string;\n column_name: string;\n foreign_table_schema: string;\n foreign_table_name: string;\n foreign_column_name: string;\n }>(\n `SELECT\n tc.constraint_name,\n tc.table_schema,\n tc.table_name,\n kcu.column_name,\n ccu.table_schema AS foreign_table_schema,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage AS ccu\n ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = ANY($1)`,\n [schemas]\n );\n const fksByTable = new Map<string, typeof fksResult.rows>();\n for (const row of fksResult.rows) {\n const tableSchema = row.table_schema;\n const tableName = row.table_name;\n const key = tableSchema === \"public\" ? tableName : `${tableSchema}.${tableName}`;\n if (!fksByTable.has(key)) {\n fksByTable.set(key, []);\n }\n fksByTable.get(key)!.push(row);\n }\n\n // ── Compare each table against the database ──────────────────────\n\n // Where boot and `db push` create each junction table.\n const junctions = resolveTableJunctions(sortTablesBySlug(tables).map(t => t.descriptor));\n\n // What push and boot build, read once. The key and the junction checks\n // compare against it rather than against a fifth reading of the\n // columns. A configuration the planner refuses has no plan; the other\n // phases name that problem, and these checks stand down.\n let plan: SchemaPlan | undefined;\n try {\n plan = planSchema(tables);\n } catch {\n plan = undefined;\n }\n const tablePlans = new Map<string, TablePlan>((plan?.tables ?? []).map(t => [t.qualified, t]));\n const checkedJunctions = new Set<string>();\n\n for (const descriptor of descriptors) {\n const tableName = descriptor.table;\n const schemaName = descriptor.schema;\n const fullTableName = schemaName === \"public\" ? tableName : `${schemaName}.${tableName}`;\n\n // A view is Rebase's to create from its query; there are no\n // columns of its own to check against the definition.\n if (descriptor.kind === \"view\") {\n if (!existingViews.has(fullTableName)) {\n issues.push({\n severity: \"error\",\n category: \"missing_table\",\n table: fullTableName,\n message: `View \"${fullTableName}\" does not exist in the database.`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n }\n continue;\n }\n\n // Check table existence\n if (!existingTables.has(fullTableName)) {\n issues.push({\n severity: \"error\",\n category: \"missing_table\",\n table: fullTableName,\n message: `Table \"${fullTableName}\" does not exist in the database.`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n continue; // Skip column checks for missing tables\n }\n\n const dbColumns = columnsByTable.get(fullTableName) ?? [];\n const dbColumnMap = new Map(dbColumns.map((c) => [c.column_name, c]));\n\n // The key. It used to be skipped outright — `id` sat in a list of\n // \"system columns\" — so a key whose type or whose columns had\n // drifted reported \"In sync\".\n const tablePlan = tablePlans.get(`${schemaName}.${tableName}`);\n if (tablePlan) {\n issues.push(...primaryKeyIssues(tablePlan, pksByTable.get(fullTableName) ?? [], fullTableName));\n }\n\n // A `belongsTo`: its foreign-key column, and the constraint on it.\n for (const relation of relationsOfKind(descriptor, \"belongsTo\")) {\n const fkColName = relation.localKey;\n if (!dbColumnMap.has(fkColName)) {\n issues.push({\n severity: \"error\",\n category: \"missing_column\",\n table: fullTableName,\n column: fkColName,\n message: `Foreign key column \"${fkColName}\" for relation \"${relation.name}\" is missing from table \"${fullTableName}\".`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n continue;\n }\n // A link written without a constraint (`constraint: false`) has none to find.\n if (!relation.constraint) continue;\n\n const target = bySlug.get(relation.target);\n const targetTableName = target?.table ?? \"unknown\";\n const targetSchemaName = target?.schema ?? \"public\";\n const hasFk = (fksByTable.get(fullTableName) ?? []).some((fk) =>\n fk.column_name === fkColName &&\n fk.foreign_table_name === targetTableName &&\n fk.foreign_table_schema === targetSchemaName\n );\n if (!hasFk) {\n issues.push({\n severity: \"warning\",\n category: \"missing_foreign_key\",\n table: fullTableName,\n column: fkColName,\n message: `Column \"${fkColName}\" exists but has no FOREIGN KEY constraint referencing \"${targetSchemaName === \"public\" ? targetTableName : `${targetSchemaName}.${targetTableName}`}\".`,\n fix: \"Run `rebase db push` or add the constraint manually\"\n });\n }\n }\n\n // Columns. A foreign-key column is typed by the key it points at,\n // and checked with its relation above.\n for (const column of descriptor.columns) {\n if (column.foreignKeyOf !== undefined) continue;\n const colName = column.column;\n\n const dbCol = dbColumnMap.get(colName);\n if (!dbCol) {\n issues.push({\n severity: \"error\",\n category: \"missing_column\",\n table: fullTableName,\n column: colName,\n message: `Column \"${colName}\" is defined in table \"${descriptor.slug}\" (backend/schema) but missing from table \"${fullTableName}\".`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n continue;\n }\n\n const planned = plannedColumnType(descriptor, column);\n if (!planned) continue;\n\n // Type check\n const expectedType = informationSchemaName(planned);\n if (expectedType) {\n const actualType = dbCol.data_type;\n let isMismatch = actualType !== expectedType;\n if (planned.kind === \"vector\" && dbCol.udt_name !== \"vector\") isMismatch = true;\n if (planned.kind === \"array\" && actualType === \"ARRAY\") {\n const expectedUdt = ARRAY_UDT_NAMES[planned.of.kind];\n if (expectedUdt && dbCol.udt_name !== expectedUdt) isMismatch = true;\n }\n if (isMismatch) {\n const expectedLabel = planned.kind === \"vector\" ? \"vector\" : expectedType;\n const actualLabel = dbCol.udt_name === \"vector\" ? \"vector\" : actualType;\n issues.push({\n severity: \"warning\",\n category: \"type_mismatch\",\n table: fullTableName,\n column: colName,\n expected: expectedLabel,\n actual: actualLabel,\n message: `Column \"${colName}\" in table \"${fullTableName}\": expected type \"${expectedLabel}\" but found \"${actualLabel}\".`,\n fix: typeMismatchFix(schemaName, tableName, colName, actualType,\n tablePlan?.columns.find(c => c.column === colName)?.type ?? planned)\n });\n }\n }\n\n // Enum value check\n if (planned.kind === \"enum\") {\n // The planner's name, cut to the 63 bytes Postgres keeps,\n // in the schema the planner put it in.\n const enumName = toPostgresIdentifier(planned.name);\n const enumSchema = planned.schema;\n const dbEnumValues = enumsByName.get(`${enumSchema}.${enumName}`);\n if (!dbEnumValues) {\n issues.push({\n severity: \"warning\",\n category: \"missing_enum\",\n table: fullTableName,\n column: colName,\n expected: enumName,\n message: `Enum type \"${enumSchema}\".\"${enumName}\" is defined in backend/schema but not found in the database.`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n } else {\n const expectedValues = planned.labels;\n const missing = expectedValues.filter((v) => !dbEnumValues.includes(v));\n const extra = dbEnumValues.filter((v) => !expectedValues.includes(v));\n\n if (missing.length > 0 || extra.length > 0) {\n const parts: string[] = [];\n if (missing.length > 0) parts.push(`missing: ${missing.join(\", \")}`);\n if (extra.length > 0) parts.push(`extra in DB: ${extra.join(\", \")}`);\n issues.push({\n severity: \"warning\",\n category: \"enum_value_mismatch\",\n table: fullTableName,\n column: colName,\n expected: expectedValues.join(\", \"),\n actual: dbEnumValues.join(\", \"),\n message: `Enum values for \"${colName}\" in table \"${fullTableName}\" are out of sync (${parts.join(\"; \")}).`,\n fix: extra.length > 0 && missing.length === 0\n // A push cannot remove a label (no ALTER TYPE … DROP VALUE), so it was never the remedy for these.\n ? `PostgreSQL cannot drop an enum label, so \\`rebase db push\\` leaves ${extra.join(\", \")} in place. Harmless unless something still writes it; to retire it, UPDATE its rows to another value, then rewrite the type in a migration (\\`rebase db generate\\`: CREATE TYPE …, ALTER TABLE … TYPE … USING, DROP TYPE) and \\`rebase db migrate\\``\n : \"Run `rebase db push` to add the missing labels\" + (extra.length > 0 ? `; it cannot remove ${extra.join(\", \")} (PostgreSQL has no ALTER TYPE … DROP VALUE) — retire those with a migration that rewrites the type` : \"\")\n });\n }\n }\n }\n }\n\n // Junction tables for many-to-many relations — where boot and\n // `db push` create them (`resolveTableJunctions`), under the name\n // with any schema prefix removed.\n for (const relation of relationsOfKind(descriptor, \"manyToMany\")) {\n const junctionTable = relation.through.table.split(\".\").pop() ?? relation.through.table;\n const junctionSchema = junctions.get(junctionTable)?.schema ?? \"public\";\n const fullJunctionTable = junctionSchema === \"public\" ? junctionTable : `${junctionSchema}.${junctionTable}`;\n if (!existingTables.has(fullJunctionTable)) {\n issues.push({\n severity: \"error\",\n category: \"missing_table\",\n table: fullJunctionTable,\n message: `Junction table \"${fullJunctionTable}\" for many-to-many relation \"${relation.name}\" is missing.`,\n fix: \"Run `rebase db push` or `rebase db generate && rebase db migrate`\"\n });\n } else if (!checkedJunctions.has(fullJunctionTable)) {\n // Both sides declare the same junction; it is checked once.\n checkedJunctions.add(fullJunctionTable);\n const junctionPlan = tablePlans.get(`${junctionSchema}.${junctionTable}`);\n if (junctionPlan) {\n issues.push(...junctionKeyIssues(\n junctionPlan,\n columnsByTable.get(fullJunctionTable) ?? [],\n pksByTable.get(fullJunctionTable) ?? [],\n fullJunctionTable\n ));\n }\n }\n }\n }\n\n if (plan) {\n issues.push(...orphanedJunctionIssues(plan, columnsByTable, pksByTable, fksByTable));\n }\n\n // The question boot asks, through boot's code: `schema.generated.ts`\n // against the catalogue. Last, so the differences the checks above\n // already named are not named twice.\n if (options.generated) {\n const differences = await readGeneratedSchemaDrift({\n client: pool,\n generated: options.generated,\n tables: defaultDatabaseTables(tables).map(t => t.descriptor),\n defaultSchema: \"public\"\n });\n issues.push(...generatedSchemaDriftIssues(differences, issues, descriptors));\n }\n } finally {\n await pool.end();\n }\n\n // An `info` note — the orphaned junction — does not make the phase fail.\n return { passed: !issues.some(issue => issue.severity !== \"info\"),\nissues };\n}\n\n/**\n * A `public` table in the junction shape that no collection declares.\n *\n * The shape is the planner's: exactly two columns, together the primary key,\n * each a single-column foreign key to a collection's table. Renaming or\n * removing a many-to-many leaves such a table behind — push and boot only\n * create — with every link row still in it and nothing reading it.\n *\n * Info, never more: the table may be data somebody still wants. The remedy is\n * shown, never run.\n */\nexport function orphanedJunctionIssues(\n plan: SchemaPlan,\n columnsByTable: Map<string, { column_name: string }[]>,\n pksByTable: Map<string, string[]>,\n fksByTable: Map<string, { constraint_name: string; column_name: string; foreign_table_schema: string; foreign_table_name: string }[]>\n): DoctorIssue[] {\n const declared = new Set(plan.tables.map(table => table.qualified));\n const collectionTables = new Set(plan.tables.filter(table => table.kind === \"collection\").map(table => table.qualified));\n const issues: DoctorIssue[] = [];\n for (const [table, columns] of columnsByTable) {\n // Keys are bare for `public` and `schema.table` elsewhere.\n if (table.includes(\".\") || declared.has(`public.${table}`)) continue;\n // Two columns and a two-column key: the key is those two columns.\n if (columns.length !== 2 || (pksByTable.get(table) ?? []).length !== 2) continue;\n\n const byConstraint = new Map<string, { column: string; target: string }[]>();\n for (const fk of fksByTable.get(table) ?? []) {\n const target = `${fk.foreign_table_schema}.${fk.foreign_table_name}`;\n byConstraint.set(fk.constraint_name, [...(byConstraint.get(fk.constraint_name) ?? []), { column: fk.column_name, target }]);\n }\n const links = [...byConstraint.values()];\n if (links.length !== 2 || links.some(link => link.length !== 1)) continue;\n if (new Set(links.map(([link]) => link.column)).size !== 2) continue;\n if (!links.every(([link]) => collectionTables.has(link.target))) continue;\n\n const targets = links.map(([link]) => link.target.replace(/^public\\./, \"\"));\n issues.push({\n severity: \"info\",\n category: \"orphaned_junction\",\n table,\n message: `Table \"${table}\" links \"${targets[0]}\" and \"${targets[1]}\" like a many-to-many junction, but no table declares it — left behind by a renamed or removed relation?`,\n fix: `DROP TABLE \"public\".\"${table}\";`\n });\n }\n return issues;\n}\n\n// ── Report Rendering ─────────────────────────────────────────────────────\n\nexport function renderReport(report: DoctorReport): void {\n out();\n out(chalk.bold(\" 🩺 Rebase Schema Doctor\"));\n out(chalk.gray(\" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"));\n out();\n\n // Phase 1\n renderPhase(\"Tables → Generated Schema\", report.collectionsToSchema);\n\n // Phase 2\n renderPhase(\"Tables → Database\", report.schemaToDatabase);\n\n // Phase 3\n renderPhase(\"Tables → SDK Types\", report.collectionsToSdk);\n\n // Summary\n out(chalk.gray(\" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"));\n const { passed, skipped, notApplicable, warnings, errors } = report.summary;\n\n const parts: string[] = [];\n parts.push(chalk.green(`${passed} passed`));\n if (skipped > 0) parts.push(chalk.yellow(`${skipped} skipped`));\n if (notApplicable > 0) parts.push(chalk.gray(`${notApplicable} not applicable`));\n if (warnings > 0) parts.push(chalk.yellow(`${warnings} warnings`));\n if (errors > 0) parts.push(chalk.red(`${errors} errors`));\n\n out(` Summary: ${parts.join(\", \")}`);\n out();\n\n if (errors > 0) {\n out(chalk.red.bold(\" ✗ Schema drift detected. Run the suggested fixes above.\"));\n } else if (warnings > 0) {\n out(chalk.yellow.bold(\" ⚠ Minor issues detected. Consider running the suggested fixes.\"));\n } else if (skipped > 0) {\n // Never \"all schemas are in sync\" off the back of a check that did not\n // run: a clean bill of health has to come from measurement.\n out(chalk.yellow.bold(` ⚠ Nothing wrong in the checks that ran, but ${skipped} did not run — this is not a clean bill of health.`));\n } else {\n out(chalk.green.bold(\" ✓ All schemas are in sync!\"));\n }\n out();\n}\n\nfunction renderPhase(label: string, phase: DoctorPhase): void {\n // A phase that never ran gets its own marker and its reason. It is neither\n // \"In sync\" nor a drift report; conflating it with the former is what let\n // doctor certify a database it had not opened.\n if (phase.skipped) {\n out(` ${chalk.yellow(\"⏭\")} ${label}: ${chalk.yellow(`skipped (${phase.skipped})`)}`);\n out();\n return;\n }\n\n // Nothing to compare against. Its own marker, and only the remedy under it\n // — the phase header already carries the reason, so re-printing the note\n // would say the same thing twice. See DoctorPhase.notApplicable.\n if (phase.notApplicable) {\n out(` ${chalk.gray(\"➖\")} ${label}: ${chalk.gray(phase.notApplicable)}`);\n for (const issue of phase.issues.filter((i) => i.severity === \"info\")) {\n out(` ${chalk.gray(issue.fix)}`);\n }\n out();\n return;\n }\n\n const issues = phase.issues;\n const errorCount = issues.filter((i) => i.severity === \"error\").length;\n const warnCount = issues.filter((i) => i.severity === \"warning\").length;\n const infoIssues = issues.filter((i) => i.severity === \"info\");\n\n // Informational notes don't make a phase unhealthy, so key the header off\n // real problems rather than `phase.passed` alone.\n if (errorCount === 0 && warnCount === 0) {\n out(` ${chalk.green(\"✅\")} ${label}: ${chalk.green(\"In sync\")}`);\n } else {\n const parts: string[] = [];\n if (errorCount > 0) parts.push(`${errorCount} error${errorCount > 1 ? \"s\" : \"\"}`);\n if (warnCount > 0) parts.push(`${warnCount} warning${warnCount > 1 ? \"s\" : \"\"}`);\n out(` ${chalk.yellow(\"⚠️\")} ${label}: ${chalk.yellow(parts.join(\", \"))}`);\n }\n out();\n\n // Notes render as a quiet one-liner, not a full drift box.\n for (const issue of infoIssues) {\n const fixPart = issue.fix ? chalk.gray(` — ${issue.fix}`) : \"\";\n out(` ${chalk.gray(\"ℹ\")} ${chalk.gray(issue.message)}${fixPart}`);\n out();\n }\n\n for (const issue of issues.filter((i) => i.severity !== \"info\")) {\n const severityIcon = issue.severity === \"error\" ? chalk.red(\"✗\") : chalk.yellow(\"⚠\");\n const categoryLabel = formatCategory(issue.category);\n out(` ${chalk.gray(\"┌─\")} ${severityIcon} ${chalk.bold(categoryLabel)} ${chalk.gray(\"─\".repeat(Math.max(0, 42 - categoryLabel.length)))}`);\n\n if (issue.table) {\n const colPart = issue.column ? ` │ Column: ${chalk.cyan(issue.column)}` : \"\";\n out(` ${chalk.gray(\"│\")} Table: ${chalk.cyan(issue.table)}${colPart}`);\n }\n\n if (issue.expected && issue.actual) {\n out(` ${chalk.gray(\"│\")} Expected: ${chalk.green(issue.expected)} │ Actual: ${chalk.red(issue.actual)}`);\n }\n\n out(` ${chalk.gray(\"│\")} ${issue.message}`);\n out(` ${chalk.gray(\"│\")} Fix: ${chalk.blue(issue.fix)}`);\n out(` ${chalk.gray(\"└\" + \"─\".repeat(48))}`);\n out();\n }\n}\n\nfunction formatCategory(cat: DoctorIssue[\"category\"]): string {\n const labels: Record<DoctorIssue[\"category\"], string> = {\n missing_table: \"Missing Table\",\n missing_column: \"Missing Column\",\n type_mismatch: \"Type Mismatch\",\n nullability_mismatch: \"Nullability Mismatch\",\n extra_column: \"Extra Column\",\n missing_constraint: \"Missing Constraint\",\n primary_key_mismatch: \"Primary Key Mismatch\",\n schema_stale: \"Stale Schema\",\n missing_enum: \"Missing Enum\",\n enum_value_mismatch: \"Enum Value Mismatch\",\n missing_foreign_key: \"Missing Foreign Key\",\n orphaned_junction: \"Orphaned Junction Table\",\n sdk_stale: \"Stale SDK Types\",\n sdk_not_generated: \"SDK Types Not Generated\",\n sdk_ungeneratable: \"SDK Cannot Be Generated\"\n };\n return labels[cat];\n}\n\n// ── Main entry point ─────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * The `tables` export of `schema.generated.ts`, imported as boot imports it.\n *\n * Nothing, and no error, when the file is not there: phase 1 reports that, and\n * boot then has nothing to compare either.\n */\nasync function loadGeneratedTables(schemaPath: string): Promise<{ tables?: Record<string, unknown>; error?: string }> {\n if (!fs.existsSync(schemaPath)) return {};\n try {\n const module: unknown = await import(pathToFileURL(schemaPath).href);\n return isRecord(module) && isRecord(module.tables) ? { tables: module.tables } : {};\n } catch (err: unknown) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nexport async function runDoctor(options: {\n schemaDir: string;\n schemaPath: string;\n sdkPath: string;\n databaseUrl?: string;\n}): Promise<DoctorReport> {\n out();\n out(chalk.bold(\" 🩺 Loading tables...\"));\n // The loader every door uses (`loadTableSchema`): a doctor that disagreed with\n // the policy generator about which tables exist would compare the wrong\n // thing. A schema that does not compile is fatal here as everywhere.\n const loaded = await loadTableSchema(options.schemaDir);\n const { descriptors, tables } = loaded;\n if (tables.length === 0) {\n outError(chalk.red(` ✗ No tables found in ${options.schemaDir} (its index.ts exports none).`));\n process.exit(1);\n }\n out(chalk.gray(` Found ${tables.length} table(s)`));\n out();\n\n // Phase 1: Collections ↔ Generated Schema\n out(chalk.gray(\" Checking Tables → Generated Schema...\"));\n const collectionsToSchema = await checkTablesVsSchema(tables, options.schemaPath);\n\n // Phase 2: Collections ↔ Database (only if we have a DATABASE_URL)\n let schemaToDatabase: DoctorPhase;\n if (options.databaseUrl) {\n out(chalk.gray(\" Checking Tables → Database...\"));\n try {\n const generated = await loadGeneratedTables(options.schemaPath);\n schemaToDatabase = await checkTablesVsDatabase(tables, options.databaseUrl, {\n generated: generated.tables,\n schemaVersion: defaultDatabaseSchemaVersion(loaded)\n });\n if (generated.error) {\n // Boot imports this module too, and would stop on it.\n schemaToDatabase.issues.push({\n severity: \"warning\",\n category: \"schema_stale\",\n message: `schema.generated.ts could not be loaded, so it was not compared against the database as boot compares it: ${generated.error}`,\n fix: \"Run `rebase schema generate`, then `rebase doctor` again\"\n });\n schemaToDatabase.passed = false;\n }\n } catch (err: unknown) {\n // A database that cannot be reached used to end the whole run: the\n // error escaped `runDoctor` and the CLI's last-resort catch printed\n // a stack. So the two phases that need no database — the generated\n // schema and the SDK types, both of which are read off disk — never\n // ran, and the one command whose job is to say what is wrong said\n // only \"Doctor failed\" over a drizzle stack trace.\n const banner = diagnoseDbError(err, options.databaseUrl);\n if (banner) outError(banner);\n const reason = deepestErrorMessage(err)\n ?? (err instanceof Error ? err.message : String(err));\n schemaToDatabase = {\n passed: false,\n issues: [],\n skipped: `could not reach ${parseHostInfo(options.databaseUrl)} — ${reason}`,\n blocked: true\n };\n }\n } else {\n // Not `{ passed: true }`: see DoctorPhase.skipped.\n schemaToDatabase = { passed: false,\nissues: [],\nskipped: \"DATABASE_URL not set\" };\n out(chalk.yellow(\" ⚠ DATABASE_URL not set — skipping database comparison.\"));\n out(chalk.gray(\" Set DATABASE_URL in your .env to enable full drift detection.\"));\n }\n\n // Phase 3: Collections ↔ SDK Types\n out(chalk.gray(\" Checking Tables → SDK Types...\"));\n const collectionsToSdk = await checkTablesVsSdk(descriptors, options.sdkPath);\n\n const phases = [collectionsToSchema, schemaToDatabase, collectionsToSdk];\n const allIssues = phases.flatMap((p) => p.issues);\n const summary = {\n // A skipped phase is not a passing one, however few issues it collected.\n // Nor is one with nothing to compare against: \"passed\" would put a\n // never-generated SDK in the same column as a verified one.\n passed: phases.filter((p) => p.passed && !p.skipped && !p.notApplicable).length,\n skipped: phases.filter((p) => p.skipped).length,\n notApplicable: phases.filter((p) => p.notApplicable && !p.skipped).length,\n warnings: allIssues.filter((i) => i.severity === \"warning\").length,\n errors: allIssues.filter((i) => i.severity === \"error\").length\n };\n\n const report: DoctorReport = { collectionsToSchema,\ncollectionsToSdk,\nschemaToDatabase,\nsummary };\n renderReport(report);\n\n return report;\n}\n","/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { loadTables } from \"./load-tables\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a schema path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero tables. Any exception at all — a table file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the tables describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(schemaDir: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), schemaDir);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const tables = await loadTables(resolvedPath);\n const descriptors = tables.map(table => table.descriptor);\n\n // Zero tables is not \"no drift\", it is nothing to compare. The loader\n // returns `[]` for a directory that does not exist, so the commonest\n // way to get here is the right directory from the wrong cwd — which\n // used to render as a green tick.\n if (descriptors.length === 0) {\n console.error(chalk.red(` ✗ No tables found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --schema-dir=<dir> if your tables live elsewhere than backend/schema.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no table\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the table reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, descriptors);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(descriptors);\n\n // Where a boot on this database writes the server-or-admin policies:\n // `TO public` where its admin switch is not live, and that is no drift.\n const drift = await checkPolicyDrift(pool, tables, { adminRoleAvailable: \"detect\" });\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your tables\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your tables (${descriptors.length} table(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every table import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: tables searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the tables\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport chalk from \"chalk\";\nimport { isIlikeSearchable } from \"@rebasepro/common\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { loadTables } from \"./load-tables\";\nimport { buildTableSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A table whose search would be `ILIKE` over these columns. */\nexport interface IlikeSearchedTable {\n slug: string;\n schema: string;\n table: string;\n /** The keys of the text columns the search reads. */\n fields: string[];\n}\n\n/**\n * The tables a search reaches without an index: no `search` block (or one\n * that does not build), and at least one column the default search reads —\n * text, without `.oneOf()` ({@link isIlikeSearchable}, the rule the search\n * conditions use).\n */\nexport function ilikeSearchedTables(tables: readonly TableDescriptor[]): IlikeSearchedTable[] {\n const found: IlikeSearchedTable[] = [];\n for (const table of tables) {\n if (table.kind === \"view\") continue;\n let indexed: boolean;\n try {\n indexed = buildTableSearchColumnSpec(table) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = table.columns.filter(column => isIlikeSearchable(column)).map(column => column.key);\n if (fields.length === 0) continue;\n found.push({ slug: table.slug, schema: table.schema, table: table.table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedTable[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedTable & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per table. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedTable & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} table(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `schemaDir`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(schemaDir: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const candidates = ilikeSearchedTables((await loadTables(schemaDir)).map(table => table.descriptor));\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","/**\n * `rebase doctor --database`: whether this database can host Rebase's request\n * role(s) under the project's `rls` settings, read from the catalogue without\n * changing anything.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import; the rendering and the table list are tested here.\n */\nimport chalk from \"chalk\";\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { resolveTableJunctions } from \"@rebasepro/common\";\nimport type { PreflightFinding } from \"../security/database-preflight\";\nimport type { ManagedTable, RawSqlRunner } from \"../security/rls-enforcement\";\nimport type { RlsSettings } from \"../security/rls-settings\";\nimport type { PolicyCheckStatus } from \"./doctor-policy-checks\";\n\n/**\n * The tables Rebase serves, as the server would list them: every declared\n * table in its schema (`public` by default), and every junction\n * table a many-to-many declares.\n */\nexport function managedTablesOf(descriptors: readonly TableDescriptor[]): ManagedTable[] {\n const tables = new Map<string, ManagedTable>();\n const add = (schema: string, table: string) => tables.set(`${schema}.${table}`, { schema, table });\n for (const descriptor of descriptors) add(descriptor.schema, descriptor.table);\n for (const junction of resolveTableJunctions(descriptors).values()) add(junction.schema, junction.table);\n return [...tables.values()];\n}\n\n/** The schemas Rebase writes to: `public`, `rebase`, and every schema a table names. */\nexport function preflightSchemasOf(descriptors: readonly TableDescriptor[]): string[] {\n return Array.from(new Set([\"public\", \"rebase\", ...descriptors.map((d) => d.schema)]));\n}\n\nconst LEVEL_ORDER: PreflightFinding[\"level\"][] = [\"fail\", \"warn\", \"ok\"];\nconst LEVEL_TITLE: Record<PreflightFinding[\"level\"], string> = {\n fail: \"Needs fixing before Rebase can serve requests here\",\n warn: \"Worth a look\",\n ok: \"Fine\"\n};\nconst LEVEL_MARK: Record<PreflightFinding[\"level\"], string> = {\n fail: chalk.red(\"✗\"),\n warn: chalk.yellow(\"⚠\"),\n ok: chalk.green(\"✓\")\n};\n\n/**\n * The report, grouped by level, failures first. Each finding that is not fine\n * shows the SQL to run as an administrator in gray, and the `rls` setting that\n * would fit Rebase to the database instead.\n */\nexport function renderPreflightFindings(\n findings: readonly PreflightFinding[],\n settings: Pick<RlsSettings, \"roles\" | \"nonDefaults\">\n): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold(\" Database preflight\"));\n lines.push(chalk.gray(\n ` Request role(s): ${settings.roles.join(\", \")}. ` +\n (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(\", \")}.` : \"The other rls settings are at their defaults.\")\n ));\n for (const level of LEVEL_ORDER) {\n const group = findings.filter((f) => f.level === level);\n if (group.length === 0) continue;\n lines.push(\"\");\n lines.push(` ${LEVEL_TITLE[level]}`);\n for (const finding of group) {\n lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);\n if (finding.sql) {\n for (const sqlLine of finding.sql.split(\"\\n\")) lines.push(chalk.gray(` ${sqlLine}`));\n }\n if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? \"or set\" : \"set\"}: ${finding.setting}`));\n }\n }\n return lines;\n}\n\n/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */\nexport function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus {\n return findings.some((f) => f.level === \"fail\") ? \"problems\" : \"ok\";\n}\n\n/**\n * Every table in `schemas` but `rebase`: what a project with no declared\n * tables serves, since its API is introspected from the database.\n */\nasync function everyTableIn(run: RawSqlRunner, schemas: readonly string[]): Promise<ManagedTable[]> {\n const names = schemas.filter((s) => s !== \"rebase\").map((s) => `'${s.replace(/'/g, \"''\")}'`);\n if (names.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${names.join(\", \")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n ORDER BY 1, 2\n `);\n return rows.map((r) => ({ schema: String(r.schema), table: String(r.name) }));\n}\n\n/**\n * Run the preflight against `databaseUrl` with the settings a command outside\n * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),\n * and print it. Never reports `ok` for a check it could not run.\n */\nexport async function runDatabasePreflight(schemaDir: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — the database preflight did NOT run\"));\n return \"unchecked\";\n }\n\n const { loadTables } = await import(\"./load-tables\");\n const { preflightDatabase } = await import(\"../security/database-preflight\");\n const { readRecordedRequestRoles } = await import(\"../security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"../security/rls-settings\");\n const { Pool } = await import(\"pg\");\n\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const run: RawSqlRunner = async (text) => (await pool.query(text)).rows as Record<string, unknown>[];\n // B-PLAN-2 step 6: the table list from the descriptors.\n const descriptors = (await loadTables(schemaDir)).map((table) => table.descriptor);\n // Only the schemas that exist: the SQL a finding carries grants on each\n // one, and a GRANT on a missing schema fails the whole script. A boot\n // grants on the ones it creates itself.\n const existing = new Set((await run(\"SELECT nspname FROM pg_namespace\")).map((row) => String(row.nspname)));\n const schemas = preflightSchemasOf(descriptors).filter((schema) => existing.has(schema));\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n\n let managedTables = managedTablesOf(descriptors);\n console.log(\"\");\n if (managedTables.length === 0) {\n managedTables = await everyTableIn(run, schemas);\n console.log(chalk.gray(\" No declared tables: every table in public is treated as served, as an introspected project serves them.\"));\n }\n\n const findings = await preflightDatabase(run, settings, { schemas, managedTables });\n for (const line of renderPreflightFindings(findings, settings)) console.log(line);\n console.log(\"\");\n return preflightStatus(findings);\n } catch (err) {\n console.error(chalk.red(\" ✗ Could not run the database preflight:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { runDatabasePreflight } from \"./doctor-database\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\nimport { DEFAULT_SCHEMA_DIR } from \"../cli-schema-dir\";\n\nasync function main() {\n const schemaDirArg = process.argv.find((a) => a.startsWith(\"--schema-dir=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n // --database runs only the preflight of the database itself: whether the\n // request role(s) can be set up and used here under the project's `rls`\n // settings. Read-only, and a gate like --policies.\n const databaseOnly = process.argv.includes(\"--database\");\n\n const schemaDir = schemaDirArg?.split(\"=\")[1] ?? DEFAULT_SCHEMA_DIR;\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly || databaseOnly) {\n // Non-zero so this can gate CI — the whole point of the flags, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n const statuses = [\n ...(databaseOnly ? [await runDatabasePreflight(schemaDir, databaseUrl)] : []),\n ...(policiesOnly ? [await runPolicyChecks(schemaDir, databaseUrl)] : [])\n ];\n process.exit(statuses.some(status => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);\n }\n\n const report = await runDoctor({\n schemaDir: path.resolve(process.cwd(), schemaDir),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(schemaDir, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(schemaDir, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAI,eAAe,cAAc,MAAM;CACtC,YAAY,SAAS;EACpB,MAAM,OA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,aAAa,eAAe,KAAA;CAChC,CAAC;CAED,MAAM,eAAe,MAAM,gBAAgB,WAAW,WAAW;CAGjE,MAAM,oBAAoB,WAAW,WAAW;CAYhD,MAAM,UAAU;EAAC,OAAO;EAAqB,OAAO;EAAkB,OAAO;CAAgB,CAAC,CACzF,MAAK,UAAS,MAAM,OAAO;CAChC,IAAI,OAAO,QAAQ,SAAS,KAAK,iBAAiB,cAAc,SAC5D,QAAQ,KAAK,CAAC;AAEtB;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAKlB,MAAM,SAAS,gBAAgB,KAAK,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,uBAAuB;CACnG,IAAI,QACA,QAAQ,MAAM,MAAM;MAEpB,QAAQ,MAAM,MAAM,IAAI,sBAAsB,gBAAgB,GAAG,GAAG,CAAC;CAEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { TableDescriptor } from "@rebasepro/types";
|
|
2
2
|
import type { PreflightFinding } from "../security/database-preflight.js";
|
|
3
3
|
import type { ManagedTable } from "../security/rls-enforcement.js";
|
|
4
4
|
import type { RlsSettings } from "../security/rls-settings.js";
|
|
5
5
|
import type { PolicyCheckStatus } from "./doctor-policy-checks.js";
|
|
6
6
|
/**
|
|
7
|
-
* The tables Rebase serves, as the server would list them: every
|
|
8
|
-
*
|
|
7
|
+
* The tables Rebase serves, as the server would list them: every declared
|
|
8
|
+
* table in its schema (`public` by default), and every junction
|
|
9
9
|
* table a many-to-many declares.
|
|
10
10
|
*/
|
|
11
|
-
export declare function managedTablesOf(
|
|
12
|
-
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a
|
|
13
|
-
export declare function preflightSchemasOf(
|
|
11
|
+
export declare function managedTablesOf(descriptors: readonly TableDescriptor[]): ManagedTable[];
|
|
12
|
+
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a table names. */
|
|
13
|
+
export declare function preflightSchemasOf(descriptors: readonly TableDescriptor[]): string[];
|
|
14
14
|
/**
|
|
15
15
|
* The report, grouped by level, failures first. Each finding that is not fine
|
|
16
16
|
* shows the SQL to run as an administrator in gray, and the `rls` setting that
|
|
@@ -24,4 +24,4 @@ export declare function preflightStatus(findings: readonly PreflightFinding[]):
|
|
|
24
24
|
* the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
|
|
25
25
|
* and print it. Never reports `ok` for a check it could not run.
|
|
26
26
|
*/
|
|
27
|
-
export declare function runDatabasePreflight(
|
|
27
|
+
export declare function runDatabasePreflight(schemaDir: string, databaseUrl?: string): Promise<PolicyCheckStatus>;
|
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
* What the RLS checks concluded.
|
|
3
3
|
*
|
|
4
4
|
* `unchecked` exists because "we could not look" and "we looked and it is fine"
|
|
5
|
-
* used to be reported identically: a
|
|
5
|
+
* used to be reported identically: a schema path that did not resolve made
|
|
6
6
|
* the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`
|
|
7
7
|
* early-returned an empty diff, and the gate printed
|
|
8
8
|
* `✓ RLS policies match your collections` having compared zero policies against
|
|
9
|
-
* zero
|
|
9
|
+
* zero tables. Any exception at all — a table file that throws on
|
|
10
10
|
* import, a `pg_policies` read the CI role is not granted, a connection reset —
|
|
11
11
|
* did the same thing through a `warn`, and exited 0.
|
|
12
12
|
*/
|
|
@@ -20,9 +20,9 @@ export type PolicyCheckStatus = "ok" | "problems" | "unchecked";
|
|
|
20
20
|
*/
|
|
21
21
|
export declare function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1;
|
|
22
22
|
/**
|
|
23
|
-
* Policies actually deployed vs the ones the
|
|
23
|
+
* Policies actually deployed vs the ones the tables describe, plus policy
|
|
24
24
|
* roles this server could never satisfy.
|
|
25
25
|
*
|
|
26
26
|
* Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.
|
|
27
27
|
*/
|
|
28
|
-
export declare function runPolicyChecks(
|
|
28
|
+
export declare function runPolicyChecks(schemaDir: string, databaseUrl?: string): Promise<PolicyCheckStatus>;
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TableDescriptor } from "@rebasepro/types";
|
|
2
2
|
/** Above this many rows an unindexed search is worth a word. */
|
|
3
3
|
export declare const UNINDEXED_SEARCH_ROWS = 10000;
|
|
4
|
-
/** A
|
|
5
|
-
export interface
|
|
4
|
+
/** A table whose search would be `ILIKE` over these columns. */
|
|
5
|
+
export interface IlikeSearchedTable {
|
|
6
6
|
slug: string;
|
|
7
7
|
schema: string;
|
|
8
8
|
table: string;
|
|
9
|
-
/** The
|
|
9
|
+
/** The keys of the text columns the search reads. */
|
|
10
10
|
fields: string[];
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
|
-
* The
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
13
|
+
* The tables a search reaches without an index: no `search` block (or one
|
|
14
|
+
* that does not build), and at least one column the default search reads —
|
|
15
|
+
* text, without `.oneOf()` ({@link isIlikeSearchable}, the rule the search
|
|
16
|
+
* conditions use).
|
|
17
17
|
*/
|
|
18
|
-
export declare function
|
|
18
|
+
export declare function ilikeSearchedTables(tables: readonly TableDescriptor[]): IlikeSearchedTable[];
|
|
19
19
|
/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */
|
|
20
|
-
export declare function unindexedSearchFindings(candidates:
|
|
20
|
+
export declare function unindexedSearchFindings(candidates: IlikeSearchedTable[], rowEstimates: ReadonlyMap<string, number>, threshold?: number): (IlikeSearchedTable & {
|
|
21
21
|
rows: number;
|
|
22
22
|
})[];
|
|
23
23
|
/**
|
|
@@ -33,13 +33,13 @@ export declare function estimateRowCounts(query: (text: string, values: unknown[
|
|
|
33
33
|
rows: string | number;
|
|
34
34
|
}[];
|
|
35
35
|
}>, schemas: string[]): Promise<Map<string, number>>;
|
|
36
|
-
/** The report, one warning per
|
|
37
|
-
export declare function formatUnindexedSearches(findings: (
|
|
36
|
+
/** The report, one warning per table. */
|
|
37
|
+
export declare function formatUnindexedSearches(findings: (IlikeSearchedTable & {
|
|
38
38
|
rows: number;
|
|
39
39
|
})[]): string[];
|
|
40
40
|
/**
|
|
41
|
-
* Print the warning for the project at `
|
|
41
|
+
* Print the warning for the project at `schemaDir`, against
|
|
42
42
|
* `databaseUrl`. Never throws and never fails the run: it is a hint, and a
|
|
43
43
|
* check that could not run says so in one grey line.
|
|
44
44
|
*/
|
|
45
|
-
export declare function runSearchScaleCheck(
|
|
45
|
+
export declare function runSearchScaleCheck(schemaDir: string, databaseUrl?: string): Promise<void>;
|