@akal/supaforge 0.0.31 → 0.0.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -11
- package/dist/base-command.d.ts +1 -0
- package/dist/base-command.js +2 -2
- package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
- package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
- package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
- package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
- package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
- package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
- package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
- package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
- package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
- package/dist/chunk-GZREXCQZ.js +207 -0
- package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
- package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
- package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
- package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
- package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
- package/dist/chunk-UWAVXC57.js +916 -0
- package/dist/commands/clone.js +10 -10
- package/dist/commands/diff.d.ts +16 -0
- package/dist/commands/diff.js +11 -12
- package/dist/commands/hukam.js +11 -12
- package/dist/commands/mcp.d.ts +1 -0
- package/dist/commands/mcp.js +18 -9
- package/dist/commands/migrate/baseline.js +3 -3
- package/dist/commands/migrate/create.js +5 -6
- package/dist/commands/migrate/list.js +4 -4
- package/dist/commands/migrate/run.js +5 -6
- package/dist/commands/report.js +3 -3
- package/dist/commands/restore.js +11 -13
- package/dist/commands/snapshot.js +6 -8
- package/dist/commands/sync.js +11 -12
- package/dist/index.d.ts +5 -0
- package/dist/index.js +16 -16
- package/package.json +10 -8
- package/bin/dev.js +0 -10
- package/dist/base-command.js.map +0 -1
- package/dist/chunk-4OU7KO5Y.js.map +0 -1
- package/dist/chunk-5QQBTLWO.js.map +0 -1
- package/dist/chunk-5Z3SAIQS.js.map +0 -1
- package/dist/chunk-6WAMNZLO.js.map +0 -1
- package/dist/chunk-BHYLBKYD.js.map +0 -1
- package/dist/chunk-BLKJWDTL.js.map +0 -1
- package/dist/chunk-DQQ5E563.js.map +0 -1
- package/dist/chunk-G2DIPIYU.js.map +0 -1
- package/dist/chunk-H5MJ5DFX.js +0 -16
- package/dist/chunk-H5MJ5DFX.js.map +0 -1
- package/dist/chunk-KIFJGON5.js.map +0 -1
- package/dist/chunk-LQXF65MC.js.map +0 -1
- package/dist/chunk-NXRSAVRU.js.map +0 -1
- package/dist/chunk-PARSNTBD.js.map +0 -1
- package/dist/chunk-RRMI5CZD.js +0 -376
- package/dist/chunk-RRMI5CZD.js.map +0 -1
- package/dist/chunk-SF3YA42C.js +0 -506
- package/dist/chunk-SF3YA42C.js.map +0 -1
- package/dist/chunk-TQJSQLWA.js.map +0 -1
- package/dist/chunk-VMTBLHN2.js.map +0 -1
- package/dist/chunk-VOXZWQ3N.js.map +0 -1
- package/dist/chunk-X6V2GGDZ.js.map +0 -1
- package/dist/chunk-XMYMIURR.js.map +0 -1
- package/dist/chunk-YVDSR4GM.js.map +0 -1
- package/dist/commands/clone.js.map +0 -1
- package/dist/commands/diff.js.map +0 -1
- package/dist/commands/help.js.map +0 -1
- package/dist/commands/hukam.js.map +0 -1
- package/dist/commands/init.js.map +0 -1
- package/dist/commands/mcp.js.map +0 -1
- package/dist/commands/migrate/baseline.js.map +0 -1
- package/dist/commands/migrate/create.js.map +0 -1
- package/dist/commands/migrate/list.js.map +0 -1
- package/dist/commands/migrate/run.js.map +0 -1
- package/dist/commands/report.js.map +0 -1
- package/dist/commands/restore.js.map +0 -1
- package/dist/commands/snapshot.js.map +0 -1
- package/dist/commands/sync.js.map +0 -1
- package/dist/help.js.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db.ts","../src/utils/error.ts","../src/checks/base.ts","../src/checks/migrations.ts","../src/utils/sql.ts"],"sourcesContent":["import pg from 'pg'\nimport { DB_CONNECT_TIMEOUT_MS } from './constants.js'\n\nexport type QueryFn = (dbUrl: string, sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n\n/**\n * Resolve the bound on establishing a connection (ms).\n *\n * SUPAFORGE_CONNECT_TIMEOUT is in seconds, so a network that legitimately\n * needs longer than the default can raise it without a code change. A\n * malformed or non-positive value falls back to the default rather than\n * forwarding something `pg` would treat as \"wait forever\" — which is the very\n * failure this bound exists to prevent (issue #44).\n */\nexport function resolveConnectTimeoutMs(): number {\n const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT\n if (raw) {\n const secs = Number(raw)\n if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1000)\n }\n return DB_CONNECT_TIMEOUT_MS\n}\n\n/**\n * Build `pg.Client` config with a connection bound always applied.\n *\n * Every client in the codebase goes through here so none can be constructed\n * without one. `queryTimeoutMs` is opt-in: it belongs on short probes, not on\n * a migration or restore that is legitimately slow.\n */\nexport function pgClientConfig(dbUrl: string, queryTimeoutMs?: number): pg.ClientConfig {\n const config: pg.ClientConfig = {\n connectionString: dbUrl,\n connectionTimeoutMillis: resolveConnectTimeoutMs(),\n }\n if (queryTimeoutMs !== undefined) {\n config.query_timeout = queryTimeoutMs\n }\n return config\n}\n\n/**\n * One pool per database, shared by every query in a run.\n *\n * `pgQuery` used to open and close a `pg.Client` per query, and each connection\n * costs several round trips before the query itself runs: TCP, startup, then\n * SCRAM authentication. Over a link with latency that dominated a diff — a full\n * run opened 47 connections for 574 round trips, and the storage check alone\n * opened 14 (issue #78). `schema-introspect.ts` already shared a pool for\n * snapshots; the diff path did not.\n *\n * `allowExitOnIdle` is what makes this safe to do without lifecycle plumbing\n * through every command: an idle pool does not hold the process open, so a CLI\n * that forgets to close one still exits. `closePgPools()` exists for tests and\n * for anywhere that wants the sockets gone at a known moment.\n */\nconst pools = new Map<string, pg.Pool>()\n\n/**\n * Concurrent checks share these, so a pool needs more than one connection —\n * but a diff is not a web server, and a Supabase pooler counts every one.\n */\nconst POOL_MAX = 4\n\nfunction poolFor(dbUrl: string): pg.Pool {\n const existing = pools.get(dbUrl)\n if (existing) return existing\n\n const pool = new pg.Pool({\n ...pgClientConfig(dbUrl),\n max: POOL_MAX,\n allowExitOnIdle: true,\n })\n // A pool emits 'error' for an idle client dropped by the server, and an\n // unhandled 'error' event would take the process down. Queries still reject\n // through their own promise, so this only has to stop the crash.\n pool.on('error', () => undefined)\n\n pools.set(dbUrl, pool)\n return pool\n}\n\nexport const pgQuery: QueryFn = async (dbUrl, sql, params) => {\n const { rows } = await poolFor(dbUrl).query(sql, params)\n return rows\n}\n\n/**\n * Run `fn` on one pooled connection inside a transaction that is always\n * rolled back — for reading what the server makes of something by creating it\n * as a temporary object, without leaving anything behind.\n */\nexport async function inRolledBackTransaction<T>(\n dbUrl: string,\n fn: (client: pg.PoolClient) => Promise<T>,\n): Promise<T> {\n const client = await poolFor(dbUrl).connect()\n try {\n await client.query('BEGIN')\n try {\n return await fn(client)\n } finally {\n await client.query('ROLLBACK').catch(() => undefined)\n }\n } finally {\n client.release()\n }\n}\n\n/** Close every pool this process opened. Safe to call more than once. */\nexport async function closePgPools(): Promise<void> {\n const open = [...pools.values()]\n pools.clear()\n await Promise.all(open.map(pool => pool.end().catch(() => undefined)))\n}\n","/**\n * Regex matching database connection URL schemes (postgres, mysql, etc.).\n * Captures the scheme + `://` and the rest of the URL up to the next whitespace.\n */\nconst DB_URL_RE = /\\b((?:postgres(?:ql)?|mysql|mariadb):\\/\\/)(\\S+)/g\n\n/**\n * Redact passwords from database connection URLs in a string.\n *\n * Replaces `://user:PASSWORD@host` with `://user:***@host` to prevent\n * credentials from leaking into logs, error messages, or terminal output.\n * Handles passwords containing special characters including `@`.\n */\nexport function redactUrls(message: string): string {\n return message.replace(DB_URL_RE, (_, scheme: string, rest: string) => {\n const lastAt = rest.lastIndexOf('@')\n if (lastAt === -1) return scheme + rest\n const creds = rest.slice(0, lastAt)\n const hostPart = rest.slice(lastAt)\n const colonIdx = creds.indexOf(':')\n if (colonIdx === -1) return scheme + rest\n return scheme + creds.slice(0, colonIdx) + ':***' + hostPart\n })\n}\n\n/** Shown when a failure carries nothing at all that could name it. */\nexport const UNDESCRIBED_ERROR = 'unknown error — no message reported'\n\n/**\n * Get something printable out of a thrown value.\n *\n * Not every failure arrives as an `Error` with a populated `message`. One did\n * not — observed when a container runtime's daemon stopped while a port mapping\n * was still registered — and every renderer downstream printed its label, a\n * colon, and nothing: `✗ Source database not reachable:` (issue #47).\n *\n * Falls back through what a driver error still carries when its message is\n * empty: the `code` (`ECONNRESET`, `EPIPE`) is the most useful, then the error\n * type, then a fixed string. The return value is never empty, which is the\n * whole point — a reason a user cannot read is worse than a generic one.\n */\nexport function describeFailure(err: unknown): string {\n if (typeof err === 'string') return err.trim() || UNDESCRIBED_ERROR\n\n const candidate = err as { message?: unknown; code?: unknown; name?: unknown } | null | undefined\n const message = typeof candidate?.message === 'string' ? candidate.message.trim() : ''\n if (message) return message\n\n const code = typeof candidate?.code === 'string' ? candidate.code.trim() : ''\n if (code) return `${code} (no further detail reported)`\n\n const name = typeof candidate?.name === 'string' ? candidate.name.trim() : ''\n if (name && name !== 'Error') return `${name} (no further detail reported)`\n\n if (err !== null && err !== undefined && !(err instanceof Error)) {\n const rendered = String(err).trim()\n if (rendered && rendered !== '[object Object]') return rendered\n }\n\n return UNDESCRIBED_ERROR\n}\n\n/**\n * Extract a concise error message from an unknown caught value.\n *\n * Safely handles Error instances, strings, and other thrown types, and never\n * returns an empty string — see describeFailure. Used across the codebase in\n * catch blocks to normalise error output. Automatically redacts database\n * credentials from the message.\n */\nexport function errMsg(err: unknown): string {\n return redactUrls(describeFailure(err))\n}\n\n/**\n * An error whose message is already written for the user — it has been\n * diagnosed, and usually carries remediation steps.\n *\n * friendlyDbError() passes these through untouched instead of pattern-matching\n * them into a generic connection error. Without this, any accurate message that\n * happens to mention a timeout (including one telling the user which timeout\n * env var to raise) got rewritten into advice to check their host and port.\n */\nexport class DiagnosticError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DiagnosticError'\n }\n}\n\n/**\n * Structural check rather than `instanceof`.\n *\n * The CLI and its tests can load a module through more than one path (src vs\n * dist, ESM vs CJS interop), which yields two distinct class identities and\n * makes `instanceof` silently false. Matching on the name keeps the guard\n * working across those boundaries.\n */\nexport function isDiagnosticError(err: unknown): boolean {\n return err instanceof DiagnosticError || (err instanceof Error && err.name === 'DiagnosticError')\n}\n\n// ─── Connection Error Patterns ───────────────────────────────────────────────\n\n/** Known patterns matched against error messages, checked in order. */\nconst CONNECTION_ERROR_PATTERNS: Array<{ test: (msg: string) => boolean; build: (host: string) => string }> = [\n {\n test: (m) => /ECONNREFUSED|Connection refused/i.test(m),\n build: (host) => `Cannot connect to PostgreSQL at ${host} — the server does not appear to be running. Start it and try again.`,\n },\n {\n test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),\n build: (host) => `Cannot resolve hostname ${host} — check the database URL in your config.`,\n },\n {\n // Deliberately narrow. A bare /timeout/i also matches our own remediation\n // text — \"set SUPAFORGE_DBDIFF_TIMEOUT=600\" contains \"TIMEOUT\" — which is\n // how an accurate \"Schema diff timed out after Ns\" message was being\n // rewritten into a wrong \"check the host and port\" one (issue #29).\n // DiagnosticError below is the primary guard; this is defence in depth.\n test: (m) => /ETIMEDOUT|connection timed out|timeout expired|statement timeout/i.test(m),\n build: (host) => `Connection to ${host} timed out — verify the host and port are correct and that the server is reachable.`,\n },\n {\n test: (m) => /password authentication failed/i.test(m),\n build: (host) => `Authentication failed for ${host} — check the username and password in your database URL.`,\n },\n {\n // Must stay anchored to \"database ... does not exist\" (Postgres SQLSTATE\n // 3D000). A bare /does not exist/ is the same trap as the timeout pattern\n // above: it matched dbdiff's own CLI complaint — The \"--allow-destructive\"\n // option does not exist — and rewrote it into \"Database does not exist on\n // 127.0.0.1:5432\", sending you off to check a database name that was fine\n // while the real cause (an outdated @dbdiff/cli) went unmentioned.\n test: (m) => /database\\s+\"[^\"]*\"\\s+does not exist|3D000/i.test(m),\n build: (host) => `Database does not exist on ${host} — verify the database name in your config.`,\n },\n {\n test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),\n build: (host) => `Connection rejected by ${host} — the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`,\n },\n]\n\n/**\n * Extract host:port from a PostgreSQL connection URL.\n * Returns just the host portion with the port for display.\n */\nfunction extractHost(dbUrl: string): string {\n try {\n const url = new URL(dbUrl)\n return url.port ? `${url.hostname}:${url.port}` : url.hostname\n } catch {\n return 'the configured host'\n }\n}\n\n/**\n * Translate a raw database error into a user-friendly message.\n *\n * Matches known pg error patterns and returns an actionable message\n * with the host identified. Returns the original (redacted) message\n * if no pattern matches.\n */\nexport function friendlyDbError(err: unknown, dbUrl?: string): string {\n const raw = errMsg(err)\n\n // Already a message written for the user, with its own diagnosis and\n // remediation — translating it again can only make it worse, and did:\n // the schema-diff timeout message was being replaced by a connection\n // error naming a host that was demonstrably reachable (issue #29).\n if (isDiagnosticError(err)) return raw\n\n const host = dbUrl ? extractHost(dbUrl) : 'the configured host'\n\n for (const pattern of CONNECTION_ERROR_PATTERNS) {\n try {\n if (pattern.test(raw)) {\n return pattern.build(host)\n }\n } catch {\n // A malformed host or an unexpected pattern failure must never turn a\n // reportable error into a crash — fall through to the raw message.\n }\n }\n\n return raw\n}\n","import type { EnvironmentConfig, SupaForgeConfig } from '../types/config'\nimport type { TableFilter } from '../utils/table-filter'\nimport type { DriftIssue, CheckName } from '../types/drift'\n\nexport interface CheckContext {\n /**\n * Which tables this run is scoped to, resolved from `checks.tables` /\n * `checks.excludeTables` and the `--tables` / `--exclude-tables` flags.\n *\n * Only the schema and data layers act on it — they are the ones backed by\n * @dbdiff/cli, which is where the table concept exists (issue #43). Absent\n * or empty means every table, which is the default.\n */\n tableFilter?: TableFilter\n /**\n * Optional sink for sub-check progress, e.g. the table counter emitted\n * during a long schema diff (issue #29). Checks that have nothing\n * fine-grained to report simply ignore it.\n */\n onDetail?: (detail: string) => void\n source: EnvironmentConfig\n target: EnvironmentConfig\n config: SupaForgeConfig\n}\n\n/**\n * Thrown by a check that cannot run — missing credentials, an absent\n * extension, nothing configured to compare.\n *\n * Checks used to signal this by returning `[]`, which is the same value a\n * genuinely clean scan returns. The distinction was lost before it reached the\n * scanner, so a layer that never ran rendered as a green zero-issue pass\n * (issue #42). Throwing keeps `scan()` returning plain issues while giving the\n * scanner something it cannot mistake for a result.\n *\n * A skip is a normal outcome, not a failure: it carries no stack for the user\n * and is reported separately from errored checks.\n */\nexport class CheckSkipped extends Error {\n /** Distinguishes a skip from a genuine error across module boundaries. */\n override readonly name = 'CheckSkipped'\n\n constructor(reason: string) {\n super(reason)\n }\n}\n\n/**\n * Name-based rather than `instanceof`, which fails when two copies of the\n * module are loaded — a real possibility with bundled output and linked\n * packages.\n */\nexport function isCheckSkipped(err: unknown): err is CheckSkipped {\n return err instanceof Error && err.name === 'CheckSkipped'\n}\n\nexport abstract class Check {\n abstract readonly name: CheckName\n abstract scan(ctx: CheckContext): Promise<DriftIssue[]>\n}\n","import { readdir as fsReaddir } from 'node:fs/promises'\nimport type { QueryFn } from '../db.js'\nimport { pgQuery } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { MIGRATIONS_TABLE } from '../constants.js'\nimport { quoteLiteral } from '../utils/sql.js'\nimport { Check, CheckSkipped, type CheckContext } from './base.js'\nimport type { MigrationsMode } from '../types/config.js'\n\nexport const DEFAULT_MIGRATIONS_DIR = 'supabase/migrations'\n\nconst MIGRATIONS_SQL = `\n SELECT version, name\n FROM ${MIGRATIONS_TABLE}\n ORDER BY version\n`\n\ninterface MigrationRecord {\n version: string\n name: string | null\n}\n\nexport interface LocalMigration {\n version: string\n name: string\n filename: string\n}\n\nexport type ReadDirFn = (dir: string) => Promise<string[]>\n\nconst defaultReadDir: ReadDirFn = async (dir) => {\n const entries = await fsReaddir(dir)\n return entries as string[]\n}\n\nexport class MigrationsCheck extends Check {\n readonly name = 'migrations' as const\n\n constructor(\n private queryFn: QueryFn = pgQuery,\n private readDirFn: ReadDirFn = defaultReadDir,\n ) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const dir = ctx.config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR\n const mode = resolveMigrationsMode(ctx.config.checks?.migrations?.mode)\n\n // Nothing to read or query when the check is switched off entirely. It is\n // still reported as skipped rather than clean, so turning it off does not\n // look like a layer that passed (issue #42).\n if (mode === 'ignore') throw new CheckSkipped(\"checks.migrations.mode is 'ignore'\")\n\n const [local, db] = await Promise.all([\n readLocalMigrations(dir, this.readDirFn),\n this.fetchDbMigrations(ctx.target.dbUrl),\n ])\n\n return diffMigrations(local, db, mode)\n }\n\n private async fetchDbMigrations(dbUrl: string): Promise<MigrationRecord[]> {\n try {\n return await this.queryFn(dbUrl, MIGRATIONS_SQL) as unknown as MigrationRecord[]\n } catch {\n // schema_migrations table doesn't exist — no records to compare\n return []\n }\n }\n}\n\n/**\n * Parse a migration filename into version + name.\n * Handles both `20240101000000_create_users.sql` and `001_initial_schema.sql`.\n */\nexport function parseFilename(filename: string): { version: string; name: string } | null {\n if (!filename.endsWith('.sql')) return null\n const match = filename.replace(/\\.sql$/, '').match(/^(\\d+)_(.+)$/)\n if (!match) return null\n return { version: match[1], name: match[2] }\n}\n\nexport async function readLocalMigrations(\n dir: string,\n readDirFn: ReadDirFn = defaultReadDir,\n): Promise<LocalMigration[]> {\n let files: string[]\n try {\n files = (await readDirFn(dir)).filter(f => f.endsWith('.sql')).sort()\n } catch {\n return []\n }\n\n const migrations: LocalMigration[] = []\n for (const filename of files) {\n const parsed = parseFilename(filename)\n if (!parsed) continue\n migrations.push({ ...parsed, filename })\n }\n return migrations\n}\n\nconst MIGRATIONS_MODES: MigrationsMode[] = ['auto', 'warn', 'ignore']\n\n/**\n * Normalise the configured mode.\n *\n * An unrecognised value falls back to 'auto' rather than throwing — a typo in\n * a config file should not take the whole scan down, and 'auto' is the least\n * surprising default.\n */\nexport function resolveMigrationsMode(raw: unknown): MigrationsMode {\n return MIGRATIONS_MODES.includes(raw as MigrationsMode) ? (raw as MigrationsMode) : 'auto'\n}\n\n/**\n * One INFO describing a project that applies migrations outside the Supabase\n * CLI, instead of one warning per file.\n *\n * schema_migrations is a Supabase CLI convention, not a database requirement.\n * Projects that apply migrations via psql or the SQL editor never populate it,\n * so every local file was reported as \"unapplied\" on every scan — all false\n * positives, and enough of them to drown the rest of the layer (issue #31).\n */\nfunction untrackedWorkflowIssue(local: LocalMigration[]): DriftIssue {\n const noun = local.length === 1 ? 'file' : 'files'\n return {\n id: 'migration-workflow-untracked',\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration workflow: ${local.length} local ${noun}, none recorded`,\n description:\n `${MIGRATIONS_TABLE} is empty while ${local.length} migration ${noun} exist locally. ` +\n 'That is the normal shape for a project applying migrations outside the Supabase CLI ' +\n '(psql, the SQL editor, or another tool), so each file is not reported separately. ' +\n 'Run `supaforge migrate baseline` to record them as applied, or set ' +\n 'checks.migrations.mode to \"warn\" to report every file, or \"ignore\" to disable this check.',\n sourceValue: `${local.length} local migration ${noun}`,\n }\n}\n\nexport function diffMigrations(\n local: LocalMigration[],\n db: MigrationRecord[],\n mode: MigrationsMode = 'auto',\n): DriftIssue[] {\n if (mode === 'ignore') return []\n\n const issues: DriftIssue[] = []\n const dbMap = new Map(db.map(r => [r.version, r]))\n const localMap = new Map(local.map(m => [m.version, m]))\n const unapplied = local.filter(m => !dbMap.has(m.version))\n\n // Nothing tracked at all, but files on disk: report the workflow once\n // rather than each file. Requires db to be *entirely* empty — a project\n // that tracks some migrations and missed others has genuine drift.\n if (mode === 'auto' && db.length === 0 && unapplied.length > 0) {\n issues.push(untrackedWorkflowIssue(local))\n } else {\n for (const migration of unapplied) {\n issues.push({\n id: `migration-unapplied-${migration.version}`,\n check: 'migrations',\n severity: 'warning',\n title: `Unapplied migration: ${migration.filename}`,\n description: `Migration file \"${migration.filename}\" exists locally but is not recorded in ${MIGRATIONS_TABLE}.`,\n sourceValue: migration.filename,\n sql: {\n up: markAppliedSql(migration.version, migration.name),\n down: `DELETE FROM ${MIGRATIONS_TABLE} WHERE version = ${quoteLiteral(migration.version)};`,\n },\n })\n }\n }\n\n // DB records without local files (untracked)\n for (const [version, record] of dbMap) {\n if (!localMap.has(version)) {\n issues.push({\n id: `migration-untracked-${version}`,\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration: ${version}`,\n description: `Migration version \"${version}\"${record.name ? ` (${record.name})` : ''} is recorded in the database but has no corresponding local file.`,\n targetValue: record,\n })\n }\n }\n\n return issues\n}\n\n/** SQL to insert a migration record into schema_migrations (mark as applied). */\nfunction markAppliedSql(version: string, name: string): string {\n return [\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)`,\n `VALUES (${quoteLiteral(version)}, ${quoteLiteral(name)}, '{}')`,\n `ON CONFLICT (version) DO NOTHING;`,\n ].join('\\n')\n}\n","/**\n * Shared SQL escaping utilities for generating safe SQL strings.\n *\n * Used across checks, snapshots, and migration layers to avoid\n * duplicating quoting logic.\n */\n\n/**\n * Quote a schema-qualified or bare identifier for safe inclusion in SQL.\n * Handles `schema.table` → `\"schema\".\"table\"` and bare `table` → `\"table\"`.\n */\nexport function quoteIdent(name: string): string {\n return name.split('.').map(p => `\"${p.replace(/\"/g, '\"\"')}\"`).join('.')\n}\n\n/**\n * Quote a bare identifier (single name, no dot-splitting).\n * Use for column/table names that should never be schema-qualified.\n */\nexport function quoteName(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`\n}\n\n/**\n * Quote a string value for safe inclusion as a SQL literal.\n * Escapes single quotes by doubling them.\n */\nexport function quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/**\n * Convert a JavaScript value to a SQL literal representation.\n * Handles null, boolean, number, array, and string types.\n */\nexport function sqlLiteral(val: unknown): string {\n if (val === null || val === undefined) return 'NULL'\n if (typeof val === 'boolean') return val ? 'true' : 'false'\n if (typeof val === 'number') return String(val)\n if (Array.isArray(val)) return `ARRAY[${val.map(v => quoteLiteral(String(v))).join(', ')}]`\n return quoteLiteral(String(val))\n}\n"],"mappings":";;;;;;AAAA,OAAO,QAAQ;AAcR,SAAS,0BAAkC;AAChD,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,KAAK;AACP,UAAM,OAAO,OAAO,GAAG;AACvB,QAAI,OAAO,SAAS,IAAI,KAAK,OAAO,EAAG,QAAO,KAAK,MAAM,OAAO,GAAI;AAAA,EACtE;AACA,SAAO;AACT;AASO,SAAS,eAAe,OAAe,gBAA0C;AACtF,QAAM,SAA0B;AAAA,IAC9B,kBAAkB;AAAA,IAClB,yBAAyB,wBAAwB;AAAA,EACnD;AACA,MAAI,mBAAmB,QAAW;AAChC,WAAO,gBAAgB;AAAA,EACzB;AACA,SAAO;AACT;AAiBA,IAAM,QAAQ,oBAAI,IAAqB;AAMvC,IAAM,WAAW;AAEjB,SAAS,QAAQ,OAAwB;AACvC,QAAM,WAAW,MAAM,IAAI,KAAK;AAChC,MAAI,SAAU,QAAO;AAErB,QAAM,OAAO,IAAI,GAAG,KAAK;AAAA,IACvB,GAAG,eAAe,KAAK;AAAA,IACvB,KAAK;AAAA,IACL,iBAAiB;AAAA,EACnB,CAAC;AAID,OAAK,GAAG,SAAS,MAAM,MAAS;AAEhC,QAAM,IAAI,OAAO,IAAI;AACrB,SAAO;AACT;AAEO,IAAM,UAAmB,OAAO,OAAO,KAAK,WAAW;AAC5D,QAAM,EAAE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AK,UAAU,SAAS,GAAG;AAC9D,WAAO,KAAK,uBAAuB,KAAK,CAAC;AAAA,EAC3C,OAAO;AACL,eAAW,aAAa,WAAW;AACjC,aAAO,KAAK;AAAA,QACV,IAAI,uBAAuB,UAAU,OAAO;AAAA,QAC5C,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO,wBAAwB,UAAU,QAAQ;AAAA,QACjD,aAAa,mBAAmB,UAAU,QAAQ,2CAA2C,gBAAgB;AAAA,QAC7G,aAAa,UAAU;AAAA,QACvB,KAAK;AAAA,UACH,IAAI,eAAe,UAAU,SAAS,UAAU,IAAI;AAAA,UACpD,MAAM,eAAe,gBAAgB,oBAAoB,aAAa,UAAU,OAAO,CAAC;AAAA,QAC1F;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAGA,aAAW,CAAC,SAAS,MAAM,KAAK,OAAO;AACrC,QAAI,CAAC,SAAS,IAAI,OAAO,GAAG;AAC1B,aAAO,KAAK;AAAA,QACV,IAAI,uBAAuB,OAAO;AAAA,QAClC,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO,wBAAwB,OAAO;AAAA,QACtC,aAAa,sBAAsB,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO,IAAI,MAAM,EAAE;AAAA,QACpF,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;AAGA,SAAS,eAAe,SAAiB,MAAsB;AAC7D,SAAO;AAAA,IACL,eAAe,gBAAgB;AAAA,IAC/B,WAAW,aAAa,OAAO,CAAC,KAAK,aAAa,IAAI,CAAC;AAAA,IACvD;AAAA,EACF,EAAE,KAAK,IAAI;AACb;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/diff.ts","../src/ci.ts"],"sourcesContent":["import { Flags } from '@oclif/core'\nimport { BaseCommand } from '../base-command.js'\nimport { createDefaultRegistry } from '../checks/index.js'\nimport { scan } from '../scanner.js'\nimport type { ScanProgressEvent } from '../scanner.js'\nimport { renderSummary, renderDetailed, formatSkips } from '../render.js'\nimport { promote, planWork, type PromoteResult } from '../promote.js'\nimport type { CheckName, ScanResult } from '../types/drift.js'\nimport { CHECK_NAMES, CHECK_META } from '../types/drift.js'\nimport { ok, warn, dim, cmd, bold } from '../ui.js'\nimport { sanitizeForReport } from '../utils/sanitize.js'\nimport { renderTip } from '../tips.js'\nimport { formatGitHubAnnotations, computeCiExitCode, formatCiSummary, type FailOn } from '../ci.js'\nimport { resolveTableFilter, isFiltered, describeTableFilter } from '../utils/table-filter.js'\nimport { parseFlagList } from '../utils/strings.js'\nimport { isCloneDatabase, sourceLooksLikeCloneOf } from '../branch.js'\nimport { proveConvergence, residualHeldBack, proofScope, comparedSchemas } from '../prove.js'\nimport { summarizeByKind } from '../scoring.js'\nimport { CLONE_SKIP_FLAGS, DEFAULT_IGNORE_SCHEMAS, schemaDiffIgnores } from '../defaults.js'\n\n/**\n * Glyph and text for a finished check, so the three outcomes are visually\n * distinct in the live progress list.\n */\nfunction describeCheckOutcome(\n status: 'clean' | 'drifted' | 'error' | 'skipped',\n issueCount: number,\n skipReason?: string,\n): { glyph: string; text: string } {\n if (status === 'error') return { glyph: warn('✗'), text: warn('error') }\n if (status === 'skipped') {\n return { glyph: dim('○'), text: dim(`skipped — ${skipReason ?? 'no reason given'}`) }\n }\n return { glyph: ok('✓'), text: `${issueCount} issues` }\n}\n\n/**\n * Flags that only mean something when fixes are being planned or executed.\n *\n * Passed on their own they used to be inert *and silent* — the run printed\n * byte-identical output to one with no flag at all. Worst for the two that read\n * as safety measures: someone reaching for `--prove` or `--dry-run` alone, the\n * natural instinct for \"don't actually do it\", got an ordinary diff and no sign\n * they had neither previewed nor proved anything (issue #71).\n *\n * `--dry-run` is deliberately absent: it now selects the planning path by\n * itself, so previewing never requires typing the flag that writes. Flags that\n * shape the *plan* rather than the execution are honoured under `--dry-run`, so\n * they are only inert when neither flag is present.\n */\nconst APPLY_ONLY_FLAGS: ReadonlyArray<{ flag: string; shapesThePlan: boolean }> = [\n { flag: 'prove', shapesThePlan: false },\n { flag: 'no-transaction', shapesThePlan: false },\n { flag: 'only', shapesThePlan: true },\n { flag: 'apply-posture', shapesThePlan: true },\n { flag: 'allow-destructive', shapesThePlan: true },\n]\n\n/** Which apply-only flags this invocation will silently ignore. */\nexport function inertApplyFlags(\n flags: Record<string, unknown>,\n): ReadonlyArray<{ flag: string; shapesThePlan: boolean }> {\n if (flags['apply']) return []\n const dryRun = Boolean(flags['dry-run'])\n\n return APPLY_ONLY_FLAGS.filter(({ flag, shapesThePlan }) => {\n const given = flags[flag]\n const passed = Array.isArray(given) ? given.length > 0 : Boolean(given)\n if (!passed) return false\n return !(dryRun && shapesThePlan)\n })\n}\n\n/**\n * Unified drift detection & resolution command.\n *\n * Default: summary of what's drifted (was: scan)\n * --detail: full SQL diffs (was: diff)\n * --apply: fix the drift (was: promote)\n * --ci: emit GitHub Actions annotations + structured exit codes\n */\nexport default class Diff extends BaseCommand {\n static override description = 'Detect drift between Supabase environments and optionally fix it'\n\n static override examples = [\n '<%= config.bin %> diff',\n '<%= config.bin %> diff --detail',\n '<%= config.bin %> diff --apply',\n '<%= config.bin %> diff --check=rls',\n '<%= config.bin %> diff --check=rls --apply',\n '<%= config.bin %> diff --source=staging --target=production',\n '<%= config.bin %> diff --skip=storage --skip=vault',\n '<%= config.bin %> diff --tables=orders,order_items',\n \"<%= config.bin %> diff --tables='billing_*' --exclude-tables='*_audit'\",\n '<%= config.bin %> diff --tables=orders --detail',\n // Built from the same constant the tips and the post-clone output use, so\n // the advice cannot fall behind the check list again: this example predated\n // Layer 14 and omitted `roles`, which on a real clone → remote diff is 227\n // of the findings someone following it was left to puzzle over (issue #70).\n `<%= config.bin %> diff ${CLONE_SKIP_FLAGS}`,\n '<%= config.bin %> diff --ci',\n '<%= config.bin %> diff --ci --fail-on=warning',\n ]\n\n /**\n * Read from the environment rather than passed as flags, because they tune\n * limits rather than select behaviour. Rendered as their own `--help`\n * section (issue #40); the README carries the same table plus the timeout\n * precedence chain.\n */\n static envVars = [\n { name: 'SUPAFORGE_CONNECT_TIMEOUT', description: 'Seconds before a database connection attempt is abandoned (default 15).' },\n { name: 'SUPAFORGE_DBDIFF_TIMEOUT', description: 'Seconds before the schema/data diff is abandoned. Overrides checks.schema.timeout (default 600).' },\n { name: 'SUPAFORGE_DBDIFF_MEMORY', description: \"PHP memory limit for @dbdiff/cli — 512M, 2G, or -1 for unlimited (default dbdiff's own 1G).\" },\n ]\n\n static override flags = {\n check: Flags.string({\n char: 'l',\n description: 'Limit to a specific check',\n options: [...CHECK_NAMES],\n }),\n skip: Flags.string({\n char: 'x',\n description: 'Skip a specific check (repeatable). Also configurable via checks.exclude in supaforge.config.json.',\n options: [...CHECK_NAMES],\n multiple: true,\n }),\n detail: Flags.boolean({\n description: 'Show detailed SQL diffs (default: summary)',\n default: false,\n }),\n apply: Flags.boolean({\n description: 'Apply SQL fixes to resolve drift in the target environment',\n default: false,\n }),\n 'allow-destructive': Flags.boolean({\n description: 'With --apply, also run fixes that drop tables or columns (destroys data)',\n default: false,\n }),\n 'dry-run': Flags.boolean({\n description: 'With --apply, print the fixes in the order they would run without executing any of them',\n default: false,\n }),\n 'no-transaction': Flags.boolean({\n description: 'With --apply, run each fix on its own instead of rolling the whole set back on the first failure',\n aliases: ['continue-on-error'],\n default: false,\n }),\n only: Flags.string({\n description: 'With --apply, only apply these issue ids (repeatable, comma-separated, globs allowed). Ids come from --json.',\n multiple: true,\n }),\n 'include-files': Flags.boolean({\n description: 'Include file-level drift detection in storage check',\n default: false,\n }),\n tables: Flags.string({\n description: 'Only compare these tables in the schema and data checks (repeatable, comma-separated, globs allowed). Overrides checks.tables.',\n multiple: true,\n }),\n 'exclude-tables': Flags.string({\n description: 'Never compare these tables (repeatable, comma-separated, globs allowed). Merged with checks.excludeTables.',\n multiple: true,\n }),\n json: Flags.boolean({ description: 'Output results as JSON' }),\n source: Flags.string({ char: 's', description: 'Source environment name' }),\n target: Flags.string({ char: 't', description: 'Target environment name' }),\n ci: Flags.boolean({\n description: 'CI mode: emit GitHub Actions annotations and use semantic exit codes (0=clean, 1=drift, 2=error)',\n default: false,\n }),\n prove: Flags.boolean({\n description:\n 'Before applying, replay the migration on a throwaway clone of the target '\n + 'and verify it reproduces the source exactly. Refuses to apply if it does not.',\n default: false,\n }),\n 'apply-posture': Flags.boolean({\n description:\n 'With --apply, also apply fixes from checks that judge the target on its own '\n + '(RLS coverage, migration history). Off by default: those fixes move the target '\n + 'away from the source and so create drift.',\n default: false,\n }),\n 'fail-on': Flags.string({\n description: 'Threshold for a non-zero exit in CI mode',\n options: ['critical', 'warning', 'any'],\n default: 'critical',\n }),\n 'fail-on-posture': Flags.boolean({\n description:\n 'Let findings from the target-only checks (RLS coverage, migration history) '\n + 'affect the exit code too. Off by default: they fire identically whichever '\n + 'pair you diff, so they cannot indicate that the environments have diverged.',\n default: false,\n }),\n }\n\n /**\n * Report what `--apply` did, or — under `--dry-run` — what it would do.\n *\n * The applied list is printed in execution order, which is now dependency\n * order rather than the order the checks reported the issues. That ordering\n * is the whole point of the dry run: it is what makes the outcome of a real\n * apply predictable before running it (issue #48).\n */\n private renderApplyResult(result: PromoteResult, dryRun: boolean): void {\n const verb = dryRun ? 'Would apply' : 'Applied'\n if (result.applied.length > 0) {\n const heading = `${verb} ${result.applied.length} fix(es)${dryRun ? ', in this order' : ''}:`\n this.log(dryRun ? bold(heading) : ok(heading))\n result.applied.forEach((stmt, i) => {\n const glyph = dryRun ? dim(`${i + 1}.`) : ok('✓')\n this.log(` ${glyph} ${dim(`[${stmt.check}]`)} ${stmt.issueId}`)\n // The SQL itself only in a dry run: it is the thing being reviewed,\n // and printing it after the fact would just repeat --detail.\n if (dryRun && stmt.sql) this.log(` ${dim(stmt.sql.replace(/\\s*\\n\\s*/g, ' '))}`)\n if (dryRun && stmt.action) this.log(` ${dim(stmt.action)}`)\n })\n }\n\n if (result.skipped.length > 0) {\n this.log(`\\n${dim(`Skipped ${result.skipped.length} issue(s):`)}`)\n // Collapsed where several share a reason: a posture check on a project\n // with 47 tables lacking RLS printed the same sentence 47 times, and\n // pushed the result of the apply off the top of the screen (issue #84).\n for (const line of formatSkips(result.skipped)) this.log(` ${dim(line)}`)\n }\n\n // Printed before the errors: the first thing to know about a failed apply\n // is whether anything landed, and the answer here is that nothing did.\n if (result.rolledBack?.length) {\n this.log(`\\n${warn(`Rolled back ${result.rolledBack.length} fix(es)`)} — the target is unchanged:`)\n for (const item of result.rolledBack) {\n this.log(` ${dim('↩')} ${dim(`[${item.check}]`)} ${item.issueId}`)\n }\n }\n\n if (result.errors.length > 0) {\n this.log(`\\n${warn(`${result.errors.length} error(s):`)}`)\n for (const item of result.errors) {\n this.log(` ${warn('✗')} ${dim(`[${item.check}]`)} ${item.issueId}: ${item.error}`)\n }\n if (result.rolledBack) {\n this.log(`\\n ${dim(`Nothing was written. Re-run with ${cmd('--no-transaction')} to apply the fixes that do work.`)}`)\n }\n }\n\n if (dryRun) {\n this.log(`\\n ${dim(`Nothing was executed. Drop ${cmd('--dry-run')} to apply.`)}`)\n }\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(Diff)\n\n // On stderr, so a --json or --ci consumer still gets clean stdout while a\n // human is told the flag did nothing.\n for (const { flag, shapesThePlan } of inertApplyFlags(flags as unknown as Record<string, unknown>)) {\n const suggestion = shapesThePlan\n ? `Add ${cmd('--apply')} (or ${cmd('--dry-run')} to preview) for it to take effect.`\n : `Add ${cmd('--apply')} for it to take effect.`\n process.stderr.write(` ${warn(`--${flag} has no effect without --apply.`)} ${suggestion}\\n`)\n }\n\n const config = await this.loadConfigOrFail()\n this.validateDualEnvConfig(config, flags.source, flags.target)\n\n const registry = createDefaultRegistry({ includeFiles: flags['include-files'] })\n const checks = flags.check ? [flags.check as CheckName] : undefined\n const skip = flags.skip?.length ? (flags.skip as CheckName[]) : undefined\n\n const tableFilter = resolveTableFilter(config, {\n tables: flags.tables,\n excludeTables: flags['exclude-tables'],\n })\n\n // Stated up front: a narrowed run must not look like a full one, and with\n // --apply the difference is which statements actually execute (issue #43).\n if (isFiltered(tableFilter) && !flags.json && !flags.ci) {\n this.log(`\\n ${dim(describeTableFilter(tableFilter)!)}`)\n }\n\n // ── Preflight: verify both databases are reachable ────────────────────────\n if (!flags.json && !flags.ci) {\n const sourceEnv = config.environments[config.source!]\n const targetEnv = config.environments[config.target!]\n const pre = this.createPreflight('Diff preflight checks')\n .addDatabase('Source', config.source!, sourceEnv.dbUrl)\n .addDatabase('Target', config.target!, targetEnv.dbUrl)\n await this.runPreflight(pre, 'Diff')\n }\n\n /** Build a progress callback for scan calls. Only active when not --json or --ci. */\n const makeProgress = (): ((event: ScanProgressEvent) => void) | undefined => {\n if (flags.json || flags.ci) return undefined\n process.stdout.write('\\n Scanning...\\n')\n return (event: ScanProgressEvent) => {\n const meta = CHECK_META[event.check]\n const label = meta?.label ?? event.check\n const idx = `[${event.index + 1}/${event.total}]`\n if (event.phase === 'check:start') {\n process.stdout.write(` ▶ ${idx} ${label}...\\n`)\n } else {\n // Clear any in-place detail line before the final result line.\n if (process.stdout.isTTY) process.stdout.write('\\r\\u001b[2K')\n const dur = `${(event.durationMs / 1000).toFixed(1)}s`\n // A skipped layer gets its own glyph and its reason. A green tick\n // beside \"0 issues\" was indistinguishable from a comparison that\n // passed (issue #42).\n const { glyph, text } = describeCheckOutcome(event.status, event.issueCount, event.skipReason)\n process.stdout.write(` ${glyph} ${idx} ${label.padEnd(24)} ${text} (${dur})\\n`)\n }\n }\n }\n\n /**\n * Render fine-grained progress from within a check, in place.\n *\n * A ~100s schema diff on one static spinner line reads as a hang\n * (issue #29). Only used on a TTY — piped or CI output would otherwise\n * accumulate thousands of partial lines.\n */\n const makeDetail = (): ((check: CheckName, detail: string) => void) | undefined => {\n if (flags.json || flags.ci || !process.stdout.isTTY) return undefined\n return (_check, detail) => {\n process.stdout.write(`\\r\\u001b[2K ${dim(detail)}`)\n }\n }\n\n // ── Apply mode (was: promote) ───────────────────────────────────────────────\n // `--dry-run` enters here without `--apply`: it plans, prints the execution\n // order, and writes nothing. Previewing an apply should not require typing\n // the flag that performs one (issue #71).\n if (flags.apply || flags['dry-run']) {\n const onProgress = makeProgress()\n const scanResult = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() })\n this.setCheckSummaries(scanResult.checks.map(c => ({\n check: c.check,\n status: c.status,\n issueCount: c.issues.length,\n durationMs: c.durationMs,\n ...(c.error ? { error: sanitizeForReport(c.error) } : {}),\n })))\n\n if (scanResult.summary.total === 0) {\n // --json promises JSON on stdout whatever the outcome. This branch used\n // to print the sentence below instead, so a script reading the result\n // of an apply failed on the one run where there was nothing to do.\n if (flags.json) {\n const empty: PromoteResult = { applied: [], skipped: [], errors: [] }\n this.json(empty)\n return\n }\n this.log(`${ok('No drift detected.')} Nothing to apply. ✓`)\n this.log(renderTip({ command: 'diff', apply: true, driftTotal: 0 }))\n return\n }\n\n const targetEnv = config.environments[config.target!]\n const dryRun = flags['dry-run']\n\n // Prove before touching the target. A migration that executes without\n // error can still leave the database in a state that is not the source —\n // a flattened partition or an index that never reached its partitions\n // both apply cleanly. Only replaying it and looking at the result catches\n // that, so when --prove is set a failure blocks the apply rather than\n // warning after the fact.\n if (flags.prove && !dryRun) {\n const sourceEnv = config.environments[config.source!]\n const planned = planWork(scanResult, {\n checks, only: parseFlagList(flags.only),\n allowDestructive: flags['allow-destructive'], tableFilter,\n applyPosture: flags['apply-posture'],\n })\n const { replay, unproved } = proofScope(planned.sqlStatements)\n const migrationSql = replay.map(s => s.sql).join('\\n')\n\n this.log(`\\n ${dim('Proving convergence on a throwaway clone…')}`)\n if (unproved.length > 0) {\n // Applied all the same; the proof just cannot speak for them.\n const byCheck = [...new Set(unproved.map(s => s.check))]\n .map(c => `${c} ×${unproved.filter(s => s.check === c).length}`).join(', ')\n this.log(` ${dim(`Not proved — act outside the proved schemas or on the whole server: ${byCheck}`)}`)\n }\n // Nothing left to replay means nothing to prove. Running it anyway\n // compared the whole schema, and refused a cron-only apply over\n // tables it was never going to touch.\n const proof = replay.length === 0\n ? { converged: false, residual: [], cloneName: '', skipped: 'none of the planned fixes is one the proof can replay' }\n : await proveConvergence({\n sourceUrl: sourceEnv.dbUrl,\n targetUrl: targetEnv.dbUrl,\n migrationSql,\n // Every schema the schema diff compares, not `public` alone: a\n // migration dropping a schema the source lacks runs against it.\n schemas: await comparedSchemas(sourceEnv.dbUrl, targetEnv.dbUrl,\n schemaDiffIgnores(config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS)),\n // The checks this run compares: without the schema check, what the\n // target already lacks elsewhere is not this migration's to fix.\n checks: scanResult.checks.map(c => c.check),\n })\n\n if (proof.skipped) {\n // Could not prove is not the same as failed to converge; say which.\n this.log(` ${warn('Convergence not proven')}: ${proof.skipped}`)\n this.log(` ${dim('Continuing — re-run without --prove to silence this.')}\\n`)\n } else if (!proof.converged && residualHeldBack(proof.residual, heldBackSql(scanResult, planned)).unexplained.length === 0) {\n // Everything left over is what this run deliberately holds back.\n this.log(` ${ok('Converged')}, apart from what is held back and stays on the target:`)\n for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`)\n this.log('')\n } else if (!proof.converged) {\n this.log(` ${warn('Migration does not reproduce the source.')} Nothing was applied.\\n`)\n const { unexplained } = residualHeldBack(proof.residual, heldBackSql(scanResult, planned))\n for (const line of unexplained.slice(0, 15)) this.log(` ${line}`)\n if (unexplained.length > 15) {\n this.log(` ${dim(`…and ${unexplained.length - 15} more`)}`)\n }\n this.log(`\\n ${dim('These objects would still differ after applying.')}`)\n this.exit(1)\n } else {\n if (proof.outOfScope?.length) {\n this.log(` ${ok('Converged')} on what this run compares. Outside it, and already different before:`)\n for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`)\n if (proof.outOfScope.length > 15) this.log(` ${dim(`…and ${proof.outOfScope.length - 15} more`)}`)\n this.log('')\n } else {\n this.log(` ${ok('Converged')} — the migration reproduces the source exactly.\\n`)\n }\n }\n }\n\n const result = await promote({\n dbUrl: targetEnv.dbUrl,\n scanResult,\n checks,\n dryRun,\n allowDestructive: flags['allow-destructive'],\n tableFilter,\n only: parseFlagList(flags.only),\n applyPosture: flags['apply-posture'],\n transactional: !flags['no-transaction'],\n })\n\n if (flags.json) {\n this.json(result)\n return\n }\n\n this.renderApplyResult(result, dryRun)\n\n if (result.errors.length > 0) {\n this.exit(1)\n }\n\n this.log(renderTip({\n command: 'diff',\n apply: true,\n driftTotal: scanResult.summary.total,\n driftedChecks: scanResult.checks.filter(c => c.status === 'drifted').map(c => c.check),\n }))\n return\n }\n\n // ── Scan mode (summary, detail, CI, or JSON) ────────────────────────────\n const onProgress = makeProgress()\n const result = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() })\n this.setCheckSummaries(result.checks.map(c => ({\n check: c.check,\n status: c.status,\n issueCount: c.issues.length,\n durationMs: c.durationMs,\n ...(c.error ? { error: sanitizeForReport(c.error) } : {}),\n })))\n\n // Whether the source is a local clone changes what `--apply` means, and so\n // changes what the closing tip should say about it (issue #48).\n //\n // Two signals, because the bookkeeping one is local and exact: a clone\n // diffed from another directory, or renamed, answered \"not a clone\" and got\n // the unqualified \"add --apply\" advice in the most destructive direction\n // (issue #71). The second signal asks the databases whether the source is\n // missing the Supabase substrate the target has, which is the property that\n // makes the advice wrong.\n const sourceUrl = config.environments[config.source!]?.dbUrl\n const sourceIsClone = await isCloneDatabase(sourceUrl)\n || await sourceLooksLikeCloneOf(sourceUrl, config.environments[config.target!]?.dbUrl)\n\n const driftedChecks = result.checks.filter(c => c.status === 'drifted').map(c => c.check)\n const skippedChecks = result.checks.filter(c => c.status === 'skipped').map(c => c.check)\n // A check that errored measured nothing — surfaced so the summary and tips\n // never present an unmeasured scan as a clean one (issue #29).\n const erroredChecks = result.checks.filter(c => c.status === 'error').map(c => c.check)\n\n // ── CI mode ──────────────────────────────────────────────────────────────\n if (flags.ci) {\n const failOn = (flags['fail-on'] ?? 'critical') as FailOn\n // Annotations go to stderr; the machine-readable summary is the *only*\n // thing on stdout. This lets a workflow capture a clean JSON artifact\n // (`supaforge diff --ci > report.json`) while GitHub Actions still renders\n // the `::error`/`::warning` workflow commands from stderr.\n const annotations = formatGitHubAnnotations(result)\n for (const line of annotations) {\n process.stderr.write(line + '\\n')\n }\n const summary = formatCiSummary(result)\n process.stdout.write(JSON.stringify(summary, null, 2) + '\\n')\n const exitCode = computeCiExitCode(result, failOn, {\n failOnPosture: flags['fail-on-posture'],\n })\n if (exitCode !== 0) {\n this.exit(exitCode)\n }\n return\n }\n\n if (flags.json) {\n this.json(result)\n } else if (flags.detail) {\n this.log(renderDetailed(result))\n this.log(renderTip({\n command: 'diff',\n detail: true,\n driftTotal: result.summary.total,\n driftedChecks,\n skippedChecks,\n erroredChecks,\n singleCheck: checks?.[0],\n sourceIsClone,\n }))\n } else {\n this.log(renderSummary(result))\n\n if (result.summary.total > 0) {\n this.log(` → Run with ${cmd('--detail')} to see SQL diffs`)\n // Direction matters here, not just in the tip below. From a clone this\n // line was recommending the command that reshapes a shared remote to\n // match a vanilla-PostgreSQL copy — dropping the roles, grants and\n // policies the clone never had (issue #71).\n this.log(\n sourceIsClone\n ? ` → ${cmd('--apply')} would push this clone's shape onto the target, `\n + `absences included — preview it first with ${cmd('--apply --dry-run')}\\n`\n : ` → Run with ${cmd('--apply')} to fix drift\\n`,\n )\n }\n\n this.log(renderTip({\n command: 'diff',\n detail: false,\n driftTotal: result.summary.total,\n driftedChecks,\n skippedChecks,\n erroredChecks,\n singleCheck: checks?.[0],\n sourceIsClone,\n }))\n }\n\n // Exit code deliberately unchanged for an errored check: `--ci` is the\n // documented contract for scripting and already exits 2 in that case\n // (0=clean, 1=drift, 2=error). Making plain `diff` exit non-zero here\n // would break every non-CI caller for a signal that already has a\n // supported home. The misleading *output* is fixed above instead.\n //\n // Only drift decides the code. A critical posture finding — RLS disabled on\n // a table, a migration file with no tracking row — is true of the target\n // whichever pair you diff, so letting it exit 1 meant a perfectly\n // synchronised pair failed a sync check forever (issue #66).\n const { drift, posture } = summarizeByKind(result.checks)\n\n // Said once, where it changes what the reader should conclude: the report\n // above shows critical findings and the command is about to succeed.\n if (drift.critical === 0 && posture.critical > 0 && !flags.json) {\n this.log(\n ` ${dim('Posture findings do not affect the exit code — they describe the target, '\n + 'not drift from the source. Add')} ${cmd('--fail-on-posture')} ${dim('to gate on them.')}\\n`,\n )\n }\n\n if (drift.critical > 0 || (flags['fail-on-posture'] && posture.critical > 0)) {\n this.exit(1)\n }\n }\n}\n\n/** The SQL of the fixes this run plans to skip, which the proof did not replay. */\nfunction heldBackSql(scanResult: ScanResult, planned: { skipped: Array<{ issueId: string }> }): string[] {\n const skipped = new Set(planned.skipped.map(s => s.issueId))\n return scanResult.checks.flatMap(c => c.issues)\n .filter(i => skipped.has(i.id) && i.sql?.up)\n .map(i => i.sql!.up)\n}\n\n","import type { ScanResult, DriftIssue } from './types/drift.js'\nimport { coverage } from './render.js'\nimport { summarizeByKind } from './scoring.js'\n\nexport type FailOn = 'critical' | 'warning' | 'any'\n\n/**\n * Escape a workflow-command *message* (the text after `::`).\n *\n * GitHub Actions uses percent-encoding, not backslash escaping. `%` must be\n * encoded first so the percent signs introduced by the other replacements are\n * not double-encoded. Mirrors `@actions/core`'s `escapeData`.\n */\nfunction escapeData(value: string): string {\n return value\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n}\n\n/**\n * Escape a workflow-command *property* value (e.g. `title=`). In addition to\n * the message escapes, `:` and `,` must be encoded because they delimit\n * properties. Mirrors `@actions/core`'s `escapeProperty`.\n */\nfunction escapeProperty(value: string): string {\n return escapeData(value)\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C')\n}\n\n/**\n * Format a DriftIssue as a GitHub Actions annotation line.\n * Spec: https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions#setting-a-notice-message\n */\nexport function formatAnnotation(issue: DriftIssue): string {\n const level = issue.severity === 'critical' ? 'error' : 'warning'\n const title = escapeProperty(issue.title)\n const message = escapeData(issue.description)\n return `::${level} title=${title}::${message}`\n}\n\n/** Emit all drift issues as GitHub Actions annotation lines. */\nexport function formatGitHubAnnotations(result: ScanResult): string[] {\n const lines: string[] = []\n for (const check of result.checks) {\n for (const issue of check.issues) {\n lines.push(formatAnnotation(issue))\n }\n }\n return lines\n}\n\n/** Does this set of counts cross the threshold? */\nfunction exceeds(counts: { critical: number; warning: number; total: number }, failOn: FailOn): boolean {\n if (failOn === 'critical') return counts.critical > 0\n if (failOn === 'warning') return counts.critical > 0 || counts.warning > 0\n return counts.total > 0\n}\n\n/**\n * Determine the exit code for CI.\n *\n * 0 = no drift above threshold\n * 1 = drift exceeds threshold\n * 2 = scan error (connection failure, etc.)\n *\n * Only the comparison checks count. RLS Coverage and Migration History judge\n * the target on its own and fire identically whichever pair you diff, so\n * including them made the exit code unable to distinguish \"the environments\n * have diverged\" from \"the target has a pre-existing gap\" — a sync check failed\n * permanently against an identical target (issue #66). `--fail-on` is a\n * *severity* threshold and could not express the difference, because the\n * difference is one of scope.\n *\n * Pass `failOnPosture` to gate on those findings too. They are never silenced:\n * they keep their severity, appear in the report and the annotations, and are\n * scored as `postureScore`.\n */\nexport function computeCiExitCode(\n result: ScanResult, failOn: FailOn = 'critical', opts: { failOnPosture?: boolean } = {},\n): number {\n const hasError = result.checks.some(c => c.status === 'error')\n if (hasError) return 2\n\n const { drift, posture } = summarizeByKind(result.checks)\n if (exceeds(drift, failOn)) return 1\n if (opts.failOnPosture && exceeds(posture, failOn)) return 1\n\n return 0\n}\n\n/**\n * Produce a structured CI summary object for GitHub Actions step summaries\n * or artifact upload.\n */\nexport function formatCiSummary(result: ScanResult): {\n timestamp: string\n /** Drift between the two environments, over the comparison checks only. */\n score: number\n /**\n * The target's own security and tracking posture, over the non-comparative\n * checks. Reported separately so a pre-existing RLS gap cannot mask, or be\n * mistaken for, environments having diverged (issue #40).\n */\n postureScore: number | null\n summary: ScanResult['summary']\n /**\n * Checks that failed to run. Empty on a healthy scan.\n *\n * Without this a reader of the uploaded artifact saw only a clean summary\n * and had no way to tell that a check never ran — the exit code carried\n * that signal, but the artifact did not (issue #29).\n */\n errors: Array<{ check: string; message: string }>\n /**\n * Checks that declined to run, with the reason.\n *\n * A skipped check is not a failure, so it does not belong in `errors` — but\n * omitting it entirely left a CI artifact that read as full coverage when\n * three layers had never opened a connection (issue #42).\n */\n skipped: Array<{ check: string; reason: string }>\n /** How many checks compared the two environments, over how many were attempted. */\n coverage: { compared: number; total: number }\n criticalIssues: Array<{ check: string; id: string; title: string }>\n warningIssues: Array<{ check: string; id: string; title: string }>\n} {\n const criticalIssues: Array<{ check: string; id: string; title: string }> = []\n const warningIssues: Array<{ check: string; id: string; title: string }> = []\n const errors: Array<{ check: string; message: string }> = []\n const skipped: Array<{ check: string; reason: string }> = []\n\n for (const check of result.checks ?? []) {\n if (check?.status === 'error') {\n errors.push({ check: check.check, message: check.error ?? 'Check failed with no error message' })\n }\n if (check?.status === 'skipped') {\n skipped.push({ check: check.check, reason: check.skipReason ?? 'no reason given' })\n }\n for (const issue of check?.issues ?? []) {\n const entry = { check: check.check, id: issue.id, title: issue.title }\n if (issue.severity === 'critical') {\n criticalIssues.push(entry)\n } else if (issue.severity === 'warning') {\n warningIssues.push(entry)\n }\n }\n }\n\n return {\n timestamp: result.timestamp,\n score: result.score,\n postureScore: result.postureScore ?? null,\n summary: result.summary,\n errors,\n skipped,\n coverage: coverage(result),\n criticalIssues,\n warningIssues,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;;;ACatB,SAAS,WAAW,OAAuB;AACzC,SAAO,MACJ,QAAQ,MAAM,KAAK,EACnB,QAAQ,OAAO,KAAK,EACpB,QAAQ,OAAO,KAAK;AACzB;AAOA,SAAS,eAAe,OAAuB;AAC7C,SAAO,WAAW,KAAK,EACpB,QA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A,aAAa,SAAS,CAAC;AAAA,QACvB;AAAA,MACF,CAAC,CAAC;AAAA,IACJ;AAYA,UAAM,EAAE,OAAO,QAAQ,IAAI,gBAAgB,OAAO,MAAM;AAIxD,QAAI,MAAM,aAAa,KAAK,QAAQ,WAAW,KAAK,CAAC,MAAM,MAAM;AAC/D,WAAK;AAAA,QACH,KAAK,IAAI,8GACyB,CAAC,IAAI,IAAI,mBAAmB,CAAC,IAAI,IAAI,kBAAkB,CAAC;AAAA;AAAA,MAC5F;AAAA,IACF;AAEA,QAAI,MAAM,WAAW,KAAM,MAAM,iBAAiB,KAAK,QAAQ,WAAW,GAAI;AAC5E,WAAK,KAAK,CAAC;AAAA,IACb;AAAA,EACF;AACF;AAGA,SAAS,YAAY,YAAwB,SAA4D;AACvG,QAAM,UAAU,IAAI,IAAI,QAAQ,QAAQ,IAAI,OAAK,EAAE,OAAO,CAAC;AAC3D,SAAO,WAAW,OAAO,QAAQ,OAAK,EAAE,MAAM,EAC3C,OAAO,OAAK,QAAQ,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAC1C,IAAI,OAAK,EAAE,IAAK,EAAE;AACvB;","names":["onProgress","result"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pg-tools.ts","../src/snapshot.ts","../src/schema-introspect.ts","../src/utils/schema-policies.ts","../src/utils/policy-equivalence.ts","../src/checks/realtime.ts"],"sourcesContent":["/**\n * pg_dump / pg_restore version detection and install guidance.\n *\n * Used by branch/clone commands that need the pg_dump ↔ pg_restore pipeline.\n * Detects local tool version, compares it against the remote server's major\n * version, and produces actionable install instructions on mismatch.\n */\nimport { execFile } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { existsSync } from 'node:fs'\nimport pg from 'pg'\nimport { pgClientConfig } from './db.js'\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface PgToolCheck {\n /** Local pg_dump major version, or null if not found. */\n localMajor: number | null\n /** Remote server major version. */\n serverMajor: number\n /** True when local tool matches or exceeds server major version. */\n compatible: boolean\n /** Human-readable message (empty when compatible). */\n message: string\n /** Resolved absolute path to a compatible pg_dump binary (may differ from PATH default). */\n pgDumpPath: string\n /** Resolved absolute path to a compatible pg_restore binary. */\n pgRestorePath: string\n}\n\n// ─── Version Parsing ─────────────────────────────────────────────────────────\n\n/** Extract major version from pg_dump --version output, e.g. \"pg_dump (PostgreSQL) 16.3\" → 16. */\nexport function parsePgDumpVersion(output: string): number | null {\n const m = output.match(/(\\d+)(?:\\.\\d+)?/)\n return m ? Number(m[1]) : null\n}\n\n/** Extract major version from `SHOW server_version`, e.g. \"17.6 (Ubuntu 17.6-1.pgdg22.04+1)\". */\nexport function parseServerVersion(versionStr: string): number | null {\n const m = versionStr.match(/^(\\d+)/)\n return m ? Number(m[1]) : null\n}\n\n// ─── Detection ───────────────────────────────────────────────────────────────\n\n/** Get local pg_dump major version (null if not installed). */\nexport async function getLocalPgDumpVersion(): Promise<number | null> {\n return new Promise((resolve) => {\n execFile('pg_dump', ['--version'], (err, stdout) => {\n if (err) return resolve(null)\n resolve(parsePgDumpVersion(stdout))\n })\n })\n}\n\n/** Get pg_dump version at a specific path (null if not found). */\nfunction getPgDumpVersionAt(path: string): Promise<number | null> {\n return new Promise((resolve) => {\n execFile(path, ['--version'], (err, stdout) => {\n if (err) return resolve(null)\n resolve(parsePgDumpVersion(stdout))\n })\n })\n}\n\n/**\n * Well-known directories where versioned PostgreSQL client binaries are installed.\n * Checked in order when the default PATH binary is too old.\n */\nconst VERSIONED_PG_DIRS: readonly string[] = [\n '/usr/lib/postgresql/{v}/bin', // Debian / Ubuntu (PGDG)\n '/opt/homebrew/opt/postgresql@{v}/bin', // macOS Homebrew (Apple Silicon)\n '/usr/local/opt/postgresql@{v}/bin', // macOS Homebrew (Intel)\n '/usr/pgsql-{v}/bin', // RHEL / CentOS (PGDG)\n]\n\n/**\n * Resolve a compatible pg_dump binary path for the given server major version.\n *\n * 1. Checks the default `pg_dump` on PATH.\n * 2. Then the directory SUPAFORGE_PG_BIN names, if set.\n * 3. Falls back to well-known versioned directories.\n *\n * Returns `{ path, major }` or `null` if no compatible binary is found.\n */\nexport async function resolvePgDumpPath(\n serverMajor: number,\n): Promise<{ path: string; major: number } | null> {\n // Check the default PATH binary first\n const defaultMajor = await getLocalPgDumpVersion()\n if (defaultMajor !== null && defaultMajor >= serverMajor) {\n return { path: 'pg_dump', major: defaultMajor }\n }\n\n // A directory of client tools named explicitly, for an install none of the\n // well-known locations below covers.\n const named = process.env.SUPAFORGE_PG_BIN?.trim()\n if (named && existsSync(`${named}/pg_dump`)) {\n const major = await getPgDumpVersionAt(`${named}/pg_dump`)\n if (major !== null && major >= serverMajor) return { path: `${named}/pg_dump`, major }\n }\n\n // Search versioned directories (highest version first)\n for (const v of versionsToCheck(serverMajor)) {\n for (const tmpl of VERSIONED_PG_DIRS) {\n const dir = tmpl.replace('{v}', String(v))\n const candidate = `${dir}/pg_dump`\n if (!existsSync(candidate)) continue\n const major = await getPgDumpVersionAt(candidate)\n if (major !== null && major >= serverMajor) {\n return { path: candidate, major }\n }\n }\n }\n\n return null\n}\n\n/**\n * Derive the pg_restore path from a resolved pg_dump path.\n * If pg_dump was resolved from PATH, returns 'pg_restore'.\n * Otherwise returns the sibling binary in the same directory.\n */\nexport function resolvePgRestorePath(pgDumpPath: string): string {\n if (pgDumpPath === 'pg_dump') return 'pg_restore'\n return pgDumpPath.replace(/pg_dump$/, 'pg_restore')\n}\n\n/** Versions to check, from the required version up to +3 (handles newer installs). */\nfunction versionsToCheck(required: number): number[] {\n const versions: number[] = []\n for (let v = required + 3; v >= required; v--) {\n versions.push(v)\n }\n return versions\n}\n\n/** Get remote PostgreSQL server major version via SQL. */\nexport async function getServerMajorVersion(dbUrl: string): Promise<number> {\n const client = new pg.Client(pgClientConfig(dbUrl))\n try {\n await client.connect()\n const { rows } = await client.query('SHOW server_version')\n const raw = (rows[0] as Record<string, string>).server_version\n const major = parseServerVersion(raw)\n if (!major) throw new Error(`Could not parse server version: ${raw}`)\n return major\n } finally {\n await client.end()\n }\n}\n\n// ─── Compatibility Check ─────────────────────────────────────────────────────\n\n/**\n * Check whether the local pg_dump is compatible with the remote server.\n *\n * pg_dump requires its major version to be ≥ the server major version.\n * Returns a structured result with an actionable install message on mismatch.\n */\nexport async function checkPgDumpCompat(dbUrl: string): Promise<PgToolCheck> {\n const serverMajor = await getServerMajorVersion(dbUrl)\n const resolved = await resolvePgDumpPath(serverMajor)\n\n if (resolved) {\n return {\n localMajor: resolved.major,\n serverMajor,\n compatible: true,\n message: '',\n pgDumpPath: resolved.path,\n pgRestorePath: resolvePgRestorePath(resolved.path),\n }\n }\n\n const localMajor = await getLocalPgDumpVersion()\n const message = buildInstallMessage(localMajor, serverMajor)\n return {\n localMajor,\n serverMajor,\n compatible: false,\n message,\n pgDumpPath: 'pg_dump',\n pgRestorePath: 'pg_restore',\n }\n}\n\n// ─── Install Guidance ────────────────────────────────────────────────────────\n\nfunction buildInstallMessage(localMajor: number | null, serverMajor: number): string {\n const header = localMajor === null\n ? `pg_dump not found. The server is PostgreSQL ${serverMajor} — install postgresql-client-${serverMajor}:`\n : `pg_dump version mismatch: local v${localMajor}, server v${serverMajor}. Install postgresql-client-${serverMajor}:`\n\n const instructions = getInstallInstructions(serverMajor)\n return `${header}\\n\\n${instructions}`\n}\n\n/** Platform-specific install instructions for a given PostgreSQL major version. */\nexport function getInstallInstructions(majorVersion: number): string {\n const os = platform()\n const v = majorVersion\n\n switch (os) {\n case 'darwin':\n return [\n ` brew install postgresql@${v}`,\n ` # Then add to PATH:`,\n ` export PATH=\"/opt/homebrew/opt/postgresql@${v}/bin:$PATH\"`,\n ].join('\\n')\n\n case 'linux':\n return [\n ` # Debian / Ubuntu:`,\n ` sudo apt-get install -y postgresql-client-${v}`,\n ` # If the package is not found, add the PGDG repository first:`,\n ` # https://www.postgresql.org/download/linux/ubuntu/`,\n ``,\n ` # RHEL / Fedora:`,\n ` sudo dnf install -y postgresql${v}`,\n ].join('\\n')\n\n case 'win32':\n return [\n ` # Download the installer from:`,\n ` # https://www.postgresql.org/download/windows/`,\n ` # Or use Chocolatey:`,\n ` choco install postgresql${v} --params '/Password:postgres'`,\n ].join('\\n')\n\n default:\n return ` Download PostgreSQL ${v} client tools from: https://www.postgresql.org/download/`\n }\n}\n","import { mkdir, writeFile, readFile, readdir, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { execFile as execFileCb } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport type { QueryFn } from './db'\nimport { pgQuery } from './db'\nimport { quoteIdent, quoteLiteral, quoteName } from './utils/sql'\nimport type { EnvironmentConfig, SupaForgeConfig, SnapshotManifest, SnapshotLayerInfo } from './types/config'\nimport { DEFAULT_IGNORE_SCHEMAS, RELATION_NOT_FOUND } from './defaults'\nimport { introspectSchema } from './schema-introspect'\nimport { createPolicySql, dropPolicySql, schemaPolicySql, type SchemaPolicy } from './utils/schema-policies'\nimport { PUBLICATION_SQL } from './checks/realtime'\nimport type { SchemaSnapshot } from './schema-introspect'\nimport { getServerMajorVersion, resolvePgDumpPath } from './pg-tools'\nimport { errMsg } from './utils/error'\nimport { ok, warn, dim } from './ui'\nimport { SUPABASE_PLATFORM_SCHEMAS } from './defaults'\nimport { SUPABASE_MGMT_API, SUPAFORGE_DIR, SNAPSHOTS_SUBDIR, MIGRATIONS_SUBDIR } from './constants'\n\nconst execFile = promisify(execFileCb)\n\nexport type FetchFn = (url: string, init?: RequestInit) => Promise<Response>\n\nexport interface SnapshotOptions {\n envName: string\n env: EnvironmentConfig\n config: SupaForgeConfig\n /** Base output directory (defaults to cwd) */\n cwd?: string\n /** Custom output directory — snapshot files are written here directly (with timestamp subfolder). */\n outputDir?: string\n queryFn?: QueryFn\n fetchFn?: FetchFn\n}\n\nexport interface SnapshotResult {\n manifest: SnapshotManifest\n dir: string\n timestamp: string\n}\n\n// ─── Timestamp Helpers ───────────────────────────────────────────────────────\n\nexport function generateTimestamp(): string {\n return new Date().toISOString().replace(/[-:]/g, '').replace(/\\.\\d+Z$/, 'Z')\n}\n\nfunction snapshotsBaseDir(cwd: string): string {\n return resolve(cwd, SUPAFORGE_DIR, SNAPSHOTS_SUBDIR)\n}\n\nexport function snapshotDir(cwd: string, timestamp: string): string {\n return join(snapshotsBaseDir(cwd), timestamp)\n}\n\n// ─── Main Snapshot Function ──────────────────────────────────────────────────\n\n/**\n * Capture a full snapshot of a single Supabase environment.\n * Each layer is exported independently; failures in one layer don't block others.\n */\nexport async function captureSnapshot(options: SnapshotOptions): Promise<SnapshotResult> {\n const cwd = options.cwd ?? process.cwd()\n const timestamp = generateTimestamp()\n const dir = options.outputDir\n ? join(resolve(options.outputDir), timestamp)\n : snapshotDir(cwd, timestamp)\n await mkdir(dir, { recursive: true })\n\n const queryFn = options.queryFn ?? pgQuery\n const fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis)\n const ignoreSchemas = options.config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS\n\n const layers: Record<string, SnapshotLayerInfo> = {}\n\n // Layer 1: Schema (SQL introspection → JSON)\n layers.schema = await captureSchema(dir, options.env.dbUrl, ignoreSchemas, queryFn)\n\n // Layer 2: RLS Policies\n layers.rls = await captureRlsPolicies(dir, options.env.dbUrl, ignoreSchemas, queryFn)\n\n // Layer 3: Edge Functions (API)\n layers['edge-functions'] = await captureEdgeFunctions(dir, options.env, fetchFn)\n\n // Layer 4: Storage (DB)\n layers.storage = await captureStorage(dir, options.env, queryFn)\n\n // Layer 5: Auth Config (API)\n layers.auth = await captureAuthConfig(dir, options.env, fetchFn)\n\n // Layer 6: Cron Jobs\n layers.cron = await captureCronJobs(dir, options.env.dbUrl, queryFn)\n\n // Layer 7: Reference Data\n const dataTables = options.config.checks?.data?.tables ?? []\n layers.data = await captureData(dir, options.env.dbUrl, dataTables, queryFn)\n\n // Layer 8: Webhooks\n layers.webhooks = await captureWebhooks(dir, options.env.dbUrl, queryFn)\n\n // Layer 9: Extensions\n layers.extensions = await captureExtensions(dir, options.env.dbUrl, queryFn)\n\n // Layers 10-12: Realtime, Vault and roles.\n //\n // `diff` checks all three and a snapshot captured none of them, so a\n // snapshot was not a record of what `diff` compares (issue #92). Realtime\n // publications and role grants are ordinary DDL. Vault records the secrets'\n // *names* only — the values cannot be read out of Vault across\n // environments, which is the same reason the vault check offers no fix\n // (issue #91) — so the file is a checklist rather than something to replay.\n layers.realtime = await captureRealtime(dir, options.env.dbUrl, queryFn)\n layers.vault = await captureVaultSecrets(dir, options.env.dbUrl, queryFn)\n layers.roles = await captureRoleGrants(dir, options.env.dbUrl, queryFn)\n\n const manifest: SnapshotManifest = {\n version: 1,\n timestamp,\n environment: options.envName,\n projectRef: options.env.projectRef,\n layers,\n }\n\n await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n')\n\n return { manifest, dir, timestamp }\n}\n\n// ─── Layer Rendering ─────────────────────────────────────────────────────────\n\n/**\n * Format a snapshot manifest's layers into per-line status strings.\n *\n * Shared by `supaforge snapshot` and `supaforge clone` so both surface exactly\n * what was captured / skipped / errored — instead of a bare \"N layers\" count.\n * Lines are returned without leading indentation; callers add their own.\n */\nexport function formatSnapshotLayers(manifest: SnapshotManifest): string[] {\n const layers = manifest.layers as Record<string, SnapshotLayerInfo>\n const lines: string[] = []\n for (const [name, info] of Object.entries(layers)) {\n if (info.captured) {\n lines.push(`${ok('✓')} ${name.padEnd(16)} ${info.itemCount} item(s)`)\n } else if (info.error) {\n lines.push(`${warn('✗')} ${name.padEnd(16)} ${warn(`error: ${info.error}`)}`)\n } else {\n const skipSuffix = info.skipReason ? ` — ${info.skipReason}` : ''\n lines.push(`${dim('○')} ${name.padEnd(16)} ${dim(`skipped${skipSuffix}`)}`)\n }\n }\n return lines\n}\n\n// ─── Layer Capture Functions ─────────────────────────────────────────────────\n\nasync function captureSchema(\n dir: string,\n dbUrl: string,\n ignoreSchemas: string[],\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'schema.json'\n try {\n const schema = await introspectSchema(dbUrl, ignoreSchemas)\n await writeFile(join(dir, file), JSON.stringify(schema, null, 2) + '\\n')\n\n return {\n captured: true,\n file,\n itemCount: schema.tables.length,\n ...await captureSchemaSql(dir, dbUrl, [\n ...new Set([...schemasIn(schema), ...await projectSchemas(dbUrl, ignoreSchemas, queryFn)]),\n ].sort()),\n }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\n/**\n * Every schema the project made, whatever it holds.\n *\n * `schemasIn` sees only the kinds introspection reports, so a schema holding\n * nothing but domains or composite types — or nothing yet — was left out of\n * the dump, and a table typed by one of those domains failed the whole\n * restore with `schema \"billing\" does not exist`. Schemas an extension owns\n * are its to create, and the platform's are excluded as everywhere else.\n */\nasync function projectSchemas(dbUrl: string, ignoreSchemas: string[], queryFn: QueryFn): Promise<string[]> {\n const rows = await queryFn(dbUrl, `SELECT n.nspname AS name FROM pg_namespace n\n WHERE n.nspname NOT LIKE 'pg\\\\_%' AND n.nspname <> 'information_schema'\n AND n.nspname <> ALL($1::text[])\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass\n AND d.objid = n.oid AND d.deptype = 'e')`, [ignoreSchemas]) as Array<{ name: string }>\n return rows.map(r => r.name)\n}\n\n/** The schemas this snapshot describes, across every object kind it holds. */\nfunction schemasIn(schema: SchemaSnapshot): string[] {\n const names = new Set<string>()\n for (const group of [\n schema.tables, schema.views, schema.functions,\n schema.triggers, schema.sequences, schema.enums,\n ]) {\n for (const item of group as Array<{ schema?: string }>) {\n if (item.schema) names.add(item.schema)\n }\n }\n return names.size > 0 ? [...names].sort() : ['public']\n}\n\n/**\n * The same schema again, as DDL `restore` can replay.\n *\n * `schema.json` above is introspection output: the right shape for diffing two\n * snapshots, and not executable. `restore` looked for a `schema.sql` that\n * nothing ever wrote, reported the layer as skipped with \"File not readable\",\n * and carried on — so restoring a snapshot into an empty database produced no\n * tables at all, and the only error was the RLS layer failing against tables\n * that were never created (issue #80).\n *\n * pg_dump writes it, scoped to the schemas the snapshot describes so the two\n * files agree about what is covered. A snapshot is still captured when pg_dump\n * is missing or too old — the JSON is what the diffing path needs, and losing\n * the whole snapshot over a missing client would be the worse trade. The reason\n * is recorded instead, so `restore` can say why rather than guessing.\n */\nasync function captureSchemaSql(\n dir: string,\n dbUrl: string,\n schemas: string[],\n): Promise<Pick<SnapshotLayerInfo, 'sqlFile' | 'sqlSkipReason'>> {\n const sqlFile = 'schema.sql'\n try {\n const serverMajor = await getServerMajorVersion(dbUrl)\n const resolved = await resolvePgDumpPath(serverMajor)\n if (!resolved) {\n return {\n sqlSkipReason:\n `no pg_dump new enough for this server (needs ${serverMajor} or later) — `\n + 'schema.json was still captured, but restore cannot replay the schema',\n }\n }\n\n const { stdout } = await execFile(resolved.path, [\n dbUrl, '--schema-only', '--no-owner', '--no-privileges',\n // Quoted: pg_dump reads --schema as a pattern, folding `App Data` to lower case.\n ...schemas.map(s => `--schema=${quoteName(s)}`),\n ], { maxBuffer: 256 * 1024 * 1024, timeout: 300_000 })\n\n if (stdout.trim().length === 0) {\n return { sqlSkipReason: 'pg_dump produced an empty schema dump' }\n }\n\n await writeFile(join(dir, sqlFile), stdout)\n return { sqlFile }\n } catch (err) {\n return { sqlSkipReason: errMsg(err) }\n }\n}\n\n/**\n * A policy's comment, which pg_policies does not carry. Restored with the\n * policy: the layer drops and recreates it, which took the comment the schema\n * dump had set before it.\n */\nconst POLICY_COMMENT = `(SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename\n AND p.polname = pg_policies.policyname) AS comment`\n\nasync function captureRlsPolicies(\n dir: string,\n dbUrl: string,\n ignoreSchemas: string[],\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'rls.sql'\n try {\n const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(', ')\n const sql = ignoreSchemas.length > 0\n ? `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}\n FROM pg_policies WHERE schemaname NOT IN (${placeholders})\n ORDER BY schemaname, tablename, policyname`\n : `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}\n FROM pg_policies ORDER BY schemaname, tablename, policyname`\n\n const rows = await queryFn(dbUrl, sql, ignoreSchemas.length > 0 ? ignoreSchemas : undefined) as unknown as RlsRow[]\n const statements = rows.map(p => generateCreatePolicySql(p))\n const output = statements.length > 0\n ? `-- SupaForge RLS Policy Snapshot\\n-- ${rows.length} policies\\n\\n${statements.join('\\n\\n')}\\n`\n : '-- No RLS policies found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: rows.length }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function captureEdgeFunctions(\n dir: string,\n env: EnvironmentConfig,\n fetchFn: FetchFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'edge-functions.json'\n const token = env.accessToken\n if (!env.projectRef || !token) {\n return { captured: false, file, itemCount: 0, skipReason: 'no projectRef or accessToken configured' }\n }\n\n try {\n const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/functions`\n const res = await fetchFn(url, {\n headers: { Authorization: `Bearer ${token}` },\n })\n if (!res.ok) throw new Error(res.statusText)\n const functions = await res.json() as unknown[]\n await writeFile(join(dir, file), JSON.stringify(functions, null, 2) + '\\n')\n return { captured: true, file, itemCount: functions.length }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function captureStorage(\n dir: string,\n env: EnvironmentConfig,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n let bucketCount = 0\n let policyCount = 0\n let storageError: string | undefined\n\n // Buckets via direct DB query\n const bucketsFile = 'storage-buckets.json'\n try {\n const buckets = await queryFn(env.dbUrl, `\n SELECT id, name, public, file_size_limit, allowed_mime_types,\n avif_autodetection, created_at, updated_at\n FROM storage.buckets\n ORDER BY name\n `)\n await writeFile(join(dir, bucketsFile), JSON.stringify(buckets, null, 2) + '\\n')\n bucketCount = buckets.length\n } catch { /* storage schema may not exist — fall through to policies */ }\n\n // Storage policies via DB\n const policiesFile = 'storage-policies.sql'\n try {\n // The storage check's own query and SQL, so a snapshot keeps what the\n // check compares — each policy's comment included.\n const rows = await queryFn(env.dbUrl, schemaPolicySql('storage'))\n const statements = (rows as unknown as SchemaPolicy[]).map(p =>\n // Dropped first so a snapshot can be restored twice, as below.\n `${dropPolicySql('storage', p)}\\n${createPolicySql('storage', p)}`)\n const output = statements.length > 0\n ? `-- SupaForge Storage Policy Snapshot\\n-- ${rows.length} policies\\n\\n${statements.join('\\n\\n')}\\n`\n : '-- No storage policies found\\n'\n await writeFile(join(dir, policiesFile), output)\n policyCount = rows.length\n } catch (err) {\n storageError = errMsg(err)\n }\n\n const captured = bucketCount > 0 || policyCount > 0\n return {\n captured,\n file: bucketsFile,\n itemCount: bucketCount + policyCount,\n ...(storageError && !policyCount ? { error: storageError } : {}),\n ...(!captured && !storageError ? { skipReason: 'no storage buckets or policies found' } : {}),\n }\n}\n\nasync function captureAuthConfig(\n dir: string,\n env: EnvironmentConfig,\n fetchFn: FetchFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'auth.json'\n const token = env.accessToken\n if (!env.projectRef || !token) {\n return { captured: false, file, itemCount: 0, skipReason: 'no projectRef or accessToken configured' }\n }\n\n try {\n const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/config/auth`\n const res = await fetchFn(url, {\n headers: { Authorization: `Bearer ${token}` },\n })\n if (!res.ok) throw new Error(res.statusText)\n const config = await res.json() as Record<string, unknown>\n await writeFile(join(dir, file), JSON.stringify(config, null, 2) + '\\n')\n return { captured: true, file, itemCount: Object.keys(config).length }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function captureCronJobs(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'cron.sql'\n try {\n const rows = await queryFn(dbUrl, `\n SELECT jobid, schedule, command, nodename, nodeport, database, username, active, jobname\n FROM cron.job ORDER BY jobname, jobid\n `)\n const statements = (rows as unknown as CronRow[]).map(job => {\n const name = job.jobname ?? `job-${job.jobid}`\n return `SELECT cron.schedule('${name}', '${job.schedule}', $$${job.command}$$);`\n })\n const output = statements.length > 0\n ? `-- SupaForge Cron Job Snapshot\\n-- ${rows.length} jobs\\n\\n${statements.join('\\n\\n')}\\n`\n : '-- No cron jobs found (pg_cron may not be installed)\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: rows.length }\n } catch (err) {\n const msg = errMsg(err)\n await writeFile(join(dir, file), '-- pg_cron extension not available\\n').catch(() => {})\n if (msg.includes(RELATION_NOT_FOUND)) {\n return { captured: false, file, itemCount: 0, skipReason: 'pg_cron extension not installed' }\n }\n return { captured: false, file, itemCount: 0, error: msg }\n }\n}\n\nasync function captureData(\n dir: string,\n dbUrl: string,\n tables: string[],\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n if (tables.length === 0) {\n return { captured: false, file: 'data/', itemCount: 0, skipReason: 'no tables configured in checks.data.tables' }\n }\n\n const dataDir = join(dir, 'data')\n await mkdir(dataDir, { recursive: true })\n let captured = 0\n const errors: string[] = []\n\n for (const table of tables) {\n try {\n await writeFile(join(dataDir, `${table}.json`), await capturedRows(dbUrl, table, queryFn) + '\\n')\n captured++\n } catch (err) {\n errors.push(`${table}: ${errMsg(err)}`)\n }\n }\n\n return {\n captured: captured > 0,\n file: 'data/',\n itemCount: captured,\n ...(errors.length > 0 ? { error: errors.join('; ') } : {}),\n }\n}\n\n\n/**\n * A table's rows, each column as PostgreSQL's own text for it — the text its\n * input function reads back exactly, as pg_dump relies on. A bigint past 2^53,\n * a long numeric, a timestamp's zone, bytea and arrays come back as they were;\n * so does a json value's text, spacing and duplicate keys included, and a JSON\n * null stays distinct from an SQL NULL. Captured as JSON values instead, json\n * was re-rendered and a JSON null read back as NULL.\n */\nasync function capturedRows(dbUrl: string, table: string, queryFn: QueryFn): Promise<string> {\n const columns = (await queryFn(dbUrl, `SELECT attname AS name FROM pg_attribute\n WHERE attrelid = ${quoteLiteral(quoteIdent(table))}::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`) as unknown as Array<{ name: string }>)\n .map(c => c.name)\n const keys = columns.map(quoteLiteral).join(', ')\n const values = columns.map(c => `t.${quoteName(c)}::text`).join(', ')\n const [{ rows }] = await queryFn(dbUrl, `SELECT jsonb_pretty(jsonb_build_object('format', 'text', 'rows',\n coalesce(jsonb_agg(json_object(ARRAY[${keys}]::text[], ARRAY[${values}]::text[])::jsonb), '[]'::jsonb))) AS rows\n FROM (SELECT * FROM ${quoteIdent(table)} ORDER BY 1) t`) as unknown as Array<{ rows: string }>\n return rows\n}\n\nasync function captureWebhooks(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'webhooks.sql'\n try {\n // The triggers themselves, exactly as the check reads them (issue #77).\n // This used to start from supabase_functions.hooks — the log of webhook\n // *invocations* — and rebuild each trigger by hand, which got the same\n // things wrong here as it did there: a webhook that had never fired had no\n // log rows and was left out of the snapshot; a deleted one still had rows\n // and was written into it; the join was on trigger name alone, so two\n // webhooks of one name on different tables collapsed; every trigger was\n // emitted as AFTER whatever its real timing; and the arguments carrying the\n // URL, method, headers, params and timeout were dropped entirely, so\n // restoring a snapshot produced webhooks that failed every write with\n // `url argument is missing`. It also re-emitted Supabase's own\n // http_request via pg_get_functiondef, so a restore replaced it.\n const rows = await queryFn(dbUrl, `\n SELECT n.nspname || '.' || c.relname AS table_name,\n t.tgname AS name,\n pg_get_triggerdef(t.oid) AS definition\n FROM pg_trigger t\n JOIN pg_class c ON c.oid = t.tgrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_proc p ON p.oid = t.tgfoid\n JOIN pg_namespace pn ON pn.oid = p.pronamespace\n WHERE NOT t.tgisinternal\n AND pn.nspname = 'supabase_functions'\n AND p.proname = 'http_request'\n ORDER BY 1, 2\n `)\n\n const statements = (rows as unknown as WebhookRow[])\n .filter(h => h.definition)\n .map(hook => [\n `-- Webhook: ${hook.name} on ${hook.table_name}`,\n `${hook.definition.replace(/;\\s*$/, '')};`,\n ].join('\\n'))\n\n const output = statements.length > 0\n ? `-- SupaForge Webhook Snapshot\\n-- ${statements.length} webhooks\\n\\n${statements.join('\\n\\n')}\\n`\n : '-- No webhooks found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: statements.length }\n } catch (err) {\n // Reading the system catalogs cannot fail for a missing `supabase_functions`\n // schema — a database without one simply has no such triggers and is\n // captured as zero webhooks, not skipped. So anything arriving here is a\n // real error rather than an absence, and is reported as one.\n const msg = errMsg(err)\n await writeFile(join(dir, file), `-- Webhook snapshot failed: ${msg}\\n`).catch(() => {})\n return { captured: false, file, itemCount: 0, error: msg }\n }\n}\n\nasync function captureRealtime(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'realtime.sql'\n try {\n const rows = await queryFn(dbUrl, PUBLICATION_SQL) as unknown as Array<{ pubname: string; schemaname: string | null; tablename: string | null }>\n\n // One CREATE per publication, then the tables added to it. `supabase_realtime`\n // exists on every Supabase project, so the CREATE is conditional and the\n // membership is what actually carries the state.\n const byPublication = new Map<string, string[]>()\n for (const row of rows) {\n const tables = byPublication.get(row.pubname) ?? []\n if (row.schemaname && row.tablename) {\n tables.push(`${quoteName(row.schemaname)}.${quoteName(row.tablename)}`)\n }\n byPublication.set(row.pubname, tables)\n }\n\n const statements: string[] = []\n for (const [pubname, tables] of byPublication) {\n statements.push(`-- Publication: ${pubname}`)\n statements.push(`DO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = ${quoteLiteral(pubname)}) THEN\n EXECUTE ${quoteLiteral(`CREATE PUBLICATION ${quoteName(pubname)}`)};\n END IF;\nEND $$;`)\n for (const table of tables) {\n statements.push(`ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${table};`)\n }\n }\n\n const output = statements.length > 0\n ? `-- SupaForge Realtime Snapshot\\n-- ${byPublication.size} publication(s)\\n\\n${statements.join('\\n')}\\n`\n : '-- No publications found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: byPublication.size }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function captureVaultSecrets(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'vault.sql'\n try {\n // vault.secrets, not decrypted_secrets: only names and descriptions are\n // wanted, and the view decrypts every value to show them. `unique_name`\n // is gone from supabase_vault 0.3, and asking for it failed with\n // `column \"unique_name\" does not exist` — which the catch below then read\n // as Vault not being installed, on a project holding secrets.\n const rows = await queryFn(dbUrl, `\n SELECT coalesce(name, id::text) AS name, description\n FROM vault.secrets\n ORDER BY 1\n `) as unknown as Array<{ name: string; description: string | null }>\n\n // Names and descriptions only. A secret's value cannot be read out of\n // Vault across environments, so this is a list of what to recreate by hand\n // rather than SQL to replay — and deliberately not runnable, so a restore\n // cannot create a secret with an invented value the way the vault check\n // used to (issue #91).\n const lines = rows.map(row =>\n `-- ${row.name}${row.description ? ` — ${row.description}` : ''}`)\n\n const output = rows.length > 0\n ? `-- SupaForge Vault Snapshot\\n-- ${rows.length} secret(s), names only:\\n`\n + '-- the values cannot be read out of Vault and must be recreated by hand.\\n'\n + `${lines.join('\\n')}\\n`\n : '-- No vault secrets found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: rows.length }\n } catch (err) {\n // Only the schema being absent means Vault is not there. Any other\n // failure — a permission, a column — is an error to report, not a reason\n // to call the layer skipped.\n if (!(await vaultInstalled(dbUrl, queryFn))) {\n return { captured: false, file, itemCount: 0, skipReason: 'vault extension not installed' }\n }\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function vaultInstalled(dbUrl: string, queryFn: QueryFn): Promise<boolean> {\n try {\n const [row] = await queryFn(dbUrl, `SELECT to_regnamespace('vault') IS NOT NULL AS installed`) as unknown as\n Array<{ installed: boolean }>\n return row?.installed === true\n } catch {\n // Cannot even ask: report the original failure rather than guess.\n return true\n }\n}\n\nasync function captureRoleGrants(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'roles.sql'\n // Supabase's own schemas are left out: their grants are the platform's, and\n // replaying them into plain PostgreSQL — the usual restore target — fails on\n // a schema that does not exist there. A snapshot of a test stack held 348\n // grants, 201 of them on storage, realtime, supabase_functions and vault.\n const excluded = SUPABASE_PLATFORM_SCHEMAS.map(quoteLiteral).join(', ')\n try {\n const rows = await queryFn(dbUrl, `\n -- From relacl, not information_schema.role_table_grants: that view\n -- counts the owner's own privileges as grants, which a restore then\n -- replayed as GRANT ... TO <owner>, creating the role on the target;\n -- and it hides grants the connecting role takes no part in.\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n n.nspname AS table_schema, c.relname AS table_name, NULL::text AS column_name,\n a.privilege_type, a.is_grantable\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE c.relacl IS NOT NULL AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n AND a.grantee <> c.relowner\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (\n 'postgres','supabase_admin','authenticator','supabase_auth_admin',\n 'supabase_storage_admin','dashboard_user','pgbouncer','supavisor'\n ))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\\\_%')\n AND n.nspname NOT IN (${excluded})\n UNION ALL\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,\n n.nspname, c.relname, att.attname, a.privilege_type, a.is_grantable\n FROM pg_attribute att\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped\n AND a.grantee <> c.relowner\n AND n.nspname NOT IN (${excluded})\n ORDER BY 1, 2, 3, 4, 5\n `) as unknown as Array<{\n grantee: string; table_schema: string; table_name: string\n column_name: string | null; privilege_type: string; is_grantable: boolean\n }>\n\n // One statement per role, object and grant option, listing the\n // privileges: one per privilege made a restore that skipped a relation\n // list it once for every privilege of every role. MAINTAIN, a PostgreSQL\n // 17 privilege, stays on its own, so an older server skips only it rather\n // than rejecting every privilege granted alongside.\n const grouped = new Map<string, typeof rows>()\n for (const row of rows) {\n const key = JSON.stringify([row.grantee, row.table_schema, row.table_name, row.column_name, Boolean(row.is_grantable),\n row.privilege_type === 'MAINTAIN'])\n grouped.set(key, [...(grouped.get(key) ?? []), row])\n }\n const statements = [...grouped.values()].map(([row, ...rest]) =>\n `GRANT ${[row, ...rest].map(r => r.privilege_type + (r.column_name ? ` (${quoteName(r.column_name)})` : '')).join(', ')}`\n + ` ON ${quoteName(row.table_schema)}.${quoteName(row.table_name)}`\n // PUBLIC is a keyword; quoted, it names a role that does not exist.\n + ` TO ${row.grantee === 'PUBLIC' ? 'PUBLIC' : quoteName(row.grantee)}`\n + (row.is_grantable ? ' WITH GRANT OPTION' : '')\n + ';')\n\n const output = statements.length > 0\n ? `-- SupaForge Role Grants Snapshot\\n-- ${rows.length} grant(s)\\n\\n${statements.join('\\n')}\\n`\n : '-- No role grants found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: rows.length }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\nasync function captureExtensions(\n dir: string,\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<SnapshotLayerInfo> {\n const file = 'extensions.sql'\n try {\n const rows = await queryFn(dbUrl, `\n SELECT extname, extversion, n.nspname AS schema\n FROM pg_extension e\n JOIN pg_namespace n ON n.oid = e.extnamespace\n ORDER BY extname\n `)\n const statements = (rows as unknown as { extname: string; extversion: string; schema: string }[]).map(ext => {\n return `CREATE EXTENSION IF NOT EXISTS ${quoteName(ext.extname)} WITH SCHEMA ${quoteName(ext.schema)};`\n })\n const output = statements.length > 0\n ? `-- SupaForge Extensions Snapshot\\n-- ${rows.length} extensions\\n\\n${statements.join('\\n')}\\n`\n : '-- No extensions found\\n'\n await writeFile(join(dir, file), output)\n return { captured: true, file, itemCount: rows.length }\n } catch (err) {\n return { captured: false, file, itemCount: 0, error: errMsg(err) }\n }\n}\n\n// ─── Snapshot Reading ────────────────────────────────────────────────────────\n\n/** Load the manifest from a snapshot directory. */\nexport async function loadSnapshot(dir: string): Promise<SnapshotManifest> {\n const raw = await readFile(join(dir, 'manifest.json'), 'utf-8')\n return JSON.parse(raw) as SnapshotManifest\n}\n\n/** Find the latest snapshot directory. */\nexport async function findLatestSnapshot(cwd = process.cwd()): Promise<string | null> {\n const base = snapshotsBaseDir(cwd)\n try {\n const entries = await readdir(base)\n const sorted = entries.filter(e => /^\\d{8}T\\d{6}Z$/.test(e)).sort()\n return sorted.length > 0 ? join(base, sorted[sorted.length - 1]) : null\n } catch {\n return null\n }\n}\n\n/** List all snapshot directories with their manifests. */\nexport async function listSnapshots(cwd = process.cwd()): Promise<{ dir: string; manifest: SnapshotManifest }[]> {\n const base = snapshotsBaseDir(cwd)\n try {\n const entries = await readdir(base)\n const sorted = entries.filter(e => /^\\d{8}T\\d{6}Z$/.test(e)).sort()\n const results: { dir: string; manifest: SnapshotManifest }[] = []\n for (const entry of sorted) {\n try {\n const manifest = await loadSnapshot(join(base, entry))\n results.push({ dir: join(base, entry), manifest })\n } catch { /* skip corrupt snapshots */ }\n }\n return results\n } catch {\n return []\n }\n}\n\n/** Default number of snapshots to keep when pruning. */\nexport const DEFAULT_KEEP_COUNT = 7\n\nexport interface PruneResult {\n /** Snapshot directories that were deleted. */\n deleted: string[]\n /** Snapshot directories that were kept. */\n kept: string[]\n /**\n * Snapshots kept despite being outside the budget, because a migration\n * names one as its `parent`.\n *\n * Deleting those broke the migration chain silently: the migration stayed,\n * referring to a snapshot that was no longer there (issue #92).\n */\n retainedForMigrations?: string[]\n}\n\n/**\n * Prune old snapshots, keeping the most recent `keep` snapshots.\n * Snapshots are sorted chronologically by their timestamp directory name.\n * Returns metadata about which directories were deleted.\n */\nexport async function pruneSnapshots(\n keep = DEFAULT_KEEP_COUNT,\n cwd = process.cwd(),\n): Promise<PruneResult> {\n const snapshots = await listSnapshots(cwd)\n\n // Already within budget — nothing to prune\n if (snapshots.length <= keep) {\n return { deleted: [], kept: snapshots.map(s => s.dir) }\n }\n\n // Snapshots come back sorted oldest-first from listSnapshots\n const candidates = snapshots.slice(0, snapshots.length - keep)\n const withinBudget = snapshots.slice(snapshots.length - keep)\n\n // A snapshot a migration names as its `parent` is the other half of that\n // migration's diff. Deleting it broke the chain silently — the migration\n // stayed, referring to something that was no longer there (issue #92). Kept\n // regardless of the budget, and reported so the count still makes sense.\n const referenced = await snapshotVersionsReferencedByMigrations(cwd)\n const toDelete = candidates.filter(s => !referenced.has(versionOf(s.dir)))\n const retained = candidates.filter(s => referenced.has(versionOf(s.dir)))\n\n for (const snap of toDelete) {\n await rm(snap.dir, { recursive: true, force: true })\n }\n\n return {\n deleted: toDelete.map(s => s.dir),\n kept: [...retained, ...withinBudget].map(s => s.dir),\n retainedForMigrations: retained.map(s => s.dir),\n }\n}\n\n/** The timestamp a snapshot directory is named for. */\nfunction versionOf(dir: string): string {\n return dir.split('/').filter(Boolean).pop() ?? dir\n}\n\n/**\n * Snapshot versions that migration files name as their parent.\n *\n * Best-effort: an unreadable migrations directory means nothing is protected,\n * which is the behaviour prune had before this existed.\n */\nasync function snapshotVersionsReferencedByMigrations(cwd: string): Promise<Set<string>> {\n const referenced = new Set<string>()\n\n try {\n const dir = resolve(cwd, SUPAFORGE_DIR, MIGRATIONS_SUBDIR)\n for (const name of await readdir(dir)) {\n if (!name.endsWith('.json')) continue\n try {\n const migration = JSON.parse(await readFile(join(dir, name), 'utf-8')) as { parent?: string | null }\n if (migration.parent) referenced.add(migration.parent)\n } catch { /* a migration that will not parse protects nothing */ }\n }\n } catch { /* no migrations directory */ }\n\n return referenced\n}\n\n\n// ─── SQL Generation Helpers (reused from checks) ────────────────────────────\n\ninterface RlsRow {\n schemaname: string\n tablename: string\n policyname: string\n permissive: string\n roles: string[] | string\n cmd: string\n qual: string | null\n with_check: string | null\n comment?: string | null\n}\n\n/**\n * Dropped first so a snapshot can be restored twice: without it a second\n * restore fails with `policy \"…\" already exists` and the layers after it\n * never run (issue #80). Written by the shared builders, which set the\n * comment after the policy.\n */\nfunction generateCreatePolicySql(p: RlsRow): string {\n return `${dropPolicySql(p.schemaname, p)}\\n${createPolicySql(p.schemaname, p)}`\n}\n\ninterface CronRow {\n jobid: number\n schedule: string\n command: string\n jobname: string | null\n}\n\ninterface WebhookRow {\n /** `schema.table` — a trigger name is only unique per table. */\n table_name: string\n /** The trigger name, which is what the Dashboard calls the webhook. */\n name: string\n /** `CREATE TRIGGER …`, as the server renders it, arguments included. */\n definition: string\n}\n","import pg from 'pg'\nimport { pgClientConfig } from './db.js'\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface SchemaColumn {\n name: string\n type: string\n nullable: boolean\n default: string | null\n identity: string | null\n generated: string | null\n}\n\nexport interface SchemaIndex {\n name: string\n definition: string\n unique: boolean\n}\n\nexport interface SchemaConstraint {\n name: string\n type: string\n definition: string\n}\n\nexport interface SchemaTable {\n schema: string\n name: string\n columns: SchemaColumn[]\n indexes: SchemaIndex[]\n constraints: SchemaConstraint[]\n}\n\nexport interface SchemaView {\n schema: string\n name: string\n definition: string\n}\n\nexport interface SchemaFunction {\n schema: string\n name: string\n args: string\n returnType: string\n language: string\n definition: string\n}\n\nexport interface SchemaTrigger {\n schema: string\n table: string\n name: string\n definition: string\n}\n\nexport interface SchemaSequence {\n schema: string\n name: string\n dataType: string\n startValue: string\n increment: string\n minValue: string\n maxValue: string\n}\n\nexport interface SchemaEnum {\n schema: string\n name: string\n labels: string[]\n}\n\nexport interface SchemaSnapshot {\n tables: SchemaTable[]\n views: SchemaView[]\n functions: SchemaFunction[]\n triggers: SchemaTrigger[]\n sequences: SchemaSequence[]\n enums: SchemaEnum[]\n}\n\n// ─── Query type for testability ──────────────────────────────────────────────\n\ntype ClientQueryFn = (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n\n// ─── Schema Introspection ────────────────────────────────────────────────────\n\n/**\n * Introspect a database schema using pg_catalog queries.\n * Returns structured JSON suitable for diffing between environments.\n *\n * Uses a connection pool to support parallel queries safely.\n */\nexport async function introspectSchema(\n dbUrl: string,\n ignoreSchemas: string[],\n clientQueryFn?: ClientQueryFn,\n): Promise<SchemaSnapshot> {\n let queryFn: ClientQueryFn\n let pool: pg.Pool | undefined\n\n if (clientQueryFn) {\n queryFn = clientQueryFn\n } else {\n pool = new pg.Pool({ ...pgClientConfig(dbUrl), max: 6 })\n queryFn = async (sql, params) => {\n const { rows } = await pool!.query(sql, params)\n return rows\n }\n }\n\n try {\n const schemaFilter = buildSchemaFilter(ignoreSchemas)\n\n const [tables, views, functions, triggers, sequences, enums] = await Promise.all([\n fetchTables(queryFn, schemaFilter),\n fetchViews(queryFn, schemaFilter),\n fetchFunctions(queryFn, schemaFilter),\n fetchTriggers(queryFn, schemaFilter),\n fetchSequences(queryFn, schemaFilter),\n fetchEnums(queryFn, schemaFilter),\n ])\n\n return { tables, views, functions, triggers, sequences, enums }\n } finally {\n await pool?.end()\n }\n}\n\n// ─── Schema filter helper ────────────────────────────────────────────────────\n\ninterface SchemaFilter {\n clause: string\n params: unknown[]\n}\n\nfunction buildSchemaFilter(ignoreSchemas: string[]): SchemaFilter {\n if (ignoreSchemas.length === 0) {\n return { clause: '', params: [] }\n }\n const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(', ')\n return {\n clause: `AND n.nspname NOT IN (${placeholders})`,\n params: [...ignoreSchemas],\n }\n}\n\n// ─── Tables ──────────────────────────────────────────────────────────────────\n\nasync function fetchTables(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaTable[]> {\n const tableRows = await query(`\n SELECT c.oid, n.nspname AS schema, c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r', 'p')\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n ORDER BY n.nspname, c.relname\n `, sf.params) as unknown as { oid: number; schema: string; name: string }[]\n\n if (tableRows.length === 0) return []\n\n const oids = tableRows.map(t => t.oid)\n\n // Fetch columns, indexes, constraints in parallel for all tables\n const [allColumns, allIndexes, allConstraints] = await Promise.all([\n fetchColumns(query, oids),\n fetchIndexes(query, oids),\n fetchConstraints(query, oids),\n ])\n\n return tableRows.map(t => ({\n schema: t.schema,\n name: t.name,\n columns: allColumns.get(t.oid) ?? [],\n indexes: allIndexes.get(t.oid) ?? [],\n constraints: allConstraints.get(t.oid) ?? [],\n }))\n}\n\nasync function fetchColumns(query: ClientQueryFn, oids: number[]): Promise<Map<number, SchemaColumn[]>> {\n const rows = await query(`\n SELECT\n a.attrelid AS oid,\n a.attname AS name,\n pg_catalog.format_type(a.atttypid, a.atttypmod) AS type,\n NOT a.attnotnull AS nullable,\n pg_get_expr(d.adbin, d.adrelid) AS \"default\",\n CASE a.attidentity WHEN 'a' THEN 'always' WHEN 'd' THEN 'by default' ELSE NULL END AS identity,\n CASE a.attgenerated WHEN 's' THEN pg_get_expr(d.adbin, d.adrelid) ELSE NULL END AS generated\n FROM pg_attribute a\n LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum\n WHERE a.attrelid = ANY($1)\n AND a.attnum > 0\n AND NOT a.attisdropped\n ORDER BY a.attrelid, a.attnum\n `, [oids]) as unknown as (SchemaColumn & { oid: number })[]\n\n const map = new Map<number, SchemaColumn[]>()\n for (const r of rows) {\n const list = map.get(r.oid) ?? []\n list.push({ name: r.name, type: r.type, nullable: r.nullable, default: r.default, identity: r.identity, generated: r.generated })\n map.set(r.oid, list)\n }\n return map\n}\n\nasync function fetchIndexes(query: ClientQueryFn, oids: number[]): Promise<Map<number, SchemaIndex[]>> {\n const rows = await query(`\n SELECT\n i.indrelid AS oid,\n c.relname AS name,\n pg_get_indexdef(i.indexrelid) AS definition,\n i.indisunique AS unique\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indexrelid\n WHERE i.indrelid = ANY($1)\n AND NOT i.indisprimary\n ORDER BY i.indrelid, c.relname\n `, [oids]) as unknown as (SchemaIndex & { oid: number })[]\n\n const map = new Map<number, SchemaIndex[]>()\n for (const r of rows) {\n const list = map.get(r.oid) ?? []\n list.push({ name: r.name, definition: r.definition, unique: r.unique })\n map.set(r.oid, list)\n }\n return map\n}\n\nasync function fetchConstraints(query: ClientQueryFn, oids: number[]): Promise<Map<number, SchemaConstraint[]>> {\n const rows = await query(`\n SELECT\n con.conrelid AS oid,\n con.conname AS name,\n CASE con.contype\n WHEN 'p' THEN 'PRIMARY KEY'\n WHEN 'u' THEN 'UNIQUE'\n WHEN 'f' THEN 'FOREIGN KEY'\n WHEN 'c' THEN 'CHECK'\n WHEN 'x' THEN 'EXCLUDE'\n ELSE con.contype::text\n END AS type,\n pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con\n WHERE con.conrelid = ANY($1)\n ORDER BY con.conrelid, con.conname\n `, [oids]) as unknown as (SchemaConstraint & { oid: number })[]\n\n const map = new Map<number, SchemaConstraint[]>()\n for (const r of rows) {\n const list = map.get(r.oid) ?? []\n list.push({ name: r.name, type: r.type, definition: r.definition })\n map.set(r.oid, list)\n }\n return map\n}\n\n// ─── Views ───────────────────────────────────────────────────────────────────\n\nasync function fetchViews(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaView[]> {\n return await query(`\n SELECT n.nspname AS schema, c.relname AS name, pg_get_viewdef(c.oid, true) AS definition\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('v', 'm')\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n ORDER BY n.nspname, c.relname\n `, sf.params) as unknown as SchemaView[]\n}\n\n// ─── Functions ───────────────────────────────────────────────────────────────\n\nasync function fetchFunctions(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaFunction[]> {\n return await query(`\n SELECT\n n.nspname AS schema,\n p.proname AS name,\n pg_get_function_arguments(p.oid) AS args,\n pg_get_function_result(p.oid) AS \"returnType\",\n l.lanname AS language,\n pg_get_functiondef(p.oid) AS definition\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n JOIN pg_language l ON l.oid = p.prolang\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n AND p.prokind IN ('f', 'p')\n ORDER BY n.nspname, p.proname, pg_get_function_arguments(p.oid)\n `, sf.params) as unknown as SchemaFunction[]\n}\n\n// ─── Triggers ────────────────────────────────────────────────────────────────\n\nasync function fetchTriggers(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaTrigger[]> {\n return await query(`\n SELECT\n n.nspname AS schema,\n c.relname AS table,\n t.tgname AS name,\n pg_get_triggerdef(t.oid) AS definition\n FROM pg_trigger t\n JOIN pg_class c ON c.oid = t.tgrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE NOT t.tgisinternal\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n ORDER BY n.nspname, c.relname, t.tgname\n `, sf.params) as unknown as SchemaTrigger[]\n}\n\n// ─── Sequences ───────────────────────────────────────────────────────────────\n\nasync function fetchSequences(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaSequence[]> {\n return await query(`\n SELECT\n n.nspname AS schema,\n c.relname AS name,\n format_type(s.seqtypid, NULL) AS \"dataType\",\n s.seqstart::text AS \"startValue\",\n s.seqincrement::text AS increment,\n s.seqmin::text AS \"minValue\",\n s.seqmax::text AS \"maxValue\"\n FROM pg_sequence s\n JOIN pg_class c ON c.oid = s.seqrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n ORDER BY n.nspname, c.relname\n `, sf.params) as unknown as SchemaSequence[]\n}\n\n// ─── Enums ───────────────────────────────────────────────────────────────────\n\nasync function fetchEnums(query: ClientQueryFn, sf: SchemaFilter): Promise<SchemaEnum[]> {\n const rows = await query(`\n SELECT\n n.nspname AS schema,\n t.typname AS name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS labels\n FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace\n JOIN pg_enum e ON e.enumtypid = t.oid\n WHERE t.typtype = 'e'\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n ${sf.clause}\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n `, sf.params) as unknown as SchemaEnum[]\n\n return rows\n}\n","/**\n * RLS policy comparison for a single, named schema.\n *\n * Supabase's own schemas are excluded from the main RLS layer because their\n * tables are product-managed — differences there mean the two projects run\n * different Supabase versions, not that anyone changed anything. But a few of\n * those tables carry policies the *user* writes:\n *\n * storage.objects — who may read or write which files\n * realtime.messages — who may join which channel (Realtime Authorization)\n *\n * Those are security rules, and they drift like any other. This module lets a\n * check compare policies inside one ignored schema without reopening the whole\n * schema to the RLS layer.\n */\nimport type { CheckName, DriftIssue } from '../types/drift'\nimport { normalizeRoles } from './strings'\nimport { quoteLiteral, quoteName } from './sql'\n\nexport interface SchemaPolicy {\n tablename: string\n policyname: string\n permissive: string\n roles: string[] | string\n cmd: string\n qual: string | null\n with_check: string | null\n /** `COMMENT ON POLICY`, which pg_policies does not carry. */\n comment?: string | null\n}\n\n/** Policies on one schema. Parameterised rather than interpolated by callers. */\nexport function schemaPolicySql(schema: string): string {\n return `\n SELECT tablename, policyname, permissive, roles, cmd, qual, with_check,\n (SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename\n AND p.polname = pg_policies.policyname) AS comment\n FROM pg_policies\n WHERE schemaname = '${schema}'\n ORDER BY tablename, policyname\n `\n}\n\nexport function policyKey(p: SchemaPolicy): string {\n return `${p.tablename}.${p.policyname}`\n}\n\n/** `\"schema\".\"table\"`, each part quoted with its own quotes doubled. */\nconst policyTable = (schema: string, p: Pick<SchemaPolicy, 'tablename'>) => `${quoteName(schema)}.${quoteName(p.tablename)}`\n\n/**\n * A role in a policy's TO list. pg_policies spells the PUBLIC pseudo-role\n * `public`, which quoted would name a role that does not exist.\n */\nconst roleSql = (role: string) => role === 'public' ? 'PUBLIC' : quoteName(role)\n\n/**\n * The SQL for a policy, used by every check and snapshot layer that writes one,\n * so a name is quoted the same way everywhere. A policy named `say \"hi\"\n * there`, written between plain quotes, was a syntax error that rolled back a\n * whole restore or apply.\n */\nexport function createPolicySql(schema: string, p: SchemaPolicy): string {\n const roles = normalizeRoles(p.roles).map(roleSql).join(', ')\n const lines = [\n `CREATE POLICY ${quoteName(p.policyname)}`,\n ` ON ${policyTable(schema, p)}`,\n ` AS ${p.permissive}`,\n ` FOR ${p.cmd}`,\n ` TO ${roles}`,\n ]\n if (p.qual) lines.push(` USING (${p.qual})`)\n if (p.with_check) lines.push(` WITH CHECK (${p.with_check})`)\n lines.push(';')\n // With the policy, since recreating one takes its comment with it.\n if (p.comment) lines.push(commentPolicySql(schema, p))\n return lines.join('\\n')\n}\n\nexport function commentPolicySql(schema: string, p: SchemaPolicy): string {\n return `COMMENT ON POLICY ${quoteName(p.policyname)} ON ${policyTable(schema, p)} IS ${p.comment ? quoteLiteral(p.comment) : 'NULL'};`\n}\n\nexport function dropPolicySql(schema: string, p: SchemaPolicy): string {\n return `DROP POLICY IF EXISTS ${quoteName(p.policyname)} ON ${policyTable(schema, p)};`\n}\n\nexport function policiesEqual(a: SchemaPolicy, b: SchemaPolicy): boolean {\n return a.permissive === b.permissive\n && a.cmd === b.cmd\n && a.qual === b.qual\n && a.with_check === b.with_check\n && normalizeRoles(a.roles).join(',') === normalizeRoles(b.roles).join(',')\n}\n\nexport interface PolicyDiffOptions {\n /** Schema the policies live in, e.g. 'storage'. */\n schema: string\n /** Which check owns the resulting issues. */\n check: CheckName\n /** Issue id prefix, e.g. 'storage-policy'. Kept stable across refactors. */\n idPrefix: string\n /**\n * Human label, lower-case: used verbatim in titles (\"Missing storage\n * policy\") and capitalised at the start of descriptions (\"Storage RLS\n * policy ...\"). Kept exactly as the messages read before this was shared, so\n * a refactor does not quietly reword output users may be matching on.\n */\n label: string\n}\n\n/**\n * Compare policies between two environments.\n *\n * A missing or altered policy is critical: both mean the target enforces\n * something different from the source, and for these schemas that is an access\n * rule. An extra policy is info — it may be deliberate, and removing it is a\n * judgement the operator should make rather than a fix to apply blindly.\n */\nexport function diffSchemaPolicies(\n source: SchemaPolicy[],\n target: SchemaPolicy[],\n opts: PolicyDiffOptions,\n): DriftIssue[] {\n const { schema, check, idPrefix, label } = opts\n const Label = label.charAt(0).toUpperCase() + label.slice(1)\n const issues: DriftIssue[] = []\n const sourceMap = new Map(source.map(p => [policyKey(p), p]))\n const targetMap = new Map(target.map(p => [policyKey(p), p]))\n\n for (const [key, sp] of sourceMap) {\n if (targetMap.has(key)) continue\n issues.push({\n id: `${idPrefix}-missing-${key}`,\n check,\n severity: 'critical',\n title: `Missing ${label} policy: ${sp.policyname} on ${sp.tablename}`,\n description: `${Label} RLS policy \"${sp.policyname}\" on ${schema}.${sp.tablename} exists in source but not in target.`,\n sourceValue: sp,\n sql: {\n up: createPolicySql(schema, sp),\n down: dropPolicySql(schema, sp),\n },\n })\n }\n\n for (const [key, tp] of targetMap) {\n if (sourceMap.has(key)) continue\n issues.push({\n id: `${idPrefix}-extra-${key}`,\n check,\n severity: 'info',\n title: `Extra ${label} policy: ${tp.policyname} on ${tp.tablename}`,\n description: `${Label} RLS policy \"${tp.policyname}\" on ${schema}.${tp.tablename} exists in target but not in source.`,\n targetValue: tp,\n sql: {\n up: dropPolicySql(schema, tp),\n down: createPolicySql(schema, tp),\n },\n })\n }\n\n for (const [key, sp] of sourceMap) {\n const tp = targetMap.get(key)\n if (!tp || policiesEqual(sp, tp)) continue\n issues.push({\n id: `${idPrefix}-changed-${key}`,\n check,\n severity: 'critical',\n title: `${Label} policy changed: ${sp.policyname} on ${sp.tablename}`,\n description: `${Label} RLS policy \"${sp.policyname}\" on ${schema}.${sp.tablename} differs between source and target.`,\n sourceValue: sp,\n targetValue: tp,\n sql: {\n up: [dropPolicySql(schema, sp), createPolicySql(schema, sp)].join('\\n'),\n down: [dropPolicySql(schema, tp), createPolicySql(schema, tp)].join('\\n'),\n },\n })\n }\n\n // A comment is reported on its own, not as a changed policy: it needs no\n // drop and recreate, and a policy whose expressions differ only in how they\n // are written is filtered out as unchanged — which would take a real comment\n // difference with it.\n for (const [key, sp] of sourceMap) {\n const tp = targetMap.get(key)\n if (!tp || (sp.comment ?? null) === (tp.comment ?? null)) continue\n issues.push({\n id: `${idPrefix}-comment-${key}`,\n check,\n severity: 'info',\n title: `${Label} policy comment changed: ${sp.policyname} on ${sp.tablename}`,\n description: `The comment on ${label} RLS policy \"${sp.policyname}\" on ${schema}.${sp.tablename} differs between source and target.`,\n sourceValue: sp.comment ?? null,\n targetValue: tp.comment ?? null,\n sql: {\n up: commentPolicySql(schema, sp),\n down: commentPolicySql(schema, tp),\n },\n })\n }\n\n return issues\n}\n","import type { CheckContext } from '../checks/base.js'\nimport { inRolledBackTransaction, pgQuery, type QueryFn } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { quoteName } from './sql.js'\n\n/**\n * The parts of a policy that decide whether two are the same. The RLS, storage\n * and realtime checks all read theirs from pg_policies.\n */\nexport interface ComparablePolicy {\n schemaname: string\n tablename: string\n policyname: string\n permissive?: string | boolean | null\n cmd?: string | null\n roles?: unknown\n qual: string | null\n with_check: string | null\n}\n\n/** A policy's USING and WITH CHECK as the server renders them after one more round trip. */\nexport type PolicyCanonicalizer = (\n dbUrl: string,\n policy: ComparablePolicy,\n) => Promise<{ qual: string | null; with_check: string | null } | null>\n\n/**\n * Re-render a policy's expressions by creating it again on a temporary copy\n * of its table, in a transaction that is always rolled back.\n *\n * PostgreSQL's rendering is not stable across a round trip:\n * `status IN ('draft', 'active')` on a varchar column renders one way as\n * written and another once recreated from that rendering, which is what a\n * dump, a restore or a clone does. Comparing text reported every such policy\n * as a critical \"Modified RLS policy\" between a project and any copy of it.\n * The second rendering is stable, so re-rendering both sides once and\n * comparing those tells a real change from the same policy printed twice.\n *\n * Null when the policy cannot be recreated there; the caller then keeps the\n * textual comparison, which is what it did before.\n */\nexport const canonicalPolicyExpressions: PolicyCanonicalizer = async (dbUrl, policy) => {\n try {\n return await inRolledBackTransaction(dbUrl, async client => {\n await client.query(\n `CREATE TEMP TABLE sf_canon (LIKE ${quoteName(policy.schemaname)}.${quoteName(policy.tablename)})`,\n )\n const command = (policy.cmd ?? 'ALL').toUpperCase()\n await client.query(\n `CREATE POLICY sf_canon_p ON sf_canon FOR ${command}`\n + (policy.qual ? ` USING (${policy.qual})` : '')\n + (policy.with_check ? ` WITH CHECK (${policy.with_check})` : ''),\n )\n const { rows } = await client.query<{ qual: string | null; with_check: string | null }>(\n `SELECT pg_get_expr(polqual, polrelid) AS qual, pg_get_expr(polwithcheck, polrelid) AS with_check\n FROM pg_policy WHERE polrelid = 'pg_temp.sf_canon'::regclass`,\n )\n return rows[0] ?? null\n })\n } catch {\n return null\n }\n}\n\n/** The real canonicalizer on the real query path; none for an injected one (tests). */\nexport function defaultCanonicalizer(queryFn: QueryFn): PolicyCanonicalizer {\n return queryFn === pgQuery ? canonicalPolicyExpressions : async () => null\n}\n\n/**\n * Drop the \"modified policy\" findings whose two sides are the same policy.\n *\n * Only a finding carrying both sides, whose command, mode and roles already\n * match — so only the rendering of its expressions can differ — is checked.\n */\nexport async function dropEquivalentPolicyChanges(\n issues: DriftIssue[],\n ctx: CheckContext,\n canonicalize: PolicyCanonicalizer,\n /** For checks scoped to one schema, whose rows do not name it. */\n schema?: string,\n): Promise<DriftIssue[]> {\n const withSchema = (p: unknown) =>\n p && typeof p === 'object' ? { schemaname: schema, ...(p as object) } as ComparablePolicy : undefined\n const kept: DriftIssue[] = []\n for (const issue of issues) {\n const source = withSchema(issue.sourceValue)\n const target = withSchema(issue.targetValue)\n if (!isPolicy(source) || !isPolicy(target) || !sameApartFromExpressions(source, target)) {\n kept.push(issue)\n continue\n }\n const [a, b] = await Promise.all([\n canonicalize(ctx.source.dbUrl, source),\n canonicalize(ctx.target.dbUrl, target),\n ])\n if (a && b && a.qual === b.qual && a.with_check === b.with_check) continue\n kept.push(issue)\n }\n return kept\n}\n\nfunction isPolicy(p: ComparablePolicy | undefined): p is ComparablePolicy {\n return !!p && typeof p.schemaname === 'string' && typeof p.policyname === 'string'\n && typeof p.tablename === 'string' && 'qual' in p\n}\n\nfunction sameApartFromExpressions(a: ComparablePolicy, b: ComparablePolicy): boolean {\n return a.schemaname === b.schemaname\n && a.tablename === b.tablename\n && a.policyname === b.policyname\n && String(a.permissive) === String(b.permissive)\n && (a.cmd ?? null) === (b.cmd ?? null)\n && JSON.stringify(a.roles) === JSON.stringify(b.roles)\n && (a.qual !== b.qual || a.with_check !== b.with_check)\n}\n","import { dropEquivalentPolicyChanges, defaultCanonicalizer } from '../utils/policy-equivalence.js'\nimport type { QueryFn } from '../db'\nimport { pgQuery } from '../db'\nimport type { DriftIssue } from '../types/drift'\nimport { quoteName } from '../utils/sql'\nimport { Check, type CheckContext } from './base'\nimport { DEFAULT_IGNORE_SCHEMAS } from '../defaults'\nimport {\n diffSchemaPolicies, schemaPolicySql, type SchemaPolicy,\n} from '../utils/schema-policies'\n\ninterface RealtimePublication {\n pubname: string\n schemaname: string\n tablename: string\n}\n\nexport class RealtimeCheck extends Check {\n readonly name = 'realtime' as const\n\n constructor(private queryFn: QueryFn = pgQuery) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const [source, target] = await Promise.all([\n this.fetchPublications(ctx.source.dbUrl),\n this.fetchPublications(ctx.target.dbUrl),\n ])\n const publicationIssues = diffPublications(source, target)\n\n // Realtime Authorization policies live on realtime.messages and decide who\n // may join which channel. They are written by the user, but the realtime\n // schema is excluded from the main RLS layer because its other tables are\n // product-managed — so nothing compared them at all. A policy relaxed from\n // `topic LIKE 'user:%'` to `true` reported no drift.\n const [srcPolicies, tgtPolicies] = await Promise.all([\n this.fetchPolicies(ctx.source.dbUrl),\n this.fetchPolicies(ctx.target.dbUrl),\n ])\n const policyIssues = await dropEquivalentPolicyChanges(\n diffSchemaPolicies(srcPolicies, tgtPolicies, {\n schema: 'realtime',\n check: 'realtime',\n idPrefix: 'realtime-policy',\n label: 'realtime authorization',\n }),\n ctx,\n defaultCanonicalizer(this.queryFn),\n 'realtime',\n )\n\n return [...publicationIssues, ...policyIssues]\n }\n\n private async fetchPolicies(dbUrl: string): Promise<SchemaPolicy[]> {\n try {\n return await this.queryFn(dbUrl, schemaPolicySql('realtime')) as unknown as SchemaPolicy[]\n } catch {\n // No realtime schema at all — nothing to compare.\n return []\n }\n }\n\n private async fetchPublications(dbUrl: string): Promise<RealtimePublication[]> {\n try {\n return await this.queryFn(dbUrl, PUBLICATION_SQL) as unknown as RealtimePublication[]\n } catch {\n // pg_publication may not be accessible\n return []\n }\n }\n}\n\n/**\n * Every publication and the tables in it.\n *\n * `supabase_realtime` used to be excluded here, with a second query defined\n * for it that nothing ever called (issue #90). That is the publication\n * Supabase Realtime actually uses: enabling Realtime on a table means adding\n * it to this publication, so excluding it hid the only Realtime drift most\n * projects will ever have. Publishing a table in dev and not in production\n * reported clean.\n *\n * Its *presence* is not drift — every Supabase project has it — and nothing\n * reports it as such, because both sides have it. Its table list is the whole\n * point.\n */\n/**\n * The publication Supabase Realtime keeps for itself. Its members are\n * `realtime.messages_YYYY_MM_DD`, daily partitions the Realtime service\n * creates and drops on its own schedule, so two projects always differ on it\n * and no fix can apply; a snapshot recording that day's partitions could not\n * be restored anywhere else, and rolled the whole restore back.\n */\nexport const PLATFORM_PUBLICATIONS = ['supabase_realtime_messages_publication']\n\n/**\n * Every publication and the tables in it — but not the platform's own\n * publications, nor member tables in a schema the platform owns. One query for\n * both the check and the snapshot, so the two agree on what Realtime state is.\n */\nexport const PUBLICATION_SQL = `\n SELECT p.pubname, pt.schemaname, pt.tablename\n FROM pg_publication p\n LEFT JOIN pg_publication_tables pt\n ON p.pubname = pt.pubname\n AND pt.schemaname <> ALL (${sqlTextArray(DEFAULT_IGNORE_SCHEMAS)})\n WHERE p.pubname <> ALL (${sqlTextArray(PLATFORM_PUBLICATIONS)})\n ORDER BY p.pubname, pt.schemaname, pt.tablename\n`\n\nfunction sqlTextArray(values: string[]): string {\n return `ARRAY[${values.map(v => `'${v.replace(/'/g, \"''\")}'`).join(', ')}]::text[]`\n}\n\nfunction pubTableKey(pub: RealtimePublication): string {\n return `${pub.pubname}.${pub.schemaname}.${pub.tablename}`\n}\n\nexport function diffPublications(source: RealtimePublication[], target: RealtimePublication[]): DriftIssue[] {\n const issues: DriftIssue[] = []\n\n // Diff publication-level presence\n const sourcePubs = new Set(source.map(p => p.pubname))\n const targetPubs = new Set(target.map(p => p.pubname))\n\n for (const pubname of sourcePubs) {\n if (!targetPubs.has(pubname)) {\n const tables = source.filter(p => p.pubname === pubname && p.tablename)\n issues.push({\n id: `realtime-missing-pub-${pubname}`,\n check: 'realtime',\n severity: 'warning',\n title: `Missing publication: ${pubname}`,\n description: `Publication \"${pubname}\" exists in source but not in target.`,\n sourceValue: tables,\n sql: {\n up: `CREATE PUBLICATION ${quoteName(pubname)}${tables.length > 0 ? ` FOR TABLE ${tables.map(t => `${quoteName(t.schemaname)}.${quoteName(t.tablename)}`).join(', ')}` : ''};`,\n down: `DROP PUBLICATION IF EXISTS ${quoteName(pubname)};`,\n },\n })\n }\n }\n\n for (const pubname of targetPubs) {\n if (!sourcePubs.has(pubname)) {\n issues.push({\n id: `realtime-extra-pub-${pubname}`,\n check: 'realtime',\n severity: 'info',\n title: `Extra publication: ${pubname}`,\n description: `Publication \"${pubname}\" exists in target but not in source.`,\n })\n }\n }\n\n // Diff table membership within shared publications\n const sharedPubs = [...sourcePubs].filter(p => targetPubs.has(p))\n for (const pubname of sharedPubs) {\n const sourceTables = new Set(\n source.filter(p => p.pubname === pubname && p.tablename).map(p => `${p.schemaname}.${p.tablename}`),\n )\n const targetTables = new Set(\n target.filter(p => p.pubname === pubname && p.tablename).map(p => `${p.schemaname}.${p.tablename}`),\n )\n\n for (const fqn of sourceTables) {\n if (!targetTables.has(fqn)) {\n issues.push({\n id: `realtime-missing-table-${pubname}-${fqn}`,\n check: 'realtime',\n severity: 'warning',\n title: `Table not published: ${fqn} in ${pubname}`,\n description: `Table \"${fqn}\" is published in source publication \"${pubname}\" but not in target.`,\n sql: {\n up: `ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${fqn};`,\n down: `ALTER PUBLICATION ${quoteName(pubname)} DROP TABLE ${fqn};`,\n },\n })\n }\n }\n\n for (const fqn of targetTables) {\n if (!sourceTables.has(fqn)) {\n issues.push({\n id: `realtime-extra-table-${pubname}-${fqn}`,\n check: 'realtime',\n severity: 'info',\n title: `Extra published table: ${fqn} in ${pubname}`,\n description: `Table \"${fqn}\" is published in target publication \"${pubname}\" but not in source.`,\n })\n }\n }\n }\n\n return issues\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AAuBR,SAAS,mBAAmB,QAA+B;AAChE,QAAM,I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ACjD;AAQA,eAAe,uCAAuC,KAAmC;AACvF,QAAM,aAAa,oBAAI,IAAY;AAEnC,MAAI;AACF,UAAM,MAAM,QAAQ,KAAK,eAAe,iBAAiB;AACzD,eAAW,QAAQ,MAAM,QAAQ,GAAG,GAAG;AACrC,UAAI,CAAC,KAAK,SAAS,OAAO,EAAG;AAC7B,UAAI;AACF,cAAM,YAAY,KAAK,MAAM,MAAM,SAAS,KAAK,KAAK,IAAI,GAAG,OAAO,CAAC;AACrE,YAAI,UAAU,OAAQ,YAAW,IAAI,UAAU,MAAM;AAAA,MACvD,QAAQ;AAAA,MAAyD;AAAA,IACnE;AAAA,EACF,QAAQ;AAAA,EAAgC;AAExC,SAAO;AACT;AAuBA,SAAS,wBAAwB,GAAmB;AAClD,SAAO,GAAG,cAAc,EAAE,YAAY,CAAC,CAAC;AAAA,EAAK,gBAAgB,EAAE,YAAY,CAAC,CAAC;AAC/E;","names":["resolve","pg","pg","execFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/clone.ts"],"sourcesContent":["import { writeFile, mkdir } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { Flags } from '@oclif/core'\nimport pg from 'pg'\nimport { pgClientConfig } from '../db.js'\nimport { BaseCommand } from '../base-command.js'\nimport { captureSnapshot, formatSnapshotLayers } from '../snapshot.js'\nimport {\n cloneRemoteToLocal,\n replaceDbName,\n listBranches,\n reconcileClones,\n deleteBranch,\n addBranchToManifest,\n} from '../branch.js'\nimport type { BranchMeta, CloneResult, RestoreFailure } from '../branch.js'\nimport { loadConfig } from '../config.js'\nimport { checkPgDumpCompat } from '../pg-tools.js'\nimport { startLocalPg, DEFAULT_LOCAL_PORT, LOCAL_PG_USER, LOCAL_PG_PASSWORD } from '../local-pg.js'\nimport { ok, warn, dim, cmd, bold } from '../ui.js'\nimport { renderTip } from '../tips.js'\nimport { DEFAULT_IGNORE_SCHEMAS, CLONE_SKIP_FLAGS } from '../defaults.js'\nimport { CLONE_EXTRA_EXCLUDE_SCHEMAS, SUPAFORGE_DIR, MIGRATIONS_SUBDIR } from '../constants.js'\nimport { errMsg, redactUrls } from '../utils/error.js'\nimport type { SupaForgeConfig } from '../types/config.js'\n\n/** Combined list of schemas to exclude from pg_dump when cloning. */\n// De-duplicated: `_realtime` is in both lists, so it was excluded — and\n// printed — twice (issue #97).\nconst CLONE_EXCLUDE_SCHEMAS = [...new Set([\n ...DEFAULT_IGNORE_SCHEMAS,\n ...CLONE_EXTRA_EXCLUDE_SCHEMAS,\n])]\n\n/**\n * Clone a remote environment to a local database and manage clones.\n *\n * Default: preflight checks (dry-run)\n * --apply: execute the clone\n * --list: list existing clones\n * --delete=NAME: remove a clone\n * --delete=NAME --apply: actually drop the database\n */\nexport default class Clone extends BaseCommand {\n static override description = 'Clone a remote Supabase environment to a local database'\n\n static override examples = [\n '<%= config.bin %> clone --env=production',\n '<%= config.bin %> clone --env=production --apply',\n '<%= config.bin %> clone --env=production --force --apply',\n '<%= config.bin %> clone --env=production --schema-only --apply',\n '<%= config.bin %> clone --env=production --start-local --apply',\n '<%= config.bin %> clone --list',\n '<%= config.bin %> clone --delete=my-clone --apply',\n ]\n\n static override flags = {\n env: Flags.string({\n char: 'e',\n description: 'Source environment to clone from (defaults to config source)',\n }),\n 'local-db': Flags.string({\n description: 'Name for the local database (default: supaforge_local)',\n default: 'supaforge_local',\n }),\n 'local-url': Flags.string({\n description: 'Local PostgreSQL URL (default: postgres://postgres:postgres@localhost:5432/postgres)',\n default: `postgres://${LOCAL_PG_USER}:${LOCAL_PG_PASSWORD}@localhost:${DEFAULT_LOCAL_PORT}/postgres`,\n }),\n 'start-local': Flags.boolean({\n description: 'Auto-start a local PostgreSQL container via Podman or Docker',\n default: false,\n }),\n 'schema-only': Flags.boolean({\n description: 'Copy schema only, no data',\n default: false,\n }),\n force: Flags.boolean({\n char: 'f',\n description: 'Drop and recreate the target database if it already exists',\n default: false,\n }),\n apply: Flags.boolean({\n description: 'Execute the operation (default: dry-run preview)',\n default: false,\n }),\n list: Flags.boolean({\n description: 'List existing clones',\n default: false,\n }),\n delete: Flags.string({\n description: 'Delete a clone by name (requires --apply to execute)',\n }),\n json: Flags.boolean({ description: 'Output results as JSON' }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(Clone)\n\n // ── List clones ──────────────────────────────────────────────────────────\n // The manifest alone misses clones it never recorded (older versions, a\n // different checkout, or a cleaned .supaforge/). Reconcile it against the\n // databases that actually exist on the local server so existing clones show\n // up too — not just freshly-created ones. Config is optional here.\n if (flags.list) {\n const softConfig = await loadConfig().catch(() => undefined)\n const localEnv = softConfig?.environments?.local\n let localServerUrl: string | undefined\n let configuredLocalDb: string | undefined\n if (localEnv?.dbUrl) {\n localServerUrl = localEnv.dbUrl\n try {\n configuredLocalDb = new URL(localEnv.dbUrl).pathname.replace(/^\\//, '') || undefined\n } catch { /* unpar-seable url — skip discovery hint */ }\n }\n\n const branches = localServerUrl\n ? await reconcileClones({ localServerUrl, configuredLocalDb })\n : (await listBranches()).map(b => ({ ...b, missing: false, discovered: false }))\n\n if (branches.length === 0) {\n this.log(`\\n No clones found. Create one with: ${cmd('supaforge clone --env=<name> --apply')}\\n`)\n return\n }\n\n if (flags.json) {\n this.json(branches)\n return\n }\n\n this.log(`\\n ${bold(`${branches.length} clone(s):`)}\\n`)\n for (const b of branches) {\n const tags = [\n b.discovered ? dim('(discovered)') : '',\n b.missing ? warn('(database missing)') : '',\n ].filter(Boolean).join(' ')\n this.log(` ${bold(b.name)}${tags ? ' ' + tags : ''}`)\n this.log(` Database: ${b.dbName}`)\n this.log(` From: ${b.createdFrom}`)\n if (b.createdAt) this.log(` Created: ${b.createdAt}`)\n this.log(` Schema: ${b.schemaOnly ? 'only' : 'full'}`)\n this.log('')\n }\n return\n }\n\n const config = await this.loadConfigOrFail()\n\n // ── Delete clone ─────────────────────────────────────────────────────────\n if (flags.delete) {\n const { env } = this.resolveEnv(config, flags.env)\n\n const branches = await listBranches()\n const branch = branches.find(b => b.name === flags.delete)\n if (!branch) {\n this.error(`Clone \"${flags.delete}\" not found. Run \"supaforge clone --list\" to see clones.`)\n }\n\n if (!flags.apply) {\n this.log(`\\n ${bold('Delete clone preview')} ${dim('(dry-run)')}\\n`)\n this.log(` Clone: ${branch.name}`)\n this.log(` Database: ${branch.dbName}`)\n this.log(` Created: ${branch.createdAt}`)\n this.log(` From: ${branch.createdFrom}`)\n this.log('')\n this.log(' This would:')\n this.log(` 1. Terminate connections to \"${branch.dbName}\"`)\n this.log(` 2. DROP DATABASE \"${branch.dbName}\"`)\n this.log(' 3. Remove clone from .supaforge/branches.json')\n this.log(`\\n → Add ${cmd('--apply')} to delete the clone.\\n`)\n return\n }\n\n this.log(`\\n Deleting clone \"${branch.name}\"...\\n`)\n await deleteBranch(flags.delete, env.dbUrl)\n this.log(` ${ok('✓')} Clone \"${branch.name}\" deleted.\\n`)\n return\n }\n\n // ── Clone: preflight + execute ───────────────────────────────────────────\n const { envName, env } = this.resolveEnv(config, flags.env)\n const localDbName = flags['local-db']\n let localBaseUrl = flags['local-url']\n\n // Auto-start a local PostgreSQL container if requested\n if (flags['start-local']) {\n this.log(`\\n ${bold('Starting local PostgreSQL container...')}\\n`)\n const info = await startLocalPg()\n localBaseUrl = info.url\n this.log(` ${ok('✓')} PostgreSQL running via ${bold(info.runtime)} on port ${info.port}\\n`)\n }\n\n const localDbUrl = replaceDbName(localBaseUrl, localDbName)\n\n // Always run preflight checks — even with --apply\n const pre = this.createPreflight('Clone preflight checks')\n .addDatabase('Remote', envName, env.dbUrl)\n .addInfo('Local DB', localDbName)\n .addInfo('Local URL', dim(redactUrls(localDbUrl)))\n .addInfo('Schema only', String(flags['schema-only']))\n\n if (flags['start-local']) {\n pre.addCheck('Local PostgreSQL', async () => ({\n detail: `auto-started via --start-local`,\n }))\n } else {\n pre.addDatabase('Local', 'local', localBaseUrl)\n }\n\n pre.addCheck('pg_dump compatibility', async () => {\n try {\n const compat = await checkPgDumpCompat(env.dbUrl)\n if (compat.compatible) {\n const pathNote = compat.pgDumpPath === 'pg_dump' ? '' : ` (${compat.pgDumpPath})`\n return { detail: `v${compat.localMajor} ↔ server v${compat.serverMajor}${pathNote}` }\n }\n return { error: compat.message }\n } catch (err) {\n return { error: `pg_dump check failed: ${(err as Error).message}` }\n }\n })\n\n pre.addCheck('Target database', async () => {\n try {\n const client = new pg.Client(pgClientConfig(localBaseUrl))\n await client.connect()\n const { rows } = await client.query(\n 'SELECT 1 FROM pg_database WHERE datname = $1',\n [localDbName],\n )\n await client.end()\n if (rows.length > 0) {\n if (flags.force) {\n return { detail: `\"${localDbName}\" exists — will be dropped (--force)` }\n }\n return {\n error: `\"${localDbName}\" already exists on local server`,\n hints: [`Use ${cmd('--force')} to drop and recreate it.`],\n }\n }\n return { detail: `\"${localDbName}\" does not exist yet` }\n } catch {\n return {} // Can't check — let the apply step handle it\n }\n })\n\n const report = await pre.run()\n\n if (!flags.apply) {\n if (flags.json) {\n this.json({ dryRun: true, passed: report.passed, localDb: localDbName })\n if (!report.passed) this.exit(1)\n return\n }\n if (report.passed) {\n this.log(` Steps that will be performed:`)\n this.log(' 1. Create local database via pg_dump | pg_restore')\n this.log(' 2. Capture full snapshot of remote environment')\n this.log(' 3. Store snapshot as baseline migration')\n this.log(' 4. Update supaforge.config.json with local + remote environments')\n this.log('')\n this.log(` → Add ${cmd('--apply')} to execute the clone.\\n`)\n this.log(renderTip({ command: 'clone', cloneApplied: false, schemaOnly: flags['schema-only'] }))\n }\n return\n }\n\n if (!report.passed) {\n this.error('Clone aborted — fix the issues above first.', { exit: 1 })\n }\n\n // Execute clone\n this.log(`\\n ${bold(`Cloning \"${envName}\" to local database \"${localDbName}\"...`)}\\n`)\n // The transfer meter, like every other line here, stays off stdout under --json.\n const progressOut = flags.json ? process.stderr : process.stdout\n\n this.log(' [1/4] Creating local database...')\n let cloned: CloneResult\n try {\n cloned = await cloneRemoteToLocal({\n remoteUrl: env.dbUrl,\n localBaseUrl,\n localDbName,\n schemaOnly: flags['schema-only'],\n force: flags.force,\n excludeSchemas: CLONE_EXCLUDE_SCHEMAS,\n onProgress: (p) => {\n const mb = (p.bytesTransferred / 1024 / 1024).toFixed(1)\n const sec = Math.round(p.elapsedMs / 1000)\n progressOut.write(`\\r ${dim(`pg_dump → pg_restore: ${mb} MB transferred (${sec}s)`)} `)\n },\n })\n progressOut.write('\\n')\n this.log(` ${ok('✓')} Database created: ${bold(localDbName)}`)\n if (cloned.extensionsInstalled.length > 0) {\n this.log(` ${dim(`Installed first, in the schema the source keeps them in: ${cloned.extensionsInstalled.join(', ')}`)}`)\n }\n for (const line of formatUnavailable(cloned.unavailable)) this.log(line)\n for (const line of formatRestoreFailures(cloned.failures)) this.log(line)\n } catch (err) {\n progressOut.write('\\n')\n const msg = errMsg(err)\n this.log(` ${warn('✗')} Failed: ${msg}`)\n this.error('Clone aborted at step 1/4.', { exit: 1 })\n }\n\n this.log(' [2/4] Capturing remote snapshot...')\n const snapshot = await captureSnapshot({ envName, env, config })\n const capturedCount = Object.values(snapshot.manifest.layers).filter(l => l.captured).length\n this.log(` ${ok('✓')} Snapshot captured: ${capturedCount} layer(s)`)\n // Show exactly what was captured / skipped / errored per layer (like supaforge diff),\n // so the user can see at a glance what made it into the baseline.\n for (const line of formatSnapshotLayers(snapshot.manifest)) {\n this.log(` ${line}`)\n }\n\n this.log(' [3/4] Storing baseline migration...')\n const migrationsDir = resolve(SUPAFORGE_DIR, MIGRATIONS_SUBDIR)\n await mkdir(migrationsDir, { recursive: true })\n const migrationFile = resolve(migrationsDir, `${snapshot.timestamp}_clone-baseline.json`)\n const migration = {\n version: snapshot.timestamp,\n description: `clone-baseline from ${envName}`,\n parent: null,\n layers: Object.entries(snapshot.manifest.layers)\n .filter(([, v]) => v.captured)\n .map(([k]) => k),\n up: { sql: [], api: [] },\n down: { sql: [], api: [] },\n }\n await writeFile(migrationFile, JSON.stringify(migration, null, 2) + '\\n')\n this.log(` ${ok('✓')} Baseline stored: ${migrationFile}`)\n\n this.log(' [4/4] Updating config...')\n const newConfig = configAfterClone(config, envName, localDbUrl)\n const configPath = resolve('supaforge.config.json')\n await writeFile(configPath, JSON.stringify(newConfig, null, 2) + '\\n')\n this.log(` ${ok('✓')} Config updated: ${configPath}`)\n\n // Say what moved. Overwriting these silently is the other half of #89:\n // whatever the project was pointed at before is gone, with no record of it\n // in the output.\n const wasSource = config.source\n const wasTarget = config.target\n if (wasSource !== envName || wasTarget !== 'local') {\n this.log(` ${dim('source:')} ${wasSource ?? dim('(unset)')} ${dim('→')} ${envName}`)\n this.log(` ${dim('target:')} ${wasTarget ?? dim('(unset)')} ${dim('→')} local ${dim('(the clone)')}`)\n this.log(` ${dim('A bare')} ${cmd('supaforge diff --apply')} ${dim('now writes into the clone, not into')} \"${envName}\".`)\n }\n\n // Register clone in .supaforge/branches.json so `clone --list` works\n const branchMeta: BranchMeta = {\n name: localDbName,\n dbName: localDbName,\n dbUrl: localDbUrl,\n createdFrom: envName,\n createdAt: new Date().toISOString(),\n schemaOnly: flags['schema-only'],\n }\n await addBranchToManifest(branchMeta)\n\n const missing = cloned.failures.length\n if (flags.json) {\n this.json({\n snapshot: snapshot.manifest, config: newConfig,\n restoreFailures: cloned.failures, unavailable: cloned.unavailable,\n })\n if (missing > 0) this.exit(1)\n return\n }\n\n this.log(missing > 0\n ? `\\n ${warn(`Clone complete, but ${missing} statement(s) could not be restored`)} ${dim('— listed under step 1.')}\\n`\n : `\\n ${ok('Clone complete!')}\\n`)\n\n // ── What was NOT cloned (Issue: set expectations before the first diff) ───\n // The pg_dump pipeline deliberately excludes Supabase-managed schemas and\n // can't carry platform-managed state (storage objects, edge functions, auth\n // config, vault secrets). Spelling this out up front explains why the first\n // diff against the remote is large — it is expected, not a tool failure.\n this.log(` ${bold('Not included in this clone')} ${dim('(expected drift on the first diff):')}`)\n this.log(` ${dim('•')} Supabase-managed schemas, excluded from the dump so they restore cleanly`)\n this.log(` on vanilla Postgres: ${dim(CLONE_EXCLUDE_SCHEMAS.join(', '))}`)\n this.log(` ${dim('•')} Platform state that lives outside the SQL dump: storage objects &`)\n this.log(` policies, edge functions, auth config, and vault secrets.`)\n // Roles arrived as Layer 14, after this list was written for 13 layers, and\n // is the second-largest source of clone noise — 227 findings on the diff in\n // issue #47. Left unmentioned, they read as unexplained drift.\n this.log(` ${dim('•')} Postgres roles & grants — Supabase's service roles do not exist`)\n this.log(` on vanilla Postgres, so every grant that references one reads as drift.`)\n if (flags['schema-only']) {\n this.log(` ${dim('•')} Table data — you passed ${cmd('--schema-only')} (structure only).`)\n }\n this.log(` ${dim('These appear as drift below but are managed by Supabase, not your migrations.')}`)\n this.log('')\n\n // ── Contextual next steps (Issue: give the exact commands for THIS clone) ─\n const skipFlags = CLONE_SKIP_FLAGS\n this.log(` ${bold('Your workflow is now:')}`)\n this.log(` 1. Develop against the local database ${dim(`(${localDbName})`)}`)\n this.log(` 2. Verify the clone matches \"${envName}\": ${cmd('supaforge diff --detail')}`)\n this.log(` ${dim('Add')} ${cmd(skipFlags)} ${dim('to hide the Supabase-managed noise above.')}`)\n this.log(` 3. See what drifted as you work: ${cmd('supaforge diff')}`)\n this.log(` 4. Capture the current state: ${cmd('supaforge snapshot --apply')}`)\n this.log('')\n // Named in full rather than as a bare `--apply`. This is the direction that\n // writes to a hosted database, and from a clone it carries the absences the\n // warning above is about — so it should not be reachable by habit.\n this.log(` ${bold(`Pushing local changes back to \"${envName}\"`)} ${dim('writes to that database:')}`)\n this.log(` ${cmd(`supaforge diff --source=local --target=${envName} --dry-run`)} ${dim('← review first')}`)\n this.log(` ${cmd(`supaforge diff --source=local --target=${envName} --apply`)}`)\n this.log(` ${dim('A clone is vanilla PostgreSQL, so')} ${cmd(skipFlags)} ${dim('belongs on those too.')}`)\n this.log('')\n this.log(renderTip({ command: 'clone', cloneApplied: true, schemaOnly: flags['schema-only'] }))\n // The clone is usable, but it is not a copy of the source, and a script\n // relying on it should not carry on as though it were.\n if (missing > 0) this.exit(1)\n }\n}\n\n/**\n * What this server cannot have, in one line: extensions it does not ship and\n * the platform's own event triggers. Every Supabase project has some, so they\n * are stated rather than counted as the clone failing — see restoreFailures.\n */\nexport function formatUnavailable(items: readonly RestoreFailure[]): string[] {\n if (items.length === 0) return []\n const extensions = items.filter(i => i.object.startsWith('extension ')).map(i => i.object.slice('extension '.length))\n const others = items.length - extensions.length\n const parts = [\n ...(extensions.length ? [`extension${extensions.length > 1 ? 's' : ''} ${extensions.join(', ')}`] : []),\n ...(others ? [`${others} event trigger(s) of the platform's`] : []),\n ]\n return [` ${dim(`Not available on this server, as expected for a Supabase project: ${parts.join('; ')}`)}`]\n}\n\n/** Shown at most, before \"…and N more\". */\nconst RESTORE_FAILURES_SHOWN = 15\n\n/**\n * What pg_restore could not reproduce, for step 1 of the output.\n *\n * pg_restore exits 1 and carries on when a statement fails, which used to be\n * read as success: the step printed a tick and the objects were simply not in\n * the clone.\n */\nexport function formatRestoreFailures(failures: readonly RestoreFailure[]): string[] {\n if (failures.length === 0) return []\n const lines = [` ${warn('⚠')} ${failures.length} statement(s) failed, so these are not in the clone:`]\n for (const f of failures.slice(0, RESTORE_FAILURES_SHOWN)) {\n lines.push(` ${dim('•')} ${f.object} ${dim(`— ${f.error}`)}`)\n }\n const rest = failures.length - RESTORE_FAILURES_SHOWN\n if (rest > 0) lines.push(` ${dim(`…and ${rest} more`)}`)\n return lines\n}\n\n/**\n * The config a clone leaves behind.\n *\n * The clone becomes the **target**, so a bare `supaforge diff --apply` in this\n * directory writes into the local copy.\n *\n * It used to be the source, with the cloned-from environment as the target —\n * and the closing guidance recommended a bare `diff --apply`. Together those\n * pointed the next unqualified apply at the hosted database the clone had just\n * been taken from, carrying with it exactly the roles-and-grants drift the same\n * screen warns about (issue #89). Pushing that way is still available and is\n * now spelled out in full, which is the direction that deserves to be explicit.\n *\n * Everything else about the config is preserved, including any environment\n * already called `local`, which is replaced rather than merged: it names a\n * database, and the clone is the database it now names.\n */\nexport function configAfterClone(\n config: SupaForgeConfig,\n envName: string,\n localDbUrl: string,\n): SupaForgeConfig {\n return {\n ...config,\n environments: {\n ...config.environments,\n local: { ...config.environments.local, dbUrl: localDbUrl },\n },\n source: envName,\n target: 'local',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,aAAa;AACjC,SAAS,eAAe;AACxB,SAAS,aAAa;AACtB,OAAO,QAAQ;AA0Bf,IAAM,wBAAwB,CAAC,GAAG,oBAAI,IAAI;AAAA,EACxC,GAAG;AAAA,EACH,GAAG;AACL,CAAC,CAAC;AAWF,IAAqB,QAArB,MAAqB,eAAc,YAAY;AAAA,EAC7C,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,KAAK,MAAM,OAAO;AAAA,MAChB,MAAM;AAAA,MACN,aAAa;AAAA,IACf,CAAC;AAAA,IACD,YAAY,MAAM,OAAO;AAAA,MACvB,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,aAAa,MAAM,OAAO;AAAA,MACxB,aAAa;AAAA,MACb,SAAS,cAAc,aAAa,IAAI,iBAAiB,cAAc,kBAAkB;AAAA,IAC3F,CAAC;AAAA,IACD,eAAe,MAAM,QAAQ;AAAA,MAC3B,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,eAAe,MAAM,QAAQ;AAAA,MAC3B,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,OAAO,MAAM,QAAQ;AAAA,MACnB,MAAM;AAAA,MACN,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,OAAO,MAAM,QAAQ;AAAA,MACnB,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,MAAM,MAAM,QAAQ;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AAA,MACV,OAAO,EAAE,GAAG,OAAO,aAAa,OAAO,OAAO,WAAW;AAAA,IAC3D;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AACF;","names":["env"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/help.ts"],"sourcesContent":["import { Args, Command, Flags, loadHelpClass } from '@oclif/core'\n\n/**\n * `supaforge help [COMMAND]`.\n *\n * oclif's `helpClass` only styles the help that `--help` renders; the `help`\n * *command* comes from `@oclif/plugin-help`, which this CLI does not install.\n * So `supaforge help migrate create` — the form people reach for first, and the\n * one every other CLI accepts — answered:\n *\n * › Error: command help:migrate:create not found\n *\n * which reads as \"there is no such command\" rather than \"there is no help\n * command\" (issue #97). Written here rather than added as a dependency because\n * the rendering is already ours: this hands straight to the same `helpClass`,\n * so `help X` and `X --help` produce identical output.\n */\nexport default class HelpCommand extends Command {\n static description = 'Display help for supaforge'\n\n static strict = false\n\n static args = {\n command: Args.string({\n description: 'Command to show help for, e.g. \"diff\" or \"migrate create\"',\n required: false,\n }),\n }\n\n static flags = {\n 'nested-commands': Flags.boolean({\n char: 'n',\n description: 'Include all nested commands in the output',\n }),\n }\n\n static examples = [\n '$ supaforge help',\n '$ supaforge help diff',\n '$ supaforge help migrate create',\n ]\n\n async run(): Promise<void> {\n const { argv, flags } = await this.parse(HelpCommand)\n\n const Help = await loadHelpClass(this.config)\n const help = new Help(this.config, {\n all: flags['nested-commands'],\n ...this.config.pjson.oclif.helpOptions,\n })\n\n // The whole argv, so a topic and its subcommand arrive together: oclif\n // addresses `migrate create` as one command, and passing only the first\n // argument would show the topic every time.\n await help.showHelp(argv as string[])\n }\n}\n"],"mappings":";AAAA,SAAS,MAAM,SAAS,OAAO,qBAAqB;AAiBpD,IAAqB,cAArB,MAAqB,qBAAoB,QAAQ;AAAA,EAC/C,OAAO,cAAc;AAAA,EAErB,OAAO,SAAS;AAAA,EAEhB,OAAO,OAAO;AAAA,IACZ,SAAS,KAAK,OAAO;AAAA,MACnB,aAAa;AAAA,MACb,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AAAA,EAEA,OAAO,QAAQ;AAAA,IACb,mBAAmB,MAAM,QAAQ;AAAA,MAC/B,MAAM;AAAA,MACN,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,OAAO,WAAW;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,MAAM,IAAI,MAAM,KAAK,MAAM,YAAW;AAEpD,UAAM,OAAO,MAAM,cAAc,KAAK,MAAM;AAC5C,UAAM,OAAO,IAAI,KAAK,KAAK,QAAQ;AAAA,MACjC,KAAK,MAAM,iBAAiB;AAAA,MAC5B,GAAG,KAAK,OAAO,MAAM,MAAM;AAAA,IAC7B,CAAC;AAKD,UAAM,KAAK,SAAS,IAAgB;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/hukam.ts"],"sourcesContent":["import Diff from './diff.js'\n\nexport default class Hukam extends Diff {\n static override hidden = true\n static override description = 'Alias for diff'\n\n static override examples = ['<%= config.bin %> hukam']\n\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAEA,IAAqB,QAArB,cAAmC,KAAK;AAAA,EACtC,OAAgB,SAAS;AAAA,EACzB,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW,CAAC,yBAAyB;AAEvD;","names":[]}
|