@akal/supaforge 0.0.32 → 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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +28 -10
  3. package/dist/commands/mcp.d.ts +1 -0
  4. package/dist/commands/mcp.js +11 -1
  5. package/package.json +10 -8
  6. package/bin/dev.js +0 -10
  7. package/dist/base-command.js.map +0 -1
  8. package/dist/chunk-2SELREHW.js.map +0 -1
  9. package/dist/chunk-3HGAV5CC.js.map +0 -1
  10. package/dist/chunk-4IVN7QVY.js.map +0 -1
  11. package/dist/chunk-6LJERPUN.js.map +0 -1
  12. package/dist/chunk-6Q7MHFBM.js.map +0 -1
  13. package/dist/chunk-6WAMNZLO.js.map +0 -1
  14. package/dist/chunk-7NAZGZPV.js.map +0 -1
  15. package/dist/chunk-BLKJWDTL.js.map +0 -1
  16. package/dist/chunk-BUOWHE36.js.map +0 -1
  17. package/dist/chunk-DMIWAJRB.js.map +0 -1
  18. package/dist/chunk-DQQ5E563.js.map +0 -1
  19. package/dist/chunk-G2DIPIYU.js.map +0 -1
  20. package/dist/chunk-GEHPTPNZ.js.map +0 -1
  21. package/dist/chunk-GZREXCQZ.js.map +0 -1
  22. package/dist/chunk-MIRLB5JM.js.map +0 -1
  23. package/dist/chunk-NTUASFQ3.js.map +0 -1
  24. package/dist/chunk-ORQJVE57.js.map +0 -1
  25. package/dist/chunk-SC2XHGIS.js.map +0 -1
  26. package/dist/chunk-SQPCWGQO.js.map +0 -1
  27. package/dist/chunk-UWAVXC57.js.map +0 -1
  28. package/dist/commands/clone.js.map +0 -1
  29. package/dist/commands/diff.js.map +0 -1
  30. package/dist/commands/help.js.map +0 -1
  31. package/dist/commands/hukam.js.map +0 -1
  32. package/dist/commands/init.js.map +0 -1
  33. package/dist/commands/mcp.js.map +0 -1
  34. package/dist/commands/migrate/baseline.js.map +0 -1
  35. package/dist/commands/migrate/create.js.map +0 -1
  36. package/dist/commands/migrate/list.js.map +0 -1
  37. package/dist/commands/migrate/run.js.map +0 -1
  38. package/dist/commands/report.js.map +0 -1
  39. package/dist/commands/restore.js.map +0 -1
  40. package/dist/commands/snapshot.js.map +0 -1
  41. package/dist/commands/sync.js.map +0 -1
  42. package/dist/help.js.map +0 -1
  43. package/dist/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/error.ts","../src/db.ts","../src/local-pg.ts","../src/preflight.ts","../src/checks/base.ts","../src/checks/migrations.ts","../src/utils/sql.ts"],"sourcesContent":["/**\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 // Before the connection timeout: the server answered, and a query ran\n // past its statement_timeout. Calling that a connection problem sent\n // people to check a host and port that were fine.\n test: (m) => /canceling statement due to statement timeout|57014/i.test(m),\n build: (host) => `A query on ${host} was cancelled by statement_timeout — the server is reachable. Raise statement_timeout for this role or connection and try again.`,\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/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 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","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport { RUNTIME_DETECT_TIMEOUT_MS, CONTAINER_RM_TIMEOUT_MS, CONTAINER_START_TIMEOUT_MS } from './constants'\n\nconst defaultExecFile = promisify(execFile)\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Injected exec function for testability. */\nexport type ExecFn = (\n cmd: string,\n args: string[],\n opts?: { timeout?: number },\n) => Promise<{ stdout: string; stderr: string }>\n\n/** Injected PostgreSQL connect function for readiness polling. */\nexport type ConnectFn = (url: string) => Promise<void>\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n/** Default PostgreSQL image used for local containers. */\nexport const PG_IMAGE = 'docker.io/library/postgres:17'\n\n/** Default host port for the local PostgreSQL container. */\nexport const DEFAULT_LOCAL_PORT = 5432\n\n/** Default container name. */\nexport const CONTAINER_NAME = 'supaforge-local-pg'\n\n/** Default credentials for the local container. */\nexport const LOCAL_PG_USER = 'postgres'\nexport const LOCAL_PG_PASSWORD = 'postgres'\n\n/** Maximum retries when waiting for PostgreSQL readiness. */\nexport const READINESS_RETRIES = 30\n\n/** Delay between readiness checks (ms). */\nexport const READINESS_INTERVAL_MS = 2000\n\n// ─── Default implementations ────────────────────────────────────────────────\n\nasync function defaultConnectFn(url: string): Promise<void> {\n const client = new pg.Client(pgClientConfig(url))\n await client.connect()\n await client.end()\n}\n\n// ─── Container Runtime Detection ─────────────────────────────────────────────\n\nexport type ContainerRuntime = 'podman' | 'docker'\n\n/**\n * Detect the available container runtime.\n * Prefers podman (rootless, daemonless) over docker.\n * Returns null if neither is available.\n */\nexport async function detectRuntime(execFn: ExecFn = defaultExecFile): Promise<ContainerRuntime | null> {\n for (const rt of ['podman', 'docker'] as const) {\n try {\n await execFn(rt, ['--version'], { timeout: RUNTIME_DETECT_TIMEOUT_MS })\n return rt\n } catch {\n continue\n }\n }\n return null\n}\n\n// ─── Container Lifecycle ─────────────────────────────────────────────────────\n\nexport interface StartLocalPgOptions {\n /** Container runtime to use. Auto-detected if not provided. */\n runtime?: ContainerRuntime\n /** Host port to bind (default: 5432). */\n port?: number\n /** PostgreSQL password (default: 'postgres'). */\n password?: string\n /** Container name (default: 'supaforge-local-pg'). */\n name?: string\n /** PostgreSQL image (default: PG_IMAGE). */\n image?: string\n /** Injected exec function for testability. */\n execFn?: ExecFn\n /** Injected connect function for testability. */\n connectFn?: ConnectFn\n}\n\nexport interface LocalPgInfo {\n runtime: ContainerRuntime\n containerName: string\n port: number\n url: string\n}\n\n/**\n * Start a local PostgreSQL container using the detected runtime.\n *\n * Uses tmpfs for ephemeral storage (fast, no disk writes).\n * Waits for PostgreSQL to accept connections before returning.\n */\nexport async function startLocalPg(options: StartLocalPgOptions = {}): Promise<LocalPgInfo> {\n const exec = options.execFn ?? defaultExecFile\n const connect = options.connectFn ?? defaultConnectFn\n const runtime = options.runtime ?? await detectRuntime(exec)\n if (!runtime) {\n throw new Error(\n 'No container runtime found. Install Podman (recommended) or Docker.\\n' +\n ' Podman: https://podman.io/docs/installation\\n' +\n ' Docker: https://docs.docker.com/engine/install/',\n )\n }\n\n const port = options.port ?? DEFAULT_LOCAL_PORT\n const password = options.password ?? LOCAL_PG_PASSWORD\n const name = options.name ?? CONTAINER_NAME\n const image = options.image ?? PG_IMAGE\n\n // Check if container already exists and is running\n const existing = await getContainerStatus(runtime, name, exec)\n if (existing === 'running') {\n return {\n runtime,\n containerName: name,\n port,\n url: buildLocalUrl(port, password),\n }\n }\n\n // Remove stopped container with same name\n if (existing === 'stopped') {\n await exec(runtime, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n }\n\n // Start the container\n const args = [\n 'run', '-d',\n '--name', name,\n '-p', `${port}:5432`,\n '-e', `POSTGRES_PASSWORD=${password}`,\n '-e', `POSTGRES_USER=${LOCAL_PG_USER}`,\n '--tmpfs', '/var/lib/postgresql/data',\n '--health-cmd', `pg_isready -U ${LOCAL_PG_USER}`,\n '--health-interval', '5s',\n '--health-timeout', '5s',\n '--health-retries', '20',\n '--health-start-period', '10s',\n image,\n ]\n\n try {\n await exec(runtime, args, { timeout: CONTAINER_START_TIMEOUT_MS })\n } catch (err) {\n throw new Error(\n `Failed to start PostgreSQL container via ${runtime}: ${(err as Error).message}`,\n )\n }\n\n // Wait for readiness using actual pg connection\n const url = buildLocalUrl(port, password)\n await waitForPg(url, connect)\n\n return { runtime, containerName: name, port, url }\n}\n\n/**\n * Stop and remove the local PostgreSQL container.\n */\nexport async function stopLocalPg(\n runtime?: ContainerRuntime,\n name: string = CONTAINER_NAME,\n execFn: ExecFn = defaultExecFile,\n): Promise<void> {\n const rt = runtime ?? await detectRuntime(execFn)\n if (!rt) return\n\n try {\n await execFn(rt, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n } catch {\n // Container may not exist — ignore\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nasync function getContainerStatus(\n runtime: ContainerRuntime,\n name: string,\n execFn: ExecFn,\n): Promise<'running' | 'stopped' | 'none'> {\n try {\n const { stdout } = await execFn(\n runtime,\n ['inspect', '--format', '{{.State.Running}}', name],\n { timeout: RUNTIME_DETECT_TIMEOUT_MS },\n )\n return stdout.trim() === 'true' ? 'running' : 'stopped'\n } catch {\n return 'none'\n }\n}\n\nfunction buildLocalUrl(port: number, password: string): string {\n return `postgres://${LOCAL_PG_USER}:${password}@localhost:${port}/postgres`\n}\n\n/**\n * Poll PostgreSQL until it accepts connections.\n * Uses actual pg.Client connection rather than relying on container health checks\n * (which may not work on all runtimes).\n */\nasync function waitForPg(url: string, connectFn: ConnectFn): Promise<void> {\n for (let i = 0; i < READINESS_RETRIES; i++) {\n try {\n await connectFn(url)\n return\n } catch {\n await sleep(READINESS_INTERVAL_MS)\n }\n }\n throw new Error(\n `PostgreSQL at ${url} did not become ready within ${READINESS_RETRIES * READINESS_INTERVAL_MS / 1000}s`,\n )\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n","import pg from 'pg'\nimport { detectRuntime } from './local-pg.js'\nimport { pgClientConfig, resolveConnectTimeoutMs } from './db.js'\nimport { DB_PROBE_TIMEOUT_MS } from './constants.js'\nimport { ok, warn, dim, cmd, bold } from './ui.js'\nimport { redactUrls, describeFailure } from './utils/error.js'\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Result of a single connectivity check. */\nexport interface ConnCheckResult {\n reachable: boolean\n version?: string\n error?: string\n}\n\n/** Outcome of a single preflight check (DB connectivity or custom). */\nexport interface CheckEntry {\n label: string\n passed: boolean\n detail?: string\n error?: string\n hints?: string[]\n}\n\n/** Full report returned by Preflight.run(). */\nexport interface PreflightReport {\n passed: boolean\n checks: CheckEntry[]\n}\n\n/** Supabase CLI default PostgreSQL port. */\nconst SUPABASE_LOCAL_PORT = '54322'\n\n/** Standard PostgreSQL port. */\nconst DEFAULT_PG_PORT = '5432'\n\n// ─── Standalone helpers (remain exported for direct use / tests) ─────────────\n\n/**\n * `pg`'s messages for the two bounds this module sets. Neither says what was\n * being waited for, and \"timeout expired\" in particular reads like a bug\n * rather than a diagnosis.\n */\nconst CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i\nconst QUERY_TIMEOUT_RE = /query read timeout/i\n\n/**\n * Replace a bare driver timeout with something that says which wait elapsed.\n *\n * Left untouched when it is not one of ours: a server-side `statement_timeout`\n * or an OS-level ETIMEDOUT is a different failure and already reads clearly.\n */\nexport function describeTimeout(message: string, connectTimeoutMs: number, probeTimeoutMs: number): string {\n if (CONNECT_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(connectTimeoutMs / 1000)}s connecting — the host accepted the connection but never completed the handshake`\n }\n if (QUERY_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(probeTimeoutMs / 1000)}s waiting for server response — connected, but the server did not answer`\n }\n return message\n}\n\n/**\n * Test that a PostgreSQL database is reachable and return the server version.\n *\n * Both waits are bounded. Without that, a host that accepts the connection and\n * then goes silent blocks here forever, and the command produces no output at\n * all past the `Checks:` header (issue #44).\n */\nexport async function checkConnection(dbUrl: string): Promise<ConnCheckResult> {\n const connectTimeoutMs = resolveConnectTimeoutMs()\n let client: pg.Client | undefined\n try {\n client = new pg.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS))\n await client.connect()\n const { rows } = await client.query('SHOW server_version')\n const version = (rows[0] as Record<string, string>).server_version\n return { reachable: true, version }\n } catch (err) {\n return {\n reachable: false,\n error: describeTimeout(describeFailure(err), connectTimeoutMs, DB_PROBE_TIMEOUT_MS),\n }\n } finally {\n // A client that timed out mid-handshake still holds an open socket, which\n // keeps the event loop alive and hangs the process after the report has\n // already printed. end() on a never-connected client is a no-op, and a\n // failure closing it must not mask the real error above.\n try {\n await client?.end()\n } catch {\n // ignore\n }\n }\n}\n\n/** Errors that indicate the server IS running but rejecting the connection. */\nconst SERVER_REACHABLE_RE = /password authentication failed|does not exist|database .* does not exist|SSL.*required|no pg_hba\\.conf entry/i\n\n/**\n * Build context-aware hints when a local PostgreSQL is not reachable.\n * Detects Supabase CLI port, available container runtimes, etc.\n *\n * When `error` is provided and indicates the server IS running (auth failure,\n * missing database, SSL rejection), startup hints are suppressed in favour of\n * configuration hints.\n */\nexport async function buildLocalHints(dbUrl: string, error?: string): Promise<string[]> {\n const hints: string[] = []\n try {\n const urlObj = new URL(dbUrl)\n const isSupabasePort = urlObj.port === SUPABASE_LOCAL_PORT\n const isLocal = ['localhost', '127.0.0.1', '::1', ''].includes(urlObj.hostname)\n\n if (!isLocal) return hints\n\n // Server is reachable but rejecting — suggest config fixes, not startup.\n if (error && SERVER_REACHABLE_RE.test(error)) {\n hints.push(`Check the username and password in your database URL.`)\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. The default password is \"postgres\".`)\n }\n return hints\n }\n\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. Run ${cmd('\"supabase start\"')} to start your local Supabase instance.`)\n }\n\n const runtime = await detectRuntime()\n if (runtime) {\n hints.push(`${bold(runtime)} detected — you can start a PostgreSQL container manually.`)\n }\n\n if (!isSupabasePort) {\n hints.push(`Start PostgreSQL manually on port ${urlObj.port || DEFAULT_PG_PORT}.`)\n }\n } catch {\n // Invalid URL — no hints\n }\n return hints\n}\n\n/**\n * Hints for a connection that was bounded rather than refused.\n *\n * These apply to any host, unlike the local-startup hints — a stalled server\n * is just as likely to be a remote one behind a dropped tunnel, which is the\n * case that motivated bounding the wait at all (issue #44).\n */\nexport function buildTimeoutHints(): string[] {\n return [\n 'The host is listening but the database did not answer.',\n 'Check the database process is running and not paused, restarting, or overloaded.',\n 'Over a VPN or tunnel, check the connection is still up.',\n `Raise the bound with ${cmd('SUPAFORGE_CONNECT_TIMEOUT')} (in seconds) if the link is simply slow.`,\n ]\n}\n\n/**\n * Pick the right hints for a failed connection.\n *\n * A timeout and a refusal need different advice, and the local-startup hints\n * are actively misleading for a remote host that stalled.\n */\nexport async function buildConnectionHints(dbUrl: string, error?: string): Promise<string[]> {\n if (error && /timed out after \\d+s/.test(error)) return buildTimeoutHints()\n return buildLocalHints(dbUrl, error)\n}\n\n// ─── Preflight class ─────────────────────────────────────────────────────────\n\ntype LogFn = (msg: string) => void\n\n/**\n * Render a transient \"in progress\" line, or clear it when passed null.\n *\n * Separate from LogFn because these lines are overwritten rather than kept:\n * on a TTY the finished result replaces them, and off a TTY they are dropped\n * entirely so piped output and CI logs stay one line per check.\n */\nexport type PendingFn = (msg: string | null) => void\n\nconst defaultPending: PendingFn = (msg) => {\n if (!process.stdout.isTTY) return\n process.stdout.write(msg === null ? '\\r\\u001b[2K' : `\\r\\u001b[2K${msg}`)\n}\n\n/** Queued database to check during run(). */\ninterface DbEntry {\n label: string\n envName: string\n dbUrl: string\n}\n\n/** Custom check callback. Return null on success, or an error string on failure. */\nexport type CustomCheckFn = () => Promise<{ error?: string; detail?: string; hints?: string[] }>\n\n/** Queued custom check. */\ninterface CustomEntry {\n label: string\n fn: CustomCheckFn\n}\n\n/**\n * Composable preflight check runner.\n *\n * Usage:\n * ```ts\n * const pre = new Preflight('Diff preflight checks', (m) => this.log(m))\n * pre.addDatabase('Source', 'local', sourceUrl)\n * pre.addDatabase('Target', 'prod', targetUrl)\n * const report = await pre.run()\n * if (!report.passed) this.error('Aborted.', { exit: 1 })\n * ```\n *\n * For commands with extra checks (e.g. clone's pg_dump compat):\n * ```ts\n * pre.addCheck('pg_dump compatibility', async () => { ... })\n * ```\n */\nexport class Preflight {\n private readonly title: string\n private readonly log: LogFn\n private readonly pending: PendingFn\n private readonly databases: DbEntry[] = []\n private readonly customs: CustomEntry[] = []\n private readonly infoLines: Array<{ label: string; value: string }> = []\n\n constructor(title: string, log: LogFn, pending: PendingFn = defaultPending) {\n this.title = title\n this.log = log\n this.pending = pending\n }\n\n /** Register a database connectivity check. */\n addDatabase(label: string, envName: string, dbUrl: string): this {\n this.databases.push({ label, envName, dbUrl })\n return this\n }\n\n /** Add an informational line to the header (displayed after database lines). */\n addInfo(label: string, value: string): this {\n this.infoLines.push({ label, value })\n return this\n }\n\n /** Register a custom check (runs after all DB connectivity checks). */\n addCheck(label: string, fn: CustomCheckFn): this {\n this.customs.push({ label, fn })\n return this\n }\n\n /** Execute all registered checks, render results, and return the report. */\n async run(): Promise<PreflightReport> {\n const entries: CheckEntry[] = []\n const log = this.log\n\n // Header\n log(`\\n ${bold(this.title)}\\n`)\n for (const db of this.databases) {\n log(` ${db.label}: ${db.envName} ${dim(`(${redactUrls(db.dbUrl)})`)}`)\n }\n for (const info of this.infoLines) {\n log(` ${info.label}: ${info.value}`)\n }\n log('')\n log(' Checks:')\n\n // Database connectivity checks\n for (const db of this.databases) {\n // Named before the wait, not after: a connection that is merely slow\n // otherwise leaves the header on screen with no clue which of the two\n // environments is holding things up (issue #44).\n // The label is already the noun — \"Database\", \"Target\", \"Source\" — so\n // appending \"database\" gave \"Database database reachable\" (issue #97).\n this.pending(` ${dim(`… connecting to ${db.label.toLowerCase()}`)}`)\n const result = await checkConnection(db.dbUrl)\n this.pending(null)\n if (result.reachable) {\n log(` ${ok('✓')} ${db.label} reachable ${dim(`(PostgreSQL ${result.version})`)}`)\n entries.push({ label: db.label, passed: true, detail: `PostgreSQL ${result.version}` })\n } else {\n log(` ${warn('✗')} ${db.label} not reachable: ${redactUrls(describeFailure(result.error))}`)\n const hints = await buildConnectionHints(db.dbUrl, result.error)\n if (hints.length > 0) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: db.label, passed: false, error: result.error, hints })\n }\n }\n\n // Custom checks\n for (const custom of this.customs) {\n this.pending(` ${dim(`… ${custom.label}`)}`)\n const result = await custom.fn()\n this.pending(null)\n if (!result.error) {\n const suffix = result.detail ? ` ${dim(result.detail)}` : ''\n log(` ${ok('✓')} ${custom.label}${suffix}`)\n entries.push({ label: custom.label, passed: true, detail: result.detail })\n } else {\n log(` ${warn('✗')} ${custom.label}: ${redactUrls(describeFailure(result.error))}`)\n if (result.hints?.length) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of result.hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: custom.label, passed: false, error: result.error, hints: result.hints })\n }\n }\n\n const passed = entries.every(e => e.passed)\n log('')\n if (!passed) {\n log(` ${warn('Some checks failed.')} Fix the issues above first.\\n`)\n } else {\n log(` ${ok('All checks passed.')}\\n`)\n }\n\n return { passed, checks: entries }\n }\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\n/**\n * SQLSTATEs that mean the thing queried isn't there: no such table or view\n * (42P01), schema (3F000) or function (42883). A project without pg_cron or\n * Realtime answers with one of these, and that is a genuine \"nothing to\n * compare\".\n *\n * Nothing else is. A wrong password, a dropped connection or a permission\n * error read as \"nothing there\" made the source look empty — and the target's\n * webhooks, cron jobs and publications then looked extra and were dropped.\n */\nconst MISSING_OBJECT_CODES = new Set(['42P01', '3F000', '42883'])\n\nexport function isMissingObject(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' && MISSING_OBJECT_CODES.has(code)\n}\n\n/** Run a read that may legitimately find nothing, returning `absent` only then. */\nexport async function readOrAbsent<T>(read: () => Promise<T>, absent: T): Promise<T> {\n try {\n return await read()\n } catch (err) {\n if (isMissingObject(err)) return absent\n throw err\n }\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, readOrAbsent, 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 // No schema_migrations table means no records; any other failure is an error.\n return readOrAbsent(async () => await this.queryFn(dbUrl, MIGRATIONS_SQL) as unknown as MigrationRecord[], [])\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":";;;;;;;;;;;;;;;AAIA,IAAM,YAAY;AASX,SAAS,WAAW,SAAyB;AAClD,SAAO,QAAQ,QAAQ,WAAW,CAAC,GAAG,QAAgB,SAAiB;AACrE,UAAM,SAAS,KAAK,YAAY,GAAG;AACnC,QAAI,WAAW,GAAI,QAAO,SAAS;AACnC,UAAM,QAAQ,KAAK,MAAM,GAAG,MAAM;AAClC,UAAM,WAAW,KAAK,MAAM,MAAM;AAClC,UAAM,WAAW,MAAM,QAAQ,GAAG;AAClC,QAAI,aAAa,GAAI,QAAO,SAAS;AACrC,WAA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AI,EAAE,OAAO,CAAC;AAKzD,MAAI,SAAS,UAAU,GAAG,WAAW,KAAK,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":["pg","pg","pg","pg"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/table-filter.ts","../src/types/drift.ts","../src/promote.ts","../src/pg-errors.ts","../src/checks/roles.ts"],"sourcesContent":["import type { SupaForgeConfig } from '../types/config.js'\nimport { parseFlagList, globToRegExp } from './strings.js'\n\n/**\n * Which tables a diff should look at.\n *\n * Empty/undefined means \"everything\", which is the default and what every\n * existing caller gets. Patterns are passed to @dbdiff/cli verbatim, so its\n * glob support (`*`, `?`) works here too.\n */\nexport interface TableFilter {\n /** Only compare these. Undefined means all. */\n tables?: string[]\n /** Never compare these. Applied after `tables`. */\n excludeTables?: string[]\n}\n\n/**\n * Split a repeatable table flag into individual patterns.\n *\n * `--tables=a,b --tables=c` and `--tables=a --tables=b --tables=c` mean the\n * same thing. The splitting itself is shared with every other repeatable list\n * flag; this name is what the table call sites read by.\n */\nexport const parseTableList = parseFlagList\n\n/**\n * Resolve the effective filter from config and CLI flags.\n *\n * `tables` is an *override*: `--tables=orders` means \"only orders\", so a\n * broader list in config must not widen it back out. `excludeTables` is a\n * *union*: an exclusion is a safety rail, and the two sources agreeing to\n * exclude more is never the surprising direction. This mirrors how `--skip`\n * already merges with `checks.exclude`.\n *\n * Tolerates a malformed config — a non-array yields no filter rather than\n * throwing, so a bad config compares everything instead of taking the scan\n * down.\n */\nexport function resolveTableFilter(\n config: SupaForgeConfig | undefined,\n cli: { tables?: string[]; excludeTables?: string[] } = {},\n): TableFilter {\n const cliTables = parseTableList(cli.tables)\n const cliExclude = parseTableList(cli.excludeTables)\n\n const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : []\n const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : []\n\n const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables)\n const excludeTables = [...new Set([...parseTableList(configExclude), ...cliExclude])]\n\n const filter: TableFilter = {}\n if (tables.length > 0) filter.tables = tables\n if (excludeTables.length > 0) filter.excludeTables = excludeTables\n return filter\n}\n\n/** True when the filter would narrow anything. */\nexport function isFiltered(filter: TableFilter | undefined): boolean {\n return Boolean(filter?.tables?.length || filter?.excludeTables?.length)\n}\n\n/**\n * One line describing what the run is scoped to, or null when it is not\n * scoped at all.\n *\n * Printed before the scan because a narrowed run must never look like a full\n * one — particularly with `--apply`, where the difference is which statements\n * get executed. It also names the layers the filter reaches: a table is a\n * concept the schema and data checks have and the others do not, so `diff\n * --tables=orders` still compares every RLS policy and storage bucket.\n */\nexport function describeTableFilter(filter: TableFilter | undefined): string | null {\n if (!isFiltered(filter)) return null\n const parts: string[] = []\n if (filter?.tables?.length) parts.push(`only ${filter.tables.join(', ')}`)\n if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(', ')}`)\n return `Scoped to ${parts.join(', ')} — applies to the schema and data checks; other layers are unfiltered.`\n}\n\n/**\n * Does `name` match a @dbdiff/cli-style glob pattern?\n *\n * Only `*` and `?` are special, matching dbdiff's own syntax. Used to narrow\n * the Reference Data table list locally, since that check picks its tables\n * from config before dbdiff is invoked and so cannot rely on `--tables` alone.\n *\n * Comparison is case-insensitive and tolerant of a schema qualifier: a pattern\n * of `orders` matches `public.orders`, because that is what a user means when\n * they name a table without a schema.\n */\nexport function matchesPattern(name: string, pattern: string): boolean {\n const candidates = [name.toLowerCase()]\n const dot = name.indexOf('.')\n if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase())\n\n const rx = globToRegExp(pattern.toLowerCase())\n return candidates.some(c => rx.test(c))\n}\n\n/**\n * Apply a filter to a concrete list of table names.\n *\n * Include first, then exclude — so `--tables='billing_*' --exclude-tables='*_audit'`\n * reads left to right the way it is written.\n */\nexport function applyTableFilter(names: string[], filter: TableFilter | undefined): string[] {\n if (!isFiltered(filter)) return names\n\n let out = names\n if (filter?.tables?.length) {\n out = out.filter(n => filter.tables!.some(p => matchesPattern(n, p)))\n }\n if (filter?.excludeTables?.length) {\n out = out.filter(n => !filter.excludeTables!.some(p => matchesPattern(n, p)))\n }\n return out\n}\n","export const CHECK_NAMES = [\n 'schema', 'rls', 'rls-coverage', 'edge-functions', 'storage', 'auth', 'cron', 'data',\n 'webhooks', 'realtime', 'vault', 'extensions', 'migrations', 'roles',\n] as const\n\nexport type CheckName = (typeof CHECK_NAMES)[number]\n\nexport type Severity = 'critical' | 'warning' | 'info'\n\nexport const CHECK_META: Record<CheckName, { number: number; emoji: string; label: string }> = {\n 'schema': { number: 1, emoji: '🗄️', label: 'Schema' },\n 'rls': { number: 2, emoji: '🔒', label: 'RLS Policies' },\n 'rls-coverage': { number: 3, emoji: '🛡️', label: 'RLS Coverage' },\n 'edge-functions': { number: 4, emoji: '⚡', label: 'Edge Functions' },\n 'storage': { number: 5, emoji: '🪣', label: 'Storage' },\n 'auth': { number: 6, emoji: '🔑', label: 'Auth Config' },\n 'cron': { number: 7, emoji: '⏰', label: 'Cron Jobs' },\n 'data': { number: 8, emoji: '🗃️', label: 'Reference Data' },\n 'webhooks': { number: 9, emoji: '⚡🔗', label: 'Webhooks' },\n 'realtime': { number: 10, emoji: '📡', label: 'Realtime Publications' },\n 'vault': { number: 11, emoji: '🔐', label: 'Vault Secrets' },\n 'extensions': { number: 12, emoji: '🧩', label: 'Postgres Extensions' },\n 'migrations': { number: 13, emoji: '📋', label: 'Migration History' },\n 'roles': { number: 14, emoji: '👤', label: 'Postgres Roles & Grants' },\n}\n\n/**\n * Whether a check compares the two environments, or reports on the target's\n * own posture regardless of what it is being compared against.\n *\n * Two of the fourteen are not comparisons:\n *\n * - **rls-coverage** reads only the target, listing tables with RLS disabled.\n * It reports the same tables whichever pair you diff.\n * - **migrations** compares local migration *files* against the target's\n * tracking table — a project-level observation, not a source-to-target one.\n *\n * Both are real and useful findings, but neither is drift. Counting them\n * toward the drift score meant diffing an environment against *itself* could\n * never score 100, so \"no drift detected\" stopped being a trustworthy signal\n * and the score was useless as a synchronisation measure (issue #40).\n */\nexport type CheckKind = 'comparison' | 'posture'\n\nexport const CHECK_KIND: Record<CheckName, CheckKind> = {\n 'schema': 'comparison',\n 'rls': 'comparison',\n 'rls-coverage': 'posture',\n 'edge-functions': 'comparison',\n 'storage': 'comparison',\n 'auth': 'comparison',\n 'cron': 'comparison',\n 'data': 'comparison',\n 'webhooks': 'comparison',\n 'realtime': 'comparison',\n 'vault': 'comparison',\n 'extensions': 'comparison',\n 'migrations': 'posture',\n 'roles': 'comparison',\n}\n\n/** Checks that compare source against target. */\nexport function isComparisonCheck(name: CheckName): boolean {\n return CHECK_KIND[name] === 'comparison'\n}\n\n/** API-based sync action for non-SQL drift fixes. */\nexport interface SyncAction {\n /** HTTP method */\n method: 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n /** Full URL (resolved at scan time, using target projectRef). */\n url: string\n /** Request headers (Authorization injected by promote). */\n headers?: Record<string, string>\n /** JSON body to send. */\n body?: unknown\n /** Human-readable description of what this action does. */\n label: string\n}\n\nexport interface DriftIssue {\n id: string\n check: CheckName\n severity: Severity\n title: string\n description: string\n sourceValue?: unknown\n targetValue?: unknown\n sql?: { up: string; down: string }\n /** API-based sync action (for non-SQL fixes like storage buckets, auth config, edge functions). */\n action?: SyncAction\n /**\n * Why this difference has no automatic fix, and what to do instead.\n *\n * For findings that are real but cannot be applied: a Vault secret whose\n * value exists only in the source, an Edge Function that needs deploying.\n * Set it rather than inventing SQL — the vault check used to emit\n * `vault.create_secret('PLACEHOLDER_VALUE', …)`, and `--apply` ran it, which\n * left the target holding a live secret with a bogus value (issue #91).\n *\n * Reported as the skip reason at apply time, so the user is told the command\n * instead of being told there is nothing to be done.\n */\n manualOnly?: string\n /**\n * Why this fix waits for --allow-destructive, when that isn't visible from\n * its SQL: a webhook is a trigger, and dropping a trigger usually isn't.\n */\n destructive?: string\n}\n\nexport interface CheckResult {\n check: CheckName\n status: 'clean' | 'drifted' | 'error' | 'skipped'\n issues: DriftIssue[]\n error?: string\n /**\n * Why the check declined to run — missing credentials, an absent extension,\n * nothing configured to compare.\n *\n * Present only when status is 'skipped'. Without it a skipped layer was\n * indistinguishable from a clean one in both the terminal output and the\n * JSON payload (issue #42).\n */\n skipReason?: string\n /**\n * Findings left out because another check reports the same object — the\n * schema check's policy findings where the RLS check has them (issue #97),\n * its extension findings where the extensions check has them. Counted so\n * the difference from the live progress line is explained.\n */\n folded?: Array<{ count: number; into: CheckName }>\n durationMs: number\n}\n\nexport interface ScanResult {\n timestamp: string\n source: string\n target: string\n checks: CheckResult[]\n /**\n * How closely the two environments match, 0–100, over the comparison checks\n * only. Posture findings are excluded so a genuinely synchronised pair can\n * reach 100 even when it carries pre-existing findings on both sides.\n */\n score: number\n /**\n * The target's own security and tracking posture, 0–100, over the posture\n * checks only. `null` when none of them ran.\n */\n postureScore: number | null\n summary: { total: number; critical: number; warning: number; info: number }\n}\n","import pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport type { ScanResult, SyncAction } from './types/drift'\nimport { errMsg } from './utils/error'\nimport { ABSENT_ON_TARGET, EXTENSION_UNAVAILABLE, UNDEFINED_COLUMN, sqlState } from './pg-errors.js'\nimport { destructiveReason } from './dbdiff'\nimport { parseStatements } from './sql-ast'\nimport {\n orderStatements, referencedTables,\n createdPolicies, createsOnlyPolicies,\n createdTriggers, createsOnlyTriggers,\n sqlSkeleton, bareName, identifierMatcher,\n} from './sql-deps.js'\nimport { splitSqlStatements, isCommentOnly } from './utils/sql-split.js'\nimport { applyTableFilter, isFiltered, type TableFilter } from './utils/table-filter.js'\nimport { isComparisonCheck } from './types/drift.js'\nimport { matchesGlob } from './utils/strings.js'\n\nexport type FetchFn = (url: string, init?: RequestInit) => Promise<Response>\n\nexport interface PromoteOptions {\n /** Target database connection string */\n dbUrl: string\n /** The scan result with SQL fixes to apply */\n scanResult: ScanResult\n /** Only promote specific checks */\n checks?: string[]\n /** Also apply posture fixes; off by default — see planWork */\n applyPosture?: boolean\n /** Dry-run mode — print SQL without executing */\n dryRun?: boolean\n /**\n * Permit statements that destroy data (DROP TABLE, DROP COLUMN).\n *\n * Off by default: those are reported as drift but skipped at apply time, so\n * `supaforge diff --apply` can never drop a table or column without the user\n * asking for it. Set by the `--allow-destructive` flag.\n */\n allowDestructive?: boolean\n /**\n * The table scope the diff ran under.\n *\n * Needed at apply time as well as scan time. `--tables` reaches dbdiff, which\n * scopes *tables* only, so a narrowed fix set still arrives carrying the\n * views, triggers and indexes that hang off the tables it excluded. Applying\n * those fails, because the column or table they need was deliberately not\n * added (issue #48).\n */\n tableFilter?: TableFilter\n /**\n * Apply only these issues, by id. Globs allowed. Undefined means all.\n *\n * Every issue in `--json` already carries a stable id, so a review step can\n * pick a subset out of one diff and apply exactly that, with no new matching\n * syntax to learn.\n */\n only?: string[]\n /**\n * Run every SQL fix in one transaction, rolling the whole set back if any\n * statement fails. On by default — see `executeSql`.\n */\n transactional?: boolean\n /** Fetch function for API-based sync actions (defaults to globalThis.fetch) */\n fetchFn?: FetchFn\n}\n\n/** Where a fix came from: which check reported it, and under which issue id. */\ninterface FixOrigin {\n check: string\n issueId: string\n}\n\nexport type PlannedSql = FixOrigin & { sql: string }\ntype PlannedAction = FixOrigin & { action: SyncAction }\ntype PlannedSkip = FixOrigin & { reason: string }\n\nexport interface PromoteResult {\n applied: (FixOrigin & { sql?: string; action?: string })[]\n skipped: PlannedSkip[]\n errors: (FixOrigin & { error: string })[]\n /**\n * Fixes that ran and were then undone because a later statement in the same\n * transaction failed. Reported separately from `applied`, which only ever\n * lists what is actually in the target now.\n */\n rolledBack?: (FixOrigin & { sql?: string })[]\n}\n\ninterface PlannedWork {\n sqlStatements: PlannedSql[]\n apiActions: PlannedAction[]\n skipped: PlannedSkip[]\n}\n\n/** What `planWork` needs to know beyond the scan result itself. */\nexport interface PlanOptions {\n checks?: string[]\n /**\n * Also apply fixes from the checks that judge the target on its own rather\n * than comparing it to the source. Off by default — see planWork.\n */\n applyPosture?: boolean\n allowDestructive?: boolean\n tableFilter?: TableFilter\n only?: string[]\n}\n\n/**\n * Why a fix cannot be applied under the current scope, or null when it can.\n *\n * A fix set narrowed by `--tables` is internally inconsistent by construction:\n * dbdiff's `--tables` covers tables, so the views, triggers and indexes\n * belonging to an excluded table survive the filter while the table change they\n * need does not. Naming the excluded table is the difference between a fix a\n * user can reason about and an error they cannot (issue #48).\n */\nexport function outOfScopeReason(sql: string, filter: TableFilter | undefined): string | null {\n if (!isFiltered(filter)) return null\n\n const referenced = referencedTables(sql)\n if (referenced.length === 0) return null\n\n const excluded = referenced.filter(t => applyTableFilter([t], filter).length === 0)\n if (excluded.length === 0) return null\n\n const names = excluded.map(t => `'${t}'`).join(', ')\n const flag = filter?.tables?.length ? '--tables' : '--exclude-tables'\n const noun = excluded.length === 1 ? 'table' : 'tables'\n return `Depends on ${noun} ${names}, excluded by ${flag}`\n}\n\n/** Does this issue id match any of the `--only` selectors? */\nfunction isSelected(issueId: string, only: string[] | undefined): boolean {\n if (!only?.length) return true\n return only.some(pattern => matchesGlob(issueId, pattern))\n}\n\n/**\n * `--only` plus the \"default grants to take back\" of every table, view or\n * routine the selection creates.\n *\n * A new table picks up the target's default privileges — on Supabase,\n * everything to anon and authenticated — and the roles check's\n * `roles-grant-default-<role>.<schema>.<table>` fixes take back what the\n * source doesn't grant. Selecting the table without them left it open to the\n * Data API, so they come along with it.\n */\nfunction withDefaultGrantRevokes(scanResult: ScanResult, only: string[] | undefined): string[] | undefined {\n if (!only?.length) return only\n const issues = scanResult.checks.flatMap(c => c.issues)\n const created = new Set(issues\n .filter(i => i.sql?.up && isSelected(i.id, only))\n .flatMap(i => relationsCreatedBy(i.sql!.up)))\n if (created.size === 0) return only\n const companions = issues\n .filter(i => i.id.startsWith('roles-grant-default-')\n && [...created].some(rel => rel.endsWith('(')\n // A routine, by schema and name: the fix spells its arguments as\n // written (`p integer DEFAULT 1`), the finding as PostgreSQL\n // identifies them (`p integer`).\n ? i.id.toLowerCase().includes(`.${rel}`)\n : i.id.toLowerCase().endsWith(`.${rel}`)))\n .map(i => i.id)\n return [...only, ...companions]\n}\n\n/** `schema.name` (lower case, `public` when unqualified) of each table and view the SQL creates, and `schema.name(` of each routine. */\nfunction relationsCreatedBy(sql: string): string[] {\n const statements = parseStatements(sql)\n if (!statements) return []\n return statements.flatMap(({ kind, node }) => {\n if (kind === 'CreateFunctionStmt') {\n // `schema.name(`, matched against routine ids by prefix.\n const parts = (node.funcname as Array<{ String?: { sval: string } }> ?? []).map(n => n.String?.sval ?? '')\n const name = parts.at(-1)\n return name ? [`${(parts.length > 1 ? parts.at(-2)! : 'public').toLowerCase()}.${name.toLowerCase()}(`] : []\n }\n const rel = kind === 'CreateStmt' ? node.relation\n : kind === 'ViewStmt' ? node.view\n : kind === 'CreateTableAsStmt' ? node.into?.rel\n : undefined\n return rel?.relname ? [`${(rel.schemaname || 'public').toLowerCase()}.${String(rel.relname).toLowerCase()}`] : []\n })\n}\n\n/**\n * Decide what happens to one issue: run its SQL, call its API, or skip it.\n *\n * Split out of planWork so each reason a fix is withheld is one readable\n * branch, and so the decision can be asserted directly in tests.\n */\nfunction classifyIssue(\n issue: { id: string; sql?: { up: string }; action?: SyncAction; manualOnly?: string; destructive?: string },\n options: PlanOptions,\n recreatedPolicies: ReadonlySet<string> = new Set(),\n): { kind: 'sql'; sql: string } | { kind: 'api'; action: SyncAction } | { kind: 'skip'; reason: string } {\n if (!isSelected(issue.id, options.only)) {\n return { kind: 'skip', reason: 'Not selected by --only' }\n }\n\n // Real, but not for an automatic apply: the finding says what to do.\n if (issue.manualOnly) return { kind: 'skip', reason: issue.manualOnly }\n\n if (!issue.sql?.up) {\n // A DELETE removes a bucket or an Edge Function as surely as DROP TABLE\n // removes a table, so it waits for the same flag.\n if (issue.action?.method === 'DELETE' && !options.allowDestructive) {\n return { kind: 'skip', reason: `Destructive — ${issue.action.label}; re-run with --allow-destructive to apply` }\n }\n if (issue.action) return { kind: 'api', action: issue.action }\n // A check that knows why it cannot offer a fix says so; \"nothing\n // available\" on its own leaves the user with no next step.\n return { kind: 'skip', reason: issue.manualOnly ?? 'No SQL fix or API action available' }\n }\n\n if (!options.allowDestructive) {\n const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies)\n if (why) {\n return { kind: 'skip', reason: `Destructive — ${why}; re-run with --allow-destructive to apply` }\n }\n }\n\n const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter)\n if (outOfScope) return { kind: 'skip', reason: outOfScope }\n\n return { kind: 'sql', sql: issue.sql.up }\n}\n\n/**\n * Policies that fixes in this apply create — the ones that will actually run.\n *\n * Lets the destructive gate tell a policy being removed from one being\n * replaced across two fixes: a column type change drops the policies reading\n * the column, and the policy's own fix creates the new definition once the\n * type has changed (they cannot be one statement, because the new definition\n * is not valid until then). Counted only from fixes that are selected and not\n * held back themselves, so `--only` a column change without its policy fix is\n * still gated as the removal it would be.\n */\nfunction policiesCreatedBySelectedFixes(checks: ScanResult['checks'], options: PlanOptions): Set<string> {\n const created = new Set<string>()\n for (const check of checks) {\n // Posture fixes do not run unless asked for (see planWork), so what they\n // would create cannot stand in for a policy another fix drops.\n const askedForExplicitly = options.checks?.includes(check.check) ?? false\n if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue\n for (const issue of check.issues) {\n const sql = issue.sql?.up\n if (!sql || !isSelected(issue.id, options.only)) continue\n if (!options.allowDestructive && destructiveReason(sql)) continue\n if (outOfScopeReason(sql, options.tableFilter)) continue\n for (const key of createdPolicies(sql)) created.add(key)\n }\n }\n return created\n}\n\n/**\n * Sort a scan result's issues into what can be run as SQL, what needs an API\n * call, and what has to be skipped.\n *\n * Kept separate from promote() so the decision of *what* to apply is one\n * self-contained, directly testable pass, and promote() is left to the\n * execution.\n *\n * The SQL comes back in dependency order rather than the order the checks\n * reported it — see `orderStatements`.\n */\nexport function planWork(scanResult: ScanResult, options: PlanOptions = {}): PlannedWork {\n options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) }\n const plan: PlannedWork = { sqlStatements: [], apiActions: [], skipped: [] }\n\n const relevant = scanResult.checks.filter(\n c => c.status === 'drifted' && (!options.checks || options.checks.includes(c.check)),\n )\n const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options)\n // What the destructive gate keeps, as the definitions that would put it\n // back — the objects still there after the apply.\n const keptBack: Array<{ issueId: string; definition: string }> = []\n\n for (const checkResult of relevant) {\n // A posture check judges the target on its own and fires identically\n // whichever pair you diff, so its fix is not a reconciliation — applying it\n // changes the target away from the source and *creates* drift. Enabling RLS\n // on a table the source leaves open is the clear case: the next diff reports\n // \"RLS enabled unexpectedly\", the next sync switches it back off, and the\n // coverage check flags it again, forever. Worse, RLS enabled without the\n // policies to go with it denies every row to non-owners, so a posture fix\n // applied to a working table can take it offline.\n //\n // Naming the check explicitly (--check=rls-coverage) or passing\n // --apply-posture is taken as asking for it on purpose.\n const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false\n if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {\n for (const issue of checkResult.issues) {\n plan.skipped.push({\n check: checkResult.check,\n issueId: issue.id,\n reason: 'Posture finding about the target, not drift from the source — '\n + 'applying it would create drift. Use --apply-posture to apply anyway.',\n })\n }\n continue\n }\n\n for (const issue of checkResult.issues) {\n const at = { check: checkResult.check, issueId: issue.id }\n const outcome = classifyIssue(issue, options, recreatedPolicies)\n\n if (outcome.kind === 'sql') plan.sqlStatements.push({ ...at, sql: outcome.sql })\n else if (outcome.kind === 'api') plan.apiActions.push({ ...at, action: outcome.action })\n else {\n plan.skipped.push({ ...at, reason: outcome.reason })\n if (outcome.reason.startsWith('Destructive') && issue.sql?.down) {\n keptBack.push({ issueId: issue.id, definition: issue.sql.down })\n }\n }\n }\n }\n\n plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant))\n // DBDiff's fixes keep the order DBDiff wrote them in, which it took from\n // the catalog; the others are placed around them — see orderStatements().\n const dbdiffOrder = new Map(plan.sqlStatements.filter(s => s.check === 'schema').map((s, i) => [s, i]))\n plan.sqlStatements = orderStatements(plan.sqlStatements, s => s.sql, s => dbdiffOrder.get(s))\n plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped)\n return plan\n}\n\n/** `DROP TYPE|DOMAIN|FUNCTION|PROCEDURE|SEQUENCE [IF EXISTS] <name>`, capturing the name. */\nconst DROPS_SUPPORTING_OBJECT = /^\\s*DROP\\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\\s+(?:IF\\s+EXISTS\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+))?)/i\n\n/**\n * Hold back the drop of a type, domain, routine or sequence that something\n * the destructive gate keeps still uses.\n *\n * The source no longer has a table and the enum its column was typed by; the\n * table's DROP is held back without --allow-destructive, and the enum's DROP\n * then fails — `cannot drop type ... because other objects depend on it` —\n * taking every other fix in the transaction with it. A kept object's own\n * definition (its fix's DOWN) says what it uses. Only a fix that does nothing\n * but drop such objects is held back; holding back more is the safe side.\n */\nfunction holdBackDropsStillInUse(\n statements: PlannedSql[],\n keptBack: Array<{ issueId: string; definition: string }>,\n skipped: PlannedWork['skipped'],\n downs: ReadonlyMap<string, string> = new Map(),\n): PlannedSql[] {\n const kept = keptBack.map(k => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }))\n let remaining = statements\n\n // Until nothing more is held back: what one held-back drop keeps can keep\n // something else — a column kept keeps its composite type, and the\n // composite keeps the enum it holds.\n for (let changed = kept.length > 0; changed;) {\n changed = false\n remaining = remaining.filter((statement) => {\n const names = droppedSupportingObjects(statement.sql)\n if (names.length === 0) return true\n\n const user = kept.find(k => names.some(n => identifierMatcher(bareName(n)).test(k.skeleton)))\n if (!user) return true\n skipped.push({\n check: statement.check,\n issueId: statement.issueId,\n reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; `\n + 're-run with --allow-destructive to apply both',\n })\n const definition = downs.get(statement.issueId)\n if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) })\n changed = true\n return false\n })\n }\n return remaining\n}\n\n/** The names a fix drops, when all it does is drop types, domains, routines or sequences. */\nfunction droppedSupportingObjects(sql: string): string[] {\n const parts = splitSqlStatements(sql).filter(s => !isCommentOnly(s))\n const names = parts.map(s => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1])\n return names.length > 0 && names.every(n => n !== undefined) ? names as string[] : []\n}\n\n/** Each issue's DOWN — the definition of what it would drop — by issue id. */\nfunction downsOf(checks: ScanResult['checks']): Map<string, string> {\n const downs = new Map<string, string>()\n for (const check of checks) {\n for (const issue of check.issues) {\n if (issue.sql?.down) downs.set(issue.id, issue.sql.down)\n }\n }\n return downs\n}\n\n/**\n * Remove a fix that an earlier statement in the same set already performs.\n *\n * Two layers can legitimately produce the same object. The schema check's SQL\n * comes from `@dbdiff/cli`, which models RLS policies as of 3.0.0-rc.10 and has\n * always modelled triggers; the rls check writes its own policies, and since\n * issue #77 the webhooks check writes its own triggers. Applied together the\n * second fails — `policy ... already exists`, `trigger ... already exists` —\n * and because the apply is transactional that single collision discards every\n * other fix with it. Reported twice now: a new policy that could not be synced\n * at all (#67), and a full apply rolling back six correct schema fixes (#77).\n *\n * Run over the statements in execution order, after `orderStatements`, so\n * \"already created\" means created by something that genuinely runs first rather\n * than merely reported first.\n *\n * Only a statement that does nothing else is dropped. The schema check bundles\n * its policy with the table and the ENABLE ROW LEVEL SECURITY beside it, and its\n * trigger with the function the trigger calls; losing either would be far worse\n * than the collision.\n */\nfunction dropDuplicateObjectFixes(\n statements: PlannedSql[],\n skipped: PlannedWork['skipped'],\n): PlannedSql[] {\n const kinds = [\n { what: 'policy', created: createdPolicies, onlyThis: createsOnlyPolicies, seen: new Set<string>() },\n { what: 'trigger', created: createdTriggers, onlyThis: createsOnlyTriggers, seen: new Set<string>() },\n ]\n const kept: PlannedSql[] = []\n\n for (const statement of statements) {\n const duplicate = kinds.find((kind) => {\n const names = kind.created(statement.sql)\n return names.length > 0\n && names.every(n => kind.seen.has(n))\n && kind.onlyThis(statement.sql)\n })\n\n if (duplicate) {\n skipped.push({\n check: statement.check,\n issueId: statement.issueId,\n reason: `Already created by the schema fix for the same ${duplicate.what}`,\n })\n continue\n }\n\n for (const kind of kinds) {\n for (const name of kind.created(statement.sql)) kind.seen.add(name)\n }\n kept.push(statement)\n }\n\n return kept\n}\n\n/**\n * Run the planned SQL against the target on a single connection.\n *\n * Transactional by default. PostgreSQL supports transactional DDL, so a fix set\n * either lands whole or not at all, and a failure leaves the target exactly as\n * it was. The alternative — the behaviour before issue #48 — left a shared\n * environment matching neither the source nor its own previous state, and the\n * person running it having to work out which fixes had landed before retrying.\n *\n * `transactional: false` restores the statement-at-a-time behaviour, for the\n * cases where partial progress is genuinely wanted.\n */\nasync function executeSql(\n dbUrl: string,\n statements: PlannedSql[],\n result: PromoteResult,\n transactional: boolean,\n): Promise<void> {\n if (statements.length === 0) return\n\n const client = new pg.Client(pgClientConfig(dbUrl))\n await client.connect()\n try {\n if (transactional) await runInTransaction(client, statements, result)\n else await runIndependently(client, statements, result)\n } finally {\n await client.end()\n }\n}\n\n/**\n * Run fixes exactly as a transactional apply would — dependency-order input,\n * one savepoint per fix, a fix whose extension or object is missing left out\n * and the rest kept — against any database. The proof replays a migration\n * this way, so it rehearses what the apply will do rather than a stricter\n * script that stopped at the first fix the server could not hold.\n */\nexport async function runLikeApply(dbUrl: string, statements: PlannedSql[]): Promise<PromoteResult> {\n const result: PromoteResult = { applied: [], skipped: [], errors: [] }\n await executeSql(dbUrl, statements, result, true)\n return result\n}\n\n/** One statement at a time: a failure is recorded and the rest still run. */\nasync function runIndependently(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<void> {\n for (const stmt of statements) {\n try {\n await client.query(stmt.sql)\n result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n } catch (err) {\n result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) })\n }\n }\n}\n\n/**\n * Does this fix consist only of `ALTER TYPE ... ADD VALUE`?\n *\n * PostgreSQL lets that run inside a transaction but not the new label be\n * *used* there until it commits:\n *\n * ERROR: unsafe use of new value \"refunded\" of enum type order_state\n * HINT: New enum values must be committed before they can be used.\n *\n * and the same apply often uses it straight away — a column default, or a\n * reference-data row the data check inserts.\n */\nexport function isEnumValueAddition(sql: string): boolean {\n const statements = splitSqlStatements(sql).filter(s => !isCommentOnly(s))\n return statements.length > 0\n && statements.every(s => /^\\s*ALTER\\s+TYPE\\s+\\S+\\s+ADD\\s+VALUE\\b/i.test(sqlSkeleton(s)))\n}\n\n/**\n * All statements in one transaction, each fix under a savepoint of its own.\n *\n * A fix that fails because the target lacks something it needs — an extension\n * the server does not ship, the type or schema that extension would have\n * created, a table or column an earlier such fix would have added — is undone\n * on its own and reported as an error, and the rest still commit. One column\n * typed `extensions.vector` on a target without pgvector used to roll back\n * every unrelated fix in the apply, which left nothing synced at all.\n *\n * Every other failure still rolls back everything. What ran before it moves to\n * `rolledBack` rather than `applied`, because none of it is in the target any\n * more.\n *\n * Enum label additions go first, in a transaction of their own that commits,\n * so the rest can use the new labels — see isEnumValueAddition. They are\n * additive and idempotent (`IF NOT EXISTS`), so keeping them when the rest\n * rolls back leaves nothing half-done; they are reported as applied because\n * they are.\n */\nasync function runInTransaction(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<void> {\n const additions = statements.filter(s => isEnumValueAddition(s.sql))\n const rest = statements.filter(s => !isEnumValueAddition(s.sql))\n\n if (additions.length > 0 && !(await runBatch(client, additions, result))) return\n await runBatch(client, rest, result)\n}\n\n/**\n * Why a fix cannot apply to this target at all, or undefined when the failure\n * is something else.\n *\n * Only \"does not exist\" failures qualify, and for `CREATE EXTENSION`, an\n * extension the server does not ship.\n */\nexport function unmetDependency(sql: string, err: unknown): string | undefined {\n const code = sqlState(err)\n if (!code) return undefined\n if (/^\\s*CREATE\\s+EXTENSION\\b/i.test(sqlSkeleton(sql))) {\n return EXTENSION_UNAVAILABLE.has(code) ? 'this server does not ship it' : undefined\n }\n if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {\n return 'it needs something the target does not have'\n }\n return undefined\n}\n\n/** One transaction; true when it committed. */\nasync function runBatch(\n client: pg.Client,\n statements: PlannedSql[],\n result: PromoteResult,\n): Promise<boolean> {\n if (statements.length === 0) return true\n const done: PromoteResult['applied'] = []\n await client.query('BEGIN')\n\n // Fixes whose dependency is missing are tried again once the others have\n // run, in case what they need comes later in the batch. Only the ones still\n // failing when a pass makes no progress are left out.\n let pending = statements\n let unmet: Array<{ stmt: PlannedSql; err: unknown; why: string }> = []\n while (pending.length > 0) {\n unmet = []\n for (const stmt of pending) {\n await client.query('SAVEPOINT sf_fix')\n try {\n await client.query(stmt.sql)\n await client.query('RELEASE SAVEPOINT sf_fix')\n done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n } catch (err) {\n const why = unmetDependency(stmt.sql, err)\n if (why && await client.query('ROLLBACK TO SAVEPOINT sf_fix').then(() => true, () => false)) {\n unmet.push({ stmt, err, why })\n continue\n }\n await client.query('ROLLBACK').catch(() => {})\n result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) })\n result.rolledBack = [...(result.rolledBack ?? []), ...done]\n return false\n }\n }\n if (unmet.length === pending.length) break\n pending = unmet.map(u => u.stmt)\n }\n\n await client.query('COMMIT')\n result.applied.push(...done)\n for (const { stmt, err, why } of unmet) {\n result.errors.push({\n check: stmt.check,\n issueId: stmt.issueId,\n error: `${errMsg(err)} — not applied: ${why}. The other fixes were.`,\n })\n }\n return true\n}\n\n/** Run the planned API-based sync actions, recording per-action failures. */\nasync function executeApiActions(\n actions: PlannedAction[],\n fetchFn: FetchFn,\n result: PromoteResult,\n): Promise<void> {\n for (const act of actions) {\n try {\n const init: RequestInit = {\n method: act.action.method,\n headers: { 'Content-Type': 'application/json', ...act.action.headers },\n }\n if (act.action.body !== undefined) {\n init.body = JSON.stringify(act.action.body)\n }\n\n const res = await fetchFn(act.action.url, init)\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText)\n throw new Error(`${act.action.method} ${act.action.url} → ${res.status}: ${text}`)\n }\n\n result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label })\n } catch (err) {\n result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) })\n }\n }\n}\n\nexport async function promote(options: PromoteOptions): Promise<PromoteResult> {\n const {\n dbUrl,\n scanResult,\n checks,\n dryRun = false,\n allowDestructive = false,\n tableFilter,\n only,\n applyPosture = false,\n transactional = true,\n fetchFn = globalThis.fetch.bind(globalThis),\n } = options\n\n // applyPosture was accepted by PromoteOptions and then dropped on the floor\n // here, so `--apply-posture` was a no-op through this path — the only caller\n // that honoured it was `--prove`, which calls planWork directly. The unit\n // tests covering the flag tested planWork rather than promote, which is\n // exactly why the gap survived them.\n const { sqlStatements, apiActions, skipped } = planWork(scanResult, {\n checks,\n allowDestructive,\n tableFilter,\n only,\n applyPosture,\n })\n const result: PromoteResult = { applied: [], skipped, errors: [] }\n\n if (dryRun) {\n for (const stmt of sqlStatements) {\n result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql })\n }\n for (const act of apiActions) {\n result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label })\n }\n return result\n }\n\n await executeSql(dbUrl, sqlStatements, result, transactional)\n\n // A rolled-back batch leaves the target untouched, so the API calls that\n // would have gone with it must not fire either — they are not transactional\n // and could not be undone.\n if (result.rolledBack) {\n for (const act of apiActions) {\n result.skipped.push({\n check: act.check,\n issueId: act.issueId,\n reason: 'Not attempted — the SQL fixes were rolled back',\n })\n }\n return result\n }\n\n await executeApiActions(apiActions, fetchFn, result)\n\n return result\n}\n","/**\n * SQLSTATEs for \"that does not exist here\": a relation, function, schema or\n * other object the statement names is missing from the database it ran on.\n */\nexport const ABSENT_ON_TARGET: ReadonlySet<string> = new Set(['42P01', '42883', '3F000', '42704'])\n\n/** A column the statement names is missing. */\nexport const UNDEFINED_COLUMN = '42703'\n\n/** SQLSTATEs for an extension the server does not ship. */\nexport const EXTENSION_UNAVAILABLE: ReadonlySet<string> = new Set(['0A000', '58P01'])\n\n/** The SQLSTATE of a PostgreSQL error, if it is one. */\nexport function sqlState(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' ? code : undefined\n}\n","import type { QueryFn } from '../db.js'\nimport { pgQuery } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { Check, type CheckContext } from './base.js'\nimport { SUPABASE_PLATFORM_SCHEMAS } from '../defaults.js'\nimport { quoteName } from '../utils/sql.js'\n\ninterface PgRole {\n rolname: string\n rolsuper: boolean\n rolinherit: boolean\n rolcreaterole: boolean\n rolcreatedb: boolean\n rolcanlogin: boolean\n rolreplication: boolean\n rolbypassrls: boolean\n rolconnlimit: number\n rolvaliduntil: string | null\n}\n\n/**\n * What a grant is on. Tables, views and the like share PostgreSQL's TABLE\n * syntax; a sequence and a routine each need their own keyword, and a\n * routine its argument types, since overloads share a name.\n */\ntype ObjectKind = 'table' | 'sequence' | 'function' | 'procedure'\n\ninterface RoleGrant {\n grantee: string\n table_schema: string\n /** The object's name; for a routine, without its arguments. */\n table_name: string\n privilege_type: string\n is_grantable: boolean\n /** Set for a column-level grant, `GRANT UPDATE (col) ON t TO r`. */\n column_name?: string | null\n /** Omitted for a table, view or other relation. */\n object_kind?: ObjectKind\n /** A routine's identity arguments, `p integer`. */\n args?: string | null\n}\n\n/**\n * Roles the platform owns outright.\n *\n * Their attributes and their grants are Supabase's to manage, and a difference\n * in either means the two projects run different Supabase versions rather than\n * that anybody changed anything.\n */\nexport const PLATFORM_ROLES = [\n 'postgres', 'supabase_admin', 'authenticator',\n 'supabase_auth_admin', 'supabase_storage_admin', 'dashboard_user',\n 'pgbouncer', 'supavisor',\n // Created by Supabase's own images for Edge Functions, Realtime, read\n // replicas and logical replication. Diffing a project against plain\n // PostgreSQL offered to create all four on the target.\n 'supabase_functions_admin', 'supabase_realtime_admin',\n 'supabase_read_only_user', 'supabase_replication_admin',\n]\n\n/**\n * The roles the Data API authenticates as.\n *\n * Their *attributes* are Supabase's — nobody usefully diffs whether `anon` can\n * log in — but their *table grants* are the application's, and are exactly the\n * drift worth catching: `REVOKE ALL ON public.plans FROM anon` is the\n * difference between a table being readable through the anon key and not\n * (issue #90). All three were filtered out of the grants query, so that change\n * reported clean.\n */\nconst API_ROLES = ['anon', 'authenticated', 'service_role']\n\nconst quoted = (names: string[]) => names.map(n => `'${n.replace(/'/g, \"''\")}'`).join(', ')\n\n/**\n * Every role but the platform's, the built-in ones, and the one this check is\n * connected as.\n *\n * The connecting role is the credential each environment was given, not part\n * of the project: two databases reached as different users reported each user\n * as drift, and the fix for the target's was `DROP ROLE` on the very role the\n * apply was running as.\n */\nconst ROLES_SQL = `\n SELECT\n rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,\n rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,\n rolvaliduntil::text AS rolvaliduntil\n FROM pg_roles\n WHERE NOT (rolname LIKE 'pg_%')\n AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})\n AND rolname <> current_user\n ORDER BY rolname\n`\n\n/**\n * Schemas whose grants are compared: everything but Supabase's own.\n *\n * Grants on `storage.objects`, `realtime.messages` or `vault.secrets` are set by\n * Supabase and move with its version. Comparing them reported one project's\n * Supabase upgrade as drift in the other — and offered `REVOKE ... ON\n * storage.objects FROM anon` as the fix, which breaks Storage. On a test stack\n * two thirds of the grants the Data API roles hold were in these schemas.\n */\nfunction grantSchemaFilter(ignoreSchemas: string[]): string {\n const excluded = [...new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])]\n return `NOT IN (${quoted(excluded)})`\n}\n\n/**\n * Table-level grants, read from `relacl` like the column grants below.\n *\n * `information_schema.role_table_grants` was read instead, and it is wrong\n * twice over for a comparison. It includes the owner's own privileges, which\n * are not grants: a table owned by `postgres` on one side and by another user\n * on the other reported every privilege of both owners as drift — 35 findings\n * for a project restored into plain PostgreSQL. And it lists only grants the\n * connecting role takes part in, so a grant between two other roles was not\n * seen at all.\n */\nconst grantsSql = (ignoreSchemas: string[]) => `\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,\n a.privilege_type, a.is_grantable,\n CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind\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\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND a.grantee <> c.relowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4\n`\n\n/**\n * Column-level grants, read from `attacl`.\n *\n * `information_schema.column_privileges` also lists every column a table-level\n * grant covers, which would report each table grant once per column. The\n * attribute ACL holds only what was granted on the column itself —\n * `GRANT UPDATE (display_name) ON profiles TO authenticated`, the usual way to\n * let a user edit some columns of their row and not others.\n */\nconst columnGrantsSql = (ignoreSchemas: string[]) => `\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, att.attname AS column_name,\n 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 c.relkind IN ('r', 'p', 'v', 'm', 'f')\n AND a.grantee <> c.relowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4, 5\n`\n\n/**\n * Routine grants, read from `proacl`.\n *\n * A NULL `proacl` is not \"no grants\": it is PostgreSQL's default, EXECUTE to\n * PUBLIC, so it is read through acldefault(). These were never compared at\n * all, and a SECURITY DEFINER function the source kept from the Data API —\n * the usual way to keep an elevated function out of reach — arrived on the\n * target callable with the anon key. Functions an extension owns are its own.\n */\nconst functionGrantsSql = (ignoreSchemas: string[]) => `\n SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n n.nspname AS table_schema, p.proname AS table_name,\n pg_get_function_identity_arguments(p.oid) AS args,\n CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind,\n a.privilege_type, a.is_grantable\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a\n WHERE a.grantee <> p.proowner\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))\n AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')\n ORDER BY 1, 2, 3, 4, 6\n`\n\n/** Each side's routines, to tell one the target lacks yet. */\nconst routinesSql = (ignoreSchemas: string[]) => `\n SELECT n.nspname AS table_schema, p.proname AS table_name,\n pg_get_function_identity_arguments(p.oid) AS args,\n CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END AS object_kind\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname ${grantSchemaFilter(ignoreSchemas)}\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')\n`\n\n/** Each side's relations, to tell a table the target lacks yet. */\nconst relationsSql = (ignoreSchemas: string[]) => `\n SELECT n.nspname AS table_schema, c.relname AS table_name,\n CASE c.relkind WHEN 'S' THEN 'sequence' ELSE 'table' END AS object_kind\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND n.nspname ${grantSchemaFilter(ignoreSchemas)}\n`\n\n/**\n * What an object the connecting role creates is granted by default, per kind\n * and schema (NULL for every schema): ALTER DEFAULT PRIVILEGES ... ON TABLES,\n * SEQUENCES and FUNCTIONS.\n *\n * A routine has a default of PostgreSQL's own as well: EXECUTE to PUBLIC. A\n * global entry for the role replaces it; without one it applies, and the\n * per-schema entries add to it. That is the second row source here.\n */\nconst DEFAULT_GRANTS_SQL = `\n SELECT CASE d.defaclobjtype WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'function' ELSE 'table' END AS object_kind,\n n.nspname AS table_schema,\n CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,\n a.privilege_type, a.is_grantable\n FROM pg_default_acl d\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE d.defaclobjtype IN ('r', 'S', 'f') AND d.defaclrole = current_user::regrole::oid\n AND a.grantee <> d.defaclrole\n UNION ALL\n SELECT 'function', NULL, 'PUBLIC', 'EXECUTE', false\n WHERE NOT EXISTS (\n SELECT 1 FROM pg_default_acl d\n WHERE d.defaclobjtype = 'f' AND d.defaclnamespace = 0 AND d.defaclrole = current_user::regrole::oid)\n`\n\ntype Relation = { table_schema: string; table_name: string; object_kind?: ObjectKind; args?: string | null }\ntype DefaultGrant = {\n table_schema: string | null; grantee: string; privilege_type: string; is_grantable: boolean\n /** Omitted for tables. A procedure gets a function's defaults. */\n object_kind?: ObjectKind\n}\n\n/** The object a grant or relation names, with its kind and a routine's arguments. */\nfunction objectKey(o: { table_schema: string; table_name: string; object_kind?: ObjectKind; args?: string | null }): string {\n const routine = o.object_kind === 'function' || o.object_kind === 'procedure'\n return `${routine ? 'routine' : o.object_kind ?? 'table'}:${o.table_schema}.${o.table_name}${routine ? `(${o.args ?? ''})` : ''}`\n}\n\n/** The kind of default privileges an object takes: a procedure's are a function's. */\nfunction defaultKind(kind: ObjectKind | undefined): ObjectKind {\n return kind === 'procedure' ? 'function' : kind ?? 'table'\n}\n\n/**\n * Leave out a missing grant the target will make by itself: one on a table it\n * does not have yet, which its default privileges grant when the schema fix\n * creates it. On Supabase that is every Data API grant on every new table —\n * most of a report, and gone again after the first apply.\n */\nexport function grantedByDefault(\n relations: Relation[],\n defaults: DefaultGrant[],\n): (g: RoleGrant) => boolean {\n const present = new Set(relations.map(objectKey))\n const granted = new Set(defaults.map(d =>\n `${defaultKind(d.object_kind)}|${d.table_schema ?? '*'}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`))\n return g => !g.column_name\n && !present.has(objectKey(g))\n && [g.table_schema, '*'].some(schema =>\n granted.has(`${defaultKind(g.object_kind)}|${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`))\n}\n\n/**\n * What the target's default privileges will grant on a table the schema fix\n * creates, and the source does not: the other half of `grantedByDefault`.\n *\n * A table kept away from the Data API (`REVOKE ALL ... FROM anon,\n * authenticated`) and created on a Supabase target got everything the\n * defaults give, and nothing took it back until a second sync, so one sync\n * left it open to the anon key. The REVOKE runs with the grants, after the\n * table is created.\n */\nexport function defaultGrantsToRevoke(\n sourceRelations: Relation[],\n targetRelations: Relation[],\n defaults: DefaultGrant[],\n sourceGrants: RoleGrant[],\n): DriftIssue[] {\n const present = new Set(targetRelations.map(objectKey))\n const held = new Set(sourceGrants.filter(g => !g.column_name)\n .map(g => `${objectKey(g)}|${g.grantee}|${g.privilege_type}`))\n const issues: DriftIssue[] = []\n for (const rel of sourceRelations) {\n if (present.has(objectKey(rel))) continue\n const name = `${rel.table_schema}.${rel.table_name}`\n const extra = new Map<string, Set<string>>()\n for (const d of defaults) {\n if (defaultKind(d.object_kind) !== defaultKind(rel.object_kind)) continue\n if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue\n if (held.has(`${objectKey(rel)}|${d.grantee}|${d.privilege_type}`)) continue\n extra.set(d.grantee, (extra.get(d.grantee) ?? new Set()).add(d.privilege_type))\n }\n for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {\n const gs: RoleGrant[] = [...privileges].sort().map(privilege_type => ({\n grantee, table_schema: rel.table_schema, table_name: rel.table_name, privilege_type, is_grantable: false,\n ...(rel.object_kind && rel.object_kind !== 'table' ? { object_kind: rel.object_kind } : {}),\n ...(rel.args !== undefined ? { args: rel.args } : {}),\n }))\n const routine = rel.object_kind === 'function' || rel.object_kind === 'procedure'\n issues.push({\n // Tables keep the id they have always had; others say what they are.\n id: `roles-grant-default-${grantee}.${name}${routine ? `(${rel.args ?? ''})` : ''}`,\n check: 'roles',\n severity: extraGrantSeverity(grantee),\n title: `Default grants to take back: ${describeGroup(gs)}`,\n description: `Creating ${describeObject(gs[0])} on the target gives ${grantee} what its default privileges grant. `\n + `The source does not grant \"${describeGroup(gs)}\", so it is revoked once it exists.`,\n targetValue: gs,\n sql: {\n up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,\n down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`,\n },\n })\n }\n }\n return issues\n}\n\n/**\n * A grant the target has and the source does not widens access. To the roles\n * the Data API serves (and PUBLIC) that is the anon key reaching a table, so\n * critical; to any other role a warning. It was info, which a sync's summary\n * does not lead with.\n */\nconst OPEN_GRANTEES = new Set(['anon', 'authenticated', 'PUBLIC'])\nfunction extraGrantSeverity(grantee: string): 'critical' | 'warning' {\n return OPEN_GRANTEES.has(grantee) ? 'critical' : 'warning'\n}\n\nexport class RolesCheck extends Check {\n readonly name = 'roles' as const\n\n constructor(private queryFn: QueryFn = pgQuery) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const ignore = ctx.config.ignoreSchemas ?? []\n const version = async (url: string) =>\n Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`) as Array<{ v: string }>)[0]?.v ?? 0)\n const [\n sourceRoles, targetRoles, sourceGrants, targetGrants, sourceColumns, targetColumns,\n sourceVersion, targetVersion, sourceRelations, targetRelations, targetDefaults,\n sourceRoutineGrants, targetRoutineGrants, sourceRoutines, targetRoutines,\n ] = await Promise.all([\n this.queryFn(ctx.source.dbUrl, ROLES_SQL) as unknown as Promise<PgRole[]>,\n this.queryFn(ctx.target.dbUrl, ROLES_SQL) as unknown as Promise<PgRole[]>,\n this.queryFn(ctx.source.dbUrl, grantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, grantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n version(ctx.source.dbUrl),\n version(ctx.target.dbUrl),\n this.queryFn(ctx.source.dbUrl, relationsSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, relationsSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, DEFAULT_GRANTS_SQL) as unknown as Promise<DefaultGrant[]>,\n this.queryFn(ctx.source.dbUrl, functionGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.target.dbUrl, functionGrantsSql(ignore)) as unknown as Promise<RoleGrant[]>,\n this.queryFn(ctx.source.dbUrl, routinesSql(ignore)) as unknown as Promise<Relation[]>,\n this.queryFn(ctx.target.dbUrl, routinesSql(ignore)) as unknown as Promise<Relation[]>,\n ])\n const sourceObjects = [...(sourceRelations ?? []), ...(sourceRoutines ?? [])]\n const targetObjects = [...(targetRelations ?? []), ...(targetRoutines ?? [])]\n const sourceAll = [...(sourceGrants ?? []), ...(sourceRoutineGrants ?? [])]\n // A routine or sequence only the target has is the schema check's finding,\n // and its grants go with it. Every routine grants EXECUTE to PUBLIC unless\n // told otherwise, so each one present on the target alone was reported\n // again as an extra grant.\n const inSource = new Set(sourceObjects.map(objectKey))\n const targetAll = [...(targetGrants ?? []), ...(targetRoutineGrants ?? [])]\n .filter(g => !g.object_kind || g.object_kind === 'table' || inSource.has(objectKey(g)))\n const comparable = comparablePrivileges(sourceVersion, targetVersion)\n const byDefault = grantedByDefault(targetObjects, targetDefaults ?? [])\n\n return [\n ...diffRoles(sourceRoles, targetRoles),\n ...diffGrants(\n [...sourceAll, ...(sourceColumns ?? [])].filter(g => comparable(g) && !byDefault(g)),\n [...targetAll, ...(targetColumns ?? [])].filter(comparable),\n ),\n ...defaultGrantsToRevoke(\n sourceObjects, targetObjects,\n (targetDefaults ?? []).filter(d => comparable(d as RoleGrant)), sourceAll),\n ]\n }\n}\n\nfunction roleAttrs(r: PgRole): string {\n const attrs: string[] = []\n if (r.rolsuper) attrs.push('SUPERUSER')\n if (r.rolinherit) attrs.push('INHERIT')\n if (r.rolcreaterole) attrs.push('CREATEROLE')\n if (r.rolcreatedb) attrs.push('CREATEDB')\n if (r.rolcanlogin) attrs.push('LOGIN')\n if (r.rolreplication) attrs.push('REPLICATION')\n if (r.rolbypassrls) attrs.push('BYPASSRLS')\n if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`)\n if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`)\n return attrs.length > 0 ? attrs.join(' ') : 'NOLOGIN'\n}\n\nfunction rolesEqual(a: PgRole, b: PgRole): boolean {\n return (\n a.rolsuper === b.rolsuper &&\n a.rolinherit === b.rolinherit &&\n a.rolcreaterole === b.rolcreaterole &&\n a.rolcreatedb === b.rolcreatedb &&\n a.rolcanlogin === b.rolcanlogin &&\n a.rolreplication === b.rolreplication &&\n a.rolbypassrls === b.rolbypassrls &&\n a.rolconnlimit === b.rolconnlimit &&\n a.rolvaliduntil === b.rolvaliduntil\n )\n}\n\nexport function diffRoles(source: PgRole[], target: PgRole[]): DriftIssue[] {\n const issues: DriftIssue[] = []\n const sourceMap = new Map(source.map(r => [r.rolname, r]))\n const targetMap = new Map(target.map(r => [r.rolname, r]))\n\n for (const [name, sr] of sourceMap) {\n if (!targetMap.has(name)) {\n issues.push({\n id: `roles-missing-${name}`,\n check: 'roles',\n severity: 'critical',\n title: `Missing role: ${name}`,\n description: `Role \"${name}\" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,\n sourceValue: sr,\n sql: {\n up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,\n down: `DROP ROLE IF EXISTS ${quoteName(name)};`,\n },\n })\n }\n }\n\n for (const [name, tr] of targetMap) {\n if (!sourceMap.has(name)) {\n issues.push({\n id: `roles-extra-${name}`,\n check: 'roles',\n severity: 'warning',\n title: `Extra role: ${name}`,\n description: `Role \"${name}\" exists in target but not in source.`,\n targetValue: tr,\n sql: {\n up: `DROP ROLE IF EXISTS ${quoteName(name)};`,\n down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`,\n },\n })\n }\n }\n\n for (const [name, sr] of sourceMap) {\n const tr = targetMap.get(name)\n if (tr && !rolesEqual(sr, tr)) {\n issues.push({\n id: `roles-modified-${name}`,\n check: 'roles',\n severity: 'warning',\n title: `Modified role: ${name}`,\n description: `Role \"${name}\" has different attributes between source and target.`,\n sourceValue: sr,\n targetValue: tr,\n sql: {\n up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,\n down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`,\n },\n })\n }\n }\n\n return issues\n}\n\nfunction grantKey(g: RoleGrant): string {\n const column = g.column_name ? `.${g.column_name}` : ''\n const routine = g.object_kind === 'function' || g.object_kind === 'procedure'\n return `${g.grantee}.${g.table_schema}.${g.table_name}${routine ? `(${g.args ?? ''})` : ''}${column}.${g.privilege_type}`\n}\n\n/** The object as SQL: `\"s\".\"t\"`, `SEQUENCE \"s\".\"q\"`, `FUNCTION \"s\".\"f\"(integer)`. */\nfunction objectSql(g: RoleGrant): string {\n const name = `${quoteName(g.table_schema)}.${quoteName(g.table_name)}`\n switch (g.object_kind) {\n case 'sequence': return `SEQUENCE ${name}`\n case 'function': return `FUNCTION ${name}(${g.args ?? ''})`\n case 'procedure': return `PROCEDURE ${name}(${g.args ?? ''})`\n default: return name\n }\n}\n\n/** The object as a reader names it: `public.t`, `sequence public.q`, `function public.f(integer)`. */\nfunction describeObject(g: RoleGrant): string {\n const name = `${g.table_schema}.${g.table_name}`\n switch (g.object_kind) {\n case 'sequence': return `sequence ${name}`\n case 'function': return `function ${name}(${g.args ?? ''})`\n case 'procedure': return `procedure ${name}(${g.args ?? ''})`\n default: return name\n }\n}\n\n/**\n * A grantee as SQL. `PUBLIC` is a keyword, not a role: quoted, it names a\n * role called \"PUBLIC\", which does not exist, so the fix failed.\n */\nfunction granteeSql(grantee: string): string {\n return grantee === 'PUBLIC' ? 'PUBLIC' : `\"${grantee.replace(/\"/g, '\"\"')}\"`\n}\n\n/** `SELECT ON \"s\".\"t\"`, or `UPDATE (\"col\") ON \"s\".\"t\"` for a column grant. */\nfunction grantTarget(g: RoleGrant): string {\n const column = g.column_name ? ` (\"${g.column_name.replace(/\"/g, '\"\"')}\")` : ''\n return `${g.privilege_type}${column} ON ${objectSql(g)}`\n}\n\nfunction describeGrant(g: RoleGrant): string {\n const column = g.column_name ? `(${g.column_name}) ` : ''\n return `${g.privilege_type} ${column}ON ${describeObject(g)} TO ${g.grantee}`\n}\n\nconst grantSql = (g: RoleGrant, withOption = g.is_grantable) =>\n `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? ' WITH GRANT OPTION' : ''};`\nconst revokeSql = (g: RoleGrant) => `REVOKE ${grantTarget(g)} FROM ${granteeSql(g.grantee)};`\n\n/**\n * The grants both servers can hold. MAINTAIN is a PostgreSQL 17 privilege:\n * a 17 source reported it missing from a 15 target, and the fix failed with\n * `unrecognized privilege type \"maintain\"`, rolling back every grant with it.\n */\nexport function comparablePrivileges(sourceVersion: number, targetVersion: number): (g: RoleGrant) => boolean {\n const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity)\n return g => g.privilege_type !== 'MAINTAIN' || both >= 170000\n}\n\n/** Grants that differ the same way, on one table (or column) to one role, as one finding. */\nfunction grouped(grants: RoleGrant[]): RoleGrant[][] {\n const groups = new Map<string, RoleGrant[]>()\n for (const g of grants) {\n const key = `${grantKey(g).replace(/\\.[^.]+$/, '')}.${Boolean(g.is_grantable)}`\n groups.set(key, [...(groups.get(key) ?? []), g])\n }\n return [...groups.values()]\n}\n\n/** `SELECT, INSERT ON \"s\".\"t\"` for a group of grants on one object. */\nfunction groupTarget(gs: RoleGrant[]): string {\n const column = gs[0].column_name ? ` (\"${gs[0].column_name.replace(/\"/g, '\"\"')}\")` : ''\n return `${gs.map(g => `${g.privilege_type}${column}`).join(', ')} ON ${objectSql(gs[0])}`\n}\n\nfunction describeGroup(gs: RoleGrant[]): string {\n const column = gs[0].column_name ? `(${gs[0].column_name}) ` : ''\n return `${gs.map(g => g.privilege_type).join(', ')} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`\n}\n\n/** A group's key: the grant key without its privilege. */\nconst groupKey = (gs: RoleGrant[]) => grantKey(gs[0]).replace(/\\.[^.]+$/, '')\n\n/**\n * Grants on the target that differ from the source's.\n *\n * Missing and extra grants are one finding per role, table (or column) and\n * grant option, listing the privileges: one finding per privilege made a\n * table granted to Supabase's three API roles twenty-odd findings, most of a\n * report.\n */\nexport function diffGrants(source: RoleGrant[], target: RoleGrant[]): DriftIssue[] {\n const issues: DriftIssue[] = []\n const sourceMap = new Map(source.map(g => [grantKey(g), g]))\n const targetMap = new Map(target.map(g => [grantKey(g), g]))\n\n const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g)\n for (const gs of grouped(missing)) {\n const plural = gs.length > 1 ? 's' : ''\n issues.push({\n id: `roles-grant-missing-${groupKey(gs)}`,\n check: 'roles',\n severity: 'warning',\n title: `Missing grant${plural}: ${describeGroup(gs)}`,\n description: `Grant${plural} \"${describeGroup(gs)}\" ${gs.length > 1 ? 'are' : 'is'} missing from target.`,\n sourceValue: gs.length > 1 ? gs : gs[0],\n sql: {\n up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? ' WITH GRANT OPTION' : ''};`,\n down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,\n },\n })\n }\n\n for (const [key, sg] of sourceMap) {\n const tg = targetMap.get(key)\n if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {\n // The same privilege, held with the grant option on one side only.\n // Keying on the privilege alone reported these identical; the grant\n // option is what lets the grantee pass the privilege on.\n const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`\n issues.push({\n id: `roles-grant-option-${key}`,\n check: 'roles',\n severity: 'warning',\n title: `Grant option differs: ${describeGrant(sg)}`,\n description: `\"${describeGrant(sg)}\" is held ${sg.is_grantable ? 'with' : 'without'} the grant option in source `\n + `and ${tg.is_grantable ? 'with' : 'without'} it in target.`,\n sourceValue: sg,\n targetValue: tg,\n sql: sg.is_grantable\n ? { up: grantSql(sg, true), down: revokeOption }\n : { up: revokeOption, down: grantSql(tg, true) },\n })\n }\n }\n\n const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g)\n for (const gs of grouped(extra)) {\n const plural = gs.length > 1 ? 's' : ''\n issues.push({\n id: `roles-grant-extra-${groupKey(gs)}`,\n check: 'roles',\n severity: extraGrantSeverity(gs[0].grantee),\n title: `Extra grant${plural}: ${describeGroup(gs)}`,\n description: `Grant${plural} \"${describeGroup(gs)}\" exist${gs.length > 1 ? '' : 's'} in target but not in source.`,\n targetValue: gs.length > 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AAU,mBAAmB,GAAG,CAAC,EAAE,OAAO;AAAA,MAC1C,OAAO,cAAc,MAAM,KAAK,cAAc,EAAE,CAAC;AAAA,MACjD,aAAa,QAAQ,MAAM,KAAK,cAAc,EAAE,CAAC,UAAU,GAAG,SAAS,IAAI,KAAK,GAAG;AAAA,MACnF,aAAa,GAAG,SAAS,IAAI,KAAK,GAAG,CAAC;AAAA,MACtC,KAAK;AAAA,QACH,IAAI,UAAU,YAAY,EAAE,CAAC,SAAS,WAAW,GAAG,CAAC,EAAE,OAAO,CAAC;AAAA,QAC/D,MAAM,SAAS,YAAY,EAAE,CAAC,OAAO,WAAW,GAAG,CAAC,EAAE,OAAO,CAAC,GAAG,GAAG,CAAC,EAAE,eAAe,uBAAuB,EAAE;AAAA,MACjH;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -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,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,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":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/commands/init.ts","../../src/errors.ts"],"sourcesContent":["import { Command, Flags } from '@oclif/core'\nimport { createInterface } from 'node:readline'\nimport { writeFile, readFile, appendFile, access } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { validateConfig, validateSingleEnvConfig, expandEnvVars, parseProjectRef } from '../config'\nimport { INIT_HINTS } from '../defaults'\nimport { UserCancelledError, isUserCancelled } from '../errors'\nimport { printBanner, printHints, ok, warn, dim, cmd, bold } from '../ui'\nimport { SUPAFORGE_DIR } from '../constants'\nimport type { SupaForgeConfig, EnvironmentConfig } from '../types/config'\n\nconst CONFIG_FILENAME = 'supaforge.config.json'\n\n/** Entries that supaforge init ensures are present in .gitignore. */\nconst GITIGNORE_ENTRIES = [CONFIG_FILENAME, `${SUPAFORGE_DIR}/`]\n\nexport type AskFn = ((question: string) => Promise<string>) & { close: () => void }\n\n/**\n * Convert an environment name to an uppercase env var prefix.\n * e.g. \"staging\" → \"STAGING\", \"my-prod\" → \"MY_PROD\"\n */\nexport function envPrefix(name: string): string {\n return name.toUpperCase().replace(/[^A-Z0-9]/g, '_')\n}\n\nexport function createPrompt(\n input: NodeJS.ReadableStream = process.stdin,\n output: NodeJS.WritableStream = process.stdout,\n): AskFn {\n const rl = createInterface({ input, output })\n let closed = false\n let rejectPending: ((err: Error) => void) | null = null\n\n rl.on('close', () => {\n closed = true\n if (rejectPending) {\n rejectPending(new UserCancelledError())\n rejectPending = null\n }\n })\n\n const ask = (question: string): Promise<string> =>\n new Promise((resolve, reject) => {\n if (closed) {\n reject(new UserCancelledError())\n return\n }\n rejectPending = reject\n rl.question(question, (answer) => {\n rejectPending = null\n resolve(answer.trim())\n })\n })\n ask.close = () => rl.close()\n return ask as AskFn\n}\n\n/**\n * Prompt until the user enters a value that matches one of the options.\n * Accepts exact match, single-char shortcut, or unambiguous prefix.\n * Returns the full option string.\n */\nexport async function fuzzySelect(\n ask: (question: string) => Promise<string>,\n log: (msg: string) => void,\n prompt: string,\n options: string[],\n defaultOption?: string,\n): Promise<string> {\n while (true) {\n const raw = await ask(prompt)\n const input = raw.toLowerCase()\n\n // Empty → default\n if (!input && defaultOption) return defaultOption\n\n // Exact match (case-insensitive)\n const exact = options.find((o) => o.toLowerCase() === input)\n if (exact) return exact\n\n // Prefix match — must be unambiguous\n const prefixMatches = options.filter((o) => o.toLowerCase().startsWith(input))\n if (prefixMatches.length === 1) return prefixMatches[0]\n\n if (prefixMatches.length > 1) {\n log(warn(` \\u26a0 \"${raw}\" is ambiguous \\u2014 could be: ${prefixMatches.join(', ')}`))\n } else {\n log(warn(` \\u26a0 \"${raw}\" is not recognised. Options: ${options.join(', ')}`))\n }\n }\n}\n\n/**\n * Prompt until the user enters a non-empty value.\n * Re-prompts with a warning on empty input; Ctrl+C propagates as UserCancelledError.\n */\nexport async function askRequired(\n ask: (question: string) => Promise<string>,\n log: (msg: string) => void,\n prompt: string,\n fieldName: string,\n): Promise<string> {\n while (true) {\n const value = await ask(prompt)\n if (value) return value\n log(warn(` ⚠ ${fieldName} is required.`))\n }\n}\n\n/**\n * Interactively collect config from the user.\n * Extracted so it can be tested without oclif scaffolding.\n */\nexport async function collectConfig(\n ask: (question: string) => Promise<string>,\n log: (msg: string) => void = console.log,\n): Promise<{ config: SupaForgeConfig; envVars: Record<string, string> }> {\n const environments: Record<string, EnvironmentConfig> = {}\n const envVars: Record<string, string> = {}\n\n let singleEnv: boolean | null = null\n while (singleEnv === null) {\n const selected = await fuzzySelect(\n ask, log,\n 'Setup mode \\u2014 compare two environments or single database? [multi/single]: ',\n ['multi', 'single'],\n 'multi',\n )\n singleEnv = selected === 'single'\n }\n log(ok(` ✓ Mode: ${singleEnv ? 'single' : 'multi'}\\n`))\n\n if (singleEnv) {\n log(bold('Set up your Supabase database.'))\n log(dim('Sensitive values (DB URL, API key) will be stored as $ENV_VAR references.\\n'))\n } else {\n log(bold('Add your Supabase environments (at least 2).'))\n log(dim('Sensitive values (DB URL, API key) will be stored as $ENV_VAR references.\\n'))\n }\n\n if (singleEnv) {\n const defaultName = 'prod'\n let name = await ask(`Environment name [${defaultName}]: `)\n if (!name) name = defaultName\n log(ok(` ✓ Environment: ${name}`))\n\n const prefix = envPrefix(name)\n const dbUrlVar = `${prefix}_DATABASE_URL`\n\n INIT_HINTS.DB_URL.forEach((l) => log(dim(l)))\n const dbUrl = await askRequired(ask, log, ` Database URL for \"${name}\": `, 'Database URL')\n envVars[dbUrlVar] = dbUrl\n\n log('')\n printHints(INIT_HINTS.PROJECT_URL, log)\n const projectUrl = await ask(` Supabase Project URL or Project ID for \"${name}\" (e.g. https://xyz.supabase.co, optional): `)\n const projectRef = projectUrl ? parseProjectRef(projectUrl) : ''\n\n let accessToken = ''\n if (projectRef) {\n log('')\n printHints(INIT_HINTS.ACCESS_TOKEN, log)\n accessToken = await ask(` Supabase access token for \"${name}\" (optional): `)\n }\n\n const accessTokenVar = `${prefix}_ACCESS_TOKEN`\n if (accessToken) {\n envVars[accessTokenVar] = accessToken\n }\n\n const env: EnvironmentConfig = { dbUrl: `$${dbUrlVar}` }\n if (projectRef) env.projectRef = projectRef\n if (accessToken) env.accessToken = `$${accessTokenVar}`\n\n environments[name] = env\n\n log('')\n printHints(INIT_HINTS.DATA_TABLES, log)\n const dataTables = await ask('Reference-data tables to track (comma-separated, or Enter to skip): ')\n const checks = dataTables\n ? { data: { tables: dataTables.split(',').map((t) => t.trim()).filter(Boolean) } }\n : undefined\n\n const config: SupaForgeConfig = { environments }\n if (checks) config.checks = checks\n\n return { config, envVars }\n }\n\n let envCount = 0\n const defaults = ['staging', 'production']\n\n while (envCount < 2 || await confirm(ask, 'Add another environment?', false)) {\n const defaultName = defaults[envCount] ?? ''\n const prompt = defaultName\n ? `Environment name [${defaultName}]: `\n : 'Environment name: '\n\n let name = await ask(prompt)\n if (!name && defaultName) name = defaultName\n\n if (!name) {\n log(warn(' \\u26a0 Name cannot be empty, try again.'))\n continue\n }\n\n if (environments[name]) {\n log(warn(` \\u26a0 \"${name}\" already exists, try again.`))\n continue\n }\n\n const prefix = envPrefix(name)\n const dbUrlVar = `${prefix}_DATABASE_URL`\n\n if (envCount === 0) {\n printHints(INIT_HINTS.DB_URL, log)\n }\n const dbUrl = await askRequired(ask, log, ` Database URL for \"${name}\": `, 'Database URL')\n\n envVars[dbUrlVar] = dbUrl\n\n if (envCount === 0) {\n log('')\n printHints(INIT_HINTS.PROJECT_URL, log)\n }\n const projectUrl = await ask(` Supabase Project URL or Project ID for \"${name}\" (e.g. https://xyz.supabase.co, optional): `)\n const projectRef = projectUrl ? parseProjectRef(projectUrl) : ''\n\n let accessToken = ''\n if (projectRef) {\n if (envCount === 0) {\n log('')\n printHints(INIT_HINTS.ACCESS_TOKEN, log)\n }\n accessToken = await ask(` Supabase access token for \"${name}\" (optional): `)\n }\n\n const accessTokenVar = `${prefix}_ACCESS_TOKEN`\n if (accessToken) {\n envVars[accessTokenVar] = accessToken\n }\n\n const env: EnvironmentConfig = { dbUrl: `$${dbUrlVar}` }\n if (projectRef) env.projectRef = projectRef\n if (accessToken) env.accessToken = `$${accessTokenVar}`\n\n environments[name] = env\n envCount++\n log(ok(` ✓ Environment \"${name}\" added`))\n log('')\n }\n\n const envNames = Object.keys(environments)\n\n const source = await selectOne(ask, log, 'Source environment (truth)', envNames, envNames[0])\n log(ok(` ✓ Source: ${source}`))\n const remaining = envNames.filter((n) => n !== source)\n const target = await selectOne(ask, log, 'Target environment (to sync)', remaining, remaining[0])\n log(ok(` ✓ Target: ${target}`))\n\n log('')\n printHints(INIT_HINTS.DATA_TABLES, log)\n const dataTables = await ask('Reference-data tables to track (comma-separated, or Enter to skip): ')\n const checks = dataTables\n ? { data: { tables: dataTables.split(',').map((t) => t.trim()).filter(Boolean) } }\n : undefined\n\n const config: SupaForgeConfig = { environments, source, target }\n if (checks) config.checks = checks\n\n return { config, envVars }\n}\n\nasync function confirm(\n ask: (question: string) => Promise<string>,\n question: string,\n defaultYes: boolean,\n): Promise<boolean> {\n const hint = defaultYes ? '[Y/n]' : '[y/N]'\n const answer = await ask(`${question} ${hint}: `)\n if (!answer) return defaultYes\n return answer.toLowerCase().startsWith('y')\n}\n\nasync function selectOne(\n ask: (question: string) => Promise<string>,\n log: (msg: string) => void,\n label: string,\n options: string[],\n defaultOption: string,\n): Promise<string> {\n const optList = options.map((o) => (o === defaultOption ? `[${o}]` : o)).join(' / ')\n return fuzzySelect(ask, log, `${label} (${optList}): `, options, defaultOption)\n}\n\n/**\n * Ensure required entries are present in .gitignore.\n * Creates the file if it doesn't exist. Returns the list of entries that were added.\n */\nexport async function ensureGitignore(\n entries: string[],\n cwd: string = process.cwd(),\n): Promise<string[]> {\n const gitignorePath = resolve(cwd, '.gitignore')\n let existing = ''\n try {\n existing = await readFile(gitignorePath, 'utf-8')\n } catch {\n // file does not exist\n }\n\n const lines = existing.split('\\n').map((l) => l.trim())\n const missing = entries.filter((e) => !lines.includes(e))\n if (missing.length === 0) return []\n\n const block = '\\n# Added by supaforge init\\n' + missing.join('\\n') + '\\n'\n if (existing) {\n await appendFile(gitignorePath, block)\n } else {\n await writeFile(gitignorePath, block.trimStart(), 'utf-8')\n }\n return missing\n}\n\nexport default class Init extends Command {\n static override description = 'Create a supaforge.config.json file interactively'\n\n static override examples = [\n '<%= config.bin %> init',\n '<%= config.bin %> init --force',\n ]\n\n static override flags = {\n force: Flags.boolean({\n char: 'f',\n description: 'Overwrite existing config file',\n default: false,\n }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(Init)\n const configPath = resolve(process.cwd(), CONFIG_FILENAME)\n\n if (!flags.force) {\n let configExists = false\n try {\n await access(configPath)\n configExists = true\n } catch {\n // File does not exist — proceed\n }\n\n if (configExists) {\n this.error(\n `${CONFIG_FILENAME} already exists. Use --force to overwrite.`,\n )\n }\n }\n\n printBanner((msg) => this.log(msg))\n this.log(bold(' 🔧 Init — create your config file\\n'))\n\n const ask = createPrompt()\n\n try {\n const { config, envVars } = await collectConfig(ask, (msg) => this.log(msg))\n\n const isSingleEnv = !config.source\n\n // Validate with env vars expanded (to catch structural issues)\n // but write the unexpanded $VAR references to the config file\n const expandedConfig = {\n ...config,\n environments: Object.fromEntries(\n Object.entries(config.environments).map(([name, env]) => [\n name,\n {\n ...env,\n dbUrl: expandEnvVars(env.dbUrl),\n ...(env.accessToken ? { accessToken: expandEnvVars(env.accessToken) } : {}),\n },\n ]),\n ),\n }\n\n if (isSingleEnv) {\n const envName = Object.keys(expandedConfig.environments)[0]\n const errors = validateSingleEnvConfig(expandedConfig, envName)\n if (errors.length > 0) {\n this.error(`Generated config is invalid:\\n ${errors.join('\\n ')}`)\n }\n } else {\n const errors = validateConfig(expandedConfig)\n if (errors.length > 0) {\n this.error(`Generated config is invalid:\\n ${errors.join('\\n ')}`)\n }\n }\n\n const json = JSON.stringify(config, null, 2) + '\\n'\n await writeFile(configPath, json, 'utf-8')\n this.log(`\\n${ok('✅ Wrote')} ${bold(CONFIG_FILENAME)}`)\n\n // Ensure supaforge paths are in .gitignore\n const added = await ensureGitignore(GITIGNORE_ENTRIES)\n if (added.length > 0) {\n this.log(`${ok('✅ Added to .gitignore:')} ${added.join(', ')}`)\n }\n\n // Write .env file with the actual secrets\n if (Object.keys(envVars).length > 0) {\n const envPath = resolve(process.cwd(), '.env')\n const envContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join('\\n') + '\\n'\n\n let envExists = false\n try {\n await access(envPath)\n envExists = true\n } catch {\n // does not exist\n }\n\n if (envExists) {\n await appendFile(envPath, '\\n# Added by supaforge init\\n' + envContent)\n this.log(`${ok('📎 Appended env vars to')} ${bold('.env')}`)\n } else {\n await writeFile(envPath, envContent, 'utf-8')\n this.log(`${ok('📎 Wrote .env')} with database credentials`)\n }\n\n // Check .gitignore and offer to add .env if missing\n const gitignorePath = resolve(process.cwd(), '.gitignore')\n let gitignoreHasEnv = false\n try {\n const gitignore = await readFile(gitignorePath, 'utf-8')\n gitignoreHasEnv = gitignore.split('\\n').some((line) => {\n const trimmed = line.trim()\n return trimmed === '.env' || trimmed === '.env*' || trimmed === '.env.*'\n })\n } catch {\n // .gitignore does not exist\n }\n\n if (!gitignoreHasEnv) {\n const addIt = await confirm(ask, `${warn('⚠️ .env is not in .gitignore.')} Add it now?`, true)\n if (addIt) {\n let gitignoreExists = false\n try {\n await access(gitignorePath)\n gitignoreExists = true\n } catch {\n // does not exist\n }\n\n if (gitignoreExists) {\n await appendFile(gitignorePath, '\\n# Secrets — added by supaforge init\\n.env\\n')\n } else {\n await writeFile(gitignorePath, '# Secrets — added by supaforge init\\n.env\\n', 'utf-8')\n }\n this.log(`${ok('✅ Added .env to .gitignore')}`)\n } else {\n this.log(`${warn('⚠️ Remember to add .env to .gitignore')} — never commit secrets to git.`)\n }\n }\n }\n\n this.log(`\\n${bold('Next steps:')}`)\n if (isSingleEnv) {\n const envName = Object.keys(config.environments)[0]\n this.log(` ${cmd(`supaforge snapshot --env=${envName}`)} ${dim('— capture current state')}`)\n this.log(` ${cmd(`supaforge clone --env=${envName} --apply`)} ${dim('— clone to local')}`)\n this.log(` ${cmd(`supaforge snapshot --env=${envName} --migration`)} ${dim('— incremental backup')}\\n`)\n } else {\n this.log(` ${cmd('supaforge diff')} ${dim('— check for drift')}`)\n this.log(` ${cmd('supaforge diff --detail')} ${dim('— see detailed SQL diffs')}`)\n this.log(` ${cmd('supaforge diff --apply')} ${dim('— fix the drift')}\\n`)\n }\n } catch (error) {\n if (isUserCancelled(error)) {\n this.log(`\\n${dim('Cancelled.')}`)\n return\n }\n throw error\n } finally {\n ask.close()\n }\n }\n}\n","/**\n * Thrown when the user cancels an interactive prompt (Ctrl+C, EOF).\n * Commands should catch this and exit silently.\n */\nexport class UserCancelledError extends Error {\n constructor() {\n super('User cancelled')\n this.name = 'UserCancelledError'\n }\n}\n\n/** Type guard for UserCancelledError. */\nexport function isUserCancelled(err: unknown): err is UserCancelledError {\n return err instanceof UserCancelledError\n}\n\n/** GitHub Issues URL for filing bug reports. */\nexport const ISSUES_URL = 'https://github.com/akalsoftware/supaforge/issues/new'\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,aAAa;AAC/B,SAAS,uBAAuB;AAChC,SAAS,WAAW,UAAU,YAAY,cAAc;AACxD,SAAS,eAAe;;;ACCjB,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,cAAc;AACZ,UAAM,gBAAgB;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAGO,SAAS,gBAAgB,KAAyC;AACvE,SAAO,eAAe;AACxB;;;ADHA,I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,4BAA4B,OAAO,EAAE,CAAC,MAAM,IAAI,8BAAyB,CAAC,EAAE;AAC9F,aAAK,IAAI,KAAK,IAAI,yBAAyB,OAAO,UAAU,CAAC,SAAS,IAAI,uBAAkB,CAAC,EAAE;AAC/F,aAAK,IAAI,KAAK,IAAI,4BAA4B,OAAO,cAAc,CAAC,MAAM,IAAI,2BAAsB,CAAC;AAAA,CAAI;AAAA,MAC3G,OAAO;AACL,aAAK,IAAI,KAAK,IAAI,gBAAgB,CAAC,eAAe,IAAI,wBAAmB,CAAC,EAAE;AAC5E,aAAK,IAAI,KAAK,IAAI,yBAAyB,CAAC,OAAO,IAAI,+BAA0B,CAAC,EAAE;AACpF,aAAK,IAAI,KAAK,IAAI,wBAAwB,CAAC,QAAQ,IAAI,sBAAiB,CAAC;AAAA,CAAI;AAAA,MAC/E;AAAA,IACF,SAAS,OAAO;AACd,UAAI,gBAAgB,KAAK,GAAG;AAC1B,aAAK,IAAI;AAAA,EAAK,IAAI,YAAY,CAAC,EAAE;AACjC;AAAA,MACF;AACA,YAAM;AAAA,IACR,UAAE;AACA,UAAI,MAAM;AAAA,IACZ;AAAA,EACF;AACF;","names":["resolve","dataTables","checks","config"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/commands/mcp.ts"],"sourcesContent":["import { Command, Flags } from '@oclif/core'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { createServer } from '../mcp/server.js'\n\nexport default class Mcp extends Command {\n static override description =\n 'Start the SupaForge MCP stdio server for use with Claude Desktop, Cursor, or any MCP-compatible AI client'\n\n static override examples = [\n '<%= config.bin %> mcp',\n '<%= config.bin %> mcp --allow-config-path',\n '# Claude Desktop / Cursor config:\\n# { \"mcpServers\": { \"supaforge\": { \"command\": \"supaforge\", \"args\": [\"mcp\"] } } }',\n ]\n\n static override flags = {\n 'allow-config-path': Flags.boolean({\n description:\n 'Let a client choose which supaforge.config.json to load. Off by default: '\n + 'a tool call, or a prompt injected into one, could otherwise point the '\n + 'server at any config on disk — including one holding production '\n + 'credentials — bypassing the one it was started with.',\n default: false,\n }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(Mcp)\n const server = createServer(process.cwd(), {\n allowConfigPath: flags['allow-config-path'],\n })\n const transport = new StdioServerTransport()\n await server.connect(transport)\n // Log to stderr so it doesn't pollute MCP stdio communication\n this.warn('SupaForge MCP server running on stdio')\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,SAAS,aAAa;AAC/B,SAAS,4BAA4B;AAGrC,IAAqB,MAArB,MAAqB,aAAY,QAAQ;AAAA,EACvC,OAAgB,cACd;AAAA,EAEF,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,qBAAqB,MAAM,QAAQ;AAAA,MACjC,aACE;AAAA,MAIF,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,KAAK,MAAM,IAAG;AACtC,UAAM,SAAS,aAAa,QAAQ,IAAI,GAAG;AAAA,MACzC,iBAAiB,MAAM,mBAAmB;AAAA,IAC5C,CAAC;AACD,UAAM,YAAY,IAAI,qBAAqB;AAC3C,UAAM,OAAO,QAAQ,SAAS;AAE9B,SAAK,KAAK,uCAAuC;AAAA,EACnD;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/commands/migrate/baseline.ts"],"sourcesContent":["import { Flags } from '@oclif/core'\nimport { BaseCommand } from '../../base-command.js'\nimport { baselineMigrations } from '../../migrate.js'\nimport { ok, dim, bold } from '../../ui.js'\n\n/**\n * Mark all local migration files as applied without executing them.\n *\n * Use this when onboarding an existing self-hosted Supabase database\n * whose schema already matches the migration files.\n *\n * Creates the supabase_migrations schema and table if they don't exist.\n */\nexport default class MigrateBaseline extends BaseCommand {\n static override description = 'Mark all local migrations as applied without executing them'\n\n static override examples = [\n '<%= config.bin %> migrate baseline --env=prod',\n '<%= config.bin %> migrate baseline --env=prod --apply',\n ]\n\n static override flags = {\n env: Flags.string({\n char: 'e',\n description: 'Target environment to baseline',\n }),\n apply: Flags.boolean({\n description: 'Write the tracking rows (previews without it)',\n default: false,\n }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(MigrateBaseline)\n\n const config = await this.loadConfigOrFail()\n const { envName, env } = this.resolveEnv(config, flags.env)\n const dir = this.resolveMigrationsDir(config)\n\n // Preflight: verify database is reachable\n const pre = this.createPreflight('Migrate baseline preflight checks')\n .addDatabase('Target', envName, env.dbUrl)\n await this.runPreflight(pre, 'Migrate baseline')\n\n this.log(`${bold('migrate baseline')} → ${dim(envName)} (${dim(this.redactUrl(env.dbUrl))})\\n`)\n\n // Previews by default, like every other state-changing command. It used to\n // write on sight with no flag but --env, which made it the easiest command\n // in the tool to run by accident (issue #88).\n const result = await baselineMigrations(env.dbUrl, dir, undefined, undefined, {\n dryRun: !flags.apply,\n })\n\n if (result.marked.length === 0 && result.skipped.length === 0) {\n this.log(`${dim('No migration files found in')} ${dir}`)\n return\n }\n\n if (result.marked.length > 0) {\n this.log(flags.apply\n ? `${ok(`Marked ${result.marked.length} migration(s) as applied:`)}`\n : `${bold(`Would mark ${result.marked.length} migration(s) as applied:`)}`)\n for (const m of result.marked) {\n this.log(` ${ok('✓')} ${m.version}_${m.name}`)\n }\n }\n\n if (result.skipped.length > 0) {\n this.log(`\\n${dim(`Skipped ${result.skipped.length} already-recorded migration(s):`)}`)\n for (const s of result.skipped) {\n this.log(` ${dim('○')} ${s.version} — ${s.reason}`)\n }\n }\n\n this.log(flags.apply\n ? `\\n${ok('Baseline complete.')} ✓`\n : `\\n${dim('Nothing was written.')} → Add ${bold('--apply')} to record these as applied.`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAatB,IAAqB,kBAArB,MAAqB,yBAAwB,YAAY;AAAA,EACvD,OAAgB,cAA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