@akal/supaforge 0.0.31 → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +1 -1
  2. package/dist/base-command.d.ts +1 -0
  3. package/dist/base-command.js +2 -2
  4. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  5. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  6. package/dist/chunk-3HGAV5CC.js.map +1 -0
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/chunk-4IVN7QVY.js.map +1 -0
  9. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  10. package/dist/chunk-6LJERPUN.js.map +1 -0
  11. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  12. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  13. package/dist/chunk-7NAZGZPV.js.map +1 -0
  14. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  15. package/dist/chunk-BUOWHE36.js.map +1 -0
  16. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  17. package/dist/chunk-DMIWAJRB.js.map +1 -0
  18. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  19. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  20. package/dist/chunk-GZREXCQZ.js +207 -0
  21. package/dist/chunk-GZREXCQZ.js.map +1 -0
  22. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  23. package/dist/chunk-MIRLB5JM.js.map +1 -0
  24. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  25. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  26. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  27. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  28. package/dist/chunk-SQPCWGQO.js.map +1 -0
  29. package/dist/chunk-UWAVXC57.js +916 -0
  30. package/dist/chunk-UWAVXC57.js.map +1 -0
  31. package/dist/commands/clone.js +10 -10
  32. package/dist/commands/diff.d.ts +16 -0
  33. package/dist/commands/diff.js +11 -12
  34. package/dist/commands/hukam.js +11 -12
  35. package/dist/commands/hukam.js.map +1 -1
  36. package/dist/commands/mcp.js +7 -8
  37. package/dist/commands/mcp.js.map +1 -1
  38. package/dist/commands/migrate/baseline.js +3 -3
  39. package/dist/commands/migrate/create.js +5 -6
  40. package/dist/commands/migrate/create.js.map +1 -1
  41. package/dist/commands/migrate/list.js +4 -4
  42. package/dist/commands/migrate/list.js.map +1 -1
  43. package/dist/commands/migrate/run.js +5 -6
  44. package/dist/commands/report.js +3 -3
  45. package/dist/commands/restore.js +11 -13
  46. package/dist/commands/restore.js.map +1 -1
  47. package/dist/commands/snapshot.js +6 -8
  48. package/dist/commands/snapshot.js.map +1 -1
  49. package/dist/commands/sync.js +11 -12
  50. package/dist/commands/sync.js.map +1 -1
  51. package/dist/index.d.ts +5 -0
  52. package/dist/index.js +16 -16
  53. package/package.json +2 -2
  54. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  55. package/dist/chunk-H5MJ5DFX.js +0 -16
  56. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  57. package/dist/chunk-LQXF65MC.js.map +0 -1
  58. package/dist/chunk-NXRSAVRU.js.map +0 -1
  59. package/dist/chunk-PARSNTBD.js.map +0 -1
  60. package/dist/chunk-RRMI5CZD.js +0 -376
  61. package/dist/chunk-RRMI5CZD.js.map +0 -1
  62. package/dist/chunk-SF3YA42C.js +0 -506
  63. package/dist/chunk-SF3YA42C.js.map +0 -1
  64. package/dist/chunk-TQJSQLWA.js.map +0 -1
  65. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  66. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  67. package/dist/chunk-XMYMIURR.js.map +0 -1
  68. package/dist/chunk-YVDSR4GM.js.map +0 -1
  69. /package/dist/{chunk-BHYLBKYD.js.map → chunk-2SELREHW.js.map} +0 -0
  70. /package/dist/{chunk-4OU7KO5Y.js.map → chunk-6Q7MHFBM.js.map} +0 -0
  71. /package/dist/{chunk-KIFJGON5.js.map → chunk-NTUASFQ3.js.map} +0 -0
  72. /package/dist/{chunk-5QQBTLWO.js.map → chunk-ORQJVE57.js.map} +0 -0
  73. /package/dist/{chunk-VMTBLHN2.js.map → chunk-SC2XHGIS.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/prove.ts","../src/state-diff.ts"],"sourcesContent":["/**\n * Convergence proof.\n *\n * A migration is only trustworthy if applying it actually produces the target\n * schema. Every silent-wrong-answer bug found so far shared one shape: the\n * generated SQL executed without error and left the database in a state that\n * was *not* the source — a duplicate primary key aborted loudly, but a\n * flattened partition, a dropped enum type name and an unpropagated index all\n * ran cleanly and lied.\n *\n * A text comparison cannot catch that class, and neither can a test suite that\n * only exercises the patterns its authors thought of. The only check that\n * generalises is to run the migration and look at what came out.\n *\n * So: copy the target's schema into a throwaway database, apply the migration\n * there, and diff the result against the source. Zero drift means the migration\n * does what it claims. Anything else is reported as residual drift, naming the\n * objects the migration failed to reproduce.\n *\n * The real target is never touched. The clone lives on the target's own server\n * (so no cross-host credentials are needed) and is dropped in a finally block\n * even when the proof throws.\n */\nimport { randomBytes } from 'node:crypto'\nimport { execFile, spawn } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { fingerprintSql, stateSql, type SchemaState } from '@akal/pg-conformance'\nimport { pgQuery, type QueryFn } from './db'\nimport { runLikeApply, type PlannedSql } from './promote'\nimport { diffState } from './state-diff'\nimport { resolvePgDumpPath, getServerMajorVersion, describeMissingPgDump } from './pg-tools'\nimport { rolesNamedBy, sqlSkeleton } from './sql-deps'\nimport { splitSqlStatements, isCommentOnly } from './utils/sql-split.js'\nimport { quoteName } from './utils/sql.js'\nimport { globToRegExp } from './utils/strings.js'\nimport { join, dirname } from 'node:path'\n\nconst exec = promisify(execFile)\n\n/**\n * Extensions on the target, and the schema each is installed into.\n *\n * The clone holds only the schemas being proved, so anything those schemas\n * reference from outside has to be put there first — and in practice that means\n * extensions: a Supabase column default calling `extensions.uuid_generate_v4()`\n * cannot be created without the extension that owns the function.\n *\n * Extensions living in a system schema are excluded, by *schema* rather than\n * by name. Filtering `plpgsql` by name left `pg_cron` — which Supabase installs\n * into `pg_catalog` — and the clone preparation then ran\n * `CREATE SCHEMA IF NOT EXISTS \"pg_catalog\"`. PostgreSQL rejects a name\n * beginning with `pg_` before it evaluates `IF NOT EXISTS`:\n *\n * error: unacceptable schema name \"pg_catalog\" (42939)\n *\n * so `--prove` aborted on every project with Cron enabled (issue #94). There is\n * nothing to create for these schemas in any case: they exist in every\n * database, and so do the extensions in them.\n */\nconst TARGET_EXTENSIONS_SQL = `\n SELECT e.extname AS name, n.nspname AS schema\n FROM pg_extension e\n JOIN pg_namespace n ON n.oid = e.extnamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_%'\n ORDER BY e.extname\n`\n\nexport interface ProofResult {\n /** True when the clone matched the source after applying. */\n converged: boolean\n /** Objects still differing after the migration — the migration's blind spots. */\n residual: string[]\n /** Name of the throwaway database, for error messages. */\n cloneName: string\n /** Set when the proof could not run at all (missing pg_dump, no CREATEDB). */\n skipped?: string\n /**\n * Fixes the replay left out because the server can't hold them — an\n * extension it does not ship, and what needs it — as the apply will. Their\n * absence is expected, not a failure to converge.\n */\n notApplied?: Array<{ issueId: string; sql: string; reason: string }>\n /**\n * For a run limited to some checks: differences the target already had,\n * still there, and of a kind none of those checks compares — see\n * outsideTheRun(). They do not count against convergence.\n */\n outOfScope?: string[]\n}\n\n/** Replace the database name in a libpq URL, keeping everything else. */\nfunction withDatabase(dbUrl: string, database: string): string {\n const url = new URL(dbUrl)\n url.pathname = `/${database}`\n return url.toString()\n}\n\n\n/**\n * The structural fingerprint comes from @akal/pg-conformance.\n *\n * It used to be defined here, and separately in the e2e harness, and again in\n * dbdiff's conformance runner. They drifted, and this copy was the one that\n * compared views, functions and triggers by name alone — so it called two\n * schemas converged when a view's predicate had been inverted, a function's\n * body replaced, or a trigger moved from AFTER INSERT to BEFORE UPDATE.\n *\n * A shared definition of \"same schema\" is the whole point of the proof, so it\n * lives in one place that both projects depend on.\n */\n\nasync function fingerprint(dbUrl: string, schemas: string[]): Promise<string> {\n const rows = await pgQuery(dbUrl, fingerprintSql(schemas)) as unknown as\n Array<{ fingerprint: string | null }>\n\n // An empty fingerprint would make every comparison succeed, so a schema that\n // produced nothing is treated as a fault rather than as \"no differences\".\n // Reading the wrong column name would fail exactly this way, silently.\n const value = rows[0]?.fingerprint\n if (value === undefined) {\n throw new Error('fingerprint query returned no \"fingerprint\" column')\n }\n return value ?? ''\n}\n\n/**\n * Say what differs, in terms a reader can act on.\n *\n * The fingerprint has already decided that something does. This turns the two\n * schema-state documents into named findings — \"column public.orders.total:\n * storage extended → plain\" — rather than two near-identical lines of catalog\n * shorthand with one field moved somewhere in the middle.\n *\n * Falls back to the raw fingerprint lines if the structured diff comes back\n * empty. That should not happen, but \"the schemas differ and I cannot tell you\n * how\" is a far worse answer than an ugly one.\n */\nasync function describeDifference(\n sourceUrl: string, cloneUrl: string, schemas: string[], want: string, got: string,\n): Promise<string[]> {\n try {\n const [before, after] = await Promise.all([\n schemaState(sourceUrl, schemas),\n schemaState(cloneUrl, schemas),\n ])\n const findings = diffState(before, after)\n if (findings.length > 0) return findings\n } catch {\n // fall through to the fingerprint lines\n }\n\n const wanted = new Set(want.split('\\n').filter(Boolean))\n const actual = new Set(got.split('\\n').filter(Boolean))\n return [\n ...[...wanted].filter(l => !actual.has(l)).map(l => `missing: ${l}`),\n ...[...actual].filter(l => !wanted.has(l)).map(l => `unexpected: ${l}`),\n ]\n}\n\n/** The schema-state document for one database. */\nasync function schemaState(dbUrl: string, schemas: string[]): Promise<SchemaState> {\n const rows = await pgQuery(dbUrl, stateSql(schemas)) as unknown as Array<{ state: string | null }>\n const value = rows[0]?.state\n if (!value) throw new Error('state query returned no \"state\" column')\n return JSON.parse(value) as SchemaState\n}\n\n/**\n * The schemas a schema diff compares between two databases: every schema\n * either has, but the system's own, an extension's own, and `ignore`\n * (globs: `*`, `?`), as `dbdiff --ignore-schemas` chooses them. What a\n * proof must cover, and nothing more.\n */\nexport async function comparedSchemas(\n sourceUrl: string, targetUrl: string, ignore: readonly string[], query: QueryFn = pgQuery,\n): Promise<string[]> {\n const sql = `SELECT n.nspname AS name FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%' AND n.nspname NOT LIKE 'pg\\\\_temp\\\\_%'\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass\n AND d.objid = n.oid AND d.deptype = 'e')`\n const ignored = ignore.map(globToRegExp)\n const names = (await Promise.all([sourceUrl, targetUrl].map(url => query(url, sql))))\n .flat().map(r => String((r as { name: unknown }).name))\n return [...new Set(names)].filter(n => !ignored.some(g => g.test(n))).sort()\n}\n\n/**\n * Prove that `migrationSql` turns the target into the source.\n *\n * Returns `converged: false` with the differing objects rather than throwing,\n * so the caller can decide whether that blocks an apply or merely warns.\n */\nexport async function proveConvergence(opts: {\n sourceUrl: string\n targetUrl: string\n migrationSql: string\n /**\n * The fixes behind migrationSql. Given, they are replayed exactly as the\n * apply will run them (see runLikeApply), so a fix the server can't hold is\n * left out rather than stopping the proof. Without them the SQL runs as one\n * script and any error ends the proof.\n */\n fixes?: PlannedSql[]\n schemas?: string[]\n /**\n * The checks the run compares. Without the schema check the migration only\n * sets out to fix part of the difference, and must not be refused for the\n * rest — see outsideTheRun(). Omitted, the whole schema must converge.\n */\n checks?: readonly string[]\n}): Promise<ProofResult> {\n const schemas = opts.schemas ?? ['public']\n const suffix = randomBytes(4).toString('hex')\n const cloneName = `supaforge_prove_${suffix}`\n const adminUrl = withDatabase(opts.targetUrl, 'postgres')\n const cloneUrl = withDatabase(opts.targetUrl, cloneName)\n\n let pgDump: string\n let psql: string\n let serverMajor: number\n let clientMajor: number\n let sourceMajor: number\n try {\n serverMajor = await getServerMajorVersion(opts.targetUrl)\n sourceMajor = await getServerMajorVersion(opts.sourceUrl).catch(() => serverMajor)\n // The proof dumps both servers: the target into the clone, and the source\n // into a copy compared like with like. A pg_dump new enough for the target\n // alone failed on a newer source, and the proof fell back to comparing a\n // 17 source's rendering with a 15 clone's, refusing correct migrations.\n const resolved = await resolvePgDumpPath(Math.max(serverMajor, sourceMajor))\n ?? await resolvePgDumpPath(serverMajor)\n if (!resolved) {\n return { converged: false, residual: [], cloneName, skipped: await describeMissingPgDump(serverMajor) }\n }\n pgDump = resolved.path\n clientMajor = resolved.major\n psql = psqlBeside(pgDump)\n } catch (err) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `could not resolve pg_dump: ${(err as Error).message}`,\n }\n }\n\n // A role is the server's, not the database's: creating one for the proof\n // would create it for real, and the apply's own CREATE ROLE then failed\n // with \"already exists\". So a migration that needs a role the server does\n // not have yet cannot be proved here — say so rather than create it.\n const absent = await absentRoles(opts.targetUrl, opts.migrationSql)\n if (absent.length > 0) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `the migration needs role(s) this server does not have yet (${absent.join(', ')}), `\n + 'and creating a role is server-wide, so it cannot be done in a throwaway database',\n }\n }\n\n let created = false\n let sourceCopyCreated = false\n let roundTripName: string | undefined\n try {\n try {\n await pgQuery(adminUrl, `CREATE DATABASE ${quoteName(cloneName)}`)\n created = true\n } catch (err) {\n // Typically insufficient privilege. Not being able to prove is not the\n // same as failing to converge, so say which it is.\n return {\n converged: false, residual: [], cloneName,\n skipped: `could not create a throwaway database: ${(err as Error).message}`,\n }\n }\n\n const tools = { pgDump, psql, clientMajor, serverMajor }\n await copyStructure(opts.targetUrl, cloneUrl, schemas, tools, opts.sourceUrl)\n const scoped = opts.checks !== undefined && !opts.checks.includes('schema')\n const before = scoped ? await schemaState(cloneUrl, schemas) : undefined\n\n // The migration under test.\n let notApplied: ProofResult['notApplied']\n if (opts.fixes) {\n const replayed = await runLikeApply(cloneUrl, opts.fixes)\n const unmet = replayed.errors.filter(e => / — not applied: /.test(e.error))\n const failed = replayed.errors.filter(e => !unmet.includes(e))\n if (failed.length > 0) {\n // A fix the apply itself would fail on: the migration can't reproduce\n // the source, and saying which fix and why is the useful answer.\n return {\n converged: false, cloneName,\n residual: failed.map(e => `fix ${e.issueId} failed: ${e.error}`),\n }\n }\n const byId = new Map(opts.fixes.map(f => [f.issueId, f.sql]))\n notApplied = unmet.map(e => ({ issueId: e.issueId, sql: byId.get(e.issueId) ?? '', reason: e.error }))\n } else {\n await runSql(psql, cloneUrl, opts.migrationSql)\n }\n const reported = (r: ProofResult): ProofResult => (notApplied?.length ? { ...r, notApplied } : r)\n\n const [want, got] = await Promise.all([\n fingerprint(opts.sourceUrl, schemas),\n fingerprint(cloneUrl, schemas),\n ])\n\n // The verdict stays with the fingerprint. It is the comparison already\n // trusted, and keeping it means the structured diff below can only change\n // how a difference is *described*, never whether one is detected.\n if (want === got) return reported({ converged: true, residual: [], cloneName })\n\n // The clone's objects have been through a dump and restore, or were\n // recreated from the SQL a rendering produced; the source's have not, and\n // PostgreSQL does not render every expression the same way twice —\n // `status IN ('draft', 'active')` on a varchar column comes back as a\n // different but equivalent ARRAY expression. So a correct migration\n // creating such a CHECK, index or policy was refused. Compared with the\n // source copied the same way, like is compared with like.\n roundTripName = `${cloneName}_src`\n const roundTripUrl = withDatabase(opts.targetUrl, roundTripName)\n const roundTrip = await copyOfSource(adminUrl, opts.sourceUrl, roundTripUrl, roundTripName, schemas, tools)\n if (roundTrip !== null) {\n sourceCopyCreated = true\n if (roundTrip.ok) {\n const wantRoundTripped = await fingerprint(roundTripUrl, schemas)\n if (wantRoundTripped === got) return reported({ converged: true, residual: [], cloneName })\n const residual = await describeDifference(roundTripUrl, cloneUrl, schemas, wantRoundTripped, got)\n return reported(withinScope(residual, before && diffState(await schemaState(roundTripUrl, schemas), before), opts.checks, cloneName))\n }\n }\n\n // Without a copy of the source on the target's server, two major versions\n // cannot be compared: each prints the same objects its own way. That is\n // not proven rather than not converged.\n if (sourceMajor !== serverMajor) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `no pg_dump ${sourceMajor} or later to copy the PostgreSQL ${sourceMajor} source onto the `\n + `PostgreSQL ${serverMajor} target's server, which comparing across the two versions needs`,\n }\n }\n const residual = await describeDifference(opts.sourceUrl, cloneUrl, schemas, want, got)\n return reported(withinScope(residual, before && diffState(await schemaState(opts.sourceUrl, schemas), before), opts.checks, cloneName))\n } finally {\n if (sourceCopyCreated && roundTripName) {\n await dropDatabase(adminUrl, roundTripName)\n }\n if (created) {\n // Never leave a clone behind, even on failure. Terminating first because\n // a failed apply can leave a session attached.\n await dropDatabase(adminUrl, cloneName)\n }\n }\n}\n\ninterface PgTools { pgDump: string; psql: string; clientMajor: number; serverMajor: number }\n\n/**\n * Copy `fromUrl`'s structure in the given schemas into the empty database at\n * `intoUrl` — data is irrelevant to a schema proof and copying it would make\n * this unusable on anything but a toy database.\n *\n * Only the schemas being proved. Listing Supabase's schemas as exclusions\n * instead left the dump carrying everything that *references* them — a\n * `CREATE EXTENSION ... WITH SCHEMA extensions`, an event trigger calling\n * `extensions.set_graphql_placeholder()` — none of which could be replayed\n * into a clone that deliberately has no such schema. `--prove` therefore\n * failed on every real Supabase project, whatever the client version.\n */\nasync function copyStructure(\n fromUrl: string, intoUrl: string, schemas: string[], tools: PgTools, migratingFrom?: string,\n): Promise<void> {\n // Prepare the copy to receive the proved schemas, and nothing else.\n await prepareClone(intoUrl, fromUrl, schemas)\n\n // And the schemas they lean on. A Supabase table referencing auth.users, or\n // a policy calling auth.uid(), cannot be created without them — every real\n // project failed here with `schema \"auth\" does not exist`. Copied, not\n // compared: the fingerprint covers only the proved schemas.\n //\n // The schemas the source's objects lean on as well, when it is a migration\n // from that source being proved: a foreign key the migration adds onto\n // another schema's table needs that schema in the clone, though nothing in\n // the target uses it yet — the proof failed with `schema \"app\" does not\n // exist` where the apply itself would have worked. Only those the target\n // has: one it lacks would fail the real apply as well.\n const supporting = await supportingSchemas(fromUrl, schemas)\n const present = new Set((await pgQuery(fromUrl, 'SELECT nspname FROM pg_namespace') as Array<{ nspname: string }>).map(r => r.nspname))\n if (migratingFrom) {\n for (const name of await supportingSchemas(migratingFrom, schemas)) {\n if (present.has(name) && !supporting.includes(name)) supporting.push(name)\n }\n }\n\n // A proved schema only the source has is the migration's to create. Each\n // name quoted: pg_dump reads --schema as a pattern, folding `App Data` to\n // lower case, which matched nothing.\n const dumpArgs = [\n fromUrl, '--schema-only', '--no-owner', '--no-privileges',\n ...[...schemas.filter(s => present.has(s)), ...supporting].map(s => `--schema=${quoteName(s)}`),\n ]\n const { stdout: structure } = await exec(tools.pgDump, dumpArgs, {\n maxBuffer: 256 * 1024 * 1024, timeout: 300_000,\n })\n\n // pg_dump writes its preamble for its own version, so a newer client can\n // hand an older server a parameter that does not exist there (issue #72).\n // A supporting schema may already exist, created for an extension living in\n // it, so its CREATE SCHEMA has to tolerate that.\n const { sql: replayable } = dropUnsupportedSetStatements(\n tolerateExistingSchemas(structure), await knownParameters(intoUrl),\n )\n\n try {\n await runSql(tools.psql, intoUrl, replayable)\n } catch (err) {\n // Rethrown, not returned as `skipped`: a caller treats `skipped` as\n // \"could not check, carry on and apply\", and this is a case where we do\n // not know what the migration would do. Blocking the apply is the\n // behaviour that was already right (issue #72 confirmed nothing was\n // written and no clone was left behind) — only the message needed to say\n // what the cause actually is.\n throw new Error(explainStructureFailure((err as Error).message, tools.clientMajor, tools.serverMajor))\n }\n}\n\n/**\n * Schemas outside `schemas` holding something an object in them depends on —\n * a referenced table, a called function, a column's type — followed\n * transitively. Extension members are left out: prepareClone installs the\n * extensions themselves.\n */\nexport async function supportingSchemas(\n dbUrl: string, schemas: string[], queryFn: QueryFn = pgQuery,\n): Promise<string[]> {\n const known = new Set(schemas)\n const found: string[] = []\n for (let from = [...schemas]; from.length > 0;) {\n const rows = await queryFn(dbUrl, SUPPORTING_SCHEMAS_SQL(from)) as unknown as Array<{ schema: string }>\n from = rows.map(r => r.schema).filter(s => !known.has(s))\n for (const schema of from) {\n known.add(schema)\n found.push(schema)\n }\n }\n return found\n}\n\n/** The namespace of any object pg_depend can name, by catalog. */\nconst NAMESPACE_OF = (cls: string, oid: string) => `CASE ${cls}\n WHEN 'pg_class'::regclass THEN (SELECT relnamespace FROM pg_class WHERE oid = ${oid})\n WHEN 'pg_proc'::regclass THEN (SELECT pronamespace FROM pg_proc WHERE oid = ${oid})\n WHEN 'pg_type'::regclass THEN (SELECT typnamespace FROM pg_type WHERE oid = ${oid})\n WHEN 'pg_constraint'::regclass THEN (SELECT connamespace FROM pg_constraint WHERE oid = ${oid})\n WHEN 'pg_attrdef'::regclass THEN (SELECT x_c.relnamespace FROM pg_attrdef x_d JOIN pg_class x_c ON x_c.oid = x_d.adrelid WHERE x_d.oid = ${oid})\n WHEN 'pg_policy'::regclass THEN (SELECT x_c.relnamespace FROM pg_policy x_p JOIN pg_class x_c ON x_c.oid = x_p.polrelid WHERE x_p.oid = ${oid})\n WHEN 'pg_trigger'::regclass THEN (SELECT x_c.relnamespace FROM pg_trigger x_t JOIN pg_class x_c ON x_c.oid = x_t.tgrelid WHERE x_t.oid = ${oid})\n WHEN 'pg_rewrite'::regclass THEN (SELECT x_c.relnamespace FROM pg_rewrite x_r JOIN pg_class x_c ON x_c.oid = x_r.ev_class WHERE x_r.oid = ${oid})\n END`\n\nconst SUPPORTING_SCHEMAS_SQL = (from: string[]) => `\n SELECT DISTINCT rn.nspname AS schema\n FROM pg_depend d\n JOIN pg_namespace n ON n.oid = ${NAMESPACE_OF('d.classid', 'd.objid')}\n JOIN pg_namespace rn ON rn.oid = ${NAMESPACE_OF('d.refclassid', 'd.refobjid')}\n WHERE n.nspname IN (${from.map(quoteLiteral).join(', ')})\n AND rn.nspname <> n.nspname\n AND rn.nspname NOT IN ('pg_catalog', 'information_schema')\n AND rn.nspname NOT LIKE 'pg\\\\_%'\n AND d.deptype IN ('n', 'a')\n AND NOT EXISTS (SELECT 1 FROM pg_depend e\n WHERE e.classid = d.refclassid AND e.objid = d.refobjid AND e.deptype = 'e')\n ORDER BY 1`\n\nfunction quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/** `CREATE SCHEMA x;` lines made `IF NOT EXISTS`. */\nexport function tolerateExistingSchemas(sql: string): string {\n return sql.replace(/^CREATE SCHEMA (?!IF NOT EXISTS )/gm, 'CREATE SCHEMA IF NOT EXISTS ')\n}\n\n/**\n * The source's structure copied onto the target's server the way the clone\n * was, for comparing like with like. `null` when the database could not be\n * created, `{ ok: false }` when the copy failed — the proof then falls back to\n * comparing against the source itself, as it did before.\n */\nasync function copyOfSource(\n adminUrl: string, sourceUrl: string, intoUrl: string, name: string, schemas: string[], tools: PgTools,\n): Promise<{ ok: boolean } | null> {\n try {\n await pgQuery(adminUrl, `CREATE DATABASE ${quoteName(name)}`)\n } catch {\n return null\n }\n try {\n await copyStructure(sourceUrl, intoUrl, schemas, tools)\n return { ok: true }\n } catch {\n return { ok: false }\n }\n}\n\n/** Drop a throwaway database, ending any session still attached first. */\nasync function dropDatabase(adminUrl: string, name: string): Promise<void> {\n await pgQuery(adminUrl,\n `SELECT pg_terminate_backend(pid) FROM pg_stat_activity\n WHERE datname = '${name}' AND pid <> pg_backend_pid()`).catch(() => undefined)\n await pgQuery(adminUrl, `DROP DATABASE IF EXISTS ${quoteName(name)}`).catch(() => undefined)\n}\n\n/**\n * Execute a multi-statement script through psql rather than a plain connection.\n *\n * pg_dump output is not pure SQL: recent versions emit psql meta-commands such\n * as `\\restrict`, which a normal client rejects with a scanner error. psql also\n * gives us ON_ERROR_STOP, so a migration that half-applies fails the proof\n * loudly instead of producing a partially-migrated clone that then reports\n * confusing residual drift.\n */\nfunction runSql(psqlPath: string, dbUrl: string, sql: string): Promise<void> {\n const trimmed = sql.trim()\n if (!trimmed) return Promise.resolve()\n\n return new Promise((resolve, reject) => {\n // Fed over stdin: promisified execFile has no `input` option, so passing\n // one silently leaves psql waiting on a stdin that never closes until the\n // timeout kills it.\n const child = spawn(psqlPath, [dbUrl, '-v', 'ON_ERROR_STOP=1', '-q', '-f', '-'], {\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let stderr = ''\n child.stderr.on('data', (d: Buffer) => { stderr += d.toString() })\n child.on('error', reject)\n child.on('close', (code) => {\n if (code === 0) resolve()\n else reject(new Error(stderr.trim() || `psql exited ${code}`))\n })\n child.stdin.write(trimmed)\n child.stdin.end()\n })\n}\n\n/** psql ships alongside pg_dump; reuse the version-matched directory. */\nfunction psqlBeside(pgDumpPath: string): string {\n return pgDumpPath === 'pg_dump' ? 'psql' : join(dirname(pgDumpPath), 'psql')\n}\n\n/**\n * Lines pg_dump emits before the first real object, in the order it emits them.\n *\n * `\\restrict` is a psql meta-command recent versions wrap the script in;\n * `SET` and `SELECT pg_catalog.set_config(...)` configure the session. Nothing\n * here creates anything, which is what makes the preamble safe to rewrite.\n */\nconst PREAMBLE_LINE =\n /^\\s*(?:--|$|\\\\(?:un)?restrict\\b|SET\\s+[\\w.]+\\s*=|SELECT\\s+pg_catalog\\.set_config\\s*\\()/i\n\n/** A top-level `SET some.guc = value;`, capturing the parameter name. */\nconst SET_STATEMENT = /^\\s*SET\\s+([\\w.]+)\\s*=/i\n\n/**\n * Drop `SET` statements from a dump's preamble that the destination server\n * would reject.\n *\n * pg_dump writes its preamble for the version of pg_dump, not the version of\n * the server the SQL will be replayed into: pg_dump 17 added an unconditional\n * `SET transaction_timeout = 0;`, and a PostgreSQL 15 or 16 server answers that\n * with `unrecognized configuration parameter`. A PostgreSQL 18 client against a\n * Supabase still on 15 is the common case rather than an exotic one, and it made\n * `--prove` unusable there — it aborted before replaying anything (issue #72).\n *\n * The filter asks the destination which parameters it actually has rather than\n * carrying a list of version-specific names, so the next parameter a future\n * pg_dump adds to the preamble needs no change here.\n *\n * Deliberately narrow in two ways. It only rewrites the leading run of\n * preamble lines, so a `SET` inside a function body — which lives after the\n * first `CREATE` — is never touched. And it only removes statements naming a\n * parameter the destination does not have, so a `SET` that fails for any other\n * reason still fails the proof loudly: `ON_ERROR_STOP` stays on, and no error\n * from the replay is ignored. Tolerating errors instead (as `pg_restore` does,\n * which is why `clone` never noticed this) would let an incomplete clone be\n * reported as converged.\n */\nexport function dropUnsupportedSetStatements(\n sql: string, knownParameters: ReadonlySet<string>,\n): { sql: string; dropped: string[] } {\n const lines = sql.split('\\n')\n const dropped: string[] = []\n const kept: string[] = []\n\n let inPreamble = true\n for (const line of lines) {\n if (inPreamble && !PREAMBLE_LINE.test(line)) inPreamble = false\n\n if (inPreamble) {\n const name = SET_STATEMENT.exec(line)?.[1]\n if (name && !knownParameters.has(name.toLowerCase())) {\n dropped.push(name.toLowerCase())\n continue\n }\n }\n kept.push(line)\n }\n\n return { sql: kept.join('\\n'), dropped }\n}\n\n/**\n * Make a fresh clone ready to receive a dump of just the proved schemas.\n *\n * Two steps, in this order.\n *\n * The proved schemas are dropped, because the dump recreates them itself —\n * pg_dump emits `CREATE SCHEMA public` for an explicitly selected schema, which\n * a database that already has one rejects.\n *\n * Then the target's extensions are installed, those living in a proved schema\n * too: `pg_dump --schema` does not carry an extension, even one in the schema\n * it dumps, so a table whose exclusion constraint needs btree_gist in `public`\n * could not be replayed. Without this, a table whose column default calls an\n * extension function — the `extensions.uuid_generate_v4()` pattern all over\n * Supabase — cannot be created either, because a default is resolved when the\n * table is created, not when it is used. The dump's own CREATE SCHEMA then\n * finds the schema there, which tolerateExistingSchemas() allows.\n */\nexport async function prepareClone(\n cloneUrl: string, targetUrl: string, schemas: string[], queryFn: QueryFn = pgQuery,\n): Promise<void> {\n for (const schema of schemas) {\n await queryFn(cloneUrl, `DROP SCHEMA IF EXISTS ${quoteName(schema)} CASCADE`)\n }\n\n const extensions = await queryFn(targetUrl, TARGET_EXTENSIONS_SQL) as unknown as\n Array<{ name: string; schema: string }>\n\n for (const ext of extensions) {\n // Tolerated for the same reason the CREATE EXTENSION below it is: a schema\n // this clone will not accept is not a reason to abandon the proof. If the\n // structure genuinely needed it, the replay fails next and says so — which\n // is a better error than this one (issue #94).\n await queryFn(cloneUrl, `CREATE SCHEMA IF NOT EXISTS ${quoteName(ext.schema)}`)\n .catch(() => undefined)\n // Best-effort: an extension the server cannot offer this database is not a\n // reason to abandon the proof. If the schema genuinely needed it, the replay\n // fails next and says so.\n await queryFn(cloneUrl,\n `CREATE EXTENSION IF NOT EXISTS ${quoteName(ext.name)} WITH SCHEMA ${quoteName(ext.schema)}`,\n ).catch(() => undefined)\n }\n}\n\n/** Configuration parameter names this server recognises. */\nexport async function knownParameters(dbUrl: string): Promise<Set<string>> {\n const rows = await pgQuery(dbUrl, 'SELECT name FROM pg_settings') as unknown as\n Array<{ name: string }>\n return new Set(rows.map(r => r.name.toLowerCase()))\n}\n\n/**\n * Explain a failure to replay the target's own structure.\n *\n * The raw psql error names a parameter or a syntax element, with nothing to\n * connect it to the real cause — a client newer than the server. Someone\n * reading `unrecognized configuration parameter` goes looking at their schema,\n * which is the one place the problem is not (issue #72).\n */\nexport function explainStructureFailure(\n message: string, clientMajor: number, serverMajor: number,\n): string {\n // Only when the error actually looks like one — a newer client emitting SQL\n // the server has no concept of. Appending it to every failure would send\n // someone chasing a version gap that has nothing to do with, say, a missing\n // schema, which is the same species of misdirection this message exists to\n // undo.\n const looksLikeVersionGap = /unrecognized configuration parameter|syntax error/i.test(message)\n const versionGap = clientMajor > serverMajor && looksLikeVersionGap\n ? ` The local client is PostgreSQL ${clientMajor} and the target server is `\n + `${serverMajor}; pg_dump ${clientMajor} can emit SQL that a ${serverMajor} `\n + `server rejects. Installing postgresql-client-${serverMajor} removes the gap.`\n : ''\n return `could not replay the target's structure onto the clone: ${message}${versionGap}`\n}\n\n/** `DROP <kind> [IF EXISTS] <name>` and `DROP COLUMN [IF EXISTS] <name>`, capturing the bare name. */\nconst DROPPED_NAME = /\\bDROP\\s+(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|COLUMN|CONSTRAINT|POLICY|TRIGGER)\\s+(?:IF\\s+EXISTS\\s+)?(?:(?:\"[^\"]+\"|[\\w$]+)\\s*\\.\\s*)?(\"[^\"]+\"|[\\w$]+)/gi\n\n/** `CREATE [OR REPLACE] <kind> [IF NOT EXISTS] <name>`, capturing the bare name. */\nconst CREATED_NAME = /\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:UNIQUE\\s+)?(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|POLICY|TRIGGER|EXTENSION)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:(?:\"[^\"]+\"|[\\w$]+)\\s*\\.\\s*)?(\"[^\"]+\"|[\\w$]+)/gi\n\n/**\n * Split a proof's residual into what the held-back fixes account for and\n * what they do not.\n *\n * A fix held back — a destructive drop without --allow-destructive, one left\n * out by --only — leaves its object on the target on purpose, and the proof\n * then reported that object as `unexpected`, refusing the whole apply. A line\n * is only accounted for when it is that shape — an object present that the\n * source lacks — and a held-back fix drops an object of that name; anything\n * else about the same table still blocks.\n */\nexport function residualHeldBack(\n residual: string[],\n heldBackSql: string[],\n): { heldBack: string[]; unexplained: string[] } {\n const dropped = new Set<string>()\n for (const sql of heldBackSql) {\n for (const m of sql.matchAll(DROPPED_NAME)) dropped.add(m[1].replace(/^\"|\"$/g, '').toLowerCase())\n }\n // And the creations a fix left out would have made: on a target that can't\n // hold them (no supabase_functions for a webhook, no auth schema for a\n // policy calling auth.uid()) the apply leaves them out, so the clone lacks\n // them by design and the line reads `…: missing`.\n const created: string[] = []\n for (const sql of heldBackSql) {\n for (const m of sql.matchAll(CREATED_NAME)) created.push(m[1].replace(/^\"|\"$/g, '').toLowerCase())\n }\n const heldBack: string[] = []\n const unexplained: string[] = []\n for (const line of residual) {\n const subject = /^[a-z ]+?\\s([^\\s:]+(?:\\s[^\\s:]+)?):\\s*unexpected$/i.exec(line)?.[1]\n const name = subject?.split(/[.\\s]/).pop()?.replace(/^\"|\"$/g, '').toLowerCase()\n const missing = /^(.*):\\s*missing$/i.exec(line)?.[1].toLowerCase()\n if (name && dropped.has(name)) heldBack.push(line)\n else if (missing && created.some(n => missing.endsWith(` ${n}`) || missing.endsWith(`.${n}`))) heldBack.push(line)\n else unexplained.push(line)\n }\n return { heldBack, unexplained }\n}\n\n/**\n * The checks whose fixes the proof replays: the ones that act on the proved\n * schemas, which is all the fingerprint compares.\n *\n * The others act on something the throwaway database does not have, or that\n * is not its own. pg_cron lives in one database per server, so\n * `cron.schedule()` failed in the clone with `schema \"cron\" does not exist`\n * and aborted the proof, blocking an apply that would have worked. A role\n * belongs to the whole server, so `CREATE ROLE` in the clone created it for\n * real. A publication, a reference-data row, a storage policy: none of them\n * is in the fingerprint, so replaying them could only fail, never prove.\n */\nconst PROVED_CHECKS: ReadonlySet<string> = new Set(['schema', 'rls', 'rls-coverage', 'extensions', 'webhooks'])\n\n/** A statement that acts on the server rather than the database it runs in. */\nconst SERVER_WIDE = [\n /^\\s*(?:CREATE|ALTER|DROP)\\s+(?:ROLE|USER|GROUP|DATABASE|TABLESPACE)\\b/i,\n /^\\s*ALTER\\s+SYSTEM\\b/i,\n // Role membership: a GRANT or REVOKE with no ON names roles, not objects.\n /^\\s*(?:GRANT|REVOKE)\\b(?![\\s\\S]*\\bON\\b)/i,\n]\n\n/**\n * Split the planned fixes into those the proof replays and those it cannot.\n *\n * A fix holding a server-wide statement is never replayed, whichever check it\n * came from: the proof must not change anything outside the database it made.\n */\nexport function proofScope<T extends { check: string; sql: string }>(\n statements: readonly T[],\n): { replay: T[]; unproved: T[] } {\n const replay: T[] = []\n const unproved: T[] = []\n for (const stmt of statements) {\n const serverWide = splitSqlStatements(stmt.sql)\n .filter(s => !isCommentOnly(s))\n .some(s => SERVER_WIDE.some(re => re.test(sqlSkeleton(s))))\n if (PROVED_CHECKS.has(stmt.check) && !serverWide) replay.push(stmt)\n else unproved.push(stmt)\n }\n return { replay, unproved }\n}\n\n/** Roles the migration grants to or scopes a policy to that the server lacks. */\nasync function absentRoles(dbUrl: string, sql: string): Promise<string[]> {\n const named = [...new Set(splitSqlStatements(sql).flatMap(s => rolesNamedBy(s)))]\n if (named.length === 0) return []\n const rows = await pgQuery(dbUrl, 'SELECT rolname FROM pg_roles WHERE rolname = ANY($1::text[])', [named]) as unknown as\n Array<{ rolname: string }>\n const present = new Set(rows.map(r => r.rolname))\n return named.filter(r => !present.has(r))\n}\n\n/**\n * The verdict for what remains after the migration.\n *\n * Unscoped — `baseline` undefined — everything remaining is a failure to\n * converge. Scoped, a remaining difference is set aside when the target\n * already had it and none of the run's checks compares that kind of object:\n * `diff --check=rls --prove` was refused for every unrelated table the target\n * lacked, which the run never set out to create.\n */\nfunction withinScope(\n residual: string[], baseline: string[] | undefined, checks: readonly string[] | undefined, cloneName: string,\n): ProofResult {\n if (!baseline || !checks) return { converged: residual.length === 0, residual, cloneName }\n const had = new Set(baseline)\n const outOfScope = residual.filter(l => had.has(l) && outsideTheRun(l, checks))\n const remaining = residual.filter(l => !outOfScope.includes(l))\n return { converged: remaining.length === 0, residual: remaining, outOfScope, cloneName }\n}\n\n/** Which state-diff lines each check compares, beyond the schema check's all. */\nconst GOVERNED: Record<string, RegExp> = {\n 'rls': /^policy on |: RLS (?:enabled|forced) /,\n 'rls-coverage': /: RLS enabled /,\n 'extensions': /^extension /,\n 'webhooks': /^trigger on /,\n}\n\n/** A difference none of the run's checks compares. */\nexport function outsideTheRun(line: string, checks: readonly string[]): boolean {\n if (checks.includes('schema')) return false\n return !checks.some(c => GOVERNED[c]?.test(line))\n}\n","/**\n * Structural diff between two schema-state documents.\n *\n * The convergence proof used to compare fingerprints — one sorted string per\n * database — and report the lines that differed. That is correct but close to\n * unreadable: a changed column arrives as two near-identical lines of catalog\n * shorthand and leaves the reader to spot the one field that moved.\n *\n * missing: col public.orders.total numeric NO - ident= gen= store=x compress=- coll=-\n * unexpected: col public.orders.total numeric NO - ident= gen= store=p compress=- coll=-\n *\n * The state document has the same information as data, so the same difference\n * can be named:\n *\n * column public.orders.total: storage extended → plain\n *\n * Detection is unchanged. The state document is verified to distinguish every\n * pair of schemas the fingerprint distinguishes, so this reports the same\n * differences — it does not find more of them, and it must not find fewer.\n */\nimport type { SchemaState, StateTable, StateColumn } from '@akal/pg-conformance'\n\n/** How a value reads when absent, so `null` never reaches the output raw. */\nconst show = (v: unknown): string => {\n if (v === null || v === undefined) return 'none'\n if (typeof v === 'boolean') return v ? 'yes' : 'no'\n if (Array.isArray(v)) return v.length ? v.join(', ') : 'none'\n if (typeof v === 'object') return JSON.stringify(v)\n return String(v)\n}\n\n/** `schema.name`, or just the name when the schema adds nothing. */\nconst qualify = (schema: string, name: string): string => `${schema}.${name}`\n\n/**\n * Compare one field of two objects, appending a finding when it moved.\n *\n * Values are compared by their rendered form rather than by identity, so an\n * array whose contents match reads as unchanged even when the two documents\n * hold different array instances.\n */\nfunction compareField(\n out: string[], subject: string, label: string, before: unknown, after: unknown,\n): void {\n const a = show(before), b = show(after)\n if (a !== b) out.push(`${subject}: ${label} ${a} → ${b}`)\n}\n\n/** Diff two collections keyed by a stable identity. */\nfunction compareKeyed<T>(\n out: string[],\n kind: string,\n before: T[] | null | undefined,\n after: T[] | null | undefined,\n keyOf: (item: T) => string,\n compare: (out: string[], subject: string, a: T, b: T) => void,\n): void {\n const a = new Map((before ?? []).map(x => [keyOf(x), x]))\n const b = new Map((after ?? []).map(x => [keyOf(x), x]))\n\n for (const [key, item] of a) {\n if (!b.has(key)) out.push(`${kind} ${key}: missing`)\n else compare(out, `${kind} ${key}`, item, b.get(key) as T)\n }\n for (const key of b.keys()) {\n if (!a.has(key)) out.push(`${kind} ${key}: unexpected`)\n }\n}\n\nfunction compareColumn(out: string[], subject: string, a: StateColumn, b: StateColumn): void {\n compareField(out, subject, 'type', a.type, b.type)\n compareField(out, subject, 'not null', a.not_null, b.not_null)\n compareField(out, subject, 'default', a.default, b.default)\n compareField(out, subject, 'identity', a.identity, b.identity)\n compareField(out, subject, 'identity options', a.identity_options, b.identity_options)\n compareField(out, subject, 'generated', a.generated, b.generated)\n compareField(out, subject, 'storage', a.storage, b.storage)\n compareField(out, subject, 'compression', a.compression, b.compression)\n compareField(out, subject, 'collation', a.collation, b.collation)\n compareField(out, subject, 'comment', a.comment, b.comment)\n}\n\nfunction compareTable(out: string[], subject: string, a: StateTable, b: StateTable): void {\n compareField(out, subject, 'kind', a.kind, b.kind)\n compareField(out, subject, 'unlogged', a.unlogged, b.unlogged)\n compareField(out, subject, 'partition of', a.partition_of, b.partition_of)\n compareField(out, subject, 'partition bound', a.partition_bound, b.partition_bound)\n compareField(out, subject, 'partition by', a.partition_by, b.partition_by)\n compareField(out, subject, 'inherits', a.inherits, b.inherits)\n compareField(out, subject, 'options', a.options, b.options)\n compareField(out, subject, 'RLS enabled', a.rls_enabled, b.rls_enabled)\n compareField(out, subject, 'RLS forced', a.rls_forced, b.rls_forced)\n compareField(out, subject, 'comment', a.comment, b.comment)\n\n // Findings name the object in full — \"column public.orders.total\" — so a\n // reader never has to hold the enclosing table in their head.\n const prefix = subject.replace(/^table /, '')\n compareKeyed(out, 'column', a.columns, b.columns,\n c => `${prefix}.${c.name}`,\n (o, s, x, y) => compareColumn(o, s, x, y))\n compareKeyed(out, `constraint on ${prefix}`, a.constraints, b.constraints,\n c => c.name,\n (o, s, x, y) => {\n compareField(o, s, 'definition', x.definition, y.definition)\n compareField(o, s, 'validated', x.validated, y.validated)\n compareField(o, s, 'deferrable', x.deferrable, y.deferrable)\n compareField(o, s, 'deferred', x.deferred, y.deferred)\n })\n compareKeyed(out, `index on ${prefix}`, a.indexes, b.indexes,\n i => i.name,\n (o, s, x, y) => compareField(o, s, 'definition', x.definition, y.definition))\n compareKeyed(out, `policy on ${prefix}`, a.policies, b.policies,\n p => p.name,\n (o, s, x, y) => {\n compareField(o, s, 'command', x.command, y.command)\n compareField(o, s, 'permissive', x.permissive, y.permissive)\n compareField(o, s, 'roles', x.roles, y.roles)\n compareField(o, s, 'using', x.using, y.using)\n compareField(o, s, 'with check', x.with_check, y.with_check)\n })\n compareKeyed(out, `trigger on ${prefix}`, a.triggers, b.triggers,\n t => t.name,\n (o, s, x, y) => compareField(o, s, 'definition', x.definition, y.definition))\n}\n\n/**\n * Everything that differs between two schema states, most structural first.\n *\n * Returns an empty array when the two are identical. Each entry names the\n * object and what about it moved, so the caller can print the list as-is.\n */\nexport function diffState(before: SchemaState, after: SchemaState): string[] {\n const out: string[] = []\n\n compareKeyed(out, 'table', before.tables, after.tables,\n t => qualify(t.schema, t.name),\n (o, s, a, b) => compareTable(o, s, a, b))\n\n compareKeyed(out, 'view', before.views, after.views,\n v => qualify(v.schema, v.name),\n (o, s, a, b) => {\n compareField(o, s, 'materialized', a.materialized, b.materialized)\n compareField(o, s, 'definition', a.definition, b.definition)\n compareField(o, s, 'options', a.options, b.options)\n })\n\n compareKeyed(out, 'sequence', before.sequences, after.sequences,\n q => qualify(q.schema, q.name),\n (o, s, a, b) => {\n for (const k of ['type', 'start', 'increment', 'min', 'max', 'cache', 'cycle', 'owned_by'] as const) {\n compareField(o, s, k.replace('_', ' '), a[k], b[k])\n }\n })\n\n compareKeyed(out, 'routine', before.routines, after.routines,\n r => `${qualify(r.schema, r.name)}(${r.arguments})`,\n (o, s, a, b) => {\n compareField(o, s, 'kind', a.kind, b.kind)\n compareField(o, s, 'definition', a.definition, b.definition)\n })\n\n compareKeyed(out, 'type', before.types, after.types,\n t => qualify(t.schema, t.name),\n (o, s, a, b) => {\n compareField(o, s, 'kind', a.kind, b.kind)\n compareField(o, s, 'labels', a.labels, b.labels)\n compareField(o, s, 'base type', a.base_type, b.base_type)\n compareField(o, s, 'not null', a.not_null, b.not_null)\n compareField(o, s, 'default', a.default, b.default)\n compareField(o, s, 'constraints', a.constraints, b.constraints)\n compareField(o, s, 'attributes', a.attributes, b.attributes)\n })\n\n compareKeyed(out, 'extension', before.extensions, after.extensions,\n e => e.name,\n (o, s, a, b) => compareField(o, s, 'version', a.version, b.version))\n\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,mBAAmB;AAC5B,SAAS,UAAU,aAAa;AAChC,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB,gBAAkC;;;ACH3D,IAAM,OAAO,CAAC,MAAuB;AACnC,MAAI,MAAM,QAAQ,MAAM,OAAW,QAAO;AAC1C,MAAI,OAAO,MAAM,UAAW,QAAO,IAAI,QAAQ;AAC/C,MAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,EAAE,SAAS,EAAE,KAAK,IAAI,IAAI;AACvD,MAAI,OAAO,MAAM,SAAU,QAAO,KAAK,UAAU,CAAC;AAClD,SAAO,OAAO,CAAC;AACjB;AAGA,IAAM,UAAU,CAAC,QAAgB,SAAyB,GAAG,MAAM,IAAI,IAAI;AAS3E,SAAS,aACP,KAAe,SAAiB,OAAe,QAAiB,OAC1D;AACN,QAAM,IAAI,KAAK,MAAM,GAAG,IAAI,KAAK,KAAK;AACtC,MAAI,MAAM,EAAG,KAAI,KAAK,GAAG,OAAO,KAAK,KAAK,IAAI,CAAC,WAAM,CAAC,EAAE;AAC1D;AAGA,SAAS,aACP,KACA,MACA,QACA,OACA,OACA,SACM;AACN,QAAM,IAAI,IAAI,KAAK,UAAU,CAAC,GAAG,IAAI,OAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AACxD,QAAM,IAAI,IAAI,KAAK,SAAS,CAAC,GAAG,IAAI,OAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAEvD,aAAW,CAAC,KAAK,IAAI,KAAK,GAAG;AAC3B,QAAI,CAAC,EAAE,IAAI,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AAK,CAAC,QAAQ,IAAI,CAAC,CAAC;AAC1C;AAWA,SAAS,YACP,UAAoB,UAAgC,QAAuC,WAC9E;AACb,MAAI,CAAC,YAAY,CAAC,OAAQ,QAAO,EAAE,WAAW,SAAS,WAAW,GAAG,UAAU,UAAU;AACzF,QAAM,MAAM,IAAI,IAAI,QAAQ;AAC5B,QAAM,aAAa,SAAS,OAAO,OAAK,IAAI,IAAI,CAAC,KAAK,cAAc,GAAG,MAAM,CAAC;AAC9E,QAAM,YAAY,SAAS,OAAO,OAAK,CAAC,WAAW,SAAS,CAAC,CAAC;AAC9D,SAAO,EAAE,WAAW,UAAU,WAAW,GAAG,UAAU,WAAW,YAAY,UAAU;AACzF;AAGA,IAAM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,YAAY;AACd;AAGO,SAAS,cAAc,MAAc,QAAoC;AAC9E,MAAI,OAAO,SAAS,QAAQ,EAAG,QAAO;AACtC,SAAO,CAAC,OAAO,KAAK,OAAK,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC;AAClD;","names":["residual","knownParameters"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  CHECK_META,
3
3
  isComparisonCheck
4
- } from "./chunk-5Z3SAIQS.js";
4
+ } from "./chunk-UWAVXC57.js";
5
5
  import {
6
6
  CHECK_LINE_PADDING,
7
7
  bold,
@@ -133,7 +133,7 @@ function formatCheckLine(lr) {
133
133
  const count = lr.issues.length;
134
134
  const noun = count === 1 ? "issue" : "issues";
135
135
  const severity = highestSeverity(lr);
136
- const sevLabel = severity ? colorSeverity(severity) : "";
136
+ const sevLabel = severity ? ` ${colorSeverity(severity)}` : "";
137
137
  const errText = lr.error || (lr.status === "error" ? "check failed" : "");
138
138
  const errLabel = errText ? ` ${warn(`(error: ${errText})`)}` : "";
139
139
  const folded = (lr.folded ?? []).map((f) => ` ${dim(`(+${f.count} reported under ${CHECK_META[f.into].label})`)}`).join("");
@@ -237,4 +237,4 @@ export {
237
237
  renderDetailed,
238
238
  formatSkips
239
239
  };
240
- //# sourceMappingURL=chunk-LQXF65MC.js.map
240
+ //# sourceMappingURL=chunk-GEHPTPNZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/render.ts"],"sourcesContent":["import type { ScanResult, CheckResult, DriftIssue } from './types/drift'\nimport { CHECK_META, isComparisonCheck } from './types/drift'\nimport { CHECK_LINE_PADDING } from './constants'\nimport { ok, warn, dim, bold, c } from './ui'\n\n/**\n * Number of checks that failed to run.\n *\n * Defensive against a malformed or partial ScanResult — an older cached\n * report, or a hand-built object in a hook — where `checks` may be missing\n * or not an array. Reporting zero errored checks is the safe fallback for\n * rendering; it never invents an error that is not there.\n */\nexport function countErrored(result: Pick<ScanResult, 'checks'>): number {\n if (!Array.isArray(result?.checks)) return 0\n return result.checks.filter(c => c?.status === 'error').length\n}\n\n/**\n * Number of checks that declined to run.\n *\n * A skipped layer was rendered identically to a clean one, so fourteen green\n * ticks could mean eleven comparisons and three layers that never opened a\n * connection (issue #42). Same defensive handling as countErrored.\n */\nexport function countSkipped(result: Pick<ScanResult, 'checks'>): number {\n if (!Array.isArray(result?.checks)) return 0\n return result.checks.filter(c => c?.status === 'skipped').length\n}\n\n/**\n * How many checks actually compared the two environments, over how many were\n * attempted.\n *\n * Printed alongside the score so a perfect number cannot be read as full\n * coverage. Skipped and errored layers both measured nothing, so neither\n * counts toward the numerator.\n */\nexport function coverage(result: Pick<ScanResult, 'checks'>): { compared: number; total: number } {\n if (!Array.isArray(result?.checks)) return { compared: 0, total: 0 }\n const total = result.checks.length\n const compared = result.checks.filter(c => c?.status === 'clean' || c?.status === 'drifted').length\n return { compared, total }\n}\n\n/**\n * Split the issue counts by whether they represent drift between the two\n * environments or the target's own posture.\n *\n * RLS Coverage and Migration History fire identically whichever pair you diff,\n * so counting them as drift made \"9 drift issues found\" the headline for a\n * comparison that found none (issue #40).\n */\nexport function splitCounts(result: Pick<ScanResult, 'checks'>): { drift: number; posture: number } {\n if (!Array.isArray(result?.checks)) return { drift: 0, posture: 0 }\n let drift = 0\n let posture = 0\n for (const check of result.checks) {\n const count = check?.issues?.length ?? 0\n if (isComparisonCheck(check?.check)) drift += count\n else posture += count\n }\n return { drift, posture }\n}\n\n/** Colour a 0–100 score green / amber / red. */\nfunction colorScore(score: number): string {\n let style: Parameters<typeof c>[0] = 'red'\n if (score >= 80) style = 'green'\n else if (score >= 50) style = 'yellow'\n return c(style, `${score}/100`)\n}\n\ninterface HeadlineCounts {\n drift: number\n noun: string\n driftedCount: number\n checkNoun: string\n erroredCount: number\n erroredNoun: string\n}\n\n/**\n * The one-line verdict.\n *\n * Drift wins over an error, and an error wins over silence: a check that could\n * not run measured nothing, so \"no drift detected\" would be a claim the scan\n * never earned (issue #29).\n */\nfunction formatHeadline(counts: HeadlineCounts): string {\n const prefix = bold('SupaForge scan complete:')\n if (counts.drift > 0) {\n return `${prefix} ${warn(`${counts.drift} drift ${counts.noun}`)} found across ${counts.driftedCount} ${counts.checkNoun}.`\n }\n if (counts.erroredCount > 0) {\n return `${prefix} ${warn(`${counts.erroredCount} ${counts.erroredNoun} could not complete`)} — drift is unknown.`\n }\n return `${prefix} ${ok('no drift detected. ✓')}`\n}\n\nexport function renderSummary(result: ScanResult): string {\n const lines: string[] = ['']\n\n // Counted separately: a posture finding is real but is not a difference\n // between the two environments (issue #40).\n const { drift, posture } = splitCounts(result)\n const noun = drift === 1 ? 'issue' : 'issues'\n const postureNoun = posture === 1 ? 'finding' : 'findings'\n const driftedCount = result.checks.filter(l => l.status === 'drifted' && isComparisonCheck(l.check)).length\n const checkNoun = driftedCount === 1 ? 'check' : 'checks'\n\n // A check that errored measured nothing. Reporting that as \"no drift\n // detected\" told users the environments matched when in truth the\n // comparison never ran (issue #29).\n const erroredCount = countErrored(result)\n const erroredNoun = erroredCount === 1 ? 'check' : 'checks'\n\n // A skipped check measured nothing either. It is a normal outcome rather\n // than a failure, so it is reported separately from an error — but it must\n // never read as a comparison that passed (issue #42).\n const skippedCount = countSkipped(result)\n const skippedNoun = skippedCount === 1 ? 'check was' : 'checks were'\n\n lines.push(formatHeadline({ drift, noun, driftedCount, checkNoun, erroredCount, erroredNoun }))\n\n // Named as what they are, so they cannot be read as the environments having\n // diverged. They are reported and scored, just not as drift.\n if (posture > 0) {\n lines.push(dim(`${posture} posture ${postureNoun} (RLS coverage / migration history) — present regardless of which pair you diff.`))\n }\n\n if (skippedCount > 0) {\n lines.push(dim(`${skippedCount} ${skippedNoun} skipped — coverage is partial.`))\n }\n\n // Drift was found *and* something failed: say so, or the count reads as the\n // whole picture.\n if (drift > 0 && erroredCount > 0) {\n lines.push(warn(`${erroredCount} further ${erroredNoun} could not complete — drift may be understated.`))\n }\n lines.push(`${dim('Source:')} ${result.source} ${dim('→')} ${dim('Target:')} ${result.target}`)\n lines.push('')\n\n for (const lr of result.checks) {\n lines.push(formatCheckLine(lr))\n }\n\n lines.push('')\n // The denominator the score was computed over, so 100/100 across a partial\n // run cannot be mistaken for a full comparison (issue #42).\n const { compared, total } = coverage(result)\n const coverageNote = compared === total ? '' : dim(` (${compared} of ${total} checks compared)`)\n lines.push(`${dim('Drift score:')} ${colorScore(result.score)}${coverageNote}`)\n\n if (result.postureScore !== null && result.postureScore !== undefined) {\n lines.push(`${dim('Posture score:')} ${colorScore(result.postureScore)}${dim(' (target only — RLS coverage, migration history)')}`)\n }\n lines.push('')\n\n return lines.join('\\n')\n}\n\nexport function renderDetailed(result: ScanResult): string {\n const lines = [renderSummary(result)]\n\n // Surface errored checks first — a check that couldn't run is more important\n // to see than the drift it failed to measure. Without this they only appeared\n // as a one-line \"(error: ...)\" in the summary with no detail or remediation.\n for (const lr of result.checks) {\n if (lr.status !== 'error') continue\n lines.push(formatErroredCheck(lr))\n }\n\n for (const lr of result.checks) {\n if (lr.issues.length === 0) continue\n const meta = CHECK_META[lr.check]\n lines.push(dim(`${'─'.repeat(2)} Layer ${meta.number}: ${meta.label} ${'─'.repeat(40)}`))\n lines.push('')\n\n for (const issue of lr.issues) {\n lines.push(formatIssue(issue))\n }\n }\n\n return lines.join('\\n')\n}\n\nfunction formatErroredCheck(lr: CheckResult): string {\n const meta = CHECK_META[lr.check]\n const lines: string[] = []\n lines.push(c('red', `── Layer ${meta.number}: ${meta.label} — could not run ${'─'.repeat(28)}`))\n lines.push('')\n lines.push(` ${c('red', '✖')} ${bold('Check failed — drift for this layer is unknown')}`)\n const errText = lr.error || 'check failed (no error message captured)'\n for (const line of errText.split('\\n')) {\n lines.push(` ${dim(line)}`)\n }\n lines.push('')\n lines.push(` ${dim('This layer was skipped in the totals above. Fix the error and re-run to')}`)\n lines.push(` ${dim('measure its drift; the score treats an errored check as unverified.')}`)\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction formatCheckLine(lr: CheckResult): string {\n const meta = CHECK_META[lr.check]\n const icon = statusIcon(lr.status)\n const prefix = ` ${icon} Layer ${meta.number} (${meta.label}):`\n\n // \"0 issues\" is the wrong thing to print for a layer that never ran — it is\n // the exact text a clean comparison produces (issue #42). Reuses the\n // `skipped — reason` form `snapshot` already uses for the same situation.\n if (lr.status === 'skipped') {\n const reason = lr.skipReason ? ` — ${lr.skipReason}` : ''\n return `${prefix.padEnd(CHECK_LINE_PADDING)}${dim(`skipped${reason}`)}`\n }\n\n const count = lr.issues.length\n const noun = count === 1 ? 'issue' : 'issues'\n const severity = highestSeverity(lr)\n const sevLabel = severity ? ` ${colorSeverity(severity)}` : ''\n const errText = lr.error || (lr.status === 'error' ? 'check failed' : '')\n const errLabel = errText ? ` ${warn(`(error: ${errText})`)}` : ''\n // The live progress line counted these before they were folded; saying so\n // keeps the two numbers from looking inconsistent (issue #97).\n const folded = (lr.folded ?? [])\n .map(f => ` ${dim(`(+${f.count} reported under ${CHECK_META[f.into].label})`)}`)\n .join('')\n return `${prefix.padEnd(CHECK_LINE_PADDING)}${count} ${noun}${sevLabel}${folded}${errLabel}`\n}\n\n/** Glyph for an issue's severity. */\nfunction severityIcon(severity: DriftIssue['severity']): string {\n switch (severity) {\n case 'critical': return c('red', '✖')\n case 'warning': return warn('⚠')\n default: return c('blue', 'ℹ')\n }\n}\n\nfunction formatIssue(issue: DriftIssue): string {\n const lines: string[] = []\n lines.push(` ${severityIcon(issue.severity)} ${colorSeverity(issue.severity)} ${bold(issue.title)}`)\n lines.push(` ${dim(issue.description)}`)\n\n if (issue.sql) {\n lines.push('')\n lines.push(` ${dim('SQL fix (UP):')}`)\n for (const line of issue.sql.up.split('\\n')) {\n lines.push(` ${c('cyan', line)}`)\n }\n } else if (issue.action) {\n lines.push('')\n lines.push(` ${dim('API action:')} ${c('cyan', issue.action.label)}`)\n }\n\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction statusIcon(status: CheckResult['status']): string {\n switch (status) {\n case 'clean': return ok('✓')\n case 'drifted': return warn('●')\n case 'error': return c('red', '✖')\n case 'skipped': return dim('○')\n }\n}\n\nfunction colorSeverity(severity: string): string {\n switch (severity) {\n case 'critical': return c('red', `[${severity.toUpperCase()}]`)\n case 'warning': return warn(`[${severity.toUpperCase()}]`)\n case 'info': return c('blue', `[${severity.toUpperCase()}]`)\n default: return `[${severity.toUpperCase()}]`\n }\n}\n\nfunction highestSeverity(lr: CheckResult): string | null {\n if (lr.issues.some(i => i.severity === 'critical')) return 'critical'\n if (lr.issues.some(i => i.severity === 'warning')) return 'warning'\n if (lr.issues.some(i => i.severity === 'info')) return 'info'\n return null\n}\n\n/** One skipped fix, as `promote` reports it. */\nexport interface SkippedFix {\n check: string\n issueId: string\n reason: string\n}\n\n/** Skipped fixes sharing a check and a reason. */\nexport interface SkipGroup {\n check: string\n reason: string\n issueIds: string[]\n}\n\n/**\n * Collapse skipped fixes that share a check and a reason (issue #84).\n *\n * The reason is a property of the *rule*, not of the issue, so a rule that\n * declines a whole check repeated itself once per issue. A posture check on a\n * project with 47 tables lacking RLS printed the same 150-character sentence\n * 47 times, and the result of the apply — the thing being looked for —\n * scrolled off the top.\n *\n * Grouped by reason rather than by check alone: one check can skip different\n * issues for different reasons, and merging those would misreport why.\n *\n * Insertion-ordered, so the output still follows the order the fixes were\n * planned in.\n */\nexport function groupSkips(skipped: readonly SkippedFix[]): SkipGroup[] {\n const groups = new Map<string, SkipGroup>()\n\n for (const item of skipped) {\n const key = `${item.check} ${item.reason}`\n const existing = groups.get(key)\n if (existing) existing.issueIds.push(item.issueId)\n else groups.set(key, { check: item.check, reason: item.reason, issueIds: [item.issueId] })\n }\n\n return [...groups.values()]\n}\n\n/** How many issue ids a collapsed group names before saying \"and N more\". */\nexport const SKIP_IDS_SHOWN = 6\n\n/**\n * An issue id with its leading check name removed.\n *\n * Only when the whole segment matches, so an id that merely begins with the\n * same letters keeps all of it, and never down to nothing.\n */\nfunction shortIssueId(issueId: string, check: string): string {\n for (const separator of ['-', ':']) {\n const prefix = `${check}${separator}`\n if (issueId.startsWith(prefix) && issueId.length > prefix.length) {\n return issueId.slice(prefix.length)\n }\n }\n return issueId\n}\n\n/**\n * Render collapsed skips, without colour so it can be asserted on.\n *\n * A group of one renders exactly as it always did — `id: reason` — so the\n * common case reads unchanged and only the repetitive case is collapsed.\n */\nexport function formatSkips(skipped: readonly SkippedFix[]): string[] {\n const lines: string[] = []\n\n for (const group of groupSkips(skipped)) {\n if (group.issueIds.length === 1) {\n lines.push(`○ [${group.check}] ${group.issueIds[0]}: ${group.reason}`)\n continue\n }\n\n // Count first: it is the part that changes between runs, and the reason\n // after it is the part that does not.\n lines.push(`○ [${group.check}] ${group.issueIds.length} issues: ${group.reason}`)\n\n // Issue ids are prefixed with their check, which is already in brackets on\n // the line above; dropping it keeps the list readable at terminal width.\n const shown = group.issueIds.slice(0, SKIP_IDS_SHOWN).map(id => shortIssueId(id, group.check))\n const rest = group.issueIds.length - shown.length\n lines.push(` ${shown.join(', ')}${rest > 0 ? `, …and ${rest} more` : ''}`)\n }\n\n return lines\n}\n"],"mappings":";;;;;;;;;;;;;;AAaO,SAAS,aAAa,QAA4C;AACvE,MAAI,CAAC,MAAM,Q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M,OAAO,MAAM;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;AAQO,SAAS,YAAY,SAA0C;AACpE,QAAM,QAAkB,CAAC;AAEzB,aAAW,SAAS,WAAW,OAAO,GAAG;AACvC,QAAI,MAAM,SAAS,WAAW,GAAG;AAC/B,YAAM,KAAK,WAAM,MAAM,KAAK,KAAK,MAAM,SAAS,CAAC,CAAC,KAAK,MAAM,MAAM,EAAE;AACrE;AAAA,IACF;AAIA,UAAM,KAAK,WAAM,MAAM,KAAK,KAAK,MAAM,SAAS,MAAM,YAAY,MAAM,MAAM,EAAE;AAIhF,UAAM,QAAQ,MAAM,SAAS,MAAM,GAAG,cAAc,EAAE,IAAI,QAAM,aAAa,IAAI,MAAM,KAAK,CAAC;AAC7F,UAAM,OAAO,MAAM,SAAS,SAAS,MAAM;AAC3C,UAAM,KAAK,OAAO,MAAM,KAAK,IAAI,CAAC,GAAG,OAAO,IAAI,eAAU,IAAI,UAAU,EAAE,EAAE;AAAA,EAC9E;AAEA,SAAO;AACT;","names":["c"]}
@@ -0,0 +1,207 @@
1
+ import {
2
+ DEFAULT_MIGRATIONS_DIR,
3
+ Preflight,
4
+ describeFailure,
5
+ redactUrls
6
+ } from "./chunk-SQPCWGQO.js";
7
+ import {
8
+ RUN_LOG_DIR,
9
+ RUN_LOG_FILE,
10
+ RUN_LOG_MAX_ENTRIES,
11
+ loadConfig,
12
+ validateConfig,
13
+ validateSingleEnvConfig
14
+ } from "./chunk-6WAMNZLO.js";
15
+
16
+ // src/base-command.ts
17
+ import { formatWithOptions } from "util";
18
+ import { Command } from "@oclif/core";
19
+
20
+ // src/run-log.ts
21
+ import { readFile, writeFile, mkdir, appendFile } from "fs/promises";
22
+ import { homedir } from "os";
23
+ import { join } from "path";
24
+ function runLogPath() {
25
+ return join(homedir(), RUN_LOG_DIR, RUN_LOG_FILE);
26
+ }
27
+ function runLogDir() {
28
+ return join(homedir(), RUN_LOG_DIR);
29
+ }
30
+ async function appendRunLog(entry) {
31
+ const dir = runLogDir();
32
+ await mkdir(dir, { recursive: true });
33
+ const path = runLogPath();
34
+ const line = JSON.stringify(entry) + "\n";
35
+ await appendFile(path, line, "utf8");
36
+ pruneRunLog(path).catch(() => {
37
+ });
38
+ }
39
+ async function readRunLog() {
40
+ try {
41
+ const raw = await readFile(runLogPath(), "utf8");
42
+ return raw.split("\n").filter(Boolean).map((line) => {
43
+ try {
44
+ return JSON.parse(line);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }).filter((e) => e !== null);
49
+ } catch {
50
+ return [];
51
+ }
52
+ }
53
+ async function pruneRunLog(path) {
54
+ try {
55
+ const raw = await readFile(path, "utf8");
56
+ const lines = raw.split("\n").filter(Boolean);
57
+ if (lines.length <= RUN_LOG_MAX_ENTRIES) return;
58
+ const trimmed = lines.slice(lines.length - RUN_LOG_MAX_ENTRIES);
59
+ await writeFile(path, trimmed.join("\n") + "\n", "utf8");
60
+ } catch {
61
+ }
62
+ }
63
+ function redactArgs(argv) {
64
+ return argv.map(redactUrls);
65
+ }
66
+
67
+ // src/base-command.ts
68
+ var BaseCommand = class extends Command {
69
+ _startTime = 0;
70
+ _logWritten = false;
71
+ _checkSummaries;
72
+ /**
73
+ * Under --json, stdout carries the JSON and nothing else: every other line a
74
+ * command prints — preflight checks, progress — goes to stderr. Before, the
75
+ * text came first and the output did not parse.
76
+ */
77
+ log(message = "", ...args) {
78
+ if (this.argv.includes("--json")) {
79
+ process.stderr.write(formatWithOptions({ colors: false }, message, ...args) + "\n");
80
+ return;
81
+ }
82
+ super.log(message, ...args);
83
+ }
84
+ _jsonWritten = false;
85
+ /** The command's result as JSON, on stdout. */
86
+ json(value) {
87
+ this._jsonWritten = true;
88
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
89
+ }
90
+ /** Call after scan() to attach per-check metadata to the run log entry. */
91
+ setCheckSummaries(summaries) {
92
+ this._checkSummaries = summaries;
93
+ }
94
+ async init() {
95
+ await super.init();
96
+ this._startTime = Date.now();
97
+ }
98
+ async catch(err) {
99
+ this._logWritten = true;
100
+ await this._writeRunLog("error", err.message);
101
+ if (this.argv?.includes("--json") && !this._jsonWritten && !isExitRequest(err)) {
102
+ this.json({ error: redactUrls(describeFailure(err)) });
103
+ }
104
+ return super.catch(err);
105
+ }
106
+ async finally(err) {
107
+ if (!this._logWritten) {
108
+ await this._writeRunLog(err ? "error" : "success", err?.message);
109
+ }
110
+ return super.finally(err);
111
+ }
112
+ async _writeRunLog(exitStatus, error) {
113
+ try {
114
+ const version = this.config?.version;
115
+ const argv = this.argv ?? [];
116
+ await appendRunLog({
117
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
118
+ command: this.id ?? "unknown",
119
+ args: redactArgs(argv),
120
+ durationMs: Date.now() - this._startTime,
121
+ exitStatus,
122
+ error,
123
+ version,
124
+ checkSummaries: this._checkSummaries
125
+ });
126
+ } catch {
127
+ }
128
+ }
129
+ /** Load config or exit with a helpful error. */
130
+ async loadConfigOrFail() {
131
+ try {
132
+ return await loadConfig();
133
+ } catch {
134
+ this.error(
135
+ 'Could not load supaforge.config.json. Run "supaforge init" first.'
136
+ );
137
+ }
138
+ }
139
+ /**
140
+ * Resolve a single environment by name.
141
+ * Accepts an explicit flag value or falls back to config.source.
142
+ */
143
+ resolveEnv(config, envFlag) {
144
+ const envName = envFlag ?? config.source;
145
+ if (!envName) {
146
+ this.error('No environment specified. Use --env=<name> or set "source" in your config.');
147
+ }
148
+ const errors = validateSingleEnvConfig(config, envName);
149
+ if (errors.length > 0) {
150
+ this.error(`Invalid configuration:
151
+ ${errors.join("\n ")}`);
152
+ }
153
+ return { envName, env: config.environments[envName] };
154
+ }
155
+ /**
156
+ * Validate a two-env (source + target) config.
157
+ * Applies flag overrides before validation.
158
+ */
159
+ validateDualEnvConfig(config, sourceFlag, targetFlag) {
160
+ if (sourceFlag) config.source = sourceFlag;
161
+ if (targetFlag) config.target = targetFlag;
162
+ const errors = validateConfig(config);
163
+ if (errors.length > 0) {
164
+ this.error(`Invalid configuration:
165
+ ${errors.join("\n ")}`);
166
+ }
167
+ }
168
+ /** Redact password from a database URL for display. */
169
+ redactUrl(url) {
170
+ return url.replace(/:([^@/]{1,})@/, ":***@");
171
+ }
172
+ /** Resolve the migrations directory from config (with default fallback). */
173
+ resolveMigrationsDir(config) {
174
+ return config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR;
175
+ }
176
+ /**
177
+ * Create, run, and enforce a preflight check.
178
+ * Returns the Preflight instance for commands that need to add custom checks.
179
+ * When `abortMessage` is provided, exits with an error if checks fail.
180
+ */
181
+ createPreflight(title) {
182
+ return new Preflight(title, (m) => this.log(m));
183
+ }
184
+ /**
185
+ * Run a preflight and abort with a user-friendly message if it fails.
186
+ * Returns the report for commands that inspect individual check results.
187
+ */
188
+ async runPreflight(preflight, commandName) {
189
+ const report = await preflight.run();
190
+ if (!report.passed) {
191
+ const reasons = report.checks.filter((c) => !c.passed).map((c) => `${c.label}: ${redactUrls(c.error ?? "failed")}`);
192
+ this.error(this.argv.includes("--json") ? `${commandName} aborted \u2014 ${reasons.join("; ")}` : `${commandName} aborted \u2014 fix the issues above first.`, { exit: 1 });
193
+ }
194
+ return report;
195
+ }
196
+ };
197
+ function isExitRequest(err) {
198
+ const oclif = err?.oclif;
199
+ return typeof oclif?.exit === "number" && err.message?.startsWith("EEXIT");
200
+ }
201
+
202
+ export {
203
+ runLogPath,
204
+ readRunLog,
205
+ BaseCommand
206
+ };
207
+ //# sourceMappingURL=chunk-GZREXCQZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/base-command.ts","../src/run-log.ts"],"sourcesContent":["import { redactUrls, describeFailure } from './utils/error.js'\nimport { formatWithOptions } from 'node:util'\nimport { Command } from '@oclif/core'\nimport { loadConfig, validateConfig, validateSingleEnvConfig } from './config.js'\nimport { Preflight } from './preflight.js'\nimport { DEFAULT_MIGRATIONS_DIR } from './checks/migrations.js'\nimport type { SupaForgeConfig, EnvironmentConfig } from './types/config.js'\nimport type { PreflightReport } from './preflight.js'\nimport { appendRunLog, redactArgs, type RunLogCheckSummary } from './run-log.js'\n\n/**\n * Shared base for all supaforge commands.\n * Extracts config loading, env resolution, URL redaction, and run logging.\n */\nexport abstract class BaseCommand extends Command {\n\n private _startTime = 0\n private _logWritten = false\n private _checkSummaries?: RunLogCheckSummary[]\n\n /**\n * Under --json, stdout carries the JSON and nothing else: every other line a\n * command prints — preflight checks, progress — goes to stderr. Before, the\n * text came first and the output did not parse.\n */\n override log(message = '', ...args: unknown[]): void {\n if (this.argv.includes('--json')) {\n process.stderr.write(formatWithOptions({ colors: false }, message, ...args) + '\\n')\n return\n }\n super.log(message, ...args)\n }\n\n private _jsonWritten = false\n\n /** The command's result as JSON, on stdout. */\n protected json(value: unknown): void {\n this._jsonWritten = true\n process.stdout.write(JSON.stringify(value, null, 2) + '\\n')\n }\n\n /** Call after scan() to attach per-check metadata to the run log entry. */\n protected setCheckSummaries(summaries: RunLogCheckSummary[]): void {\n this._checkSummaries = summaries\n }\n\n override async init(): Promise<void> {\n await super.init()\n this._startTime = Date.now()\n }\n\n override async catch(err: Error): Promise<void> {\n this._logWritten = true\n await this._writeRunLog('error', err.message)\n // --json promises JSON on stdout. A connection error that ended the\n // command before it produced any reached stderr only, and a script reading\n // stdout got nothing to parse. A deliberate exit (this.exit) is not an\n // error to report: its JSON, if any, is already written.\n if (this.argv?.includes('--json') && !this._jsonWritten && !isExitRequest(err)) {\n this.json({ error: redactUrls(describeFailure(err)) })\n }\n return super.catch(err)\n }\n\n override async finally(err: Error | undefined): Promise<void> {\n if (!this._logWritten) {\n await this._writeRunLog(err ? 'error' : 'success', err?.message)\n }\n return super.finally(err)\n }\n\n private async _writeRunLog(exitStatus: 'success' | 'error', error?: string): Promise<void> {\n try {\n const version = this.config?.version\n const argv = this.argv ?? []\n await appendRunLog({\n timestamp: new Date().toISOString(),\n command: this.id ?? 'unknown',\n args: redactArgs(argv),\n durationMs: Date.now() - this._startTime,\n exitStatus,\n error,\n version,\n checkSummaries: this._checkSummaries,\n })\n } catch {\n // Never let logging failures surface to users\n }\n }\n\n /** Load config or exit with a helpful error. */\n protected async loadConfigOrFail(): Promise<SupaForgeConfig> {\n try {\n return await loadConfig()\n } catch {\n this.error(\n 'Could not load supaforge.config.json. Run \"supaforge init\" first.',\n )\n }\n }\n\n /**\n * Resolve a single environment by name.\n * Accepts an explicit flag value or falls back to config.source.\n */\n protected resolveEnv(\n config: SupaForgeConfig,\n envFlag?: string,\n ): { envName: string; env: EnvironmentConfig } {\n const envName = envFlag ?? config.source\n if (!envName) {\n this.error('No environment specified. Use --env=<name> or set \"source\" in your config.')\n }\n\n const errors = validateSingleEnvConfig(config, envName)\n if (errors.length > 0) {\n this.error(`Invalid configuration:\\n ${errors.join('\\n ')}`)\n }\n\n return { envName, env: config.environments[envName] }\n }\n\n /**\n * Validate a two-env (source + target) config.\n * Applies flag overrides before validation.\n */\n protected validateDualEnvConfig(\n config: SupaForgeConfig,\n sourceFlag?: string,\n targetFlag?: string,\n ): void {\n if (sourceFlag) config.source = sourceFlag\n if (targetFlag) config.target = targetFlag\n\n const errors = validateConfig(config)\n if (errors.length > 0) {\n this.error(`Invalid configuration:\\n ${errors.join('\\n ')}`)\n }\n }\n\n /** Redact password from a database URL for display. */\n protected redactUrl(url: string): string {\n return url.replace(/:([^@/]{1,})@/, ':***@')\n }\n\n /** Resolve the migrations directory from config (with default fallback). */\n protected resolveMigrationsDir(config: SupaForgeConfig): string {\n return config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR\n }\n\n /**\n * Create, run, and enforce a preflight check.\n * Returns the Preflight instance for commands that need to add custom checks.\n * When `abortMessage` is provided, exits with an error if checks fail.\n */\n protected createPreflight(title: string): Preflight {\n return new Preflight(title, (m) => this.log(m))\n }\n\n /**\n * Run a preflight and abort with a user-friendly message if it fails.\n * Returns the report for commands that inspect individual check results.\n */\n protected async runPreflight(preflight: Preflight, commandName: string): Promise<PreflightReport> {\n const report = await preflight.run()\n if (!report.passed) {\n // Under --json the checks above went to stderr, so the JSON error names\n // what failed rather than pointing at lines a script never sees.\n const reasons = report.checks.filter(c => !c.passed).map(c => `${c.label}: ${redactUrls(c.error ?? 'failed')}`)\n this.error(this.argv.includes('--json')\n ? `${commandName} aborted — ${reasons.join('; ')}`\n : `${commandName} aborted — fix the issues above first.`, { exit: 1 })\n }\n return report\n }\n}\n\n/** oclif's this.exit() throws an ExitError; it carries `oclif.exit`. */\nfunction isExitRequest(err: unknown): boolean {\n const oclif = (err as { oclif?: { exit?: unknown } } | null)?.oclif\n return typeof oclif?.exit === 'number' && (err as Error).message?.startsWith('EEXIT')\n}\n","/**\n * Persistent command run log stored at ~/.supaforge/run-log.jsonl.\n *\n * Each entry is one JSON object per line (JSONL format) recording:\n * timestamp, command, args (with URLs redacted), duration, exitStatus, error.\n *\n * Used by `supaforge report` to show recent command history.\n * Entries older than RUN_LOG_MAX_ENTRIES are pruned automatically on append.\n */\nimport { readFile, writeFile, mkdir, appendFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { redactUrls } from './utils/error.js'\nimport { RUN_LOG_MAX_ENTRIES, RUN_LOG_DIR, RUN_LOG_FILE } from './constants.js'\n\n/**\n * Per-check summary attached to diff/apply run log entries.\n * Contains only operational metadata — never SQL, table names, or data values.\n * Error strings are sanitized (URLs and file paths stripped) before storage.\n */\nexport interface RunLogCheckSummary {\n check: string\n status: string\n issueCount: number\n durationMs: number\n error?: string\n}\n\nexport interface RunLogEntry {\n timestamp: string\n command: string\n args: string[]\n durationMs: number\n exitStatus: 'success' | 'error'\n error?: string\n /** supaforge version that produced this entry */\n version?: string\n /** Populated by diff/apply: per-check status and counts, no SQL content. */\n checkSummaries?: RunLogCheckSummary[]\n}\n\n/** Full path to the run log file. */\nexport function runLogPath(): string {\n return join(homedir(), RUN_LOG_DIR, RUN_LOG_FILE)\n}\n\n/** Full path to the run log directory. */\nexport function runLogDir(): string {\n return join(homedir(), RUN_LOG_DIR)\n}\n\n/** Append a single run entry to the log. Prunes old entries if needed. */\nexport async function appendRunLog(entry: RunLogEntry): Promise<void> {\n const dir = runLogDir()\n await mkdir(dir, { recursive: true })\n const path = runLogPath()\n const line = JSON.stringify(entry) + '\\n'\n await appendFile(path, line, 'utf8')\n // Prune asynchronously — don't block command output\n pruneRunLog(path).catch(() => {})\n}\n\n/** Read all run log entries (most recent last). Returns [] if file doesn't exist. */\nexport async function readRunLog(): Promise<RunLogEntry[]> {\n try {\n const raw = await readFile(runLogPath(), 'utf8')\n return raw\n .split('\\n')\n .filter(Boolean)\n .map(line => {\n try { return JSON.parse(line) as RunLogEntry }\n catch { return null }\n })\n .filter((e): e is RunLogEntry => e !== null)\n } catch {\n return []\n }\n}\n\n/** Remove oldest entries, keeping at most RUN_LOG_MAX_ENTRIES. */\nasync function pruneRunLog(path: string): Promise<void> {\n try {\n const raw = await readFile(path, 'utf8')\n const lines = raw.split('\\n').filter(Boolean)\n if (lines.length <= RUN_LOG_MAX_ENTRIES) return\n const trimmed = lines.slice(lines.length - RUN_LOG_MAX_ENTRIES)\n await writeFile(path, trimmed.join('\\n') + '\\n', 'utf8')\n } catch {\n // Non-fatal\n }\n}\n\n/** Build a redacted args list safe for logging. Strips passwords from URLs. */\nexport function redactArgs(argv: string[]): string[] {\n return argv.map(redactUrls)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,SAAS,yBAAyB;AAClC,SAAS,eAAe;;;ACOxB,SAAS,UAAU,WAAW,OAAO,kBAAkB;AACvD,SAAS,eAAe;AACxB,SAAS,YAAY;AA+Bd,SAAS,aAAqB;AACnC,SAAO,KAAK,QAAQ,GAAG,aAAa,YAAY;AAClD;AAGO,SAAS,YAAoB;AAClC,SAAO,KAAK,QAAQ,GAAG,WAAW;AACpC;AAGA,eAAsB,aAAa,OAAmC;AACpE,QAAM,MAAM,UAAU;AACtB,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACpC,QAAM,OAAO,WAAW;AACxB,QAAM,OA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QAAQ,CAAC,EAAE;AAC9G,WAAK,MAAM,KAAK,KAAK,SAAS,QAAQ,IAClC,GAAG,WAAW,mBAAc,QAAQ,KAAK,IAAI,CAAC,KAC9C,GAAG,WAAW,+CAA0C,EAAE,MAAM,EAAE,CAAC;AAAA,IACzE;AACA,WAAO;AAAA,EACT;AACF;AAGA,SAAS,cAAc,KAAuB;AAC5C,QAAM,QAAS,KAA+C;AAC9D,SAAO,OAAO,OAAO,SAAS,YAAa,IAAc,SAAS,WAAW,OAAO;AACtF;","names":[]}
@@ -9,8 +9,9 @@ import {
9
9
  pgQuery,
10
10
  quoteIdent,
11
11
  quoteLiteral,
12
- quoteName
13
- } from "./chunk-X6V2GGDZ.js";
12
+ quoteName,
13
+ readOrAbsent
14
+ } from "./chunk-SQPCWGQO.js";
14
15
  import {
15
16
  DEFAULT_IGNORE_SCHEMAS,
16
17
  MIGRATIONS_SUBDIR,
@@ -64,15 +65,18 @@ var VERSIONED_PG_DIRS = [
64
65
  // RHEL / CentOS (PGDG)
65
66
  ];
66
67
  async function resolvePgDumpPath(serverMajor) {
67
- const defaultMajor = await getLocalPgDumpVersion();
68
- if (defaultMajor !== null && defaultMajor >= serverMajor) {
69
- return { path: "pg_dump", major: defaultMajor };
70
- }
71
68
  const named = process.env.SUPAFORGE_PG_BIN?.trim();
72
- if (named && existsSync(`${named}/pg_dump`)) {
69
+ if (named) {
70
+ if (!existsSync(`${named}/pg_dump`)) {
71
+ throw new Error(`SUPAFORGE_PG_BIN is set to "${named}", which has no pg_dump`);
72
+ }
73
73
  const major = await getPgDumpVersionAt(`${named}/pg_dump`);
74
74
  if (major !== null && major >= serverMajor) return { path: `${named}/pg_dump`, major };
75
75
  }
76
+ const defaultMajor = await getLocalPgDumpVersion();
77
+ if (defaultMajor !== null && defaultMajor >= serverMajor) {
78
+ return { path: "pg_dump", major: defaultMajor };
79
+ }
76
80
  for (const v of versionsToCheck(serverMajor)) {
77
81
  for (const tmpl of VERSIONED_PG_DIRS) {
78
82
  const dir = tmpl.replace("{v}", String(v));
@@ -86,6 +90,16 @@ async function resolvePgDumpPath(serverMajor) {
86
90
  }
87
91
  return null;
88
92
  }
93
+ async function describeMissingPgDump(neededMajor) {
94
+ const onPath = await getLocalPgDumpVersion();
95
+ const named = process.env.SUPAFORGE_PG_BIN?.trim();
96
+ const namedMajor = named ? await getPgDumpVersionAt(`${named}/pg_dump`) : null;
97
+ const found = [
98
+ onPath === null ? "none on PATH" : `${onPath} on PATH`,
99
+ ...named ? [`${namedMajor ?? "none"} in SUPAFORGE_PG_BIN`] : []
100
+ ].join(", ");
101
+ return `no pg_dump ${neededMajor} or newer (found: ${found}); set SUPAFORGE_PG_BIN to a directory of PostgreSQL ${neededMajor}+ client tools`;
102
+ }
89
103
  function resolvePgRestorePath(pgDumpPath) {
90
104
  if (pgDumpPath === "pg_dump") return "pg_restore";
91
105
  return pgDumpPath.replace(/pg_dump$/, "pg_restore");
@@ -592,18 +606,10 @@ var RealtimeCheck = class extends Check {
592
606
  return [...publicationIssues, ...policyIssues];
593
607
  }
594
608
  async fetchPolicies(dbUrl) {
595
- try {
596
- return await this.queryFn(dbUrl, schemaPolicySql("realtime"));
597
- } catch {
598
- return [];
599
- }
609
+ return readOrAbsent(async () => await this.queryFn(dbUrl, schemaPolicySql("realtime")), []);
600
610
  }
601
611
  async fetchPublications(dbUrl) {
602
- try {
603
- return await this.queryFn(dbUrl, PUBLICATION_SQL);
604
- } catch {
605
- return [];
606
- }
612
+ return readOrAbsent(async () => await this.queryFn(dbUrl, PUBLICATION_SQL), []);
607
613
  }
608
614
  };
609
615
  var PLATFORM_PUBLICATIONS = ["supabase_realtime_messages_publication"];
@@ -1095,11 +1101,12 @@ async function captureRoleGrants(dir, dbUrl, queryFn) {
1095
1101
  -- and it hides grants the connecting role takes no part in.
1096
1102
  SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
1097
1103
  n.nspname AS table_schema, c.relname AS table_name, NULL::text AS column_name,
1098
- a.privilege_type, a.is_grantable
1104
+ a.privilege_type, a.is_grantable,
1105
+ CASE c.relkind WHEN 'S' THEN 'SEQUENCE' ELSE '' END AS keyword, NULL::text AS args
1099
1106
  FROM pg_class c
1100
1107
  JOIN pg_namespace n ON n.oid = c.relnamespace
1101
1108
  CROSS JOIN LATERAL aclexplode(c.relacl) a
1102
- WHERE c.relacl IS NOT NULL AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
1109
+ WHERE c.relacl IS NOT NULL AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
1103
1110
  AND a.grantee <> c.relowner
1104
1111
  AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (
1105
1112
  'postgres','supabase_admin','authenticator','supabase_auth_admin',
@@ -1108,8 +1115,26 @@ async function captureRoleGrants(dir, dbUrl, queryFn) {
1108
1115
  AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\_%')
1109
1116
  AND n.nspname NOT IN (${excluded})
1110
1117
  UNION ALL
1118
+ -- Routines, through acldefault(): a NULL proacl is EXECUTE to PUBLIC,
1119
+ -- and leaving routines out restored a SECURITY DEFINER function the
1120
+ -- source kept from the API as callable by anyone.
1121
+ SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,
1122
+ n.nspname, p.proname, NULL::text, a.privilege_type, a.is_grantable,
1123
+ CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, pg_get_function_identity_arguments(p.oid)
1124
+ FROM pg_proc p
1125
+ JOIN pg_namespace n ON n.oid = p.pronamespace
1126
+ CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
1127
+ WHERE a.grantee <> p.proowner
1128
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
1129
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (
1130
+ 'postgres','supabase_admin','authenticator','supabase_auth_admin',
1131
+ 'supabase_storage_admin','dashboard_user','pgbouncer','supavisor'
1132
+ ))
1133
+ AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\_%')
1134
+ AND n.nspname NOT IN (${excluded})
1135
+ UNION ALL
1111
1136
  SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,
1112
- n.nspname, c.relname, att.attname, a.privilege_type, a.is_grantable
1137
+ n.nspname, c.relname, att.attname, a.privilege_type, a.is_grantable, '', NULL::text
1113
1138
  FROM pg_attribute att
1114
1139
  JOIN pg_class c ON c.oid = att.attrelid
1115
1140
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -1117,21 +1142,23 @@ async function captureRoleGrants(dir, dbUrl, queryFn) {
1117
1142
  WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
1118
1143
  AND a.grantee <> c.relowner
1119
1144
  AND n.nspname NOT IN (${excluded})
1120
- ORDER BY 1, 2, 3, 4, 5
1145
+ ORDER BY 1, 2, 3, 8, 4, 5
1121
1146
  `);
1122
1147
  const grouped = /* @__PURE__ */ new Map();
1123
1148
  for (const row of rows) {
1124
1149
  const key = JSON.stringify([
1125
1150
  row.grantee,
1151
+ row.keyword,
1126
1152
  row.table_schema,
1127
1153
  row.table_name,
1154
+ row.args,
1128
1155
  row.column_name,
1129
1156
  Boolean(row.is_grantable),
1130
1157
  row.privilege_type === "MAINTAIN"
1131
1158
  ]);
1132
1159
  grouped.set(key, [...grouped.get(key) ?? [], row]);
1133
1160
  }
1134
- const statements = [...grouped.values()].map(([row, ...rest]) => `GRANT ${[row, ...rest].map((r) => r.privilege_type + (r.column_name ? ` (${quoteName(r.column_name)})` : "")).join(", ")} ON ${quoteName(row.table_schema)}.${quoteName(row.table_name)} TO ${row.grantee === "PUBLIC" ? "PUBLIC" : quoteName(row.grantee)}` + (row.is_grantable ? " WITH GRANT OPTION" : "") + ";");
1161
+ const statements = [...grouped.values()].map(([row, ...rest]) => `GRANT ${[row, ...rest].map((r) => r.privilege_type + (r.column_name ? ` (${quoteName(r.column_name)})` : "")).join(", ")} ON ${row.keyword ? `${row.keyword} ` : ""}${quoteName(row.table_schema)}.${quoteName(row.table_name)}` + (row.args !== null && row.keyword !== "SEQUENCE" && row.keyword ? `(${row.args})` : "") + ` TO ${row.grantee === "PUBLIC" ? "PUBLIC" : quoteName(row.grantee)}` + (row.is_grantable ? " WITH GRANT OPTION" : "") + ";");
1135
1162
  const output = statements.length > 0 ? `-- SupaForge Role Grants Snapshot
1136
1163
  -- ${rows.length} grant(s)
1137
1164
 
@@ -1251,6 +1278,7 @@ export {
1251
1278
  dropEquivalentPolicyChanges,
1252
1279
  RealtimeCheck,
1253
1280
  resolvePgDumpPath,
1281
+ describeMissingPgDump,
1254
1282
  getServerMajorVersion,
1255
1283
  checkPgDumpCompat,
1256
1284
  captureSnapshot,
@@ -1261,4 +1289,4 @@ export {
1261
1289
  DEFAULT_KEEP_COUNT,
1262
1290
  pruneSnapshots
1263
1291
  };
1264
- //# sourceMappingURL=chunk-YVDSR4GM.js.map
1292
+ //# sourceMappingURL=chunk-MIRLB5JM.js.map