@rebasepro/server-postgres 0.17.3 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +0 -1
- package/README.md +31 -0
- package/dist/BranchService-ByLfM_Tt.js +360 -0
- package/dist/BranchService-ByLfM_Tt.js.map +1 -0
- package/dist/__vite-browser-external-BnuHet1e.js +46 -0
- package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
- package/dist/arg-Dni7MzLB.js +87 -0
- package/dist/arg-Dni7MzLB.js.map +1 -0
- package/dist/auth-users-columns-D2LBFrMH.js +116 -0
- package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
- package/dist/backup-argv.d.ts +19 -0
- package/dist/backup-cli-oM9WQVlV.js +408 -0
- package/dist/backup-cli-oM9WQVlV.js.map +1 -0
- package/dist/backup-service-Br3tqwsy.js +715 -0
- package/dist/backup-service-Br3tqwsy.js.map +1 -0
- package/dist/branch-argv.d.ts +28 -0
- package/dist/branch-prune.d.ts +77 -0
- package/dist/cli-collections-path.d.ts +31 -0
- package/dist/cli-errors-DxN4yzdH.js +657 -0
- package/dist/cli-errors-DxN4yzdH.js.map +1 -0
- package/dist/cli-errors.d.ts +123 -0
- package/dist/cli-flags.d.ts +101 -0
- package/dist/cli-helpers.d.ts +94 -10
- package/dist/cli-output-CNdMql-L.js +47 -0
- package/dist/cli-output-CNdMql-L.js.map +1 -0
- package/dist/cli.js +2020 -0
- package/dist/cli.js.map +1 -0
- package/dist/collection-index-BHgT_TKd.js +276 -0
- package/dist/collection-index-BHgT_TKd.js.map +1 -0
- package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
- package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
- package/dist/{connection-GOKU3Hu5.js → databasePoolManager-Bj5FbeAs.js} +112 -40
- package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
- package/dist/databasePoolManager.d.ts +27 -0
- package/dist/doctor-D7HWmGzs.js +974 -0
- package/dist/doctor-D7HWmGzs.js.map +1 -0
- package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-2c2NV8zX.js} +7 -27
- package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
- package/dist/ensure-tables-CIojK-Rx.js +650 -0
- package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
- package/dist/{ensure-collection-tables-DgVixhX3.js → generate-postgres-ddl-logic-CtnpIBVv.js} +126 -984
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.es.js +7423 -1133
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
- package/dist/policy-drift-kNJ6X2Uj.js +313 -0
- package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
- package/dist/{backup-service-DCk7KhhL.js → rls-bootstrap-sql-DLDnUjtx.js} +737 -2689
- package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
- package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-DeYEjYLt.js} +65 -190
- package/dist/rls-enforcement-DeYEjYLt.js.map +1 -0
- package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/column-type-drift.d.ts +79 -0
- package/dist/schema/doctor-cli.js +129 -0
- package/dist/schema/doctor-cli.js.map +1 -0
- package/dist/schema/doctor.d.ts +42 -0
- package/dist/schema/ensure-collection-tables.d.ts +90 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema.js +24 -0
- package/dist/schema/generate-drizzle-schema.js.map +1 -0
- package/dist/schema/generate-next-step.d.ts +30 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl.js +138 -0
- package/dist/schema/generate-postgres-ddl.js.map +1 -0
- package/dist/schema/generated-schema-staleness.d.ts +37 -0
- package/dist/schema/introspect-db-queries.d.ts +34 -0
- package/dist/schema/introspect-db.js +866 -0
- package/dist/schema/introspect-db.js.map +1 -0
- package/dist/security/rls-enforcement.d.ts +63 -2
- package/dist/services/BranchService.d.ts +86 -1
- package/dist/services/collection-helpers.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +30 -2
- package/dist/services/row-pipeline.d.ts +12 -1
- package/dist/source-Br7L7GOI.js +410 -0
- package/dist/source-Br7L7GOI.js.map +1 -0
- package/dist/utils/pg-error-utils.d.ts +3 -1
- package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
- package/dist/vector-index-DkWxm2de.js +309 -0
- package/dist/vector-index-DkWxm2de.js.map +1 -0
- package/package.json +32 -27
- package/dist/backup-service-DCk7KhhL.js.map +0 -1
- package/dist/collection-index-BRUg10H5.js +0 -5690
- package/dist/collection-index-BRUg10H5.js.map +0 -1
- package/dist/connection-GOKU3Hu5.js.map +0 -1
- package/dist/ensure-collection-policies-UCqgv_8c.js.map +0 -1
- package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
- package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
- package/dist/src-DiB5RP2Z.js +0 -541
- package/dist/src-DiB5RP2Z.js.map +0 -1
- package/dist/websocket-BZ4H5wUz.js +0 -8198
- package/dist/websocket-BZ4H5wUz.js.map +0 -1
- package/src/PostgresAdapter.ts +0 -91
- package/src/PostgresBackendDriver.ts +0 -1857
- package/src/PostgresBootstrapper.ts +0 -1157
- package/src/auth/ensure-tables.ts +0 -896
- package/src/auth/schema-version.ts +0 -260
- package/src/auth/services.ts +0 -1610
- package/src/backup/backup-cli.ts +0 -520
- package/src/backup/backup-cron.ts +0 -212
- package/src/backup/backup-logic.ts +0 -93
- package/src/backup/backup-service.ts +0 -485
- package/src/backup/index.ts +0 -12
- package/src/backup/pg-tools.ts +0 -403
- package/src/backup/retention.ts +0 -86
- package/src/cli-errors.ts +0 -265
- package/src/cli-helpers.ts +0 -569
- package/src/cli-output.ts +0 -43
- package/src/cli.ts +0 -1339
- package/src/collections/PostgresCollectionRegistry.ts +0 -108
- package/src/collections/buildRegistry.ts +0 -68
- package/src/collections/validate-relations.ts +0 -402
- package/src/connection.ts +0 -333
- package/src/data-transformer.ts +0 -845
- package/src/databasePoolManager.ts +0 -95
- package/src/history/HistoryService.ts +0 -254
- package/src/history/ensure-history-table.ts +0 -53
- package/src/index.ts +0 -19
- package/src/interfaces.ts +0 -60
- package/src/module-dir.ts +0 -7
- package/src/schema/atlas-argv.ts +0 -94
- package/src/schema/auth-schema.ts +0 -298
- package/src/schema/auth-users-columns.ts +0 -131
- package/src/schema/carved-out-migration.ts +0 -404
- package/src/schema/classify-change.ts +0 -436
- package/src/schema/collection-index.ts +0 -427
- package/src/schema/collections-schema-version.ts +0 -103
- package/src/schema/destructive-sql.ts +0 -94
- package/src/schema/doctor-cli.ts +0 -66
- package/src/schema/doctor-policy-checks.ts +0 -105
- package/src/schema/doctor.ts +0 -837
- package/src/schema/drizzle-ddl.ts +0 -33
- package/src/schema/dynamic-tables.test.ts +0 -302
- package/src/schema/dynamic-tables.ts +0 -293
- package/src/schema/ensure-collection-policies.ts +0 -198
- package/src/schema/ensure-collection-tables.test.ts +0 -518
- package/src/schema/ensure-collection-tables.ts +0 -1267
- package/src/schema/generate-drizzle-schema-logic.ts +0 -957
- package/src/schema/generate-drizzle-schema.ts +0 -143
- package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
- package/src/schema/generate-postgres-ddl.ts +0 -180
- package/src/schema/generate-schema-commit.ts +0 -267
- package/src/schema/generated-schema-staleness.ts +0 -284
- package/src/schema/introspect-db-constraints.ts +0 -385
- package/src/schema/introspect-db-inference.ts +0 -255
- package/src/schema/introspect-db-logic.ts +0 -1387
- package/src/schema/introspect-db-naming.ts +0 -15
- package/src/schema/introspect-db-project.ts +0 -78
- package/src/schema/introspect-db-queries.ts +0 -326
- package/src/schema/introspect-db-structure.ts +0 -670
- package/src/schema/introspect-db-types.ts +0 -56
- package/src/schema/introspect-db.ts +0 -257
- package/src/schema/introspect-runtime.test.ts +0 -260
- package/src/schema/introspect-runtime.ts +0 -327
- package/src/schema/non-sql-collections.test.ts +0 -131
- package/src/schema/rls-bootstrap-sql.ts +0 -288
- package/src/schema/search-column.ts +0 -643
- package/src/schema/test-schema.ts +0 -11
- package/src/schema/vector-index.ts +0 -491
- package/src/security/anonymous-grants.test.ts +0 -73
- package/src/security/policy-drift.test.ts +0 -435
- package/src/security/policy-drift.ts +0 -473
- package/src/security/rls-enforcement.ts +0 -505
- package/src/services/BranchService.ts +0 -326
- package/src/services/FetchService.ts +0 -2115
- package/src/services/PersistService.ts +0 -557
- package/src/services/RelationService.ts +0 -978
- package/src/services/RelationWriteService.ts +0 -653
- package/src/services/cdc/CdcListener.ts +0 -103
- package/src/services/cdc/junction-tables.ts +0 -91
- package/src/services/cdc/trigger-cdc.ts +0 -173
- package/src/services/channel-bus/ChannelBus.ts +0 -44
- package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
- package/src/services/channel-bus/index.ts +0 -114
- package/src/services/channel-history.ts +0 -424
- package/src/services/channel-presence.ts +0 -185
- package/src/services/collection-helpers.ts +0 -420
- package/src/services/dataService.ts +0 -256
- package/src/services/index.ts +0 -14
- package/src/services/junction-writes.ts +0 -295
- package/src/services/nested-path.ts +0 -145
- package/src/services/pg-notify-listener.ts +0 -151
- package/src/services/realtimeService.ts +0 -2545
- package/src/services/row-pipeline.ts +0 -240
- package/src/services/write-denial.ts +0 -55
- package/src/types.ts +0 -4
- package/src/utils/connection-string.ts +0 -58
- package/src/utils/drizzle-conditions.ts +0 -2743
- package/src/utils/pg-array-null-patch.ts +0 -42
- package/src/utils/pg-error-utils.ts +0 -391
- package/src/websocket.ts +0 -855
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-errors-DxN4yzdH.js","names":[],"sources":["../src/utils/pg-error-utils.ts","../src/cli-errors.ts"],"sourcesContent":["/**\n * Shared PostgreSQL error extraction and user-friendly message formatting.\n *\n * Drizzle wraps native PG errors in a `.cause` chain. These utilities\n * unwrap that chain to get the real PostgreSQL error (identified by a\n * 5-character alphanumeric `code` such as `42P01`) and translate it into\n * a message that is safe and helpful to show to end-users.\n */\n\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Shape of a deliberate client-facing error — `ApiError` from\n * `@rebasepro/server`, or anything else carrying a 4xx `statusCode`.\n *\n * Matched structurally rather than with `instanceof`: `@rebasepro/server` can\n * be loaded twice (published dist vs. workspace source), which breaks class\n * identity — `PersistService` hedges against the same thing by also accepting\n * `name === \"ApiError\"`.\n */\ninterface ClientFacingError extends Error {\n statusCode?: number;\n code?: string;\n /** See `ApiError.expected` — routine outcomes log at debug, not warn. */\n expected?: boolean;\n}\n\n/**\n * Return the error when it is a deliberate 4xx, otherwise null.\n *\n * A thrown `ApiError` is a decision the server made about the request, not a\n * database failure: its message and code are already written for the client.\n */\nfunction asClientFacingError(error: unknown): ClientFacingError | null {\n if (!(error instanceof Error)) return null;\n const e = error as ClientFacingError;\n if (typeof e.statusCode !== \"number\" || e.statusCode < 400 || e.statusCode >= 500) return null;\n return e;\n}\n\n/** Shape of PostgreSQL errors with diagnostic metadata. */\nexport interface PostgresError extends Error {\n code?: string;\n detail?: string;\n hint?: string;\n constraint?: string;\n column?: string;\n table?: string;\n dataType?: string;\n cause?: unknown;\n}\n\n/**\n * Extract the underlying PostgreSQL error from a Drizzle wrapper.\n * Drizzle wraps PG errors in a `cause` property — this function\n * recursively walks the chain until it finds an object with a PG\n * error code (5-char alphanumeric, e.g. `42P01`).\n */\nexport function extractPgError(error: unknown): PostgresError | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) {\n // Check non-Error objects for a cause chain (Drizzle sometimes wraps oddly)\n if (\"cause\" in error && (error as Record<string, unknown>).cause && typeof (error as Record<string, unknown>).cause === \"object\") {\n return extractPgError((error as Record<string, unknown>).cause);\n }\n return null;\n }\n\n // Check if the error itself has a PG error code\n if (\"code\" in error && typeof (error as PostgresError).code === \"string\" && /^[0-9A-Z]{5}$/.test((error as PostgresError).code!)) {\n return error as PostgresError;\n }\n\n // Check the cause chain (Drizzle wraps PG errors)\n if (error.cause && typeof error.cause === \"object\") {\n return extractPgError(error.cause);\n }\n\n return null;\n}\n\n/**\n * Whether the failure came back from Postgres rather than from building the\n * query — which decides whether a fallback query is worth issuing.\n *\n * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds\n * RLS). Once a statement raises, that transaction is aborted, and every later\n * statement on it returns `25P02` — \"current transaction is aborted, commands\n * ignored until end of transaction block\". So a retry after a database error\n * cannot succeed, and it replaces a precise diagnosis (\"invalid input syntax\n * for type uuid\") with a generic one. Rethrow instead.\n *\n * A query the driver could not even build — a missing reciprocal relation, say\n * — never reached Postgres, leaves the transaction usable, and is exactly what\n * the fallback paths exist for.\n */\nexport function reachedDatabase(error: unknown): boolean {\n return extractPgError(error) !== null;\n}\n\n/**\n * Walk the error cause chain and return the deepest meaningful message.\n */\nexport function extractCauseMessage(error: unknown): string | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) return null;\n\n if (error.cause && typeof error.cause === \"object\") {\n const deeper = extractCauseMessage(error.cause);\n if (deeper) return deeper;\n // The cause itself has a message\n if (error.cause instanceof Error && error.cause.message) {\n return error.cause.message;\n }\n }\n return null;\n}\n\n/**\n * Codes that mean \"this connection will never work as configured\".\n *\n * A wrong password or a database that does not exist is a settled fact about\n * the connection string, not a transient fault — retrying produces the same\n * answer forever.\n */\nconst UNRECOVERABLE_CONNECT_CODES = new Set([\n \"28P01\", // invalid_password\n \"28000\", // invalid_authorization_specification\n \"3D000\", // invalid_catalog_name — the database does not exist\n \"42501\" // insufficient_privilege\n]);\n\nexport interface ConnectFailure {\n /** True when retrying cannot help: the connection string itself is wrong. */\n fatal: boolean;\n /** The deepest message available — the Postgres one where there is one. */\n reason: string;\n /** The `SQLSTATE`, when the failure came from Postgres rather than the socket. */\n code?: string;\n}\n\n/**\n * Describe a failed connection attempt in terms a developer can act on.\n *\n * The error a caller catches is Drizzle's wrapper: its message is\n * `Failed query: SELECT 1` and its stack runs through drizzle internals, while\n * the sentence that says what is actually wrong — \"password authentication\n * failed for user …\", \"database … does not exist\" — sits in `.cause`. Logging\n * the wrapper, as the bootstrapper used to, tells a developer with a typo in\n * their `DATABASE_URL` nothing at all.\n */\nexport function classifyConnectFailure(error: unknown): ConnectFailure {\n const pgError = extractPgError(error);\n const reason =\n pgError?.message ??\n extractCauseMessage(error) ??\n (error instanceof Error ? error.message : String(error));\n return {\n fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),\n reason,\n code: pgError?.code\n };\n}\n\n/**\n * Detect whether an error is specifically a role-switching permission failure\n * (e.g. \"permission denied to set role\" or \"must be member of role\"),\n * as opposed to a table-level permission denial.\n *\n * This is used by the backend driver to auto-disable role switching when the\n * connection user lacks SET ROLE privileges, rather than surfacing a confusing\n * error to the Studio SQL Editor user.\n */\nexport function isRoleSwitchingPermissionError(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n const msg = pgError.message.toLowerCase();\n return msg.includes(\"set role\") || msg.includes(\"member of role\");\n}\n\n/**\n * Was this `42501` the *caller* being refused by a policy, rather than the\n * server lacking a privilege?\n *\n * Both arrive as `insufficient_privilege`, and they are opposite kinds of\n * problem. A row-level-security refusal is a working access-control system\n * doing its job: the caller asked for something their policies do not permit,\n * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being\n * wrong — the connection role cannot touch the table at all, no policy is\n * involved, and nothing the caller changes about the request will help.\n *\n * Postgres distinguishes them in the message, so this does too:\n *\n * new row violates row-level security policy for table \"notes\" → the caller\n * permission denied for table notes → the server\n *\n * Only writes reach this. A read that RLS excludes is not an error — the rows\n * are filtered and the caller gets an empty page — so the erroring case is\n * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.\n *\n * Matched on the message because that is the only thing carrying the\n * distinction; the SQLSTATE is identical either way. Narrow by design: anything\n * not naming row-level security stays the server's problem, since reporting a\n * genuine privilege misconfiguration as \"forbidden\" would send an operator\n * hunting for a policy bug that does not exist.\n */\nexport function isRowLevelSecurityDenial(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n return pgError.message.toLowerCase().includes(\"row-level security policy\");\n}\n\n/**\n * Translate a raw PostgreSQL error into a user-friendly message.\n *\n * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})\n * @param context - A human-readable context string (e.g. collection slug or path)\n * @returns An object with a `message` safe for the client and the PG `code`.\n */\nexport function pgErrorToFriendlyMessage(\n pgError: PostgresError,\n context: string,\n options: { verbose?: boolean } = {}\n): { message: string; code: string } {\n // Postgres's own `DETAIL` and `HINT`, and the raw driver message, are what\n // make these errors useful while you are building — and what makes them an\n // oracle once the server is answering strangers.\n //\n // The sharp one is `23505`: its detail reads `Key (email)=(a@b.c) already\n // exists.`, which answers \"is this person registered?\" for any address, on\n // a table whose rows RLS is otherwise hiding completely. The rest leak\n // physical column and constraint names, which are the map for the next\n // question. So in production the shape of the failure is served — what\n // rule was broken, and where — and the values are not.\n //\n // The full text is not lost: the caller logs the original error. This\n // decides what crosses the wire, not what is recorded.\n const verbose = options.verbose ?? process.env.NODE_ENV !== \"production\";\n\n const detail = verbose ? (pgError.detail as string | undefined) : undefined;\n const hint = verbose ? (pgError.hint as string | undefined) : undefined;\n const constraint = pgError.constraint as string | undefined;\n const column = pgError.column as string | undefined;\n const table = pgError.table as string | undefined;\n const dataType = verbose ? (pgError.dataType as string | undefined) : undefined;\n const rawMessage = pgError.message || \"Unknown database error\";\n const pgMessage = verbose ? rawMessage : \"\";\n const code = pgError.code || \"UNKNOWN\";\n\n const suffix = hint ? ` Hint: ${hint}` : \"\";\n const tableRef = table ?? context;\n\n /** `\": <postgres said>\"`, or nothing when the details are withheld. */\n const said = pgMessage ? `: ${pgMessage}` : \"\";\n\n switch (pgError.code) {\n case \"23503\": // foreign_key_violation\n return {\n message: detail\n ? `Foreign key constraint violated: ${detail}${suffix}`\n : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"23505\": // unique_violation\n return {\n message: detail\n ? `Duplicate value: ${detail}${suffix}`\n : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"23502\": // not_null_violation\n return {\n message: `Missing required field: \"${column ?? \"unknown\"}\" in \"${tableRef}\" cannot be empty.${suffix}`,\n code\n };\n case \"23514\": // check_violation\n return {\n message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code\n };\n case \"22P02\": // invalid_text_representation (e.g. invalid UUID, wrong enum value)\n return {\n message: `Invalid data format in \"${context}\"${said}.${suffix}`,\n code\n };\n case \"22001\": // string_data_right_truncation (value too long)\n return {\n message: `Value too long for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code\n };\n case \"22003\": // numeric_value_out_of_range\n return {\n message: `Numeric value out of range for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code\n };\n case \"42703\": // undefined_column\n return {\n message: `Unknown column in \"${tableRef}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code\n };\n case \"42P01\": // undefined_table\n return {\n message: `Table not found for \"${context}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code\n };\n case \"42501\": // insufficient_privilege\n // Two unrelated failures share this SQLSTATE, and the old message\n // named both causes because it could not tell them apart — which\n // meant it was half wrong whichever one had happened, and sent the\n // reader to check the other. Postgres says which in its own message.\n return rawMessage.toLowerCase().includes(\"row-level security policy\")\n ? {\n // The caller. Their policies do not permit this row; the\n // deployment is working exactly as configured.\n message: `Not permitted to write this row in \"${tableRef}\": it does not satisfy the row-level security policy.${suffix}`,\n code\n }\n : {\n // The deployment. No policy is involved — the connecting\n // role cannot touch the table at all.\n message: `Permission denied on \"${tableRef}\": the database role this server connects as lacks privileges on it.${suffix}`,\n code\n };\n case \"28000\": // invalid_authorization_specification\n return {\n message: `Authorization failed for \"${context}\". Check your database credentials.${suffix}`,\n code\n };\n default: {\n // Unhandled PG code — still surface the actual database message\n const parts = [`Database error in \"${context}\" [${code}]${said}`];\n if (detail) parts.push(`Detail: ${detail}`);\n if (column) parts.push(`Column: ${column}`);\n if (dataType) parts.push(`Data type: ${dataType}`);\n if (constraint) parts.push(`Constraint: ${constraint}`);\n if (hint) parts.push(`Hint: ${hint}`);\n return { message: parts.join(\". \"), code };\n }\n }\n}\n\n/**\n * Sanitize any error into a message safe and helpful for the client.\n *\n * A deliberate 4xx (`ApiError`) passes through untouched — the server already\n * decided what the client should read. Otherwise the PG error is extracted\n * from the Drizzle cause chain, falling back to a generic message that\n * doesn't leak SQL.\n *\n * @param error - The raw caught error\n * @param context - A human-readable context string (e.g. collection path)\n * @returns An object with `message` (user-friendly) and optional `code`\n * (the `ApiError` code, or the PG SQLSTATE).\n */\nexport function sanitizeErrorForClient(error: unknown, context: string): { message: string; code?: string } {\n // ── A deliberate 4xx is not a database failure ──────────────────\n // Its message and code are written for the client; replacing them with\n // \"Check server logs\" would discard the only diagnosis the caller gets\n // (e.g. the offending filter field and the collection's valid ones).\n // Log level follows the same convention as the HTTP error handler in\n // @rebasepro/server: routine outcomes at debug, everything else at warn.\n const clientError = asClientFacingError(error);\n if (clientError) {\n const line = `[API ${clientError.statusCode} ${clientError.code ?? \"BAD_REQUEST\"}] in \"${context}\": ${clientError.message}`;\n if (clientError.expected) {\n logger.debug(line);\n } else {\n logger.warn(`⚠️ ${line}`);\n }\n return { message: clientError.message, ...(clientError.code && { code: clientError.code }) };\n }\n\n // ── Always log the full, unsanitized error server-side ──────────\n const pgError = extractPgError(error);\n\n if (pgError) {\n logger.error(`[PG ${pgError.code}] Error in \"${context}\"`, {\n code: pgError.code,\n message: pgError.message,\n detail: pgError.detail,\n hint: pgError.hint,\n column: pgError.column,\n table: pgError.table,\n constraint: pgError.constraint,\n dataType: pgError.dataType\n // The outer Drizzle wrapper message used to be logged here \"for\n // full context\": it is `Failed query: <sql>\\nparams: <values>`, so\n // it published the statement and every bound value (an email, a\n // password hash) on every realtime data failure. The SQLSTATE,\n // detail, table, column and constraint above are the diagnostic\n // value; the wrapper added only the leak. `logger` strips the\n // wrapper as well, but the field itself carried nothing else.\n });\n return pgErrorToFriendlyMessage(pgError, context);\n }\n\n // No PG error found — log the raw error as-is\n logger.error(`Database error in \"${context}\" (no PG error extracted)`, {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n cause: error instanceof Error && error.cause\n ? (error.cause instanceof Error ? error.cause.message : String(error.cause))\n : undefined\n });\n\n // Try to get the deepest cause message\n const causeMessage = extractCauseMessage(error);\n if (causeMessage) {\n return { message: `Database error in \"${context}\": ${causeMessage}` };\n }\n\n // Last resort — generic message, never leak raw SQL\n return { message: `Could not load data for \"${context}\". Check server logs for details.` };\n}\n","import chalk from \"chalk\";\nimport { outWarn, outError } from \"./cli-output\";\nimport { extractCauseMessage } from \"./utils/pg-error-utils\";\n\n/**\n * Detect whether an error (or AggregateError wrapping multiple attempts)\n * represents an ECONNREFUSED — i.e. the database is simply not running.\n *\n * Handles:\n * - Direct `{ code: \"ECONNREFUSED\" }` errors from Node `net`\n * - `AggregateError` from dual-stack IPv4+IPv6 connection attempts\n * - Drizzle's `cause`-wrapped pg errors\n */\nexport function isEconnrefused(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; cause?: unknown; errors?: unknown[] };\n if (e.code === \"ECONNREFUSED\") return true;\n // AggregateError from Node net (dual-stack IPv4 + IPv6)\n if (Array.isArray(e.errors)) {\n return e.errors.some(inner =>\n inner && typeof inner === \"object\" && (inner as { code?: string }).code === \"ECONNREFUSED\"\n );\n }\n // Drizzle wraps the pg error in `cause`\n if (e.cause && typeof e.cause === \"object\") {\n return isEconnrefused(e.cause);\n }\n return false;\n}\n\n/**\n * Detect PostgreSQL authentication failures.\n * PG error codes: 28P01 (invalid_password), 28000 (invalid_authorization_specification)\n */\nexport function isAuthFailure(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; cause?: unknown };\n if (e.code === \"28P01\" || e.code === \"28000\") return true;\n if (e.cause && typeof e.cause === \"object\") {\n return isAuthFailure(e.cause);\n }\n // Also check the message for common pg auth failure text\n if (\"message\" in e && typeof (e as { message?: string }).message === \"string\") {\n const msg = (e as { message: string }).message.toLowerCase();\n if (msg.includes(\"password authentication failed\") || msg.includes(\"no pg_hba.conf entry\")) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Detect the \"SSL is not enabled on the server\" failure — the client attempted\n * an SSL handshake against a Postgres server that doesn't support it (common\n * with a plain local dev database). The fix is `?sslmode=disable` on the URL.\n */\nexport function isSslNotEnabled(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { message?: string; cause?: unknown };\n if (typeof e.message === \"string\" && e.message.toLowerCase().includes(\"ssl is not enabled on the server\")) {\n return true;\n }\n if (e.cause && typeof e.cause === \"object\") {\n return isSslNotEnabled(e.cause);\n }\n return false;\n}\n\n/**\n * Detect PostgreSQL \"cannot drop ... because other objects depend on it\"\n * (error code 2BP01, dependent_objects_still_exist). This is the failure that\n * strands a declarative `db push` half-applied when a collection is removed but\n * an enum type it defined is still referenced by another object.\n */\nexport function isDependencyDropError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; message?: string; cause?: unknown };\n if (e.code === \"2BP01\") return true;\n if (typeof e.message === \"string\") {\n const msg = e.message.toLowerCase();\n if (msg.includes(\"other objects depend on it\") || msg.includes(\"cannot drop type\")) {\n return true;\n }\n }\n if (e.cause && typeof e.cause === \"object\") {\n return isDependencyDropError(e.cause);\n }\n return false;\n}\n\n/**\n * Parse host:port from a DATABASE_URL for display purposes.\n *\n * Exported because every message about a connection has to name the thing it\n * could not reach, and the boot path needs the same rendering the CLI banners\n * use — including the same refusal to print the URL itself, which carries the\n * password.\n */\nexport function parseHostInfo(databaseUrl: string): string {\n try {\n const parsed = new URL(databaseUrl);\n return `${parsed.hostname}:${parsed.port || 5432}`;\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * The sentence the operating system actually produced, dug out of the wrappers.\n *\n * `connect ECONNREFUSED 127.0.0.1:5432` is written by `net`, then wrapped by\n * `pg`, then wrapped again by Drizzle as `Failed query: …` — and on a\n * dual-stack host it is not in `.cause` at all but inside the\n * `AggregateError.errors` array of one attempt per resolved address. Printing\n * the banner without it loses the one token every search engine, runbook and\n * colleague recognises.\n */\nexport function deepestErrorMessage(err: unknown): string | null {\n if (!err || typeof err !== \"object\") return null;\n const e = err as { message?: string; code?: string; cause?: unknown; errors?: unknown[] };\n\n if (Array.isArray(e.errors)) {\n for (const inner of e.errors) {\n const deeper = deepestErrorMessage(inner);\n if (deeper) return deeper;\n }\n }\n if (e.cause) {\n const deeper = deepestErrorMessage(e.cause);\n if (deeper) return deeper;\n }\n if (typeof e.message === \"string\" && e.message && !e.message.startsWith(\"Failed query:\")) {\n return e.code ? `${e.message} (${e.code})` : e.message;\n }\n return null;\n}\n\n/** One indented line naming the driver's own reason, or nothing. */\nfunction driverReasonLine(err: unknown): string {\n const reason = err === undefined ? null : deepestErrorMessage(err);\n return reason ? ` The driver said: ${reason}\\n\\n` : \"\";\n}\n\n/**\n * Format a diagnostic banner for ECONNREFUSED errors.\n */\nfunction formatConnectionRefusedBanner(databaseUrl: string, err?: unknown): string {\n const hostInfo = parseHostInfo(databaseUrl);\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Cannot connect to PostgreSQL at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n driverReasonLine(err) +\n ` The database server is not running or is not accepting\\n` +\n ` connections. Common fixes:\\n` +\n `\\n` +\n ` • docker compose up -d db (the service a Rebase scaffold ships)\\n` +\n ` • brew services start postgresql@18\\n` +\n ` • Verify DATABASE_URL in your .env file\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for authentication failures.\n */\nfunction formatAuthFailureBanner(databaseUrl: string, err?: unknown): string {\n const hostInfo = parseHostInfo(databaseUrl);\n let username = \"unknown\";\n try {\n username = new URL(databaseUrl).username || \"unknown\";\n } catch { /* ignore */ }\n\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Authentication failed for user \"${username}\" at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n driverReasonLine(err) +\n ` PostgreSQL rejected the credentials. Common fixes:\\n` +\n `\\n` +\n ` • Check the username and password in DATABASE_URL\\n` +\n ` • Verify the user exists: psql -c \"\\\\du\"\\n` +\n ` • Reset the password: ALTER USER ${username} PASSWORD 'new_password';\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for \"SSL is not enabled on the server\".\n */\nfunction formatSslNotEnabledBanner(databaseUrl: string): string {\n const hostInfo = parseHostInfo(databaseUrl);\n const suggestion = databaseUrl.includes(\"?\") ? \"&sslmode=disable\" : \"?sslmode=disable\";\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ SSL is not enabled on the PostgreSQL server at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` The client tried to connect over SSL, but the server does not\\n` +\n ` support it. This is normal for a plain local dev database.\\n` +\n `\\n` +\n ` Fix: append ${chalk.bold(\"sslmode=disable\")} to DATABASE_URL, e.g.\\n` +\n `\\n` +\n ` DATABASE_URL=...${suggestion}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for a dependency-drop failure during `db push`.\n * Explains that the database may be left partially migrated and how to recover.\n */\nfunction formatDependencyDropBanner(): string {\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Schema push failed: a type/table could not be dropped\\n` +\n ` because other objects still depend on it.\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` ${chalk.yellow(\"The database may now be partially migrated.\")} Atlas applies\\n` +\n ` statements individually, so earlier changes in this push may\\n` +\n ` already be committed while later ones failed.\\n` +\n `\\n` +\n ` This commonly happens when a collection is removed but an enum\\n` +\n ` type it defined is still referenced. To recover:\\n` +\n `\\n` +\n ` 1. Inspect the leftover object named in the error above.\\n` +\n ` 2. Drop it with CASCADE, e.g.:\\n` +\n ` psql \"$DATABASE_URL\" -c 'DROP TYPE \"<name>\" CASCADE;'\\n` +\n ` 3. Re-run: ${chalk.bold.green(\"rebase db push\")}\\n` +\n `\\n` +\n ` Prefer a safe, versioned workflow? Use ${chalk.bold(\"rebase db generate\")}\\n` +\n ` + ${chalk.bold(\"rebase db migrate\")} instead of push for destructive changes.\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Pre-flight check: verify that the database is reachable before running\n * a heavy subprocess (Atlas, migrations, etc.).\n *\n * Exits with code 1 and a friendly banner on known failure modes.\n * On unknown errors, logs a warning and allows the caller to proceed.\n */\nexport async function checkDatabaseConnectivity(databaseUrl: string): Promise<void> {\n let client: import(\"pg\").Client | undefined;\n try {\n const { Client } = await import(\"pg\");\n client = new Client({\n connectionString: databaseUrl,\n connectionTimeoutMillis: 5000\n });\n await client.connect();\n await client.query(\"SELECT 1\");\n } catch (err: unknown) {\n if (isEconnrefused(err)) {\n outError(formatConnectionRefusedBanner(databaseUrl, err));\n process.exit(1);\n }\n if (isAuthFailure(err)) {\n outError(formatAuthFailureBanner(databaseUrl, err));\n process.exit(1);\n }\n if (isSslNotEnabled(err)) {\n outError(formatSslNotEnabledBanner(databaseUrl));\n process.exit(1);\n }\n // Unknown error — warn but don't block; let the downstream tool surface details\n outWarn(chalk.yellow(` ⚠ Could not verify database connectivity: ${err instanceof Error ? err.message : String(err)}`));\n outWarn(chalk.gray(\" Proceeding anyway — the command may fail if the database is unreachable.\"));\n } finally {\n try {\n await client?.end();\n } catch {\n // ignore cleanup errors\n }\n }\n}\n\n/**\n * Post-hoc error diagnosis for direct database operations (e.g. applyPolicies).\n * Returns a formatted diagnostic string if the error matches a known pattern,\n * or null if unrecognized.\n */\nexport function diagnoseDbError(err: unknown, databaseUrl?: string): string | null {\n if (isEconnrefused(err)) {\n return formatConnectionRefusedBanner(databaseUrl || \"\", err);\n }\n if (isAuthFailure(err)) {\n return formatAuthFailureBanner(databaseUrl || \"\", err);\n }\n if (isSslNotEnabled(err)) {\n return formatSslNotEnabledBanner(databaseUrl || \"\");\n }\n if (isDependencyDropError(err)) {\n return formatDependencyDropBanner();\n }\n return null;\n}\n\n/**\n * Say why the command failed, on the way out.\n *\n * The entry point below used to be `.catch(() => process.exit(1))`, which threw\n * the error away. Every message this file and its services raise — \"Branch\n * \\\"x\\\" already exists.\", \"the source database has active connections\", \"Branch\n * name is too long\" — was written, wrapped in the right PG error code, and then\n * discarded one frame before it reached a terminal. What a developer saw was a\n * header line, no error, and exit 1.\n *\n * Two shapes are deliberately kept quiet:\n *\n * - **A child process that already spoke.** Atlas, `pg_dump` and `psql` run\n * with inherited stdio, so their diagnosis is on the terminal already and\n * execa's wrapper adds only `Command failed with exit code 1: atlas …`.\n * `packages/cli` filters exactly these two phrasings one level up\n * (`runDbCommand`), and this is that filter, for the process that is actually\n * throwing.\n *\n * - **A message that is only a query.** Drizzle reports failures as\n * `Failed query: <sql> params:` and hides the real PostgreSQL error in\n * `cause`, so the wrapper alone tells a reader nothing they can act on. The\n * cause is appended when it says something the message does not.\n *\n * - **An error that has already printed its own diagnosis**, marked\n * `alreadyReported`. `CollectionsPathMissing` is one: it prints the path, what\n * it resolved to and the cwd it resolved against, and then throws so the entry\n * point owns the exit code. Repeating its one-line summary underneath would\n * undo the \"printed once\" this whole path exists for.\n */\nexport function reportCommandFailure(error: unknown): void {\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n\n if ((error as { alreadyReported?: boolean } | null)?.alreadyReported) return;\n if (!message || /Command failed|exited with code/i.test(message)) return;\n\n outError(\"\");\n outError(chalk.red(` ✗ ${message}`));\n\n const cause = extractCauseMessage(error);\n if (cause && !message.includes(cause)) {\n outError(chalk.gray(` ${cause}`));\n }\n outError(\"\");\n}\n\n/* ------------------------------------------------------------------------- *\n * Atlas failures that have a remedy\n *\n * Atlas runs with a teed stderr, so what reaches these is its output as text,\n * not a `pg` error object carrying a `code`. They are deliberately NOT part of\n * `diagnoseDbError`: that one is shared with the boot path, and \"record a\n * baseline with `rebase db migrate`\" is advice for somebody standing at a\n * terminal, not for a container that has just failed to start.\n * ------------------------------------------------------------------------- */\n\n/**\n * `migrate apply` refusing because the database already has the schema.\n *\n * `42710` (duplicate_object) and `42P07` (duplicate_table) are what a migration\n * hits when boot-ensure — or a `db push` — has already provisioned the objects\n * it was going to create. Since boot-ensure provisions *every* production\n * database, this is the normal case rather than the exotic one, and the raw\n * failure (`pq: type \"posts_status\" already exists (42710)`, then `sql/migrate:\n * write revision: … current transaction is aborted`) names no way forward.\n */\nexport function parseAlreadyProvisioned(text: string): { object: string; code: string } | null {\n const withCode = /(?:type|relation|constraint|schema) \"([^\"]+)\" already exists \\((42710|42P07)\\)/.exec(text);\n if (withCode) return { object: withCode[1], code: withCode[2] };\n // Some Atlas builds keep the SQLSTATE on a following line instead.\n const bare = /(?:type|relation|constraint|schema) \"([^\"]+)\" already exists/.exec(text);\n if (bare && /42710|42P07/.test(text)) return { object: bare[1], code: /42P07/.test(text) ? \"42P07\" : \"42710\" };\n return null;\n}\n\n/**\n * What to do about it: tell Atlas the database is already at a version.\n *\n * Atlas's own mechanism (`migrate apply --baseline <version>`), not a ledger of\n * ours — it writes the revision row Atlas reads, so every later `rebase db\n * migrate` is an ordinary one.\n */\nexport function formatBaselineRemedy(version: string | null, object?: string): string {\n const versionToken = version ?? \"<version>\";\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ This database already has the schema this migration creates\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n (object ? ` ${chalk.gray(`\"${object}\" is already there, so the migration cannot create it.`)}\\n\\n` : \"\") +\n ` Nothing is wrong with the migration — the database was provisioned\\n` +\n ` another way. Every Rebase boot ensures the schema, and ${chalk.bold(\"rebase db push\")}\\n` +\n ` applies it directly, so a database that has ever run either one is\\n` +\n ` ahead of a migration history that was never recorded.\\n` +\n `\\n` +\n ` Record where it already is, then migrate normally:\\n` +\n `\\n` +\n ` ${chalk.bold.green(`rebase db migrate --baseline ${versionToken}`)}\\n` +\n ` ${chalk.bold.green(\"rebase db migrate\")}\\n` +\n `\\n` +\n ` The baseline is the version already applied — the numeric prefix of\\n` +\n ` the migration file describing what is in the database now. Migrations\\n` +\n ` after it run; it and everything before it are marked done.\\n` +\n `\\n` +\n ` On a database nothing has ever booted against, none of this is needed.\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** `ALTER TABLE … SET NOT NULL` on a table that already holds rows (23502). */\nexport function parseNotNullViolation(text: string): { table: string; column: string } | null {\n const match = /column \"([^\"]+)\" of relation \"([^\"]+)\" contains null values/.exec(text);\n return match ? { table: match[2], column: match[1] } : null;\n}\n\n/**\n * The three ways out, because there is no fourth.\n *\n * Boot-ensure handles this case — it adds the column nullable and sets NOT NULL\n * only when the table is empty — so a push that dies here is strictly worse\n * than the boot that would have run instead, and the developer deserves to be\n * told which of the three they want rather than left with `pq: … contains null\n * values (23502)` and no next step.\n */\nexport function formatNotNullViolationBanner(\n violation: { table: string; column: string },\n rowCount: number | null\n): string {\n const { table, column } = violation;\n const rows = rowCount === null\n ? ` \"${table}\" already holds rows, and none of them has a value for \"${column}\".\\n`\n : ` \"${table}\" already holds ${rowCount} row${rowCount === 1 ? \"\" : \"s\"}, and they have no value for \"${column}\".\\n`;\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Cannot make \"${table}\".\"${column}\" required: existing rows are null\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n rows +\n ` PostgreSQL will not add the NOT NULL until every one of them does.\\n` +\n `\\n` +\n ` Three ways forward:\\n` +\n `\\n` +\n ` 1. Give the property a default, so the push can backfill:\\n` +\n ` ${chalk.gray(`{ type: \"string\", defaultValue: \"…\", validation: { required: true } }`)}\\n` +\n ` 2. Backfill by hand first, then push again:\\n` +\n ` ${chalk.gray(`psql \"$DATABASE_URL\" -c 'UPDATE \"${table}\" SET \"${column}\" = … WHERE \"${column}\" IS NULL;'`)}\\n` +\n ` 3. Leave it optional — take \\`validation.required\\` off the property.\\n` +\n `\\n` +\n ` ${chalk.gray(\"Nothing was applied for this column. `rebase dev` would have added it\")}\\n` +\n ` ${chalk.gray(\"nullable instead: boot sets NOT NULL only when it is safe.\")}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** Atlas refusing to remove a label from an enum — a renamed `enum` option id. */\nexport function parseEnumLabelDrop(text: string): { label: string; enumType: string } | null {\n const match = /dropping (?:enum )?value \"([^\"]+)\" from enum \"([^\"]+)\" is not supported/.exec(text);\n return match ? { label: match[1], enumType: match[2] } : null;\n}\n\n/**\n * Why the two paths disagree, and what retiring an option id actually costs.\n *\n * Boot-ensure adds enum labels and never removes one, so `rebase dev` accepts\n * the very edit that stops `db push` dead. PostgreSQL has no `ALTER TYPE …\n * DROP VALUE`: a label goes only by rewriting the type, which is a data\n * migration and not a schema push.\n */\nexport function formatEnumLabelDropBanner(drop: { label: string; enumType: string }): string {\n const { label, enumType } = drop;\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ \"${label}\" cannot be removed from the enum \"${enumType}\"\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` PostgreSQL has no ALTER TYPE … DROP VALUE. An option id can be added\\n` +\n ` to an enum but never taken out of one, so renaming an id reads as a\\n` +\n ` removal and a push cannot carry it.\\n` +\n `\\n` +\n ` ${chalk.yellow(\"Nothing was applied.\")} ${chalk.bold(\"rebase dev\")} accepts this same edit — boot adds\\n` +\n ` new labels and never removes one — so the two paths disagree by\\n` +\n ` design, and the old label would simply have stayed behind, unused.\\n` +\n `\\n` +\n ` To keep the id: put \"${label}\" back and change only its label text.\\n` +\n `\\n` +\n ` To retire it for real, it is a data migration:\\n` +\n `\\n` +\n ` 1. Add the new id alongside the old one, and push.\\n` +\n ` 2. Move the rows: ${chalk.gray(`UPDATE … SET … = '<new>' WHERE … = '${label}';`)}\\n` +\n ` 3. Rewrite the type, which is what actually drops the label:\\n` +\n ` ${chalk.gray(\"rebase db generate retire_option && rebase db migrate\")}\\n` +\n ` ${chalk.gray(\"(a migration can CREATE TYPE …, ALTER TABLE … TYPE … USING, DROP TYPE)\")}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** How many rows a table holds, or `null` when we cannot say. */\nasync function countRows(databaseUrl: string | undefined, table: string): Promise<number | null> {\n if (!databaseUrl) return null;\n try {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5000 });\n await client.connect();\n try {\n // Identifier interpolation, and it has to be: the name comes from\n // PostgreSQL's own error text, and `count(*)` takes no parameter in\n // that position. Quoted, with any embedded quote doubled.\n const res = await client.query(`SELECT count(*)::int AS n FROM \"${table.replace(/\"/g, \"\\\"\\\"\")}\"`);\n return (res.rows[0] as { n: number } | undefined)?.n ?? null;\n } finally {\n await client.end();\n }\n } catch {\n return null;\n }\n}\n\n/**\n * The remedy for an Atlas invocation that failed, or `null`.\n *\n * Scoped by the invocation, because the same database state means different\n * things to different subcommands: \"already exists\" under `migrate apply` wants\n * a baseline, while under `schema apply` it is a genuine conflict.\n */\nexport async function diagnoseAtlasFailure(context: {\n domain: string;\n args: string[];\n stderr: string;\n databaseUrl?: string;\n /** The newest migration version on disk, named in the baseline remedy. */\n latestMigrationVersion?: string | null;\n}): Promise<string | null> {\n const { domain, args, stderr, databaseUrl } = context;\n\n if (domain === \"migrate\" && args.includes(\"apply\")) {\n const provisioned = parseAlreadyProvisioned(stderr);\n if (provisioned) {\n return formatBaselineRemedy(context.latestMigrationVersion ?? null, provisioned.object);\n }\n }\n\n if (domain === \"schema\" && args.includes(\"apply\")) {\n const enumDrop = parseEnumLabelDrop(stderr);\n if (enumDrop) return formatEnumLabelDropBanner(enumDrop);\n\n const notNull = parseNotNullViolation(stderr);\n if (notNull) return formatNotNullViolationBanner(notNull, await countRows(databaseUrl, notNull.table));\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,oBAAoB,OAA0C;CACnE,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CACtC,MAAM,IAAI;CACV,IAAI,OAAO,EAAE,eAAe,YAAY,EAAE,aAAa,OAAO,EAAE,cAAc,KAAK,OAAO;CAC1F,OAAO;AACX;;;;;;;AAoBA,SAAgB,eAAe,OAAsC;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,IAAI,EAAE,iBAAiB,QAAQ;EAE3B,IAAI,WAAW,SAAU,MAAkC,SAAS,OAAQ,MAAkC,UAAU,UACpH,OAAO,e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AE,QAAQ,MAAM,QAAQ,gBAAgB;CAE9C,IAAI,WAAW,aAAa,KAAK,SAAS,OAAO,GAAG;EAChD,MAAM,cAAc,wBAAwB,MAAM;EAClD,IAAI,aACA,OAAO,qBAAqB,QAAQ,0BAA0B,MAAM,YAAY,MAAM;CAE9F;CAEA,IAAI,WAAW,YAAY,KAAK,SAAS,OAAO,GAAG;EAC/C,MAAM,WAAW,mBAAmB,MAAM;EAC1C,IAAI,UAAU,OAAO,0BAA0B,QAAQ;EAEvD,MAAM,UAAU,sBAAsB,MAAM;EAC5C,IAAI,SAAS,OAAO,6BAA6B,SAAS,MAAM,UAAU,aAAa,QAAQ,KAAK,CAAC;CACzG;CAEA,OAAO;AACX"}
|
package/dist/cli-errors.d.ts
CHANGED
|
@@ -26,6 +26,26 @@ export declare function isSslNotEnabled(err: unknown): boolean;
|
|
|
26
26
|
* an enum type it defined is still referenced by another object.
|
|
27
27
|
*/
|
|
28
28
|
export declare function isDependencyDropError(err: unknown): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Parse host:port from a DATABASE_URL for display purposes.
|
|
31
|
+
*
|
|
32
|
+
* Exported because every message about a connection has to name the thing it
|
|
33
|
+
* could not reach, and the boot path needs the same rendering the CLI banners
|
|
34
|
+
* use — including the same refusal to print the URL itself, which carries the
|
|
35
|
+
* password.
|
|
36
|
+
*/
|
|
37
|
+
export declare function parseHostInfo(databaseUrl: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* The sentence the operating system actually produced, dug out of the wrappers.
|
|
40
|
+
*
|
|
41
|
+
* `connect ECONNREFUSED 127.0.0.1:5432` is written by `net`, then wrapped by
|
|
42
|
+
* `pg`, then wrapped again by Drizzle as `Failed query: …` — and on a
|
|
43
|
+
* dual-stack host it is not in `.cause` at all but inside the
|
|
44
|
+
* `AggregateError.errors` array of one attempt per resolved address. Printing
|
|
45
|
+
* the banner without it loses the one token every search engine, runbook and
|
|
46
|
+
* colleague recognises.
|
|
47
|
+
*/
|
|
48
|
+
export declare function deepestErrorMessage(err: unknown): string | null;
|
|
29
49
|
/**
|
|
30
50
|
* Pre-flight check: verify that the database is reachable before running
|
|
31
51
|
* a heavy subprocess (Atlas, migrations, etc.).
|
|
@@ -40,3 +60,106 @@ export declare function checkDatabaseConnectivity(databaseUrl: string): Promise<
|
|
|
40
60
|
* or null if unrecognized.
|
|
41
61
|
*/
|
|
42
62
|
export declare function diagnoseDbError(err: unknown, databaseUrl?: string): string | null;
|
|
63
|
+
/**
|
|
64
|
+
* Say why the command failed, on the way out.
|
|
65
|
+
*
|
|
66
|
+
* The entry point below used to be `.catch(() => process.exit(1))`, which threw
|
|
67
|
+
* the error away. Every message this file and its services raise — "Branch
|
|
68
|
+
* \"x\" already exists.", "the source database has active connections", "Branch
|
|
69
|
+
* name is too long" — was written, wrapped in the right PG error code, and then
|
|
70
|
+
* discarded one frame before it reached a terminal. What a developer saw was a
|
|
71
|
+
* header line, no error, and exit 1.
|
|
72
|
+
*
|
|
73
|
+
* Two shapes are deliberately kept quiet:
|
|
74
|
+
*
|
|
75
|
+
* - **A child process that already spoke.** Atlas, `pg_dump` and `psql` run
|
|
76
|
+
* with inherited stdio, so their diagnosis is on the terminal already and
|
|
77
|
+
* execa's wrapper adds only `Command failed with exit code 1: atlas …`.
|
|
78
|
+
* `packages/cli` filters exactly these two phrasings one level up
|
|
79
|
+
* (`runDbCommand`), and this is that filter, for the process that is actually
|
|
80
|
+
* throwing.
|
|
81
|
+
*
|
|
82
|
+
* - **A message that is only a query.** Drizzle reports failures as
|
|
83
|
+
* `Failed query: <sql> params:` and hides the real PostgreSQL error in
|
|
84
|
+
* `cause`, so the wrapper alone tells a reader nothing they can act on. The
|
|
85
|
+
* cause is appended when it says something the message does not.
|
|
86
|
+
*
|
|
87
|
+
* - **An error that has already printed its own diagnosis**, marked
|
|
88
|
+
* `alreadyReported`. `CollectionsPathMissing` is one: it prints the path, what
|
|
89
|
+
* it resolved to and the cwd it resolved against, and then throws so the entry
|
|
90
|
+
* point owns the exit code. Repeating its one-line summary underneath would
|
|
91
|
+
* undo the "printed once" this whole path exists for.
|
|
92
|
+
*/
|
|
93
|
+
export declare function reportCommandFailure(error: unknown): void;
|
|
94
|
+
/**
|
|
95
|
+
* `migrate apply` refusing because the database already has the schema.
|
|
96
|
+
*
|
|
97
|
+
* `42710` (duplicate_object) and `42P07` (duplicate_table) are what a migration
|
|
98
|
+
* hits when boot-ensure — or a `db push` — has already provisioned the objects
|
|
99
|
+
* it was going to create. Since boot-ensure provisions *every* production
|
|
100
|
+
* database, this is the normal case rather than the exotic one, and the raw
|
|
101
|
+
* failure (`pq: type "posts_status" already exists (42710)`, then `sql/migrate:
|
|
102
|
+
* write revision: … current transaction is aborted`) names no way forward.
|
|
103
|
+
*/
|
|
104
|
+
export declare function parseAlreadyProvisioned(text: string): {
|
|
105
|
+
object: string;
|
|
106
|
+
code: string;
|
|
107
|
+
} | null;
|
|
108
|
+
/**
|
|
109
|
+
* What to do about it: tell Atlas the database is already at a version.
|
|
110
|
+
*
|
|
111
|
+
* Atlas's own mechanism (`migrate apply --baseline <version>`), not a ledger of
|
|
112
|
+
* ours — it writes the revision row Atlas reads, so every later `rebase db
|
|
113
|
+
* migrate` is an ordinary one.
|
|
114
|
+
*/
|
|
115
|
+
export declare function formatBaselineRemedy(version: string | null, object?: string): string;
|
|
116
|
+
/** `ALTER TABLE … SET NOT NULL` on a table that already holds rows (23502). */
|
|
117
|
+
export declare function parseNotNullViolation(text: string): {
|
|
118
|
+
table: string;
|
|
119
|
+
column: string;
|
|
120
|
+
} | null;
|
|
121
|
+
/**
|
|
122
|
+
* The three ways out, because there is no fourth.
|
|
123
|
+
*
|
|
124
|
+
* Boot-ensure handles this case — it adds the column nullable and sets NOT NULL
|
|
125
|
+
* only when the table is empty — so a push that dies here is strictly worse
|
|
126
|
+
* than the boot that would have run instead, and the developer deserves to be
|
|
127
|
+
* told which of the three they want rather than left with `pq: … contains null
|
|
128
|
+
* values (23502)` and no next step.
|
|
129
|
+
*/
|
|
130
|
+
export declare function formatNotNullViolationBanner(violation: {
|
|
131
|
+
table: string;
|
|
132
|
+
column: string;
|
|
133
|
+
}, rowCount: number | null): string;
|
|
134
|
+
/** Atlas refusing to remove a label from an enum — a renamed `enum` option id. */
|
|
135
|
+
export declare function parseEnumLabelDrop(text: string): {
|
|
136
|
+
label: string;
|
|
137
|
+
enumType: string;
|
|
138
|
+
} | null;
|
|
139
|
+
/**
|
|
140
|
+
* Why the two paths disagree, and what retiring an option id actually costs.
|
|
141
|
+
*
|
|
142
|
+
* Boot-ensure adds enum labels and never removes one, so `rebase dev` accepts
|
|
143
|
+
* the very edit that stops `db push` dead. PostgreSQL has no `ALTER TYPE …
|
|
144
|
+
* DROP VALUE`: a label goes only by rewriting the type, which is a data
|
|
145
|
+
* migration and not a schema push.
|
|
146
|
+
*/
|
|
147
|
+
export declare function formatEnumLabelDropBanner(drop: {
|
|
148
|
+
label: string;
|
|
149
|
+
enumType: string;
|
|
150
|
+
}): string;
|
|
151
|
+
/**
|
|
152
|
+
* The remedy for an Atlas invocation that failed, or `null`.
|
|
153
|
+
*
|
|
154
|
+
* Scoped by the invocation, because the same database state means different
|
|
155
|
+
* things to different subcommands: "already exists" under `migrate apply` wants
|
|
156
|
+
* a baseline, while under `schema apply` it is a genuine conflict.
|
|
157
|
+
*/
|
|
158
|
+
export declare function diagnoseAtlasFailure(context: {
|
|
159
|
+
domain: string;
|
|
160
|
+
args: string[];
|
|
161
|
+
stderr: string;
|
|
162
|
+
databaseUrl?: string;
|
|
163
|
+
/** The newest migration version on disk, named in the baseline remedy. */
|
|
164
|
+
latestMigrationVersion?: string | null;
|
|
165
|
+
}): Promise<string | null>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The flags each driver command takes, in one place, and the check that
|
|
3
|
+
* enforces them.
|
|
4
|
+
*
|
|
5
|
+
* Every parser in `cli.ts` runs `arg(..., { permissive: true })`, which does not
|
|
6
|
+
* mean "be lenient" — it means **an undeclared flag becomes a positional**. So
|
|
7
|
+
* `rebase db push --alow-destructive` did not fail: the typo landed in `_`, the
|
|
8
|
+
* push ran with the destructive gate still closed, and the developer read the
|
|
9
|
+
* refusal as Rebase ignoring the flag they had just typed. `rebase schema
|
|
10
|
+
* generate --ouput src/schema.ts` was worse — it wrote the default path and
|
|
11
|
+
* said nothing, so the next build compiled a file nobody had regenerated.
|
|
12
|
+
*
|
|
13
|
+
* The check has to live at the entry point rather than in those parsers, and
|
|
14
|
+
* that is not a detail: `db push` and `db generate` re-enter `schemaCommand`
|
|
15
|
+
* and `generatePostgresDdlCommand` with the *db* line, so a strict parser
|
|
16
|
+
* inside either of them would reject `--allow-destructive` on a line where it
|
|
17
|
+
* is correct. One validation, once, against the spec for the command the user
|
|
18
|
+
* actually named; the inner parsers keep reading an already-validated line.
|
|
19
|
+
*
|
|
20
|
+
* Commands with their own argument handling — `db branch` (`unexpectedBranchArgs`),
|
|
21
|
+
* `db backup`, `db restore`, `db backups` — are deliberately absent: they own
|
|
22
|
+
* their spec, and a second list here would be one more thing to keep in step.
|
|
23
|
+
* An absent entry is "not checked here", never "takes nothing".
|
|
24
|
+
*/
|
|
25
|
+
import arg from "arg";
|
|
26
|
+
/** Keyed by `"<domain> <subcommand>"`, the way the user types it. */
|
|
27
|
+
export declare const DRIVER_FLAG_SPECS: Record<string, arg.Spec>;
|
|
28
|
+
/**
|
|
29
|
+
* One destination flag, two spellings, everywhere.
|
|
30
|
+
*
|
|
31
|
+
* `--out` is the primary on `rebase build`, an alias on `generate-sdk`, `db
|
|
32
|
+
* backup` and `cloud env pull`, and was refused outright by the three `schema`
|
|
33
|
+
* commands — so the spelling a user learned on one command was an
|
|
34
|
+
* "unknown or unexpected option" on the next. Neither name can be retired (both
|
|
35
|
+
* are shipped), so both are accepted, and {@link assertOutputAliasesPaired}
|
|
36
|
+
* makes that the rule rather than a habit.
|
|
37
|
+
*/
|
|
38
|
+
export declare const OUTPUT_FLAG_ALIASES: readonly ["--out", "--output"];
|
|
39
|
+
/**
|
|
40
|
+
* Every spec that names one of the pair names both.
|
|
41
|
+
*
|
|
42
|
+
* Exported so the CLI's own specs can be held to it too: the drift this fixes
|
|
43
|
+
* ran across two packages, and a check that only reads this file would let the
|
|
44
|
+
* next `--out`-only command through.
|
|
45
|
+
*/
|
|
46
|
+
export declare function assertOutputAliasesPaired(specs: Record<string, arg.Spec>): string[];
|
|
47
|
+
/**
|
|
48
|
+
* The `--collections` path the user typed, or `null` if they typed none.
|
|
49
|
+
*
|
|
50
|
+
* Read once, at the entry point, because every command that takes it re-enters
|
|
51
|
+
* the generators with the same line and each of them resolved it again — which
|
|
52
|
+
* is how "Collections path not found" came to be printed four times before the
|
|
53
|
+
* real output, and how a path that does not exist got as far as *writing* an
|
|
54
|
+
* empty schema.
|
|
55
|
+
*
|
|
56
|
+
* Permissive, and it has to be: {@link assertKnownFlags} has already judged the
|
|
57
|
+
* line, and `db push` carries flags the `--collections` spec does not name.
|
|
58
|
+
*/
|
|
59
|
+
export declare function collectionsPathIn(args: string[]): string | null;
|
|
60
|
+
/**
|
|
61
|
+
* The long flags a `--help` usage line documents.
|
|
62
|
+
*
|
|
63
|
+
* `"rebase db push [--collections <dir>] [--dry-run] …"` → `["--collections",
|
|
64
|
+
* "--dry-run"]`. Placeholders (`<dir>`) and the alternation inside a positional
|
|
65
|
+
* (`<create|list|switch>`) are not flags and are not returned.
|
|
66
|
+
*/
|
|
67
|
+
export declare function flagsInUsage(usage: string): string[];
|
|
68
|
+
/**
|
|
69
|
+
* Every flag the help documents is accepted, and every flag accepted is documented.
|
|
70
|
+
*
|
|
71
|
+
* The drift this catches shipped: `rebase db push --help` has printed
|
|
72
|
+
* `[--dry-run]` since the flag was written, `DRIVER_FLAG_SPECS["db push"]` never
|
|
73
|
+
* listed it, and {@link assertKnownFlags} — added later to stop typos being
|
|
74
|
+
* swallowed — turned the documented flag into `unknown or unexpected option`.
|
|
75
|
+
* The only way to see a push's SQL was to trip the destructive gate, which is
|
|
76
|
+
* the exact problem `--dry-run` was written to solve. Worse in a project on an
|
|
77
|
+
* older driver, whose permissive parser *applied* the schema on that line.
|
|
78
|
+
*
|
|
79
|
+
* Two hand-maintained lists in two packages cannot be kept in step by care, so
|
|
80
|
+
* they are held to each other instead: `usages` is keyed the way
|
|
81
|
+
* {@link DRIVER_FLAG_SPECS} is (`"db push"`), and comes from the CLI's own help
|
|
82
|
+
* pages. A key in only one of the two is not this function's business — the
|
|
83
|
+
* help covers commands that parse their own lines (`db branch`, `db backup`),
|
|
84
|
+
* and an absent spec entry means "not checked here".
|
|
85
|
+
*
|
|
86
|
+
* Aliases (`"-c": "--collections"`, `"--out": "--output"`) need no line of their
|
|
87
|
+
* own: they are spellings of a documented flag. Neither do {@link RELAYED_FLAGS},
|
|
88
|
+
* which every driver command accepts because the CLI relays them.
|
|
89
|
+
*/
|
|
90
|
+
export declare function assertSpecMatchesUsage(specs: Record<string, arg.Spec>, usages: Record<string, string>): string[];
|
|
91
|
+
/**
|
|
92
|
+
* Reject a flag the named command does not take.
|
|
93
|
+
*
|
|
94
|
+
* `args` is the driver's whole line — `["db", "push", …]` — so the flags are
|
|
95
|
+
* read from `args.slice(2)`, past the two command words.
|
|
96
|
+
*
|
|
97
|
+
* Throws rather than exiting: `runPluginCommand`'s caller already turns a
|
|
98
|
+
* thrown error into one red line and exit 1, and a thrown error is what the
|
|
99
|
+
* tests can see.
|
|
100
|
+
*/
|
|
101
|
+
export declare function assertKnownFlags(domain: string, subcommand: string | undefined, args: string[]): void;
|
package/dist/cli-helpers.d.ts
CHANGED
|
@@ -22,22 +22,106 @@ import type { CollectionConfig } from "@rebasepro/types";
|
|
|
22
22
|
* second, matching the order {@link resolveLocalBin} searches — the driver may
|
|
23
23
|
* be installed a level up from where the command runs.
|
|
24
24
|
*/
|
|
25
|
-
export
|
|
25
|
+
export type ProjectPackageManager = "pnpm" | "npm" | "yarn" | "bun" | "unknown";
|
|
26
|
+
/**
|
|
27
|
+
* Which package manager installed this project, read off its lockfile.
|
|
28
|
+
*
|
|
29
|
+
* Every remedy for a blocked build script is package-manager specific, and
|
|
30
|
+
* naming the wrong one is the same failure as naming none: `pnpm approve-builds`
|
|
31
|
+
* is not a thing an npm user can run, and `pnpm.onlyBuiltDependencies` is a key
|
|
32
|
+
* npm does not read. This existed as a pnpm-only message for long enough that
|
|
33
|
+
* npm 12 — which blocks dependency lifecycle scripts by default, the way pnpm 10
|
|
34
|
+
* does — could ship and leave every npm reader three unfollowable commands deep.
|
|
35
|
+
*
|
|
36
|
+
* The lockfile, not `npm_config_user_agent`: the question is how the project's
|
|
37
|
+
* `node_modules` was built, not which binary happens to be invoking us. Walks up
|
|
38
|
+
* because commands run from `backend/` in a scaffolded project, and the lockfile
|
|
39
|
+
* is at the workspace root.
|
|
40
|
+
*/
|
|
41
|
+
export declare function detectProjectPackageManager(startDir?: string): ProjectPackageManager;
|
|
42
|
+
/**
|
|
43
|
+
* How to let `@ariga/atlas` run its `preinstall`, in the reader's own package
|
|
44
|
+
* manager.
|
|
45
|
+
*
|
|
46
|
+
* Returns the lines to print after "the binary is missing but the package is
|
|
47
|
+
* installed". Kept next to {@link detectProjectPackageManager} so the two move
|
|
48
|
+
* together, and returned rather than printed so it can be asserted on.
|
|
49
|
+
*/
|
|
50
|
+
export declare function describeBuildScriptRemedy(packageName: string, manager?: ProjectPackageManager): string[];
|
|
51
|
+
/**
|
|
52
|
+
* "Install again, from scratch", in the reader's own package manager.
|
|
53
|
+
*
|
|
54
|
+
* For the `bin-link-missing` state: the tree is half-written, and re-resolving
|
|
55
|
+
* it is what recreates the `.bin` shim. `--force` on pnpm is what makes it
|
|
56
|
+
* relink rather than decide the tree is already up to date.
|
|
57
|
+
*/
|
|
58
|
+
export declare function describeReinstallCommand(manager?: ProjectPackageManager): string;
|
|
59
|
+
/** `add <pkg>` as a dev dependency, in the reader's own package manager. */
|
|
60
|
+
export declare function describeDevAddCommand(packageName: string, manager?: ProjectPackageManager): string;
|
|
61
|
+
/**
|
|
62
|
+
* Why a dependency's binary is not on `PATH`.
|
|
63
|
+
*
|
|
64
|
+
* `bin-link-missing` is the third state, and the reason this is not a boolean.
|
|
65
|
+
* The `preinstall` did run and the binary IS on disk — only the
|
|
66
|
+
* `node_modules/.bin` shim that points at it is absent. pnpm produces exactly
|
|
67
|
+
* that when it writes the link before the script that creates the target
|
|
68
|
+
* ("Failed to create bin … ENOENT"), and so does a tree copied without its
|
|
69
|
+
* symlinks. Telling that reader their build scripts are blocked sends them to
|
|
70
|
+
* `approve-builds`, which does nothing, because nothing is blocked.
|
|
71
|
+
*/
|
|
72
|
+
export type MissingBinDiagnosis = "not-installed" | "build-script-blocked" | "bin-link-missing";
|
|
73
|
+
/**
|
|
74
|
+
* The binaries a package's own manifest declares, as absolute paths.
|
|
75
|
+
*
|
|
76
|
+
* `bin` is a string for a single binary named after the package, or a map.
|
|
77
|
+
* Both forms appear in the wild and `@ariga/atlas` uses the map.
|
|
78
|
+
*/
|
|
79
|
+
export declare function declaredBinaries(manifestPath: string): string[];
|
|
80
|
+
export declare function diagnoseMissingBin(packageName: string): MissingBinDiagnosis;
|
|
26
81
|
export declare function resolveLocalBin(binName: string): string | null;
|
|
27
82
|
export declare function getTableIncludesFromCollections(allCollections: CollectionConfig[]): Promise<string[]>;
|
|
28
83
|
export declare function getTableIncludes(collectionsPath: string): Promise<string[]>;
|
|
84
|
+
export declare function loadCollectionsForCli(collectionsPath: string): Promise<CollectionConfig[]>;
|
|
85
|
+
export declare function getDevDatabaseUrl(databaseUrl: string): string;
|
|
29
86
|
/**
|
|
30
|
-
*
|
|
87
|
+
* Create the scratch database Atlas plans against, and say so when we cannot.
|
|
88
|
+
*
|
|
89
|
+
* Atlas needs a `--dev-url` — an empty database it can build the desired state
|
|
90
|
+
* in — and this makes `<db>_dev_diff` next to the real one. The whole body used
|
|
91
|
+
* to be wrapped in an empty catch commented "Ignore, let Atlas handle
|
|
92
|
+
* connection failures", and Atlas's version of handling it is `postgres:
|
|
93
|
+
* querying system variables: pq: database "app_dev_diff" does not exist
|
|
94
|
+
* (3D000)` — the symptom, four frames downstream of the cause, with the cause
|
|
95
|
+
* thrown away.
|
|
31
96
|
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
97
|
+
* The cause is almost always `42501`: `CREATE DATABASE` is a privilege managed
|
|
98
|
+
* providers do not grant, so this is the first thing a hosted user hits and the
|
|
99
|
+
* one they can do least with.
|
|
100
|
+
*
|
|
101
|
+
* @returns whether the scratch database was created by *this* call — the only
|
|
102
|
+
* case in which dropping it afterwards is ours to do.
|
|
37
103
|
*/
|
|
38
|
-
export declare function
|
|
39
|
-
|
|
40
|
-
|
|
104
|
+
export declare function ensureDevDatabaseExists(databaseUrl: string, devDatabaseUrl: string): Promise<boolean>;
|
|
105
|
+
/**
|
|
106
|
+
* What went wrong creating the scratch database, and what to do about it.
|
|
107
|
+
*
|
|
108
|
+
* Exported for its test: the `42501` branch is the one that matters and it
|
|
109
|
+
* cannot be provoked without a non-superuser role.
|
|
110
|
+
*/
|
|
111
|
+
export declare function describeDevDatabaseFailure(err: unknown, devDbName: string): string;
|
|
112
|
+
/**
|
|
113
|
+
* Drop the scratch database again, after the command that needed it succeeded.
|
|
114
|
+
*
|
|
115
|
+
* It is a full copy of the schema — no rows, but every table, type and index —
|
|
116
|
+
* and it was left behind per target forever. The only notice anyone got was
|
|
117
|
+
* `rebase db branch prune` reporting "3 Atlas scratch database(s) left over
|
|
118
|
+
* from db push", and on a provider that bills per database it is a silent cost.
|
|
119
|
+
*
|
|
120
|
+
* Deliberately NOT called on the failure path: after a failed push the scratch
|
|
121
|
+
* database holds the state Atlas was planning against, which is the one thing
|
|
122
|
+
* worth inspecting.
|
|
123
|
+
*/
|
|
124
|
+
export declare function dropDevDatabase(databaseUrl: string, devDatabaseUrl: string): Promise<void>;
|
|
41
125
|
/**
|
|
42
126
|
* The generated SQL for the project's `search` blocks, if it has any.
|
|
43
127
|
*
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
__createRequire(import.meta.url);
|
|
3
|
+
//#region src/cli-output.ts
|
|
4
|
+
/**
|
|
5
|
+
* Terminal output for the `rebase db|schema|doctor` commands.
|
|
6
|
+
*
|
|
7
|
+
* These commands used to write every line through `logger`, and that is a
|
|
8
|
+
* category error with three separate consequences:
|
|
9
|
+
*
|
|
10
|
+
* - `logger` prefixes each line with its own level, so a box-drawn report
|
|
11
|
+
* arrived as `ℹ️ [INFO] ┌─ ✗ Missing Column ───` and the frame no longer
|
|
12
|
+
* lined up with anything;
|
|
13
|
+
* - `logger` is gated by `LOG_LEVEL`, which ships in the scaffold's own
|
|
14
|
+
* `.env.example` — a developer who quietened their dev server with
|
|
15
|
+
* `LOG_LEVEL=warn` got a `rebase db push` that printed almost nothing and
|
|
16
|
+
* still exited non-zero, indistinguishable from a crash;
|
|
17
|
+
* - under `NODE_ENV=production` `logger` emits JSON, so the whole report
|
|
18
|
+
* became log records with the chalk escape codes embedded in them.
|
|
19
|
+
*
|
|
20
|
+
* A CLI's report *is* its return value. It goes to the terminal unconditionally
|
|
21
|
+
* and unadorned. `packages/cli` has always written its output this way; this is
|
|
22
|
+
* the same three functions for the plugin CLI that `rebase` delegates to.
|
|
23
|
+
*
|
|
24
|
+
* `logger` still belongs in this package's *runtime* — a request handler has no
|
|
25
|
+
* terminal and its lines want levels, timestamps and redaction. The rule is the
|
|
26
|
+
* caller, not the severity: anything a developer reads because they typed a
|
|
27
|
+
* command goes here, anything a server emits while running goes to `logger`.
|
|
28
|
+
*
|
|
29
|
+
* Errors and warnings go to stderr so `rebase db push > plan.txt` keeps the
|
|
30
|
+
* diagnosis on the terminal where it is readable.
|
|
31
|
+
*/
|
|
32
|
+
/** One line of human-facing output on stdout. */
|
|
33
|
+
var out = (line = "") => {
|
|
34
|
+
console.log(line);
|
|
35
|
+
};
|
|
36
|
+
/** One line of human-facing warning output on stderr. */
|
|
37
|
+
var outWarn = (line = "") => {
|
|
38
|
+
console.warn(line);
|
|
39
|
+
};
|
|
40
|
+
/** One line of human-facing error output on stderr. */
|
|
41
|
+
var outError = (line = "") => {
|
|
42
|
+
console.error(line);
|
|
43
|
+
};
|
|
44
|
+
//#endregion
|
|
45
|
+
export { outError as n, outWarn as r, out as t };
|
|
46
|
+
|
|
47
|
+
//# sourceMappingURL=cli-output-CNdMql-L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-output-CNdMql-L.js","names":[],"sources":["../src/cli-output.ts"],"sourcesContent":["/**\n * Terminal output for the `rebase db|schema|doctor` commands.\n *\n * These commands used to write every line through `logger`, and that is a\n * category error with three separate consequences:\n *\n * - `logger` prefixes each line with its own level, so a box-drawn report\n * arrived as `ℹ️ [INFO] ┌─ ✗ Missing Column ───` and the frame no longer\n * lined up with anything;\n * - `logger` is gated by `LOG_LEVEL`, which ships in the scaffold's own\n * `.env.example` — a developer who quietened their dev server with\n * `LOG_LEVEL=warn` got a `rebase db push` that printed almost nothing and\n * still exited non-zero, indistinguishable from a crash;\n * - under `NODE_ENV=production` `logger` emits JSON, so the whole report\n * became log records with the chalk escape codes embedded in them.\n *\n * A CLI's report *is* its return value. It goes to the terminal unconditionally\n * and unadorned. `packages/cli` has always written its output this way; this is\n * the same three functions for the plugin CLI that `rebase` delegates to.\n *\n * `logger` still belongs in this package's *runtime* — a request handler has no\n * terminal and its lines want levels, timestamps and redaction. The rule is the\n * caller, not the severity: anything a developer reads because they typed a\n * command goes here, anything a server emits while running goes to `logger`.\n *\n * Errors and warnings go to stderr so `rebase db push > plan.txt` keeps the\n * diagnosis on the terminal where it is readable.\n */\n\n/** One line of human-facing output on stdout. */\nexport const out = (line = \"\"): void => {\n console.log(line);\n};\n\n/** One line of human-facing warning output on stderr. */\nexport const outWarn = (line = \"\"): void => {\n console.warn(line);\n};\n\n/** One line of human-facing error output on stderr. */\nexport const outError = (line = \"\"): void => {\n console.error(line);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,OAAO,OAAO,OAAa;CACpC,QAAQ,IAAI,IAAI;AACpB;;AAGA,IAAa,WAAW,OAAO,OAAa;CACxC,QAAQ,KAAK,IAAI;AACrB;;AAGA,IAAa,YAAY,OAAO,OAAa;CACzC,QAAQ,MAAM,IAAI;AACtB"}
|