@akal/supaforge 0.0.0-stage → 0.0.31

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 (99) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +134 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dbdiff.ts","../src/dbdiff-units.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport { createRequire } from 'node:module'\nimport { readFile, unlink, access } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { DriftIssue } from './types/drift'\nimport { errMsg, friendlyDbError, DiagnosticError } from './utils/error'\nimport { DBDIFF_EXEC_TIMEOUT_MS, DBDIFF_MAX_BUFFER } from './constants'\nimport { schemaDiffIgnores } from './defaults'\nimport { parseStatements, names, relationName, type Statement } from './sql-ast.js'\nimport { sqlSkeleton, policiesRemoved } from './sql-deps'\nimport { escapeRegex } from './utils/strings'\nimport { pairUnits, parseUnits, REPLACING_KINDS, type DbDiffUnit } from './dbdiff-units'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface DbDiffOptions {\n sourceUrl: string\n targetUrl: string\n type: 'schema' | 'data' | 'all'\n include: 'up' | 'down' | 'both'\n tables?: string[]\n ignoreTables?: string[]\n /** Schemas to exclude — converted to --ignore-tables=schema.* glob patterns. */\n ignoreSchemas?: string[]\n /**\n * Seconds before the diff is abandoned, from the target environment's\n * checks.schema.timeout. SUPAFORGE_DBDIFF_TIMEOUT still wins over this.\n */\n timeoutSeconds?: number\n /**\n * Called as dbdiff reports progress on individual tables, so a long schema\n * diff reads as working rather than hung (issue #29).\n */\n onProgress?: (progress: { table: string; tablesSeen: number }) => void\n /**\n * Ask a schema diff for `--units` (the default). Set false for a dbdiff\n * that predates the flag — runDbDiff does so itself when one refuses it.\n */\n units?: boolean\n}\n\nexport interface DbDiffResult {\n up: string\n down: string\n}\n\n/**\n * Resolve the @dbdiff/cli binary path from node_modules.\n *\n * Uses createRequire to locate the installed package, then returns\n * the path to `bin/dbdiff.js`. Falls back to 'npx' if the package\n * is not installed locally (e.g. global install).\n *\n * `SUPAFORGE_DBDIFF_BIN` overrides both with an executable of your own — a\n * DBDiff checkout's `dbdiff` script, say. That is how DBDiff's CI runs\n * SupaForge's scenarios against an unreleased change, and how a fix can be\n * tried through SupaForge before it ships, without touching node_modules.\n */\nexport function resolveDbDiffBin(): { command: string; prefixArgs: string[] } {\n const override = process.env.SUPAFORGE_DBDIFF_BIN?.trim()\n if (override) return { command: override, prefixArgs: [] }\n try {\n const require = createRequire(import.meta.url)\n const binPath = require.resolve('@dbdiff/cli/bin/dbdiff.js')\n return { command: process.execPath, prefixArgs: [binPath] }\n } catch {\n // Fallback: try npx for global installs\n return { command: 'npx', prefixArgs: ['@dbdiff/cli'] }\n }\n}\n\n/**\n * Run @dbdiff/cli and parse UP/DOWN SQL output.\n *\n * Writes to a temp file via --output, reads it back, then parses\n * the `-- ==================== UP ====================` /\n * `-- ==================== DOWN ====================` markers.\n *\n * When @dbdiff/cli is not installed, throws with a clear message.\n */\n/**\n * Resolve the effective dbdiff timeout (ms).\n *\n * Honours the SUPAFORGE_DBDIFF_TIMEOUT environment variable (in seconds) so\n * users with very large schemas can raise the ceiling without a code change.\n * Falls back to DBDIFF_EXEC_TIMEOUT_MS.\n */\nexport function resolveDbDiffTimeoutMs(configuredSeconds?: number): number {\n // Precedence: env var > per-environment config > default. The env var is the\n // runtime escape hatch, so it has to beat a committed config value.\n const raw = process.env.SUPAFORGE_DBDIFF_TIMEOUT\n if (raw) {\n const secs = Number(raw)\n if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1000)\n }\n if (Number.isFinite(configuredSeconds) && (configuredSeconds as number) > 0) {\n return Math.round((configuredSeconds as number) * 1000)\n }\n return DBDIFF_EXEC_TIMEOUT_MS\n}\n\n/**\n * dbdiff logs a line per table as it works. Recognising them turns a silent\n * multi-minute spinner into visible progress.\n *\n * Matches both the per-table diff line and the batch pre-scan summary, and is\n * tolerant of the ANSI colour codes dbdiff emits.\n */\nconst DBDIFF_TABLE_LINE = /calculating schema diff for table [`\"']?([\\w.$]+)/i\n\nexport function parseDbDiffProgress(line: string): string | null {\n return DBDIFF_TABLE_LINE.exec(line)?.[1] ?? null\n}\n\n/**\n * Resolve the PHP memory limit to hand to @dbdiff/cli, if any.\n *\n * @dbdiff/cli caps itself at 1G by default, which is ample for most Supabase\n * projects but can be exceeded by a very large schema or a wide data diff.\n * SUPAFORGE_DBDIFF_MEMORY passes straight through to `--memory-limit`, taking\n * the same values dbdiff accepts: \"512M\", \"2G\", or \"-1\" for unlimited.\n *\n * Returns undefined when unset or malformed, leaving dbdiff on its own default\n * rather than forwarding a value it would reject.\n */\nexport function resolveDbDiffMemoryLimit(): string | undefined {\n const raw = process.env.SUPAFORGE_DBDIFF_MEMORY?.trim()\n if (!raw) return undefined\n return /^-?\\d+[KMG]?$/i.test(raw) ? raw : undefined\n}\n\n/**\n * Strip @dbdiff/cli progress / spinner noise from captured output.\n *\n * dbdiff logs informational lines such as \"ℹ Now generating UP migration\"\n * to stdout while it works. When the process is killed (e.g. on timeout)\n * that last progress line is the only thing in the buffer — surfacing it as\n * the \"error\" is misleading. Drop any line that begins with a known\n * info/spinner glyph and keep only genuine error-looking content.\n */\nconst DBDIFF_NOISE_LINE = /^\\s*[ℹ✔✓⚠⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u\n\nexport function stripDbDiffNoise(text: string): string {\n return text\n .split('\\n')\n .filter(line => line.trim() !== '' && !DBDIFF_NOISE_LINE.test(line))\n .join('\\n')\n .trim()\n}\n\n/**\n * Build the full @dbdiff/cli argument list for a diff run.\n *\n * Split out of runDbDiff() so the flag surface is one readable unit and can be\n * asserted directly in tests, rather than only through a spawned process.\n */\nexport function buildDbDiffArgs(options: DbDiffOptions, outputFile: string): string[] {\n const args = [\n 'diff',\n `--server1-url=${options.sourceUrl}`,\n `--server2-url=${options.targetUrl}`,\n `--type=${options.type}`,\n // Was hardcoded to 'both', silently ignoring options.include. Every caller\n // passes 'both' (sqlToIssues pairs each UP statement with its DOWN\n // counterpart, so it needs both directions), but the option was part of the\n // public interface and did nothing.\n `--include=${options.include}`,\n '--nocomments',\n // @dbdiff/cli >= 3.0.0-rc.3 refuses to emit a migration containing\n // DROP TABLE or DROP COLUMN unless this is passed, exiting non-zero and\n // writing no output file. SupaForge is a *detection* tool: an extra table\n // or column on the target is the single most common form of drift, and it\n // has to be reported rather than turned into a hard failure. The safety\n // gate belongs at apply time instead — see isDestructiveSql()/promote(),\n // which skip these statements unless the user opts in explicitly.\n '--allow-destructive',\n `--output=${outputFile}`,\n ]\n\n // Each schema change marked as one unit, so a change of several statements\n // is one finding and its DOWN is found by name — see dbdiff-units.ts. Data\n // diffs stay statement by statement: a unit there is a table's rows, and\n // rows are reviewed and applied one at a time.\n if (options.type === 'schema' && options.units !== false) {\n args.push('--units')\n }\n\n const memoryLimit = resolveDbDiffMemoryLimit()\n if (memoryLimit) {\n args.push(`--memory-limit=${memoryLimit}`)\n }\n\n // A schema diff compares every schema but the ignored ones. dbdiff named\n // tables without their schema, so these were once passed as table globs\n // (auth.*) that matched nothing: dbdiff read `public` alone. Data diffs\n // name their tables in checks.data.tables, which are in `public`.\n if (options.type === 'schema' && options.ignoreSchemas) {\n args.push(`--ignore-schemas=${schemaDiffIgnores(options.ignoreSchemas).join(',')}`)\n }\n const ignore = options.ignoreTables ?? []\n\n if (options.tables?.length) {\n args.push(`--tables=${options.tables.join(',')}`)\n }\n if (ignore.length) {\n args.push(`--ignore-tables=${ignore.join(',')}`)\n }\n\n return args\n}\n\n/**\n * Forward dbdiff's per-table log lines to a progress callback.\n *\n * Entirely best-effort: any failure here must never affect the diff itself,\n * so every step is guarded. A missing stdout (possible if the process dies\n * immediately) simply means no progress is reported.\n */\nfunction attachProgress(\n running: { child?: { stdout?: NodeJS.ReadableStream | null } },\n onProgress?: (progress: { table: string; tablesSeen: number }) => void,\n): void {\n if (!onProgress) return\n try {\n const stdout = running.child?.stdout\n if (!stdout) return\n\n let buffer = ''\n let tablesSeen = 0\n stdout.on('data', (chunk: Buffer | string) => {\n try {\n buffer += String(chunk)\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const table = parseDbDiffProgress(line)\n if (table) {\n tablesSeen++\n onProgress({ table, tablesSeen })\n }\n }\n } catch {\n // Progress reporting is cosmetic — never let it break the run.\n }\n })\n stdout.on('error', () => {})\n } catch {\n // Same: cosmetic only.\n }\n}\n\nexport async function runDbDiff(options: DbDiffOptions): Promise<DbDiffResult> {\n const { command, prefixArgs } = resolveDbDiffBin()\n const outputFile = join(tmpdir(), `supaforge-dbdiff-${Date.now()}-${Math.random().toString(36).slice(2)}.sql`)\n\n const args = [...prefixArgs, ...buildDbDiffArgs(options, outputFile)]\n\n const timeoutMs = resolveDbDiffTimeoutMs(options.timeoutSeconds)\n\n try {\n const running = execFileAsync(command, args, {\n timeout: timeoutMs,\n maxBuffer: DBDIFF_MAX_BUFFER,\n })\n\n // Attach to the child's stdout for progress without changing how it is\n // executed — promisified execFile exposes the ChildProcess as `.child`,\n // so timeout, maxBuffer and every error path stay exactly as they were.\n attachProgress(running, options.onProgress)\n\n await running\n\n // When schemas are identical, dbdiff exits 0 but doesn't write the file\n const fileExists = await access(outputFile).then(() => true, () => false)\n if (!fileExists) {\n return { up: '', down: '' }\n }\n\n const output = await readFile(outputFile, 'utf8')\n return parseDbDiffOutput(output)\n } catch (err: unknown) {\n const errObj = (err ?? {}) as Record<string, unknown>\n const message = errMsg(err)\n const stderr = String(errObj.stderr ?? '').trim()\n const stdout = String(errObj.stdout ?? '').trim()\n const combined = `${message} ${stderr}`\n\n // A dbdiff older than --units (3.0.0-rc.17) refuses the flag; its output\n // is read statement by statement instead.\n if (options.units !== false && /\"--units\" option does not exist/.test(`${combined} ${stdout}`)) {\n return runDbDiff({ ...options, units: false })\n }\n\n if (\n combined.includes('ENOENT') ||\n combined.includes('not found') ||\n combined.includes('ERR_MODULE_NOT_FOUND') ||\n combined.includes('could not determine executable') ||\n combined.includes('404')\n ) {\n throw new DiagnosticError(\n '@dbdiff/cli is not installed. Install it with: npm install @dbdiff/cli',\n )\n }\n\n // @dbdiff/cli exits 1 when differences are found (standard diff convention).\n // The output file is written before exit — read it if it has real content.\n const fileExists = await access(outputFile).then(() => true, () => false)\n if (fileExists) {\n const output = await readFile(outputFile, 'utf8')\n const parsed = parseDbDiffOutput(output)\n if (parsed.up || parsed.down) return parsed\n }\n\n // Timeout / killed process. execFileAsync sets `killed: true` and a SIGTERM\n // signal when it kills the child on timeout. Previously this fell through and\n // surfaced dbdiff's last progress line (\"ℹ Now generating UP migration\") as\n // the error — hiding the real cause. Report it clearly instead.\n const timedOut =\n errObj.killed === true ||\n errObj.signal === 'SIGTERM' ||\n errObj.code === 'ETIMEDOUT' ||\n /ETIMEDOUT|timed out/i.test(combined)\n if (timedOut) {\n const secs = Math.round(timeoutMs / 1000)\n throw new DiagnosticError(\n `Schema diff timed out after ${secs}s — the schema is very large or the ` +\n `database connection is slow.\\n` +\n ` Remediations:\\n` +\n ` • Raise the limit: set SUPAFORGE_DBDIFF_TIMEOUT=600 (seconds) and re-run.\\n` +\n ` • Narrow the scan: diff one layer at a time with --check=schema.\\n` +\n ` • Exclude large internal schemas via \"ignoreSchemas\" in supaforge.config.json.`,\n )\n }\n\n // No usable output file → genuine error (connection refused, auth, etc.).\n // Prefer stderr; otherwise fall back to stdout with dbdiff's progress/spinner\n // noise stripped so an info line never masquerades as the error. Strip the raw\n // \"Command failed: /path/to/node ...\" prefix which leaks connection URLs.\n const realError = stderr || stripDbDiffNoise(stdout)\n const cleanMessage = realError\n ? realError\n : message.replace(/^Command failed:[^\\n]*/m, '').trim() || 'dbdiff failed with no error output'\n throw new Error(friendlyDbError(cleanMessage, options.sourceUrl))\n } finally {\n await unlink(outputFile).catch(() => {})\n }\n}\n\nconst UP_MARKER = '-- ==================== UP ===================='\nconst DOWN_MARKER = '-- ==================== DOWN ===================='\n\nconst CREATE_FUNCTION = 'create-function'\nconst DROP_FUNCTION = 'drop-function'\n\nconst DROP_TYPES = ['drop', 'drop-view', DROP_FUNCTION, 'drop-trigger', 'drop-type', 'drop-sequence']\n\n/**\n * Does this statement destroy data, or weaken access control, if executed?\n *\n * Still narrower than DROP_TYPES: dropping a view, function, trigger or type\n * loses a definition the migration can recreate. What is gated is losing rows\n * or losing a policy.\n *\n * It used to cover `DROP TABLE` and `ALTER TABLE … DROP COLUMN` only, so two\n * things went through `--apply` that the flag exists to hold back (issue #88):\n *\n * - `DELETE FROM`, which is how the data check removes rows the source does\n * not have. Rows are exactly what `--allow-destructive` is about.\n * - `DROP POLICY`, which is not recoverable from the schema and, for a\n * RESTRICTIVE policy, *grants* access by removing it. The RLS check renders\n * a *modified* policy as a drop and a create of the same name, and that is\n * a replacement rather than a removal — so only a policy left dropped\n * counts.\n *\n * Matching runs over `sqlSkeleton`, so the words appearing inside a string\n * literal or a routine body cannot trigger it — and matching is no longer\n * anchored to the start, since a merged replacement pair puts the second\n * statement mid-string.\n */\nexport function isDestructiveSql(sql: string): boolean {\n return destructiveReason(sql) !== undefined\n}\n\n/**\n * Why this statement is gated, in the words the skip line should use.\n *\n * `recreatedElsewhere` holds the policies (`schema.table.policy`, as createdPolicies\n * keys them) that other fixes applied alongside this one create.\n *\n * \"Destructive (drops data)\" was printed for every case once policies joined\n * the list, which is wrong for a policy — nothing is lost from a table, and\n * saying so obscures the part that matters, that removing a RESTRICTIVE policy\n * opens access up.\n */\nexport function destructiveReason(\n sql: string,\n recreatedElsewhere: ReadonlySet<string> = new Set(),\n): string | undefined {\n const statements = parseStatements(sql)\n return statements\n ? destructiveInTree(statements, recreatedElsewhere)\n : destructiveInText(sql, recreatedElsewhere)\n}\n\n/**\n * destructiveReason() read from PostgreSQL's parse tree — see sql-ast.ts.\n *\n * The tree says what each statement is, so none of the cases the text\n * version guards against can arise: `GRANT TRUNCATE` is a GrantStmt, not a\n * TruncateStmt, and a function body mentioning `DROP TABLE` is a string.\n */\nfunction destructiveInTree(statements: Statement[], recreatedElsewhere: ReadonlySet<string>): string | undefined {\n const dropped = (type: string) => statements.some(s => s.kind === 'DropStmt' && s.node.removeType === type)\n if (dropped('OBJECT_SCHEMA')) return 'drops a schema and everything in it'\n if (dropped('OBJECT_TABLE')) return 'drops a table and its rows'\n if (statements.some(s => s.kind === 'TruncateStmt')) return 'deletes every row in a table'\n if (columnsDroppedForGoodInTree(statements).length > 0) return 'drops a column and its values'\n if (statements.some(s => s.kind === 'DeleteStmt')) return 'deletes rows'\n if (statements.some(s => s.kind === 'DropRoleStmt')) return 'drops a role, and every login and grant it holds'\n\n // A policy the same SQL creates again is being replaced, not removed — as\n // is one another fix in the apply recreates (recreatedElsewhere).\n // Keyed `schema.table.policy`, as createdPolicies keys them: `public` where\n // the table names no schema.\n const key = (schema: string | undefined, table: string, policy: string) =>\n `${(schema || 'public').toLowerCase()}.${table.toLowerCase()}.${policy.toLowerCase()}`\n const created = new Set(statements.filter(s => s.kind === 'CreatePolicyStmt')\n .map(s => key(s.node.table?.schemaname, relationName(s.node.table), s.node.policy_name)))\n const policies = statements\n .filter(s => s.kind === 'DropStmt' && s.node.removeType === 'OBJECT_POLICY')\n .flatMap(s => (s.node.objects as Array<Record<string, any>>).map(o => names(o.List?.items)))\n .map(parts => key(parts.at(-3), parts.at(-2) ?? '', parts.at(-1) ?? ''))\n .filter(k => !created.has(k) && !recreatedElsewhere.has(k))\n if (policies.length > 0) {\n return policies.length === 1\n ? `removes the policy ${policies[0]}, which may widen access`\n : `removes ${policies.length} policies, which may widen access`\n }\n return undefined\n}\n\n/** Columns an ALTER TABLE drops, unless a later command in the same SQL adds them back. */\nfunction columnsDroppedForGoodInTree(statements: Statement[]): string[] {\n const commands = statements\n .filter(s => s.kind === 'AlterTableStmt')\n .flatMap(s => (s.node.cmds as Array<Record<string, any>>).map(c => ({ table: relationName(s.node.relation), cmd: c.AlterTableCmd })))\n return commands.flatMap(({ table, cmd }, i) => {\n if (cmd?.subtype !== 'AT_DropColumn') return []\n const readded = commands.slice(i + 1).some(later =>\n later.table === table && later.cmd?.subtype === 'AT_AddColumn' && later.cmd.def?.ColumnDef?.colname === cmd.name)\n return readded ? [] : [cmd.name as string]\n })\n}\n\n/**\n * destructiveReason() read from the text, for SQL PostgreSQL's parser does not\n * accept — a fragment, or a dialect it does not speak. What it did before the\n * parse tree was used.\n */\nfunction destructiveInText(sql: string, recreatedElsewhere: ReadonlySet<string>): string | undefined {\n const skeleton = sqlSkeleton(sql).toUpperCase()\n\n if (/\\bDROP\\s+SCHEMA\\b/.test(skeleton)) return 'drops a schema and everything in it'\n if (/\\bDROP\\s+TABLE\\b/.test(skeleton)) return 'drops a table and its rows'\n // At the start of a statement only. TRUNCATE is also a privilege and a\n // trigger event, so `GRANT TRUNCATE ON t TO anon` and `BEFORE TRUNCATE ON t`\n // were held back as though they emptied the table — and Supabase's default\n // `GRANT ALL` includes TRUNCATE, so every grant fix for a new table tripped it.\n if (/(?:^|;)\\s*TRUNCATE\\b/.test(skeleton)) return 'deletes every row in a table'\n if (columnsDroppedForGood(skeleton).length > 0) return 'drops a column and its values'\n if (/\\bDELETE\\s+FROM\\b/.test(skeleton)) return 'deletes rows'\n // A role is not schema: it is who can log in. The roles check offered\n // `DROP ROLE` for every role only the target had, including the one the\n // apply was connected as, and nothing held it back.\n if (/(?:^|;)\\s*DROP\\s+(?:ROLE|USER|GROUP)\\b/.test(skeleton)) return 'drops a role, and every login and grant it holds'\n\n // A policy another fix in the same apply creates again is being replaced,\n // not removed: a column type change drops the policies reading the column\n // and the policy's own fix puts the new one back once the type has changed.\n const policies = policiesRemoved(sql).filter(key => !recreatedElsewhere.has(key))\n if (policies.length > 0) {\n return policies.length === 1\n ? `removes the policy ${policies[0]}, which may widen access`\n : `removes ${policies.length} policies, which may widen access`\n }\n\n return undefined\n}\n\n/**\n * Columns a statement drops and does not add back.\n *\n * A stored generated column whose expression changes, or that reads a column\n * being retyped, is dropped and re-added in the same change — recomputed from\n * its expression, so nothing is lost — and was held back as though its values\n * were. Matched on the upper-cased skeleton, so names compare as written.\n */\nfunction columnsDroppedForGood(skeleton: string): string[] {\n const ident = String.raw`(\"(?:[^\"]|\"\")+\"|[\\w$]+)`\n const dropped = [...skeleton.matchAll(new RegExp(String.raw`\\bDROP\\s+COLUMN\\s+(?:IF\\s+EXISTS\\s+)?` + ident, 'g'))]\n return dropped\n .filter(m => !new RegExp(String.raw`\\bADD\\s+COLUMN\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?` + escapeRegex(m[1]) + String.raw`(?![\\w$\"])`)\n .test(skeleton.slice((m.index ?? 0) + m[0].length)))\n .map(m => m[1])\n}\n\nexport function parseDbDiffOutput(output: string): DbDiffResult {\n const upIdx = output.indexOf(UP_MARKER)\n const downIdx = output.indexOf(DOWN_MARKER)\n\n if (upIdx === -1 && downIdx === -1) {\n // Might be UP-only output without markers\n return { up: output.trim(), down: '' }\n }\n\n let up = ''\n let down = ''\n\n if (upIdx !== -1) {\n const upStart = upIdx + UP_MARKER.length\n const upEnd = downIdx !== -1 ? downIdx : output.length\n up = output.slice(upStart, upEnd).trim()\n }\n\n if (downIdx !== -1) {\n const downStart = downIdx + DOWN_MARKER.length\n down = output.slice(downStart).trim()\n }\n\n return { up, down }\n}\n\n/**\n * Convert @dbdiff/cli SQL output into DriftIssues.\n *\n * Each SQL statement (separated by `;`) becomes its own issue\n * with the appropriate severity and layer.\n *\n * When `ignoreSchemas` is provided, FK constraint statements that\n * reference tables in ignored schemas are filtered out — these are\n * false positives caused by dbdiff seeing stub tables.\n *\n * `ignoredSchemaTables` is an optional pre-queried set of table names\n * (lowercase) that exist inside ignored schemas. When provided it lets the\n * filter catch unqualified REFERENCES like `REFERENCES \"users\"` where\n * \"users\" lives in the ignored \"auth\" schema but dbdiff omitted the prefix.\n */\nexport function sqlToIssues(\n result: DbDiffResult,\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n const issues = unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables)\n return check === 'schema' ? foldCommentsIntoCreates(issues) : issues\n}\n\n/** What a comment title names: `public.orders.total (column)` → the name and kind. */\nconst COMMENT_TITLE = /^(?:Comment changed|Comment missing): (?:schema (.+)|(.+) \\(([a-z ]+)\\))$/\n/**\n * A finding that creates an object, `Table missing: public.orders`, or\n * recreates one, `View modified: public.v`: dbdiff sets a recreated object's\n * comments again, and apart those read as \"Comment changed\" on a comment that\n * had not.\n */\nconst CREATE_TITLE = /^(Schema|Table|View|Function|Procedure|Type|Domain|Sequence|Index|Policy|Trigger|Extension) (?:missing|modified): (.+)$/\n/** Kinds named after the table (or domain) they belong to. */\nconst ON_A_TABLE = new Set(['column', 'constraint', 'trigger', 'policy', 'rule'])\n\n/**\n * A comment on an object the target does not have yet goes with the finding\n * that creates it.\n *\n * DBDiff emits each comment on its own, so a missing table with three\n * commented columns was four findings, three of them titled \"Comment changed\"\n * on an object that was not there to change. Folded, the comment runs right\n * after its object is made; dropping the object takes the comment with it, so\n * nothing is added to the DOWN.\n */\nexport function foldCommentsIntoCreates(issues: DriftIssue[]): DriftIssue[] {\n const creates = new Map<string, DriftIssue>()\n /** New routines by name alone, for a comment whose signature is spelled differently. */\n const routines = new Map<string, DriftIssue[]>()\n for (const issue of issues) {\n const m = CREATE_TITLE.exec(issue.title)\n if (!m) continue\n creates.set(`${m[1] === 'Schema' ? 'schema' : 'object'}:${m[2]}`, issue)\n if (m[1] === 'Function' || m[1] === 'Procedure') {\n const base = routineBaseName(m[2])\n routines.set(base, [...(routines.get(base) ?? []), issue])\n }\n }\n\n return issues.filter(issue => {\n const up = issue.sql?.up\n if (!up) return true\n const owner = commentOwner(issue, up, creates, routines) ?? rlsFlagsOwner(issue, up, creates)\n if (!owner?.sql) return true\n\n owner.sql = { ...owner.sql, up: `${owner.sql.up.trimEnd()}\\n${up.trim()}` }\n return false\n })\n}\n\n/**\n * The finding creating the object a comment is on. dbdiff names a routine by\n * its argument types in a comment (`f2(integer,pg_catalog.text)`) and by its\n * parameter list in the create (`f2(p_x integer, p_y text DEFAULT 'a')`), so a\n * routine is matched by name when only one new routine has it.\n */\nfunction commentOwner(\n issue: DriftIssue, up: string, creates: Map<string, DriftIssue>, routines: Map<string, DriftIssue[]>,\n): DriftIssue | undefined {\n const m = COMMENT_TITLE.exec(issue.title)\n if (!m || splitStatements(up).length !== 1) return undefined\n const [, schema, name, kind] = m\n const candidates = schema !== undefined\n ? [`schema:${schema}`]\n : [`object:${name}`, ...(ON_A_TABLE.has(kind) ? [`object:${name.slice(0, name.lastIndexOf('.'))}`] : [])]\n const exact = candidates.map(c => creates.get(c)).find(Boolean)\n if (exact || (kind !== 'function' && kind !== 'procedure')) return exact\n const sameName = routines.get(routineBaseName(name)) ?? []\n return sameName.length === 1 ? sameName[0] : undefined\n}\n\n/** A routine's name without its argument list. */\nconst routineBaseName = (name: string) => name.includes('(') ? name.slice(0, name.indexOf('(')) : name\n\n/** `ALTER TABLE t ENABLE ROW LEVEL SECURITY` and the like, the whole of a finding. */\nconst RLS_FLAG = /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?\\S+\\s+(?:ENABLE|DISABLE|(?:NO\\s+)?FORCE)\\s+ROW\\s+LEVEL\\s+SECURITY\\s*;?\\s*$/i\n\n/**\n * The finding creating a table whose RLS flags a finding sets: a table that\n * does not exist yet had them as a separate \"Table altered\".\n */\nfunction rlsFlagsOwner(issue: DriftIssue, up: string, creates: Map<string, DriftIssue>): DriftIssue | undefined {\n const m = /^Table altered: (.+)$/.exec(issue.title)\n if (!m || !splitStatements(up).every(sql => RLS_FLAG.test(sql))) return undefined\n return creates.get(`object:${m[1]}`)\n}\n\nfunction unfoldedIssues(\n result: DbDiffResult,\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n if (!result.up && !result.down) return []\n\n const upUnits = parseUnits(result.up)\n if (upUnits) {\n return issuesFromUnits(upUnits, parseUnits(result.down) ?? [], check, ignoreSchemas, ignoredSchemaTables)\n }\n\n let upStatements = splitStatements(result.up)\n let downStatements = splitStatements(result.down)\n\n // Filter out FK constraints that reference tables in ignored schemas.\n // These arise because dbdiff compares stub tables vs real Supabase tables.\n // We check both UP and DOWN statements — dbdiff generates broken REFERENCES \"\" (\"\")\n // in the DOWN when the referenced table is in an ignored schema.\n // `ignoredSchemaTables` additionally catches unqualified refs like\n // REFERENCES \"users\" where \"users\" lives in the ignored \"auth\" schema.\n if (ignoreSchemas?.length && check === 'schema') {\n const keep = filterCrossSchemaFks(upStatements, downStatements, ignoreSchemas, ignoredSchemaTables)\n upStatements = upStatements.filter((_, i) => keep[i])\n downStatements = downStatements.filter((_, i) => keep[i])\n }\n\n if (upStatements.length === 0) return []\n\n upStatements = groupColumnTypeChanges(upStatements)\n downStatements = groupColumnTypeChanges(downStatements)\n\n const merged = mergeReplacements(upStatements, downStatements)\n\n // Generate one issue per UP statement, paired with its DOWN counterpart\n return merged.map(({ up: upSql, down: downSql, modified }, i) => {\n // A grouped column type change is named by its ALTER, not by the DROP\n // that opens the group.\n const lead = columnTypeChangeOf(upSql) ?? upSql\n const type = classifyStatement(lead)\n\n if (modified) {\n const report = REPLACEABLE_REPORT[modified.kind]\n return {\n id: `${check}-alter-${report.idPart}-${i + 1}`,\n check,\n severity: 'warning' as const,\n title: `${report.label}: ${qualifySchemaName(modified.name)}`,\n description: `${report.what} differs between source and target.`,\n sql: { up: upSql, down: downSql },\n }\n }\n\n return {\n id: `${check}-${type}-${i + 1}`,\n check,\n severity: DROP_TYPES.includes(type) ? 'critical' : 'warning',\n // The DOWN counterpart is passed so a title can recover a schema the UP\n // statement does not carry — see routineLabel (issue #47).\n title: summariseStatement(lead, check, downSql),\n description: `${check === 'schema' ? 'Schema' : 'Data'} difference detected by @dbdiff/cli.`,\n sql: { up: upSql, down: downSql },\n }\n })\n}\n\n/**\n * One finding per dbdiff unit (see dbdiff-units.ts), paired with the DOWN\n * unit for the same change.\n *\n * Named as the statement-by-statement path names them: a unit replacing one\n * object — a changed routine, policy, or enum whose labels were removed — is\n * \"<Kind> modified\"; anything else by its leading statement, which for a\n * table change is its first ALTER TABLE rather than a view it stands aside.\n */\nfunction issuesFromUnits(\n upUnits: DbDiffUnit[],\n downUnits: DbDiffUnit[],\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) =>\n !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)))\n\n return pairs.map(({ up, down }, i) => {\n const upSql = up.sql\n const downSql = down?.sql ?? ''\n const statements = splitStatements(upSql)\n const replaced = replacedObject(up, statements)\n const manualOnly = manualEnumChange(up)\n const manual = manualOnly ? { manualOnly } : {}\n\n if (replaced) {\n const report = REPLACEABLE_REPORT[replaced.kind]\n return {\n id: `${check}-alter-${report.idPart}-${i + 1}`,\n check,\n severity: 'warning' as const,\n title: `${report.label}: ${qualifySchemaName(replaced.name)}`,\n description: `${report.what} differs between source and target.`,\n sql: { up: upSql, down: downSql },\n ...manual,\n }\n }\n\n const lead = leadStatement(up, statements)\n const type = classifyStatement(lead)\n return {\n id: `${check}-${type}-${i + 1}`,\n check,\n severity: DROP_TYPES.includes(type) ? 'critical' : 'warning',\n title: summariseStatement(lead, check, downSql),\n description: `${check === 'schema' ? 'Schema' : 'Data'} difference detected by @dbdiff/cli.`,\n sql: { up: upSql, down: downSql },\n ...manual,\n }\n })\n}\n\n/**\n * Why an enum change cannot be applied automatically, when dbdiff says so.\n *\n * Removing or reordering labels moves everything using the type to a new one;\n * what a move cannot carry — a routine taking the type, a domain over it — dbdiff\n * names in a comment and falls back to replacing the type, which PostgreSQL\n * refuses. Applied, that one refusal rolled back every other fix with it, so\n * it is reported as a manual step instead, naming what is in the way.\n */\nfunction manualEnumChange(unit: DbDiffUnit): string | undefined {\n if (unit.kind !== 'AlterEnum' || !/^--.*\\benum labels\\b/im.test(unit.sql)) return undefined\n const blockers = [...unit.sql.matchAll(/^--\\s{3}(.+)$/gm)].map(m => m[1].trim())\n return 'removing or reordering these enum labels needs the type replaced'\n + (blockers.length > 0 ? `, and these use it in ways that cannot be moved automatically: ${blockers.join(', ')}` : '')\n + '. Migrate them first, then re-run, or apply the change by hand.'\n}\n\n/**\n * A constraint change about a foreign key into an ignored schema — a false\n * positive from dbdiff seeing that schema's tables as stubs. The reference is\n * in the ADD, which is the UP of an added key and the DOWN of a dropped one.\n */\nfunction isCrossSchemaFkUnit(\n up: DbDiffUnit,\n down: DbDiffUnit | undefined,\n schemas: string[],\n ignoredSchemaTables?: Set<string>,\n): boolean {\n if (!/Constraint$/.test(up.kind)) return false\n return [up.sql, down?.sql ?? ''].some(sql =>\n /\\bFOREIGN\\s+KEY\\b/i.test(sql)\n && (hasCrossSchemaRef(sql, schemas, ignoredSchemaTables) || hasBrokenRef(sql)))\n}\n\n/** The object a unit drops and recreates, when that is what it does. */\nfunction replacedObject(\n unit: DbDiffUnit,\n statements: string[],\n): { kind: ReplaceableKind; name: string } | undefined {\n const kind = REPLACING_KINDS[unit.kind]\n const drop = statements.find(sql => replaceablePart(sql)?.drop)\n if (!kind || !drop) return undefined\n\n if (kind === 'type') return { kind, name: unit.object }\n const create = [...statements].reverse().find(sql => replaceablePart(sql)?.drop === false) ?? drop\n return {\n kind,\n name: kind === 'routine'\n ? extractRoutineName(create) + extractRoutineArgs(drop)\n : REPLACEABLE_NAME[kind](create),\n }\n}\n\n/**\n * The statement a unit is named by: for a table change, its first ALTER\n * TABLE (a column type change opens by standing views aside; a serial column\n * by creating its sequence); otherwise its first statement.\n */\nfunction leadStatement(unit: DbDiffUnit, statements: string[]): string {\n if (unit.kind.startsWith('AlterTable')) {\n const alter = statements.find(sql => /^\\s*ALTER\\s+TABLE\\b/i.test(sql))\n if (alter) return alter\n }\n return statements[0] ?? unit.sql\n}\n\n/** `ALTER TABLE t ALTER COLUMN c TYPE ...`, capturing the table and column. */\nconst ALTER_COLUMN_TYPE = /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+ALTER\\s+COLUMN\\s+(\"[^\"]+\"|[\\w$]+)\\s+(?:SET\\s+DATA\\s+)?TYPE\\b/i\n\n/** The ALTER ... TYPE statement inside a grouped column change, if this is one. */\nfunction columnTypeChangeOf(sql: string): string | undefined {\n if (!/^\\s*DROP\\s+/i.test(sql)) return undefined\n return splitStatements(sql).find(s => ALTER_COLUMN_TYPE.test(s))\n}\n\n/** An identifier without quotes or a `public.` qualifier, for comparing names. */\nfunction plainName(identifier: string): string {\n return identifier.replace(/\"/g, '').replace(/^public\\./i, '').trim()\n}\n\n/**\n * Keep a column type change together with the dependants dbdiff drops and\n * recreates around it.\n *\n * PostgreSQL refuses `ALTER COLUMN ... TYPE` while a view, policy or trigger\n * condition reads the column, so @dbdiff/cli brackets the change: drop them,\n * retype, recreate them with their grants and comments. As separate issues\n * that bracket came apart — the DROP POLICY was held back by the destructive\n * gate as a removal while the ALTER went ahead and failed, and two column\n * changes under one view each became a CREATE VIEW, the second of which\n * failed on the first. One change, one issue.\n *\n * Recognised by shape: the DROP ... IF EXISTS statements immediately before\n * the ALTER, and after it the rest of that column's change and the statements\n * that recreate, grant, comment on or index what was dropped. A plain type\n * change with nothing around it is left exactly as it was.\n */\nexport function groupColumnTypeChanges(statements: string[]): string[] {\n const out: string[] = []\n let i = 0\n\n while (i < statements.length) {\n const alter = ALTER_COLUMN_TYPE.exec(statements[i])\n if (!alter) {\n out.push(statements[i])\n i++\n continue\n }\n\n const [, table, column] = alter\n const views = new Set<string>()\n const attached = new Set<string>() // `name@table` for policies and triggers\n\n // Walk back over the drops dbdiff emitted for this change.\n const drops: Array<{ index: number; view?: string; attached?: string; table?: string }> = []\n let start = out.length\n while (start > 0) {\n const drop = /^\\s*DROP\\s+(?:(MATERIALIZED\\s+VIEW|VIEW)|(POLICY|TRIGGER))\\s+IF\\s+EXISTS\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)(?:\\s+ON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?))?\\s*;?\\s*$/i\n .exec(out[start - 1])\n if (!drop) break\n if (drop[1]) {\n views.add(plainName(drop[3]))\n drops.unshift({ index: start - 1, view: plainName(drop[3]) })\n } else {\n const key = `${plainName(drop[3])}@${plainName(drop[4] ?? '')}`\n attached.add(key)\n drops.unshift({ index: start - 1, attached: key, table: plainName(drop[4] ?? '') })\n }\n start--\n }\n if (drops.length === 0) {\n out.push(statements[i])\n i++\n continue\n }\n\n const onView = (name: string) => views.has(plainName(name))\n const recreated = new Set<string>()\n const belongs = (sql: string): boolean => {\n const sameColumn = ALTER_COLUMN_TYPE.exec(sql)\n ?? /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+ALTER\\s+COLUMN\\s+(\"[^\"]+\"|[\\w$]+)\\s+(?:SET|DROP)\\b/i.exec(sql)\n if (sameColumn) return plainName(sameColumn[1]) === plainName(table) && plainName(sameColumn[2]) === plainName(column)\n\n let m = /^\\s*CREATE\\s+(?:MATERIALIZED\\s+)?VIEW\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+(?:TABLE\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+(?:TO|FROM)\\b/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*COMMENT\\s+ON\\s+(?:MATERIALIZED\\s+VIEW|VIEW)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*COMMENT\\s+ON\\s+COLUMN\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\.(?:\"[^\"]+\"|[\\w$]+)\\s+IS\\b/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*CREATE\\s+(?:POLICY|(?:CONSTRAINT\\s+)?TRIGGER)\\s+(\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) {\n const key = `${plainName(m[1])}@${plainName(m[2])}`\n if (attached.has(key)) { recreated.add(key); return true }\n return onView(m[2])\n }\n return false\n }\n\n let end = i + 1\n while (end < statements.length && belongs(statements[end])) end++\n\n // A policy or trigger drop that is neither on the altered table nor put\n // back here belongs to another diff that happened to land next to this\n // one — a policy genuinely being removed. Grouping it would put the whole\n // column change behind the destructive gate with it, so the run is\n // trimmed from its far end until only this change's own drops remain.\n const foreign = (d: typeof drops[number]) =>\n d.attached !== undefined && d.table !== plainName(table) && !recreated.has(d.attached)\n while (drops.length > 0 && foreign(drops[0])) {\n drops.shift()\n start++\n }\n if (drops.length === 0) {\n out.push(statements[i])\n i++\n continue\n }\n\n const group = [...out.splice(start), ...statements.slice(i, end)]\n out.push(group.join('\\n'))\n i = end\n }\n\n return out\n}\n\ninterface MergedStatement {\n up: string\n down: string\n /** Set when this entry is a DROP+CREATE pair replacing one object. */\n modified?: { kind: ReplaceableKind; name: string }\n}\n\n/**\n * The object kinds dbdiff replaces by dropping and recreating.\n *\n * Routines were the first (issue #35). Types, domains and sequences behave the\n * same way — an enum whose values changed arrives as `DROP TYPE` + `CREATE\n * TYPE` — and needed the same treatment for the same two reasons (issue #81).\n */\ntype ReplaceableKind = 'routine' | 'type' | 'sequence' | 'policy' | 'trigger' | 'view'\n\n/** How each kind's identifier is read out of a statement. */\nconst REPLACEABLE_NAME: Record<ReplaceableKind, (sql: string) => string> = {\n routine: extractRoutineName,\n type: (sql) => extractQualifiedName(sql, /\\b(?:TYPE|DOMAIN)\\s+(?:IF\\s+EXISTS\\s+)?/i),\n sequence: (sql) => extractQualifiedName(sql, /\\bSEQUENCE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i),\n // `table.policy`: a policy name is unique only per table.\n policy: (sql) => policyLabel(sql),\n // `schema.table.trigger`, for the same reason.\n trigger: (sql) => triggerLabel(sql),\n view: (sql) => extractQualifiedName(sql, AFTER.view),\n}\n\n/** How a merged pair of each kind is reported. */\nconst REPLACEABLE_REPORT: Record<ReplaceableKind, { idPart: string; label: string; what: string }> = {\n routine: { idPart: 'function', label: 'Function modified', what: 'Function body' },\n type: { idPart: 'type', label: 'Type modified', what: 'Type definition' },\n sequence: { idPart: 'sequence', label: 'Sequence modified', what: 'Sequence definition' },\n policy: { idPart: 'policy', label: 'Policy modified', what: 'Policy definition' },\n trigger: { idPart: 'trigger', label: 'Trigger modified', what: 'Trigger definition' },\n view: { idPart: 'view', label: 'View modified', what: 'View definition' },\n}\n\n/** Whether a statement drops or creates a replaceable object, and of which kind. */\nfunction replaceablePart(sql: string): { kind: ReplaceableKind; drop: boolean } | undefined {\n // dbdiff renders a changed policy as DROP POLICY + CREATE POLICY, adjacent.\n // Apart, the DROP read as a policy *removed* and was held back by the\n // destructive gate (issue #88), leaving the CREATE to fail on the policy\n // still there. Together they are a replacement, which the gate allows.\n if (/^\\s*DROP\\s+POLICY\\b/i.test(sql)) return { kind: 'policy', drop: true }\n if (/^\\s*CREATE\\s+POLICY\\b/i.test(sql)) return { kind: 'policy', drop: false }\n // A changed trigger is dropped and recreated the same way, and read apart\n // was a critical \"Extra trigger\" for a trigger that is still wanted.\n if (/^\\s*DROP\\s+TRIGGER\\b/i.test(sql)) return { kind: 'trigger', drop: true }\n // A changed view too: dbdiff can only replace one, and a PostgreSQL 15\n // and 16+ pair printed every view differently.\n if (/^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i.test(sql)) return { kind: 'view', drop: true }\n if (/^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i.test(sql)) return { kind: 'view', drop: false }\n if (/^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i.test(sql)) return { kind: 'trigger', drop: false }\n switch (classifyStatement(sql)) {\n case CREATE_FUNCTION: return { kind: 'routine', drop: false }\n case DROP_FUNCTION: return { kind: 'routine', drop: true }\n case 'create-type': return { kind: 'type', drop: false }\n case 'drop-type': return { kind: 'type', drop: true }\n case 'create-sequence': return { kind: 'sequence', drop: false }\n case 'drop-sequence': return { kind: 'sequence', drop: true }\n default: return undefined\n }\n}\n\n/** Kind and bare name together, so a function and a type of one name cannot pair. */\nfunction replacementKey(kind: ReplaceableKind, sql: string): string {\n const name = REPLACEABLE_NAME[kind](sql)\n if (kind === 'policy') return `policy:${name.replace(/\"/g, '').toLowerCase()}`\n // Table and trigger, without the schema a DROP may leave out.\n if (kind === 'trigger') return `trigger:${name.split('.').slice(-2).join('.').toLowerCase()}`\n return `${kind}:${name.slice(name.lastIndexOf('.') + 1).toLowerCase()}`\n}\n\n/**\n * Collapse `DROP FUNCTION` + `CREATE [OR REPLACE] FUNCTION` pairs for the same\n * routine into a single entry.\n *\n * dbdiff replaces a changed function by emitting both statements. Treating them\n * as independent issues reported one modified function twice — once as a\n * CRITICAL \"Extra function\" and once as a WARNING \"Function missing\" — when it\n * is neither extra nor missing (issue #35). On a real diff that inflated 105\n * genuine differences into 149 reported issues, and dragged the drift score\n * down via the bogus criticals.\n *\n * Only a DROP followed by a CREATE for the same routine is merged; an\n * unpaired DROP is still a genuine \"Extra function\".\n *\n * Postgres allows overloading, so one name can own several DROP+CREATE pairs\n * whose argument types differ. They cannot be told apart by name, and the\n * statements do not agree on a signature to match them by (see `replacementKey`),\n * so pairing goes by position:\n *\n * - Adjacent DROP+CREATE always merge. dbdiff renders a changed routine from a\n * single diff object, so the two statements come out together — adjacency is\n * what a replacement actually looks like.\n * - A non-adjacent pair merges only when that name has exactly one DROP and one\n * CREATE in the batch, where there is nothing to confuse it with. This is\n * the case issue #35 was about.\n *\n * Anything else stays unmerged and is reported as a genuine extra or missing\n * routine, which is the safe direction: over-reporting is noise, whereas a\n * wrong pairing writes a migration that drops an overload and recreates a\n * different one in its place.\n */\nexport function mergeReplacements(\n upStatements: string[],\n downStatements: string[],\n): MergedStatement[] {\n // Per key, the indices of the CREATEs still up for grabs, in source order.\n const unclaimedCreates = new Map<string, number[]>()\n const dropCounts = new Map<string, number>()\n upStatements.forEach((sql, i) => {\n const part = replaceablePart(sql)\n if (!part) return\n\n const key = replacementKey(part.kind, sql)\n if (part.drop) {\n dropCounts.set(key, (dropCounts.get(key) ?? 0) + 1)\n } else {\n unclaimedCreates.set(key, [...(unclaimedCreates.get(key) ?? []), i])\n }\n })\n\n const absorbed = new Set<number>()\n const out: MergedStatement[] = []\n\n upStatements.forEach((upSql, i) => {\n if (absorbed.has(i)) return\n\n const down = downStatements[i] ?? ''\n const part = replaceablePart(upSql)\n if (!part?.drop) {\n out.push({ up: upSql, down })\n return\n }\n\n const key = replacementKey(part.kind, upSql)\n const unambiguous = dropCounts.get(key) === 1 && unclaimedCreates.get(key)?.length === 1\n const createIdx = claimCreateFor(unclaimedCreates, key, i, unambiguous)\n if (createIdx === undefined) {\n out.push({ up: upSql, down })\n return\n }\n\n const createSql = upStatements[createIdx]\n absorbed.add(createIdx)\n out.push({\n // Drop first, create second, in one statement. Kept together rather than\n // ordered apart because `orderStatements` sends drops to the last phase\n // and creates to an early one, which put the CREATE before the DROP it\n // was replacing — `type \"order_state\" already exists`, and the whole\n // apply rolled back (issue #81). Phasing reads the CREATE in a merged\n // pair, so the pair runs where the object it leaves behind belongs.\n up: `${upSql}\\n${createSql}`,\n down: [down, downStatements[createIdx] ?? ''].filter(Boolean).join('\\n'),\n modified: {\n kind: part.kind,\n // A routine's name is qualified by its argument types, since overloads\n // share a name; nothing else can be overloaded.\n name: part.kind === 'routine'\n ? extractRoutineName(createSql) + extractRoutineArgs(upSql)\n : REPLACEABLE_NAME[part.kind](createSql),\n },\n })\n })\n\n return out\n}\n\n/**\n * Claim the CREATE that replaces the DROP at `dropIdx`, removing it so a later\n * DROP of the same name cannot claim it too.\n *\n * Normally that is the immediately following statement. When `unambiguous` —\n * one DROP and one CREATE for this name in the whole batch — any later CREATE\n * will do, since there is no second candidate to get it wrong.\n */\nfunction claimCreateFor(\n unclaimed: Map<string, number[]>,\n key: string,\n dropIdx: number,\n unambiguous: boolean,\n): number | undefined {\n const queue = unclaimed.get(key)\n if (!queue) return undefined\n\n const at = queue.findIndex((idx) => (unambiguous ? idx > dropIdx : idx === dropIdx + 1))\n if (at === -1) return undefined\n\n return queue.splice(at, 1)[0]\n}\n\n/**\n * Identify which UP statements to keep after filtering cross-schema FK false positives.\n *\n * Two-pass approach:\n * 1. Mark ADD CONSTRAINT ... FOREIGN KEY statements where the UP references an\n * ignored schema or the DOWN counterpart has broken `REFERENCES \"\" (\"\")`,\n * or the referenced table (even unqualified) is in `ignoredSchemaTables`.\n * 2. Mark paired DROP CONSTRAINT statements that share the same constraint name.\n */\nfunction filterCrossSchemaFks(\n upStmts: string[],\n downStmts: string[],\n schemas: string[],\n ignoredSchemaTables?: Set<string>,\n): boolean[] {\n const keep = new Array<boolean>(upStmts.length).fill(true)\n\n // Collect constraint names that are cross-schema FKs\n const crossSchemaConstraints = new Set<string>()\n\n // Pass 1: detect ADD CONSTRAINT ... FOREIGN KEY with cross-schema refs\n for (let i = 0; i < upStmts.length; i++) {\n const upper = upStmts[i].toUpperCase()\n if (!upper.includes('ADD CONSTRAINT') || !upper.includes('FOREIGN KEY')) continue\n\n const isCrossSchema =\n hasCrossSchemaRef(upStmts[i], schemas, ignoredSchemaTables) ||\n (downStmts[i] != null && hasBrokenRef(downStmts[i]))\n\n if (isCrossSchema) {\n keep[i] = false\n const name = upStmts[i].match(/CONSTRAINT\\s+\"([^\"]+)\"/i)?.[1]\n if (name) crossSchemaConstraints.add(name)\n }\n }\n\n // Pass 2: filter paired DROP CONSTRAINT for the same FK names\n for (let i = 0; i < upStmts.length; i++) {\n if (!keep[i]) continue\n const upper = upStmts[i].toUpperCase()\n if (!upper.includes('DROP CONSTRAINT')) continue\n const name = upStmts[i].match(/DROP\\s+CONSTRAINT\\s+\"([^\"]+)\"/i)?.[1]\n if (name && crossSchemaConstraints.has(name)) {\n keep[i] = false\n }\n }\n\n return keep\n}\n\n/**\n * Check if a REFERENCES clause points to an ignored schema, is empty/broken,\n * or is unqualified but the referenced table exists in an ignored schema.\n *\n * Handles three forms:\n * REFERENCES \"\" (\"\") — broken ref from dbdiff, always filtered\n * REFERENCES \"auth\".\"users\" (\"id\") — schema-qualified into an ignored schema: kept\n * when the target has that table, else filtered\n * REFERENCES \"users\" (\"id\") — unqualified, filtered if \"users\" is in\n * ignoredSchemaTables (queried from target DB)\n */\nfunction hasCrossSchemaRef(sql: string, schemas: string[], ignoredSchemaTables?: Set<string>): boolean {\n const refsMatch = sql.match(/REFERENCES\\s+\"([^\"]*)\"(?:\\s*\\.\\s*\"([^\"]*)\")?\\s*\\(\\s*\"([^\"]*)\"\\s*\\)/i)\n if (!refsMatch) return false\n const [, first, second] = refsMatch\n // Broken: REFERENCES \"\" (\"\")\n if (first === '') return true\n // Schema-qualified: REFERENCES \"auth\".\"users\" (\"id\"). A key from the user's\n // own schema onto an ignored one — every Supabase table referencing\n // auth.users — is real drift, kept when the target has the table it\n // references. Filtered only when that is not known, as before: dbdiff\n // before 3.0.0-rc.18 rendered these without the schema, which is why they\n // were all dropped, and so they were never synced.\n if (second !== undefined) {\n if (!schemas.some(s => s.toLowerCase() === first.toLowerCase())) return false\n return !ignoredSchemaTables?.has(`${first}.${second}`.toLowerCase())\n }\n // Unqualified: REFERENCES \"users\" (\"id\") — filter if the table lives in an ignored schema.\n // This catches the case where pg_dump or dbdiff drops the schema prefix due to\n // search_path, so the reference appears unqualified even though it targets e.g. auth.users.\n return ignoredSchemaTables ? ignoredSchemaTables.has(first.toLowerCase()) : false\n}\n\n/** Check if SQL contains a broken REFERENCES \"\" (\"\") from dbdiff. */\nfunction hasBrokenRef(sql: string): boolean {\n return /REFERENCES\\s+\"\"\\s*\\(\\s*\"\"\\s*\\)/i.test(sql)\n}\n\nfunction splitStatements(sql: string): string[] {\n if (!sql) return []\n\n const statements: string[] = []\n let buf = ''\n let i = 0\n\n while (i < sql.length) {\n // Dollar-quoted string: $tag$...$tag$ consumed as a single token so that\n // semicolons inside function/trigger/procedure bodies are not treated as\n // statement boundaries. The tag is /\\$([A-Za-z0-9_]*)\\$/ e.g. $$ or $body$.\n if (sql[i] === '$') {\n const tagMatch = sql.slice(i + 1).match(/^([A-Za-z0-9_]*)\\$/)\n if (tagMatch) {\n const tag = `$${tagMatch[1]}$`\n const closeIdx = sql.indexOf(tag, i + tag.length)\n if (closeIdx !== -1) {\n buf += sql.slice(i, closeIdx + tag.length)\n i = closeIdx + tag.length\n continue\n }\n }\n }\n\n // Statement boundary: ';' optionally followed by spaces/tabs/CR then '\\n'\n if (sql[i] === ';') {\n buf += ';'\n i++\n let j = i\n while (j < sql.length && (sql[j] === ' ' || sql[j] === '\\t' || sql[j] === '\\r')) j++\n if (j >= sql.length || sql[j] === '\\n') {\n const stmt = withoutLeadingComments(buf)\n if (stmt.length > 0) {\n statements.push(stmt)\n }\n buf = ''\n i = j < sql.length ? j + 1 : j\n }\n continue\n }\n\n buf += sql[i]\n i++\n }\n\n // Flush any trailing content without a statement-ending newline\n const last = withoutLeadingComments(buf)\n if (last.length > 0) {\n statements.push(last.endsWith(';') ? last : `${last};`)\n }\n\n return statements\n}\n\n/**\n * A statement without the `--` lines in front of it.\n *\n * A statement opening with a comment used to be dropped whole — and dbdiff\n * puts notes in front of statements: the DROP TYPE replacing an enum whose\n * labels it could not move came after three lines saying why, so it never\n * reached a finding.\n */\nfunction withoutLeadingComments(chunk: string): string {\n return chunk.trim().replace(/^(?:--[^\\n]*(?:\\n|$)\\s*)+/, '').trim()\n}\n\nexport function classifyStatement(sql: string): string {\n const upper = sql.toUpperCase().trimStart()\n // Views\n if (upper.startsWith('CREATE VIEW') || upper.startsWith('CREATE OR REPLACE VIEW')) return 'create-view'\n if (upper.startsWith('ALTER VIEW')) return 'alter-view'\n if (upper.startsWith('DROP VIEW')) return 'drop-view'\n // Functions / procedures\n if (upper.startsWith('CREATE FUNCTION') || upper.startsWith('CREATE OR REPLACE FUNCTION')) return CREATE_FUNCTION\n if (upper.startsWith('ALTER FUNCTION')) return 'alter-function'\n if (upper.startsWith('DROP FUNCTION')) return DROP_FUNCTION\n if (upper.startsWith('CREATE PROCEDURE') || upper.startsWith('CREATE OR REPLACE PROCEDURE')) return CREATE_FUNCTION\n if (upper.startsWith('DROP PROCEDURE')) return DROP_FUNCTION\n // Triggers\n if (upper.startsWith('CREATE TRIGGER') || upper.startsWith('CREATE OR REPLACE TRIGGER')) return 'create-trigger'\n if (upper.startsWith('ALTER TRIGGER')) return 'alter-trigger'\n if (upper.startsWith('DROP TRIGGER')) return 'drop-trigger'\n // Types / enums / domains\n if (upper.startsWith('CREATE TYPE')) return 'create-type'\n if (upper.startsWith('ALTER TYPE')) return 'alter-type'\n if (upper.startsWith('DROP TYPE')) return 'drop-type'\n if (upper.startsWith('CREATE DOMAIN')) return 'create-type'\n if (upper.startsWith('ALTER DOMAIN')) return 'alter-type'\n if (upper.startsWith('DROP DOMAIN')) return 'drop-type'\n // Tables\n if (upper.startsWith('ALTER TABLE')) return 'alter'\n if (upper.startsWith('CREATE TABLE')) return 'create-table'\n if (upper.startsWith('DROP TABLE')) return 'drop'\n // Indexes\n if (upper.startsWith('CREATE INDEX') || upper.startsWith('CREATE UNIQUE INDEX')) return 'create-index'\n if (upper.startsWith('DROP INDEX')) return 'drop'\n // Sequences\n if (upper.startsWith('CREATE SEQUENCE')) return 'create-sequence'\n if (upper.startsWith('ALTER SEQUENCE')) return 'alter-sequence'\n if (upper.startsWith('DROP SEQUENCE')) return 'drop-sequence'\n // Data\n if (upper.startsWith('INSERT')) return 'insert'\n if (upper.startsWith('UPDATE')) return 'update'\n if (upper.startsWith('DELETE')) return 'delete'\n return 'change'\n}\n\n/**\n * One title format for every schema finding: `<Finding>: <schema>.<name>`.\n *\n * Each kind used to carry its own ad-hoc regex, and two of them read the wrong\n * capture group: `/INDEX\\s+.../` never reached the index name at all, so\n * `CREATE INDEX idx_orders_status ON public.orders` was titled \"Index missing on\n * public\" — the schema, in the name's place (issue #47). The rules below all\n * go through one schema-aware identifier parser instead.\n *\n * Matched in order and anchored at the start of the statement, so a trigger\n * that executes a function is a trigger, not a function.\n */\ninterface SummaryRule {\n match: RegExp\n label: string\n name: (sql: string, downSql?: string) => string\n}\n\n/** Head patterns for the identifier that follows each keyword. */\nconst AFTER = {\n view: /\\bVIEW\\s+(?:IF\\s+EXISTS\\s+)?/i,\n trigger: /\\bTRIGGER\\s+(?:IF\\s+EXISTS\\s+)?/i,\n type: /\\bTYPE\\s+(?:IF\\s+EXISTS\\s+)?/i,\n domain: /\\bDOMAIN\\s+(?:IF\\s+EXISTS\\s+)?/i,\n sequence: /\\bSEQUENCE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i,\n table: /\\bTABLE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(?:ONLY\\s+)?/i,\n index: /\\bINDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i,\n policy: /\\bPOLICY\\s+(?:IF\\s+EXISTS\\s+)?/i,\n on: /\\bON\\s+(?:ONLY\\s+)?/i,\n}\n\n/** Name an object by the identifier following `head`. */\nconst named = (head: RegExp) => (sql: string) => extractQualifiedName(sql, head)\n\n/**\n * `table.policy` for a policy statement.\n *\n * A policy name is unique only per table, so the table is part of its\n * identity — the same keying the RLS check uses, which means the two checks\n * now name the same policy the same way.\n */\nfunction policyLabel(sql: string): string {\n const policy = extractQualifiedName(sql, AFTER.policy)\n const table = extractQualifiedName(sql, AFTER.on)\n\n if (policy === UNKNOWN_NAME) return UNKNOWN_NAME\n if (table === UNKNOWN_NAME) return policy\n\n // The table is qualified here rather than by the caller: the caller only\n // qualifies a name with no dot in it, and `orders.p` already has one.\n return `${qualifySchemaName(table)}.${policy}`\n}\n\n/**\n * `schema.table.trigger` for a trigger statement.\n *\n * A trigger name is unique only per table, like a policy's, and one name is\n * commonly reused on every table (`set_updated_at`): titled by the name alone,\n * three findings about three tables read as the same one three times. dbdiff\n * leaves the table of a DROP unqualified, so its schema is read off the\n * counterpart CREATE when that is on the same table.\n */\nfunction triggerLabel(sql: string, downSql?: string): string {\n const trigger = extractQualifiedName(sql, AFTER.trigger)\n let table = extractQualifiedName(sql, AFTER.on)\n if (trigger === UNKNOWN_NAME) return UNKNOWN_NAME\n if (table === UNKNOWN_NAME) return trigger\n\n if (!table.includes('.') && downSql) {\n const counterpart = extractQualifiedName(downSql, AFTER.on)\n if (counterpart.includes('.') && unqualify(counterpart) === table.toLowerCase()) table = counterpart\n }\n return `${qualifySchemaName(table)}.${trigger}`\n}\n\n/**\n * The schema @dbdiff/cli compares.\n *\n * Its Postgres adapter is scoped to `public` throughout — every catalogue query\n * filters on `schemaname = 'public'` — so a name it emits without a qualifier is\n * a `public` object, not an object of unknown schema. Restoring the qualifier is\n * recovering information the SQL dropped, not guessing at it.\n */\nconst DBDIFF_SCHEMA = 'public'\n\n/**\n * Put every schema finding's name in the same form: `schema.name`.\n *\n * Whether a name arrived qualified depended on which statement dbdiff happened\n * to emit — `CREATE INDEX ... ON public.orders` carries a schema, `DROP TABLE\n * \"legacy_notes\"` does not — so titles for one run were a mix of both, split by\n * object type rather than by anything a reader could predict, and the mix did\n * not even hold within a type (issue #70). A long list then neither sorted nor\n * aligned.\n *\n * Splits at the first `(` so a routine's argument list cannot be mistaken for a\n * qualifier: `dist(numeric(10,2))` contains dots that are not schema separators.\n */\nfunction qualifySchemaName(name: string): string {\n if (name === UNKNOWN_NAME) return name\n const paren = name.indexOf('(')\n const head = paren === -1 ? name : name.slice(0, paren)\n if (head.includes('.')) return name\n return `${DBDIFF_SCHEMA}.${name}`\n}\n\n/**\n * Qualify an index with the schema of the table it is on.\n *\n * Postgres puts an index in its table's schema and its grammar does not let\n * the CREATE qualify the index name, so the `ON` clause is where the schema\n * actually is. Left bare when the table is unqualified too — the schema is\n * then genuinely unknown, and inventing `public` would be a guess.\n */\nfunction indexLabel(sql: string): string {\n const name = extractQualifiedName(sql, AFTER.index)\n if (name === UNKNOWN_NAME || name.includes('.')) return name\n\n const table = extractQualifiedName(sql, AFTER.on)\n const dot = table.lastIndexOf('.')\n return dot === -1 ? name : `${table.slice(0, dot)}.${name}`\n}\n\nconst SCHEMA_RULES: SummaryRule[] = [\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'View missing', name: named(AFTER.view) },\n { match: /^\\s*ALTER\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'View altered', name: named(AFTER.view) },\n { match: /^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'Extra view', name: named(AFTER.view) },\n\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?FUNCTION\\b/i, label: 'Function missing', name: routineLabel },\n { match: /^\\s*ALTER\\s+FUNCTION\\b/i, label: 'Function altered', name: routineLabel },\n { match: /^\\s*DROP\\s+FUNCTION\\b/i, label: 'Extra function', name: routineLabel },\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?PROCEDURE\\b/i, label: 'Procedure missing', name: routineLabel },\n { match: /^\\s*DROP\\s+PROCEDURE\\b/i, label: 'Extra procedure', name: routineLabel },\n\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i, label: 'Trigger missing', name: triggerLabel },\n { match: /^\\s*ALTER\\s+TRIGGER\\b/i, label: 'Trigger altered', name: triggerLabel },\n { match: /^\\s*DROP\\s+TRIGGER\\b/i, label: 'Extra trigger', name: triggerLabel },\n\n { match: /^\\s*CREATE\\s+TYPE\\b/i, label: 'Type missing', name: named(AFTER.type) },\n { match: /^\\s*ALTER\\s+TYPE\\b/i, label: 'Type altered', name: named(AFTER.type) },\n { match: /^\\s*DROP\\s+TYPE\\b/i, label: 'Extra type', name: named(AFTER.type) },\n { match: /^\\s*CREATE\\s+DOMAIN\\b/i, label: 'Domain missing', name: named(AFTER.domain) },\n { match: /^\\s*ALTER\\s+DOMAIN\\b/i, label: 'Domain altered', name: named(AFTER.domain) },\n { match: /^\\s*DROP\\s+DOMAIN\\b/i, label: 'Extra domain', name: named(AFTER.domain) },\n\n { match: /^\\s*ALTER\\s+TABLE\\b/i, label: 'Table altered', name: named(AFTER.table) },\n { match: /^\\s*CREATE\\s+TABLE\\b/i, label: 'Table missing', name: named(AFTER.table) },\n { match: /^\\s*DROP\\s+TABLE\\b/i, label: 'Extra table', name: named(AFTER.table) },\n\n { match: /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b/i, label: 'Index missing', name: indexLabel },\n { match: /^\\s*DROP\\s+INDEX\\b/i, label: 'Extra index', name: named(AFTER.index) },\n\n // Policies. Without these, dbdiff's own CREATE/DROP POLICY statements fell\n // through to the catch-all and were titled \"Schema change: unknown\" — the\n // one finding in a report that named no object at all (issue #97). Keyed\n // `table.policy`, which is how a policy is identified and how the RLS check\n // names the same one.\n { match: /^\\s*CREATE\\s+POLICY\\b/i, label: 'Policy missing', name: policyLabel },\n { match: /^\\s*ALTER\\s+POLICY\\b/i, label: 'Policy altered', name: policyLabel },\n { match: /^\\s*DROP\\s+POLICY\\b/i, label: 'Extra policy', name: policyLabel },\n\n // Comments (rc.21) and extensions (rc.22), named like everything else, and\n // a comment by the object it is on and that object's kind.\n { match: /^\\s*COMMENT\\s+ON\\b/i, label: 'Comment changed', name: commentLabel },\n { match: /^\\s*CREATE\\s+EXTENSION\\b/i, label: 'Extension missing', name: extensionLabel },\n { match: /^\\s*DROP\\s+EXTENSION\\b/i, label: 'Extra extension', name: extensionLabel },\n\n { match: /^\\s*CREATE\\s+SEQUENCE\\b/i, label: 'Sequence missing', name: named(AFTER.sequence) },\n { match: /^\\s*ALTER\\s+SEQUENCE\\b/i, label: 'Sequence altered', name: named(AFTER.sequence) },\n { match: /^\\s*DROP\\s+SEQUENCE\\b/i, label: 'Extra sequence', name: named(AFTER.sequence) },\n]\n\n/** An identifier as written, unquoted: `\"App Data\"` → `App Data`. */\nconst unquoted = (part: string) => part.replace(/^\"|\"$/g, '').replace(/\"\"/g, '\"')\n\n/**\n * `public.orders.own (policy)` for `COMMENT ON POLICY \"own\" ON \"public\".\"orders\"`:\n * the object, qualified as written, and its kind. A constraint, trigger or\n * policy is named after the table (or domain) it is on.\n */\nfunction commentLabel(sql: string): string {\n const m = /^\\s*COMMENT\\s+ON\\s+(MATERIALIZED\\s+VIEW|FOREIGN\\s+TABLE|[A-Z]+)\\s+([\\s\\S]*?)\\s+IS\\s/i.exec(sql)\n if (!m) return UNKNOWN_NAME\n const kind = m[1].toLowerCase().replace(/\\s+/g, ' ')\n const on = /^(\"(?:[^\"]|\"\")+\"|\\S+)\\s+ON\\s+(?:DOMAIN\\s+)?([\\s\\S]+)$/i.exec(m[2].trim())\n const object = on ? `${on[2].trim()}.${on[1]}` : m[2].trim()\n const name = object.split(/\\.(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/).map(unquoted).join('.')\n return `${name} (${kind})`\n}\n\n/** `schema.extension` for CREATE EXTENSION ... WITH SCHEMA, or the bare name. */\nfunction extensionLabel(sql: string): string {\n const name = /\\bEXTENSION\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(\"[^\"]+\"|[\\w$-]+)/i.exec(sql)?.[1]\n const schema = /\\bSCHEMA\\s+(\"[^\"]+\"|[\\w$]+)/i.exec(sql)?.[1]\n if (!name) return UNKNOWN_NAME\n return schema ? `${unquoted(schema)}.${unquoted(name)}` : unquoted(name)\n}\n\n/** Titles for a schema made, dropped or commented on, which have no schema of their own. */\nfunction schemaTitle(sql: string, downSql?: string): string | undefined {\n const m = /^\\s*(CREATE|DROP|COMMENT\\s+ON)\\s+SCHEMA\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(\"[^\"]+\"|[\\w$]+)/i.exec(sql)\n if (!m) return undefined\n const label = { CREATE: 'Schema missing', DROP: 'Extra schema' }[m[1].toUpperCase() as 'CREATE' | 'DROP']\n return label ? `${label}: ${unquoted(m[2])}` : `${commentChange(sql, downSql)}: schema ${unquoted(m[2])}`\n}\n\nconst CLEARS_COMMENT = /\\bIS\\s+NULL\\s*;?\\s*$/i\n\n/**\n * What a comment finding does. \"Comment changed\" was the title for all three,\n * including a comment on an object the target does not have yet, where there\n * is nothing to change: the DOWN of a comment only the source has clears it,\n * and the UP of one only the target has does.\n */\nfunction commentChange(sql: string, downSql?: string): string {\n if (CLEARS_COMMENT.test(sql)) return 'Extra comment'\n if (downSql && CLEARS_COMMENT.test(downSql)) return 'Comment missing'\n return 'Comment changed'\n}\n\n/** Titles for the row-level findings of the data check. */\nfunction summariseDataStatement(sql: string): string {\n const table = extractQualifiedName(sql, /\\b(?:INTO|FROM|UPDATE)\\s+(?:ONLY\\s+)?/i)\n const upper = sql.toUpperCase().trimStart()\n if (upper.startsWith('INSERT')) return `Missing row in ${table}`\n if (upper.startsWith('DELETE')) return `Extra row in ${table}`\n if (upper.startsWith('UPDATE')) return `Modified row in ${table}`\n return `Data change in ${table}`\n}\n\n/**\n * Title one finding.\n *\n * `downSql` is the paired counterpart statement, used only to recover a schema\n * the UP statement does not carry — see `routineLabel`.\n */\nexport function summariseStatement(sql: string, check: 'schema' | 'data', downSql?: string): string {\n if (check === 'data') return summariseDataStatement(sql)\n\n const schema = schemaTitle(sql, downSql)\n if (schema) return schema\n\n for (const rule of SCHEMA_RULES) {\n if (rule.match.test(sql)) {\n const label = rule.name === commentLabel ? commentChange(sql, downSql) : rule.label\n return `${label}: ${qualifySchemaName(rule.name(sql, downSql))}`\n }\n }\n\n // Same `<finding>: <schema>.<name>` shape as every rule above, so an\n // unclassified change lines up with the rest of the list too.\n return `Schema change: ${qualifySchemaName(\n extractQualifiedName(sql, /\\b(?:TABLE|INTO|FROM|UPDATE)\\s+(?:ONLY\\s+)?/i),\n )}`\n}\n\n/**\n * Name a routine in an issue title, schema-qualified, with its argument\n * signature.\n *\n * The detection has been signature-aware since overloads were fixed, but only\n * the \"Function modified\" title carried the signature through — \"Extra\n * function\" printed the bare name (issue #40). For an overloaded routine that\n * left the title unable to say which overload was being dropped, and two\n * target-only overloads of one name produced two identical titles.\n *\n * The schema is still never invented, but it no longer has to be missing.\n * dbdiff emits a DROP unqualified (`DROP FUNCTION IF EXISTS \"example_fn\"(uuid)`)\n * while the DOWN statement that restores the same routine comes from\n * `pg_get_functiondef` and *is* qualified. So when the UP has no schema, it is\n * read off that counterpart — a schema dbdiff itself reported, not a guess —\n * which is what left \"Extra function\" the one unqualified schema title\n * (issue #47).\n *\n * The counterpart is only trusted when it names the same routine; a mismatched\n * pair would otherwise attach one routine's schema to another's name.\n */\nexport function routineLabel(sql: string, downSql?: string): string {\n const name = extractRoutineName(sql)\n const args = extractRoutineArgs(sql)\n if (!downSql || name === UNKNOWN_NAME || name.includes('.')) return name + args\n\n const counterpart = extractRoutineName(downSql)\n const sameRoutine = unqualify(counterpart) === unqualify(name)\n return (counterpart.includes('.') && sameRoutine ? counterpart : name) + args\n}\n\n/** The last segment of a possibly schema-qualified name, lowercased. */\nfunction unqualify(name: string): string {\n return name.slice(name.lastIndexOf('.') + 1).toLowerCase()\n}\n\n/**\n * Extract a routine name from a FUNCTION or PROCEDURE statement.\n *\n * A bare `/FUNCTION\\s+\"?(\\w+)\"?/` gets this wrong in both directions\n * (issue #35): it returns \"IF\" for `DROP FUNCTION IF EXISTS \"f\"`, and the\n * schema qualifier \"public\" for `CREATE OR REPLACE FUNCTION public.f(...)`.\n * Neither title named the routine at all.\n *\n * Skips an optional IF EXISTS, then takes the optionally schema-qualified,\n * optionally quoted identifier, normalising `\"public\" . \"f\"` to `public.f`.\n */\nexport function extractRoutineName(sql: string): string {\n return extractQualifiedName(sql, /\\b(?:FUNCTION|PROCEDURE)\\s+(?:IF\\s+EXISTS\\s+)?/i)\n}\n\n/** What a title shows when the identifier cannot be read out of the SQL. */\nexport const UNKNOWN_NAME = 'unknown'\n\n/**\n * Read the optionally schema-qualified, optionally quoted identifier that\n * follows `head`, normalising `\"public\" . \"f\"` to `public.f`.\n *\n * The one identifier parser behind every schema title. Before it, each kind\n * carried its own `/KEYWORD\\s+[\"'`]?(\\w+)/`, and those got it wrong in both\n * directions (issues #35, #47): \"IF\" for `DROP FUNCTION IF EXISTS \"f\"`, and the\n * schema qualifier \"public\" for anything written `public.name` — which is how\n * an index came to be titled by its schema instead of its name.\n *\n * Matched piecewise rather than as one expression. A combined pattern needs an\n * optional quote on both sides of each identifier (\"?[\\w$]+\"?), and that\n * ambiguity backtracks super-linearly on adversarial input — a real concern for\n * SQL arriving from an external process.\n */\nexport function extractQualifiedName(sql: string, head: RegExp): string {\n const found = head.exec(sql)\n if (!found) return UNKNOWN_NAME\n\n let rest = sql.slice(found.index + found[0].length)\n const parts: string[] = []\n\n for (let depth = 0; depth < 2; depth++) {\n // A quoted name doubles any quote inside it: \"say \"\"hi\"\" there\".\n const ident = /^(?:\"((?:[^\"]|\"\")*)\"|([\\w$]+))/.exec(rest)\n if (!ident) break\n parts.push(ident[1] !== undefined ? ident[1].replace(/\"\"/g, '\"') : ident[2])\n rest = rest.slice(ident[0].length)\n\n const dot = /^\\s*\\.\\s*/.exec(rest)\n if (!dot) break\n rest = rest.slice(dot[0].length)\n }\n\n return parts.length > 0 ? parts.join('.') : UNKNOWN_NAME\n}\n\n/**\n * Extract the argument list of a `DROP FUNCTION`, parens included.\n *\n * @dbdiff/cli >= 3.0.0-rc.7 qualifies the DROP with the argument types so an\n * overloaded routine can be dropped unambiguously — `DROP FUNCTION IF EXISTS\n * \"dist\"(bigint,bigint)`. Earlier versions emitted a bare name, and MySQL has\n * no overloading, so both return ''.\n *\n * Scanned rather than matched. The types can themselves contain parens\n * (`numeric(10,2)`), so this counts depth instead of taking the first `)`.\n */\nexport function extractRoutineArgs(sql: string): string {\n const open = sql.indexOf('(')\n if (open === -1) return ''\n\n let depth = 0\n for (let i = open; i < sql.length; i++) {\n if (sql[i] === '(') depth++\n else if (sql[i] === ')' && --depth === 0) return sql.slice(open, i + 1)\n }\n return ''\n}\n","/**\n * dbdiff's `--units` output: each change's statements between\n *\n * -- dbdiff:unit <Kind> <object>\n * ...\n * -- dbdiff:end\n *\n * Some changes are several statements that only work together and in order —\n * an enum label swap, a column type change with the views reading it stood\n * aside, a generated column re-added, a serial column turned into an identity.\n * Split into separate findings they were reordered, half-applied, or held back\n * as destructive for a DROP the same change undoes a statement later. The\n * markers say where each change starts and ends, and which object it is, so\n * nothing here has to guess that from the SQL:\n *\n * - a unit is one finding, whatever it holds;\n * - its DOWN is the unit of the same kind and object in the DOWN section,\n * not whatever happens to sit at the same position there.\n */\n\n/** One change, as dbdiff marked it. */\nexport interface DbDiffUnit {\n /** dbdiff's diff class: `AlterTableChangeColumn`, `AlterEnum`, `CreateView`, … */\n kind: string\n /** `table`, `table.column`, `table.name` or `name` — empty when dbdiff gave none. */\n object: string\n /** The unit's SQL, statements in order, without the marker lines. */\n sql: string\n}\n\nconst BEGIN = /^-- dbdiff:unit (\\S+)(?: (.*))?$/\nconst END = '-- dbdiff:end'\n\n/**\n * The units of one section (UP or DOWN), or undefined when it carries no\n * markers — output from a dbdiff without `--units`.\n *\n * Text outside any unit is ignored: dbdiff writes nothing there but blank\n * lines and, without `--nocomments`, its own header.\n */\nexport function parseUnits(section: string): DbDiffUnit[] | undefined {\n if (!section.includes('-- dbdiff:unit ')) return undefined\n\n const units: DbDiffUnit[] = []\n let open: { kind: string; object: string; lines: string[] } | undefined\n\n for (const line of section.split('\\n')) {\n const begin = BEGIN.exec(line.trimEnd())\n if (begin) {\n open = { kind: begin[1], object: (begin[2] ?? '').trim(), lines: [] }\n } else if (line.trimEnd() === END && open) {\n units.push({ kind: open.kind, object: open.object, sql: open.lines.join('\\n').trim() })\n open = undefined\n } else if (open) {\n open.lines.push(line)\n }\n }\n\n return units.filter(u => u.sql !== '')\n}\n\n/** What identifies a change across the two sections. */\nexport function unitKey(unit: DbDiffUnit): string {\n return `${unit.kind} ${unit.object}`\n}\n\n/**\n * Each UP unit with the DOWN unit for the same change, if there is one.\n *\n * By kind and object, in order: two units with the same key (two overloads of\n * one routine, say) pair first with first. A change can have nothing to do in\n * one direction — a column's storage on a column the DOWN drops anyway — so\n * an UP unit may have no DOWN.\n */\nexport function pairUnits(\n up: DbDiffUnit[],\n down: DbDiffUnit[],\n): Array<{ up: DbDiffUnit; down: DbDiffUnit | undefined }> {\n const unclaimed = new Map<string, DbDiffUnit[]>()\n for (const unit of down) {\n const key = unitKey(unit)\n unclaimed.set(key, [...(unclaimed.get(key) ?? []), unit])\n }\n return up.map(unit => ({ up: unit, down: unclaimed.get(unitKey(unit))?.shift() }))\n}\n\n/** The kinds dbdiff renders as dropping and recreating one object. */\nexport const REPLACING_KINDS: Record<string, 'routine' | 'type' | 'sequence' | 'policy' | 'trigger' | 'view' | undefined> = {\n AlterRoutine: 'routine',\n AlterEnum: 'type',\n AlterCompositeType: 'type',\n AlterDomain: 'type',\n AlterPolicy: 'policy',\n AlterTrigger: 'trigger',\n AlterView: 'view',\n AlterMatView: 'view',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,UAAU,QAAQ,cAAc;AACzC,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;;;ACyB1B,IAAM,QAAQ;AACd,IAAM,MAAM;AASL,SAAS,WAAW,SAA2C;AACpE,MAAI,CAAC,QAAQ,SAAS,iBAAiB,EAAG,QAAO;AAEjD,QAAM,QAAsB,CAAC;AAC7B,MAAI;AAEJ,aAAW,QAAQ,QAAQ,MAAM,IAAI,GAAG;AACtC,UAAM,QAAQ,MAAM,KAAK,KAAK,QAAQ,CAAC;AACvC,QAAI,OAAO;AACT,aAAO,EAAE,MAAM,MAAM,CAAC,GAAG,SAAS,MAAM,CAAC,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,EAAE;AAAA,IACtE,WAAW,KAAK,QAAQ,MAAM,OAAO,MAAM;AACzC,YAAM,KAAK,EAAE,MAAM,KAAK,MAAM,QAAQ,KAAK,QAAQ,KAAK,KAAK,MAAM,KAAK,I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";
8
+ function resolveConnectTimeoutMs() {
9
+ const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT;
10
+ if (raw) {
11
+ const secs = Number(raw);
12
+ if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1e3);
13
+ }
14
+ return DB_CONNECT_TIMEOUT_MS;
15
+ }
16
+ function pgClientConfig(dbUrl, queryTimeoutMs) {
17
+ const config = {
18
+ connectionString: dbUrl,
19
+ connectionTimeoutMillis: resolveConnectTimeoutMs()
20
+ };
21
+ if (queryTimeoutMs !== void 0) {
22
+ config.query_timeout = queryTimeoutMs;
23
+ }
24
+ return config;
25
+ }
26
+ var pools = /* @__PURE__ */ new Map();
27
+ var POOL_MAX = 4;
28
+ function poolFor(dbUrl) {
29
+ const existing = pools.get(dbUrl);
30
+ if (existing) return existing;
31
+ const pool = new pg.Pool({
32
+ ...pgClientConfig(dbUrl),
33
+ max: POOL_MAX,
34
+ allowExitOnIdle: true
35
+ });
36
+ pool.on("error", () => void 0);
37
+ pools.set(dbUrl, pool);
38
+ return pool;
39
+ }
40
+ var pgQuery = async (dbUrl, sql, params) => {
41
+ const { rows } = await poolFor(dbUrl).query(sql, params);
42
+ return rows;
43
+ };
44
+ async function inRolledBackTransaction(dbUrl, fn) {
45
+ const client = await poolFor(dbUrl).connect();
46
+ try {
47
+ await client.query("BEGIN");
48
+ try {
49
+ return await fn(client);
50
+ } finally {
51
+ await client.query("ROLLBACK").catch(() => void 0);
52
+ }
53
+ } finally {
54
+ client.release();
55
+ }
56
+ }
57
+
58
+ // src/utils/error.ts
59
+ var DB_URL_RE = /\b((?:postgres(?:ql)?|mysql|mariadb):\/\/)(\S+)/g;
60
+ function redactUrls(message) {
61
+ return message.replace(DB_URL_RE, (_, scheme, rest) => {
62
+ const lastAt = rest.lastIndexOf("@");
63
+ if (lastAt === -1) return scheme + rest;
64
+ const creds = rest.slice(0, lastAt);
65
+ const hostPart = rest.slice(lastAt);
66
+ const colonIdx = creds.indexOf(":");
67
+ if (colonIdx === -1) return scheme + rest;
68
+ return scheme + creds.slice(0, colonIdx) + ":***" + hostPart;
69
+ });
70
+ }
71
+ var UNDESCRIBED_ERROR = "unknown error \u2014 no message reported";
72
+ function describeFailure(err) {
73
+ if (typeof err === "string") return err.trim() || UNDESCRIBED_ERROR;
74
+ const candidate = err;
75
+ const message = typeof candidate?.message === "string" ? candidate.message.trim() : "";
76
+ if (message) return message;
77
+ const code = typeof candidate?.code === "string" ? candidate.code.trim() : "";
78
+ if (code) return `${code} (no further detail reported)`;
79
+ const name = typeof candidate?.name === "string" ? candidate.name.trim() : "";
80
+ if (name && name !== "Error") return `${name} (no further detail reported)`;
81
+ if (err !== null && err !== void 0 && !(err instanceof Error)) {
82
+ const rendered = String(err).trim();
83
+ if (rendered && rendered !== "[object Object]") return rendered;
84
+ }
85
+ return UNDESCRIBED_ERROR;
86
+ }
87
+ function errMsg(err) {
88
+ return redactUrls(describeFailure(err));
89
+ }
90
+ var DiagnosticError = class extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = "DiagnosticError";
94
+ }
95
+ };
96
+ function isDiagnosticError(err) {
97
+ return err instanceof DiagnosticError || err instanceof Error && err.name === "DiagnosticError";
98
+ }
99
+ var CONNECTION_ERROR_PATTERNS = [
100
+ {
101
+ test: (m) => /ECONNREFUSED|Connection refused/i.test(m),
102
+ build: (host) => `Cannot connect to PostgreSQL at ${host} \u2014 the server does not appear to be running. Start it and try again.`
103
+ },
104
+ {
105
+ test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),
106
+ build: (host) => `Cannot resolve hostname ${host} \u2014 check the database URL in your config.`
107
+ },
108
+ {
109
+ // Deliberately narrow. A bare /timeout/i also matches our own remediation
110
+ // text — "set SUPAFORGE_DBDIFF_TIMEOUT=600" contains "TIMEOUT" — which is
111
+ // how an accurate "Schema diff timed out after Ns" message was being
112
+ // rewritten into a wrong "check the host and port" one (issue #29).
113
+ // DiagnosticError below is the primary guard; this is defence in depth.
114
+ test: (m) => /ETIMEDOUT|connection timed out|timeout expired|statement timeout/i.test(m),
115
+ build: (host) => `Connection to ${host} timed out \u2014 verify the host and port are correct and that the server is reachable.`
116
+ },
117
+ {
118
+ test: (m) => /password authentication failed/i.test(m),
119
+ build: (host) => `Authentication failed for ${host} \u2014 check the username and password in your database URL.`
120
+ },
121
+ {
122
+ // Must stay anchored to "database ... does not exist" (Postgres SQLSTATE
123
+ // 3D000). A bare /does not exist/ is the same trap as the timeout pattern
124
+ // above: it matched dbdiff's own CLI complaint — The "--allow-destructive"
125
+ // option does not exist — and rewrote it into "Database does not exist on
126
+ // 127.0.0.1:5432", sending you off to check a database name that was fine
127
+ // while the real cause (an outdated @dbdiff/cli) went unmentioned.
128
+ test: (m) => /database\s+"[^"]*"\s+does not exist|3D000/i.test(m),
129
+ build: (host) => `Database does not exist on ${host} \u2014 verify the database name in your config.`
130
+ },
131
+ {
132
+ test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),
133
+ build: (host) => `Connection rejected by ${host} \u2014 the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`
134
+ }
135
+ ];
136
+ function extractHost(dbUrl) {
137
+ try {
138
+ const url = new URL(dbUrl);
139
+ return url.port ? `${url.hostname}:${url.port}` : url.hostname;
140
+ } catch {
141
+ return "the configured host";
142
+ }
143
+ }
144
+ function friendlyDbError(err, dbUrl) {
145
+ const raw = errMsg(err);
146
+ if (isDiagnosticError(err)) return raw;
147
+ const host = dbUrl ? extractHost(dbUrl) : "the configured host";
148
+ for (const pattern of CONNECTION_ERROR_PATTERNS) {
149
+ try {
150
+ if (pattern.test(raw)) {
151
+ return pattern.build(host);
152
+ }
153
+ } catch {
154
+ }
155
+ }
156
+ return raw;
157
+ }
158
+
159
+ // src/checks/base.ts
160
+ var CheckSkipped = class extends Error {
161
+ /** Distinguishes a skip from a genuine error across module boundaries. */
162
+ name = "CheckSkipped";
163
+ constructor(reason) {
164
+ super(reason);
165
+ }
166
+ };
167
+ function isCheckSkipped(err) {
168
+ return err instanceof Error && err.name === "CheckSkipped";
169
+ }
170
+ var Check = class {
171
+ };
172
+
173
+ // src/checks/migrations.ts
174
+ import { readdir as fsReaddir } from "fs/promises";
175
+
176
+ // src/utils/sql.ts
177
+ function quoteIdent(name) {
178
+ return name.split(".").map((p) => `"${p.replace(/"/g, '""')}"`).join(".");
179
+ }
180
+ function quoteName(name) {
181
+ return `"${name.replace(/"/g, '""')}"`;
182
+ }
183
+ function quoteLiteral(value) {
184
+ return `'${value.replace(/'/g, "''")}'`;
185
+ }
186
+ function sqlLiteral(val) {
187
+ if (val === null || val === void 0) return "NULL";
188
+ if (typeof val === "boolean") return val ? "true" : "false";
189
+ if (typeof val === "number") return String(val);
190
+ if (Array.isArray(val)) return `ARRAY[${val.map((v) => quoteLiteral(String(v))).join(", ")}]`;
191
+ return quoteLiteral(String(val));
192
+ }
193
+
194
+ // src/checks/migrations.ts
195
+ var DEFAULT_MIGRATIONS_DIR = "supabase/migrations";
196
+ var MIGRATIONS_SQL = `
197
+ SELECT version, name
198
+ FROM ${MIGRATIONS_TABLE}
199
+ ORDER BY version
200
+ `;
201
+ var defaultReadDir = async (dir) => {
202
+ const entries = await fsReaddir(dir);
203
+ return entries;
204
+ };
205
+ var MigrationsCheck = class extends Check {
206
+ constructor(queryFn = pgQuery, readDirFn = defaultReadDir) {
207
+ super();
208
+ this.queryFn = queryFn;
209
+ this.readDirFn = readDirFn;
210
+ }
211
+ name = "migrations";
212
+ async scan(ctx) {
213
+ const dir = ctx.config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR;
214
+ const mode = resolveMigrationsMode(ctx.config.checks?.migrations?.mode);
215
+ if (mode === "ignore") throw new CheckSkipped("checks.migrations.mode is 'ignore'");
216
+ const [local, db] = await Promise.all([
217
+ readLocalMigrations(dir, this.readDirFn),
218
+ this.fetchDbMigrations(ctx.target.dbUrl)
219
+ ]);
220
+ return diffMigrations(local, db, mode);
221
+ }
222
+ async fetchDbMigrations(dbUrl) {
223
+ try {
224
+ return await this.queryFn(dbUrl, MIGRATIONS_SQL);
225
+ } catch {
226
+ return [];
227
+ }
228
+ }
229
+ };
230
+ function parseFilename(filename) {
231
+ if (!filename.endsWith(".sql")) return null;
232
+ const match = filename.replace(/\.sql$/, "").match(/^(\d+)_(.+)$/);
233
+ if (!match) return null;
234
+ return { version: match[1], name: match[2] };
235
+ }
236
+ async function readLocalMigrations(dir, readDirFn = defaultReadDir) {
237
+ let files;
238
+ try {
239
+ files = (await readDirFn(dir)).filter((f) => f.endsWith(".sql")).sort();
240
+ } catch {
241
+ return [];
242
+ }
243
+ const migrations = [];
244
+ for (const filename of files) {
245
+ const parsed = parseFilename(filename);
246
+ if (!parsed) continue;
247
+ migrations.push({ ...parsed, filename });
248
+ }
249
+ return migrations;
250
+ }
251
+ var MIGRATIONS_MODES = ["auto", "warn", "ignore"];
252
+ function resolveMigrationsMode(raw) {
253
+ return MIGRATIONS_MODES.includes(raw) ? raw : "auto";
254
+ }
255
+ function untrackedWorkflowIssue(local) {
256
+ const noun = local.length === 1 ? "file" : "files";
257
+ return {
258
+ id: "migration-workflow-untracked",
259
+ check: "migrations",
260
+ severity: "info",
261
+ title: `Untracked migration workflow: ${local.length} local ${noun}, none recorded`,
262
+ description: `${MIGRATIONS_TABLE} is empty while ${local.length} migration ${noun} exist locally. That is the normal shape for a project applying migrations outside the Supabase CLI (psql, the SQL editor, or another tool), so each file is not reported separately. Run \`supaforge migrate baseline\` to record them as applied, or set checks.migrations.mode to "warn" to report every file, or "ignore" to disable this check.`,
263
+ sourceValue: `${local.length} local migration ${noun}`
264
+ };
265
+ }
266
+ function diffMigrations(local, db, mode = "auto") {
267
+ if (mode === "ignore") return [];
268
+ const issues = [];
269
+ const dbMap = new Map(db.map((r) => [r.version, r]));
270
+ const localMap = new Map(local.map((m) => [m.version, m]));
271
+ const unapplied = local.filter((m) => !dbMap.has(m.version));
272
+ if (mode === "auto" && db.length === 0 && unapplied.length > 0) {
273
+ issues.push(untrackedWorkflowIssue(local));
274
+ } else {
275
+ for (const migration of unapplied) {
276
+ issues.push({
277
+ id: `migration-unapplied-${migration.version}`,
278
+ check: "migrations",
279
+ severity: "warning",
280
+ title: `Unapplied migration: ${migration.filename}`,
281
+ description: `Migration file "${migration.filename}" exists locally but is not recorded in ${MIGRATIONS_TABLE}.`,
282
+ sourceValue: migration.filename,
283
+ sql: {
284
+ up: markAppliedSql(migration.version, migration.name),
285
+ down: `DELETE FROM ${MIGRATIONS_TABLE} WHERE version = ${quoteLiteral(migration.version)};`
286
+ }
287
+ });
288
+ }
289
+ }
290
+ for (const [version, record] of dbMap) {
291
+ if (!localMap.has(version)) {
292
+ issues.push({
293
+ id: `migration-untracked-${version}`,
294
+ check: "migrations",
295
+ severity: "info",
296
+ title: `Untracked migration: ${version}`,
297
+ description: `Migration version "${version}"${record.name ? ` (${record.name})` : ""} is recorded in the database but has no corresponding local file.`,
298
+ targetValue: record
299
+ });
300
+ }
301
+ }
302
+ return issues;
303
+ }
304
+ function markAppliedSql(version, name) {
305
+ return [
306
+ `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)`,
307
+ `VALUES (${quoteLiteral(version)}, ${quoteLiteral(name)}, '{}')`,
308
+ `ON CONFLICT (version) DO NOTHING;`
309
+ ].join("\n");
310
+ }
311
+
312
+ export {
313
+ resolveConnectTimeoutMs,
314
+ pgClientConfig,
315
+ pgQuery,
316
+ inRolledBackTransaction,
317
+ redactUrls,
318
+ describeFailure,
319
+ errMsg,
320
+ DiagnosticError,
321
+ friendlyDbError,
322
+ quoteIdent,
323
+ quoteName,
324
+ quoteLiteral,
325
+ sqlLiteral,
326
+ CheckSkipped,
327
+ isCheckSkipped,
328
+ Check,
329
+ DEFAULT_MIGRATIONS_DIR,
330
+ MigrationsCheck,
331
+ readLocalMigrations
332
+ };
333
+ //# sourceMappingURL=chunk-X6V2GGDZ.js.map