@rebasepro/server-postgres 0.25.0-canary.g70dad01 → 0.25.0

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 (48) hide show
  1. package/dist/{BranchService-DO_3_CXt.js → BranchService-iXXZeVYD.js} +133 -20
  2. package/dist/BranchService-iXXZeVYD.js.map +1 -0
  3. package/dist/backup/backup-service.d.ts +8 -3
  4. package/dist/backup/pg-tools.d.ts +13 -1
  5. package/dist/{backup-cli-Ap2WX2uW.js → backup-cli-B2CAn9fR.js} +3 -3
  6. package/dist/{backup-cli-Ap2WX2uW.js.map → backup-cli-B2CAn9fR.js.map} +1 -1
  7. package/dist/{backup-service-DytMimsL.js → backup-service-Bb39plam.js} +67 -10
  8. package/dist/backup-service-Bb39plam.js.map +1 -0
  9. package/dist/{boot-ddl-D1lMCZLd.js → boot-ddl-s_3Hkz94.js} +2 -2
  10. package/dist/{boot-ddl-D1lMCZLd.js.map → boot-ddl-s_3Hkz94.js.map} +1 -1
  11. package/dist/{cli-console-CQGsBzSY.js → cli-console-DQ_K-sdM.js} +4 -4
  12. package/dist/{cli-console-CQGsBzSY.js.map → cli-console-DQ_K-sdM.js.map} +1 -1
  13. package/dist/{cli-errors-CJTKAKax.js → cli-errors-DwQnNATs.js} +52 -2
  14. package/dist/{cli-errors-CJTKAKax.js.map → cli-errors-DwQnNATs.js.map} +1 -1
  15. package/dist/cli-errors.d.ts +10 -0
  16. package/dist/cli.js +29 -24
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{deferred-index-build-BiTqxqdl.js → deferred-index-build-Cis_HoGn.js} +3 -3
  19. package/dist/{deferred-index-build-BiTqxqdl.js.map → deferred-index-build-Cis_HoGn.js.map} +1 -1
  20. package/dist/{doctor-N3J88BN_.js → doctor-DvJH-IQG.js} +2 -2
  21. package/dist/{doctor-N3J88BN_.js.map → doctor-DvJH-IQG.js.map} +1 -1
  22. package/dist/{ensure-collection-policies-CVP6kIPT.js → ensure-collection-policies-CCqayoUz.js} +4 -4
  23. package/dist/{ensure-collection-policies-CVP6kIPT.js.map → ensure-collection-policies-CCqayoUz.js.map} +1 -1
  24. package/dist/{ensure-collection-tables-1WVNALOW.js → ensure-collection-tables-DvvImXDe.js} +5 -5
  25. package/dist/{ensure-collection-tables-1WVNALOW.js.map → ensure-collection-tables-DvvImXDe.js.map} +1 -1
  26. package/dist/{ensure-tables-D-Nm2k3S.js → ensure-tables-Dpgwx5sy.js} +2 -2
  27. package/dist/{ensure-tables-D-Nm2k3S.js.map → ensure-tables-Dpgwx5sy.js.map} +1 -1
  28. package/dist/{enum-labels-kept-e_93v2Ic.js → enum-labels-kept-CUlUlRkO.js} +2 -2
  29. package/dist/{enum-labels-kept-e_93v2Ic.js.map → enum-labels-kept-CUlUlRkO.js.map} +1 -1
  30. package/dist/index.es.js +6 -6
  31. package/dist/{open-rebase-Cwnqo5LU.js → open-rebase-BKA7Nyoe.js} +21 -16
  32. package/dist/{open-rebase-Cwnqo5LU.js.map → open-rebase-BKA7Nyoe.js.map} +1 -1
  33. package/dist/{pg-error-utils-Cmo8wZPy.js → pg-error-utils-Bv5n2PLn.js} +2 -2
  34. package/dist/{pg-error-utils-Cmo8wZPy.js.map → pg-error-utils-Bv5n2PLn.js.map} +1 -1
  35. package/dist/{push-index-prebuild-SXRlWBjc.js → push-index-prebuild-DIequ4bV.js} +3 -3
  36. package/dist/{push-index-prebuild-SXRlWBjc.js.map → push-index-prebuild-DIequ4bV.js.map} +1 -1
  37. package/dist/{push-legacy-renames-B37yKDac.js → push-legacy-renames-BqJut4F3.js} +3 -3
  38. package/dist/{push-legacy-renames-B37yKDac.js.map → push-legacy-renames-BqJut4F3.js.map} +1 -1
  39. package/dist/{push-policy-plan-jXzHAWSu.js → push-policy-plan-CvX8hiPb.js} +2 -2
  40. package/dist/{push-policy-plan-jXzHAWSu.js.map → push-policy-plan-CvX8hiPb.js.map} +1 -1
  41. package/dist/schema/doctor-cli.js +2 -2
  42. package/dist/schema/introspect-db.js +1 -1
  43. package/dist/services/BranchService.d.ts +40 -4
  44. package/dist/{websocket-BT85Yv_G.js → websocket-MC0zTBar.js} +3 -3
  45. package/dist/{websocket-BT85Yv_G.js.map → websocket-MC0zTBar.js.map} +1 -1
  46. package/package.json +7 -7
  47. package/dist/BranchService-DO_3_CXt.js.map +0 -1
  48. package/dist/backup-service-DytMimsL.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"backup-cli-Ap2WX2uW.js","names":[],"sources":["../src/backup/backup-cli.ts"],"sourcesContent":["/**\n * CLI handlers for `rebase db backup`, `rebase db restore`, and\n * `rebase db backups list`. Kept out of the main `cli.ts` dispatcher so the\n * backup surface stays self-contained.\n */\nimport type arg from \"arg\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport chalk from \"chalk\";\n// Aliased: `out` is already a local in two of the commands below (the `--out`\n// backup destination).\nimport { out as print, outWarn, outError } from \"../cli-output\";\nimport { closestWord, parseCommandFlags } from \"../cli-flags\";\nimport { redactConnectionPasswords } from \"../utils/connection-string\";\nimport { promptConfirm } from \"../cli-prompt\";\nimport { checkDatabaseConnectivity } from \"../cli-errors\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport {\n BackupDestination,\n globalsFileForDump,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString,\n withDatabaseName\n} from \"./pg-tools\";\nimport {\n applyGlobals,\n BackupToolError,\n CleanRestoreFailed,\n createDump,\n discardPartialDump,\n ensureDatabaseExists,\n findCleanExtras,\n findRestoreConflicts,\n listBackups,\n preflight,\n readDumpObjects,\n restoreDump,\n restoreDumpReplacing,\n uploadBackup,\n validateDump\n} from \"./backup-service\";\nimport { resolvePgBinary } from \"./pg-binary\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n\n/** A web stream's chunks, for piping into a file. */\nasync function* webChunks(stream: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * The controller for an object-storage destination, or `null` for a local one.\n *\n * Built by `backupStorageFromEnv` from `@rebasepro/server` — the function the\n * Backups panel's routes use — so the CLI and the panel read a bucket the same\n * way. This file had its own copy, and the two had already drifted once\n * (`S3_FORCE_PATH_STYLE` read as `=== \"true\"`, so a MinIO backup addressed the\n * bucket as a host).\n *\n * Exported for its test.\n */\nexport async function resolveStorageForDestination(\n dest: BackupDestination,\n env: Record<string, string | undefined>\n): Promise<StorageController | null> {\n if (dest.kind === \"local\") return null;\n const { backupStorageFromEnv } = await import(\"@rebasepro/server\");\n try {\n return backupStorageFromEnv(dest, env);\n } catch (error) {\n throw new BackupToolError(\n error instanceof Error ? error.message : String(error),\n \"Set the same S3_* variables your backend uses for storage.\"\n );\n }\n}\n\n/**\n * The directory `rebase` was run from, which `rebase` puts here for the driver.\n *\n * The driver runs in the project's `backend/`, so a relative path resolved\n * against its own working directory named a different place from the one the\n * user typed it in: `rebase db backup --out ./backups` wrote to `<root>/backups`\n * (the CLI resolves explicit paths itself) while `rebase db backups list`\n * looked in `<root>/backend/backups`. Spelled the same in\n * `packages/cli/src/commands/db.ts`.\n */\nexport const INVOCATION_CWD_ENV = \"REBASE_INVOCATION_CWD\";\n\n/** Where a relative path the user typed is relative to: where they ran `rebase`. */\nexport function invocationDir(env: Readonly<Record<string, string | undefined>> = process.env): string {\n const dir = env[INVOCATION_CWD_ENV]?.trim();\n return dir && path.isAbsolute(dir) ? dir : process.cwd();\n}\n\n/**\n * Where `db backup` writes and `db backups list` reads, by one rule.\n *\n * - `--out` is relative to where `rebase` was run, like any path typed on a\n * command line.\n * - `BACKUP_DESTINATION` is relative to the backend directory, because the\n * server reads the same variable there: the Backups panel and the scheduled\n * backup have to find what the CLI wrote.\n * - With neither, `./backups` where `rebase` was run, as the help says.\n *\n * An `s3://` or `gs://` destination is returned as given.\n */\nexport function resolveBackupLocation(opts: {\n flag?: string;\n configured?: string;\n invocationDir: string;\n backendDir: string;\n}): string {\n const flag = opts.flag?.trim();\n if (flag) return isRemoteDestination(flag) ? flag : path.resolve(opts.invocationDir, flag);\n const configured = opts.configured?.trim();\n if (configured) return isRemoteDestination(configured) ? configured : path.resolve(opts.backendDir, configured);\n return path.join(opts.invocationDir, \"backups\");\n}\n\nfunction isRemoteDestination(value: string): boolean {\n return parseBackupDestination(value).kind !== \"local\";\n}\n\n/** {@link resolveBackupLocation} for this process. */\nfunction backupLocation(flag: string | undefined): string {\n return resolveBackupLocation({\n flag,\n configured: process.env.BACKUP_DESTINATION,\n invocationDir: invocationDir(),\n backendDir: process.cwd()\n });\n}\n\nfunction requireConnection(): string {\n const conn = resolveConnectionString(process.env);\n if (!conn) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return conn;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backup\n// ─────────────────────────────────────────────────────────────────────────\nconst BACKUP_FLAGS = {\n \"--out\": String,\n // The same alias `build` and `cloud env pull` carry. `--output` is the\n // canonical spelling in this CLI, and `rebase db backup --output ./backups`\n // has to write there.\n \"--output\": \"--out\",\n \"--exclude-schema\": [String],\n \"--no-owner\": Boolean,\n \"--enable-row-security\": Boolean,\n \"--row-security-role\": String,\n \"-o\": \"--out\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db backup …` line. An undeclared flag is refused (see\n * `parseCommandFlags`), and so is a positional: `rebase db backup ./backups`\n * means `--out ./backups`, and taken as nothing it wrote to the default\n * directory.\n */\nexport function parseBackupLine(rawArgs: string[]) {\n const args = parseCommandFlags(BACKUP_FLAGS, rawArgs.slice(2), \"db backup\");\n const [stray] = args._;\n if (stray !== undefined) {\n throw new Error(\n `\\`rebase db backup\\` takes no argument \"${stray}\". Nothing was run. ` +\n `To choose where the backup goes, pass --out ${stray}.`\n );\n }\n const dropsRebase = (args[\"--exclude-schema\"] ?? []).find(excludesRebaseSchema);\n if (dropsRebase !== undefined) {\n throw new Error(\n `--exclude-schema ${dropsRebase} leaves out the rebase schema, and a backup without it cannot be restored: ` +\n \"it holds the users, roles and the functions every policy calls. Nothing was run.\"\n );\n }\n return args;\n}\n\n/**\n * Whether a `pg_dump --exclude-schema` pattern matches the `rebase` schema, by\n * pg_dump's own rules: `*` and `?` are wildcards, an unquoted name is folded\n * to lower case and a double-quoted one is taken as written, and a\n * `<database>.<schema>` pattern is matched on its schema.\n */\nexport function excludesRebaseSchema(pattern: string): boolean {\n let source = \"\";\n let quoted = false;\n for (const char of pattern) {\n if (char === \"\\\"\") {\n quoted = !quoted;\n } else if (char === \".\" && !quoted) {\n // What came before was the database: the schema is what follows.\n source = \"\";\n } else if (char === \"*\" && !quoted) {\n source += \".*\";\n } else if (char === \"?\" && !quoted) {\n source += \".\";\n } else {\n const literal = quoted ? char : char.toLowerCase();\n source += literal.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n }\n return new RegExp(`^(?:${source})$`).test(\"rebase\");\n}\n\nexport async function backupCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printBackupHelp();\n return;\n }\n const args = parseBackupLine(rawArgs);\n\n const connectionString = requireConnection();\n const dbName = parseDbNameFromUrl(connectionString) ?? \"database\";\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n print(\"\");\n print(chalk.bold(\" 💾 Rebase DB Backup\"));\n print(chalk.gray(` Database: ${dbName}`));\n print(chalk.gray(` Destination: ${out}`));\n print(\"\");\n\n // A database that is not running is said the way `db push` says it — the\n // host, the port and what to start — before pg_dump's version probe meets\n // it as a bare `connect ECONNREFUSED`.\n await checkDatabaseConnectivity(connectionString);\n\n // Version pre-flight (doctor-style).\n const pf = await preflight(\"pg_dump\", connectionString);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n print(chalk.gray(` Using pg_dump ${pf.toolMajor} against server ${pf.serverMajor}.`));\n\n // Opt-in, and loud. With row security on, pg_dump stops refusing to read\n // rows it cannot see and starts leaving them out — an exit-0 backup that\n // is quietly short. Anyone choosing that should know they chose it.\n const rowSecurity = args[\"--enable-row-security\"]\n ? { uid: \"rebase-db-backup\", roles: [args[\"--row-security-role\"] || \"admin\"] }\n : undefined;\n\n if (rowSecurity) {\n outWarn(\"\");\n outWarn(chalk.yellow(\" ⚠ Dumping with row-level security ON.\"));\n outWarn(chalk.gray(` Reading as roles [${rowSecurity.roles.join(\", \")}], which satisfies the generated`));\n outWarn(chalk.gray(\" `admin_full_access` policy. This backup contains exactly the rows those\"));\n outWarn(chalk.gray(\" policies admit — a table whose policies have no admin rule comes out short,\"));\n outWarn(chalk.gray(\" and pg_dump will not say so. Prefer granting the dumping role BYPASSRLS.\"));\n outWarn(\"\");\n }\n\n try {\n if (dest.kind === \"local\") {\n // Honour an explicit `…/name.dump` path; otherwise treat it as a\n // directory and auto-name the file.\n const explicitFile = dest.path.endsWith(\".dump\");\n const dump = await createDump({\n connectionString,\n dbName,\n outDir: explicitFile ? path.dirname(dest.path) : dest.path,\n fileName: explicitFile ? path.basename(dest.path) : undefined,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n await assertDumpValid(dump.localFile);\n print(\"\");\n print(chalk.green(` ✓ Backup written to ${dump.localFile} (${formatBytes(dump.sizeBytes)})`));\n if (dump.globalsFile) {\n print(chalk.gray(` ✓ Roles captured to ${dump.globalsFile} (needed so RLS survives a restore).`));\n }\n } else {\n const storage = await resolveStorageForDestination(dest, process.env);\n const dump = await createDump({\n connectionString,\n dbName,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n try {\n await assertDumpValid(dump.localFile);\n const uploaded = await uploadBackup(storage!, dump.localFile, dest);\n print(\"\");\n print(chalk.green(` ✓ Backup uploaded to ${uploaded.storageUrl} (${formatBytes(dump.sizeBytes)})`));\n // Upload the roles sidecar next to the dump so a restore can\n // recreate roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const globalsUpload = await uploadBackup(storage!, dump.globalsFile, dest);\n print(chalk.gray(` ✓ Roles uploaded to ${globalsUpload.storageUrl} (needed so RLS survives a restore).`));\n }\n print(chalk.gray(\" Ensure this bucket is private — backups may contain secrets and PII.\"));\n } finally {\n if (fs.existsSync(dump.localFile)) fs.unlinkSync(dump.localFile);\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) fs.unlinkSync(dump.globalsFile);\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db restore <backup>\n// ─────────────────────────────────────────────────────────────────────────\nconst RESTORE_FLAGS = {\n \"--target-db\": String,\n \"--create-db\": Boolean,\n \"--clean\": Boolean,\n \"--no-owner\": Boolean,\n \"--continue-on-error\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db restore …` line; the one positional is the backup.\n *\n * Strict, because this is the command where a typo costs most: parsed\n * permissively, `--targt-db x` became a second positional, the target fell\n * back to DATABASE_URL's own database, and the restore ran against the live\n * one.\n */\nexport function parseRestoreLine(rawArgs: string[]) {\n const args = parseCommandFlags(RESTORE_FLAGS, rawArgs.slice(2), \"db restore\");\n if (args._.length > 1) {\n throw new Error(\n `\\`rebase db restore\\` restores one backup, and was given ${args._.length}: ` +\n `${args._.map(word => `\"${word}\"`).join(\", \")}. Nothing was run.`\n );\n }\n return args;\n}\n\n/**\n * The restore's one question, asked before anything can change.\n *\n * `--yes` skips it. On a terminal it asks for a typed 'yes'. With no terminal\n * nobody can answer, and the refusal says to pass `--yes`, as `db reset`,\n * `db pull` and `db branch prune` do: \"Aborted. No changes were made.\" alone\n * read as though someone had answered no.\n *\n * @returns whether to go on. When not, it has said why.\n */\nexport async function confirmRestore(opts: {\n target: string;\n yes: boolean;\n interactive: boolean;\n ask: (question: string) => Promise<boolean>;\n}): Promise<boolean> {\n if (opts.yes) return true;\n outWarn(chalk.yellow(` ⚠️ This will restore into \"${opts.target}\" and may overwrite existing data.`));\n if (!opts.interactive) {\n outError(chalk.red(\" ✗ Nothing was restored: there is no terminal to confirm on.\"));\n outError(chalk.gray(` Re-run with --yes to restore into \"${opts.target}\".`));\n return false;\n }\n const confirmed = await opts.ask(chalk.yellow(\" Type 'yes' to continue: \"));\n if (!confirmed) print(chalk.gray(\" Aborted. No changes were made.\"));\n return confirmed;\n}\n\n/** How many of the conflicting objects a refusal names before counting the rest. */\nconst CONFLICTS_NAMED = 5;\n\n/**\n * What `db restore` says when the target already holds what the backup\n * creates, and the two ways round it: `--clean` replaces them with the\n * backup's copy, a new database restores beside them.\n *\n * `line` is the rest of what the user typed — the database it names, `--yes`,\n * `--no-owner` — which both commands keep, so the one copied runs against the\n * same database and does not stop again to ask. `--target-db` goes on the\n * `--clean` one only: the other names a new database.\n */\nexport function describeRestoreConflict(\n target: string,\n backupArg: string,\n conflicts: readonly string[],\n line: { targetDb?: string; carried?: readonly string[] } = {}\n): { message: string; hint: string } {\n const named = conflicts.slice(0, CONFLICTS_NAMED).join(\", \");\n const more = conflicts.length > CONFLICTS_NAMED ? `, and ${conflicts.length - CONFLICTS_NAMED} more` : \"\";\n const carried = line.carried?.length ? ` ${line.carried.join(\" \")}` : \"\";\n const sameTarget = line.targetDb ? ` --target-db ${line.targetDb}` : \"\";\n return {\n message: `\"${target}\" already holds ${named}${more}, which this backup creates. ` +\n \"Without --clean, pg_restore stops at the first of them. Nothing was restored or changed.\",\n hint: [\n `To replace them with the backup's copy: rebase db restore ${backupArg}${sameTarget} --clean${carried}`,\n `To restore beside them, in a new database: rebase db restore ${backupArg} --create-db --target-db <new name>${carried}`\n ].join(\"\\n \")\n };\n}\n\n/** How many of the objects `--clean` drops beyond the backup's own it names before counting the rest. */\nconst EXTRAS_NAMED = 10;\n\n/**\n * What `restore --clean` says, before it asks, about what it drops that the\n * backup does not hold — see `findCleanExtras`. Nothing when there is none.\n */\nexport function describeCleanExtras(schemas: readonly string[], extras: readonly string[]): string[] {\n if (extras.length === 0) return [];\n const replaced = schemas.filter((schema) => schema !== \"public\");\n const lead = replaced.length > 0\n ? `--clean replaces ${replaced.length === 1 ? \"schema\" : \"schemas\"} ${replaced.join(\", \")} whole, so it also drops what this backup does not hold:`\n : \"--clean also drops what this backup does not hold:\";\n return [\n lead,\n ...extras.slice(0, EXTRAS_NAMED).map((extra) => ` ${extra}`),\n ...(extras.length > EXTRAS_NAMED ? [` and ${extras.length - EXTRAS_NAMED} more`] : [])\n ];\n}\n\n/**\n * What a `restore --clean` that stopped says: it ran as one transaction, so\n * nothing changed. The cluster roles the sidecar recreated are the exception,\n * and are said to be.\n */\nexport function describeCleanRestoreFailure(\n target: string,\n failure: { tool: \"pg_restore\" | \"psql\"; lockTimeout: boolean },\n rolesApplied: number\n): { message: string; hint?: string } {\n const why = failure.tool === \"pg_restore\"\n ? \"pg_restore could not read the whole backup\"\n : failure.lockTimeout\n ? `it waited too long for a lock on \"${target}\"`\n : \"a statement failed\";\n const hints = [\n ...(failure.lockTimeout\n ? [\"Something holds a lock on it — usually a `rebase dev` serving from it. Stop that, then restore again.\"]\n : []),\n ...(rolesApplied > 0\n ? [`The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay.`]\n : [])\n ];\n return {\n message: `Nothing was restored or changed: the restore ran as one transaction, and it was rolled back when ${why} (above). ` +\n `\"${target}\" holds what it held before.`,\n hint: hints.length > 0 ? hints.join(\"\\n \") : undefined\n };\n}\n\nexport async function restoreCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printRestoreHelp();\n return;\n }\n const args = parseRestoreLine(rawArgs);\n\n const backupArg = args._[0];\n if (!backupArg) {\n printRestoreHelp();\n process.exit(1);\n }\n\n const baseConnection = requireConnection();\n\n // Choose the target connection: an explicit --target-db swaps the database\n // name so the live one isn't clobbered. Without it the target is\n // DATABASE_URL's own database, and `--create-db` only creates it when it is\n // missing.\n const targetDb = args[\"--target-db\"] ?? parseDbNameFromUrl(baseConnection) ?? undefined;\n const targetConnection = args[\"--target-db\"]\n ? withDatabaseName(baseConnection, args[\"--target-db\"])\n : baseConnection;\n\n print(\"\");\n print(chalk.bold(\" ♻️ Rebase DB Restore\"));\n print(chalk.gray(` Source: ${backupArg}`));\n print(chalk.gray(` Target: ${targetDb ?? \"(from DATABASE_URL)\"}`));\n print(\"\");\n\n // Before anything is downloaded, and in `db push`'s words: see backupCommand.\n await checkDatabaseConnectivity(baseConnection);\n\n // Resolve the local file to restore from (download object-storage keys).\n // Also resolve the `.globals.sql` roles sidecar so cluster roles can be\n // recreated before the restore — without them the dump's GRANT/RLS\n // statements fail and RLS is silently lost.\n let localFile: string;\n let globalsSql: string | null = null;\n let cleanupTemp = false;\n try {\n if (/^(s3|gs):\\/\\//.test(backupArg)) {\n const dest = parseBackupDestination(backupArg.replace(/\\/[^/]+$/, \"\"));\n const storage = await resolveStorageForDestination(dest, process.env);\n if (!storage) throw new BackupToolError(\"Could not resolve storage for the given URL.\");\n const key = backupArg.replace(/^(s3|gs):\\/\\/[^/]+\\//, \"\");\n const bucket = backupArg.replace(/^(s3|gs):\\/\\/([^/]+)\\/.*$/, \"$2\");\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-restore-\"));\n localFile = path.join(tmpDir, path.basename(key));\n cleanupTemp = true;\n // Streamed to disk: buffered, a dump was held twice in memory and\n // one over 2 GiB could not be written in one call at all.\n const object = storage.getObjectStream\n ? await storage.getObjectStream(key, { bucket })\n : await storage.getObject(key, bucket).then((file) => file && { stream: file.stream() });\n if (!object) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);\n await pipeline(Readable.from(webChunks(object.stream)), fs.createWriteStream(localFile));\n const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);\n if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString(\"utf-8\");\n } else {\n localFile = path.resolve(invocationDir(), backupArg);\n if (!fs.existsSync(localFile)) throw new BackupToolError(`Backup file not found: ${localFile}`);\n const globalsPath = globalsFileForDump(localFile);\n if (fs.existsSync(globalsPath)) globalsSql = fs.readFileSync(globalsPath, \"utf-8\");\n }\n\n // Version pre-flight. Check against the base connection — the server\n // version is identical for every database, and the target may not\n // exist yet when --create-db is used.\n // Thrown, not exited, from here down: an exit skipped the `finally`\n // that removes a dump downloaded from object storage.\n const pf = await preflight(\"pg_restore\", baseConnection);\n if (!pf.compatible) throw new BackupToolError(pf.reason ?? \"pg_restore cannot restore into this server.\");\n\n // `--create-db` needs a name before anything else can be decided.\n if (args[\"--create-db\"] && !targetDb) {\n throw new BackupToolError(\"--create-db requires a resolvable target database name (use --target-db).\");\n }\n\n // Destructive-action gate. Restores overwrite data; never run without\n // an explicit yes (interactive confirmation or --yes).\n //\n // Ahead of `--create-db`, not after it. Creating the database first\n // meant an aborted run had already changed the cluster, while printing\n // \"No changes were made\" — and it left an empty database behind that a\n // second, confirmed run then reported as \"already exists\". The gate is\n // now the first thing that can stop the command, so its own message is\n // true whichever way the answer goes.\n // Before the question and before anything is applied, roles included:\n // without --clean, pg_restore stops at the first object the target\n // already has, and said so in its own words and execa's, after the\n // roles had run. A target that does not exist yet holds nothing.\n const objects = await readDumpObjects(localFile);\n if (!args[\"--clean\"]) {\n const conflicts = await findRestoreConflicts(targetConnection, objects);\n if (conflicts.length > 0) {\n const { message, hint } = describeRestoreConflict(targetDb ?? \"the target database\", backupArg, conflicts, {\n targetDb: args[\"--target-db\"],\n carried: [\n ...(args[\"--database-url\"] ? [\"--database-url\", `\"${args[\"--database-url\"]}\"`] : []),\n ...(args[\"--docker\"] ? [\"--docker\"] : []),\n ...(args[\"--no-owner\"] ? [\"--no-owner\"] : []),\n ...(args[\"--yes\"] ? [\"--yes\"] : [])\n ]\n });\n throw new BackupToolError(message, hint);\n }\n }\n\n // `--clean` replaces the backup's schemas whole, in one transaction\n // with the restore — see `restoreDumpReplacing`. `--continue-on-error`\n // asks for the opposite of one transaction, and gets pg_restore's own\n // `--clean`, statement by statement, as it asked.\n const replacing = args[\"--clean\"] === true && args[\"--continue-on-error\"] !== true;\n if (replacing) {\n if (!resolvePgBinary(\"psql\")) {\n throw new BackupToolError(\n \"Could not find the 'psql' binary, which runs a --clean restore as one transaction. Nothing was restored or changed.\",\n \"Install the PostgreSQL client tools (they ship psql beside pg_restore), or set PSQL_PATH to its full path.\"\n );\n }\n const extras = describeCleanExtras(objects.schemas, await findCleanExtras(targetConnection, objects));\n if (extras.length > 0) {\n outWarn(chalk.yellow(` ⚠️ ${extras[0]}`));\n for (const extra of extras.slice(1)) outWarn(chalk.yellow(` ${extra}`));\n }\n }\n\n const confirmed = await confirmRestore({\n target: targetDb ?? \"the target database\",\n yes: args[\"--yes\"] === true,\n interactive: process.stdin.isTTY === true,\n ask: promptConfirm\n });\n if (!confirmed) {\n // An exit code, so the `finally` still removes a downloaded dump.\n process.exitCode = 1;\n return;\n }\n\n // Create the target database when requested.\n if (args[\"--create-db\"]) {\n const created = await ensureDatabaseExists(baseConnection, targetDb!);\n print(chalk.gray(created ? ` ✓ Created database \"${targetDb}\".` : ` • Database \"${targetDb}\" already exists.`));\n }\n\n // Recreate cluster roles before restoring so GRANT/RLS statements in\n // the dump apply. Best-effort and idempotent (see applyGlobals).\n let rolesApplied = 0;\n if (globalsSql) {\n print(chalk.gray(\" Recreating cluster roles from the backup's roles sidecar…\"));\n const { applied, skipped } = await applyGlobals(\n targetConnection,\n globalsSql,\n (m) => print(chalk.gray(m))\n );\n rolesApplied = applied;\n print(chalk.gray(` ✓ Roles: ${applied} applied, ${skipped} skipped (already present or not permitted).`));\n } else {\n outWarn(chalk.yellow(\" ⚠️ No roles sidecar (.globals.sql) accompanies this backup.\"));\n outWarn(chalk.yellow(\" If the dump grants to roles that don't exist (e.g. rebase_user), the restore\"));\n outWarn(chalk.yellow(\" will fail — recreate those roles first, or use a backup that includes its globals.\"));\n }\n\n try {\n if (replacing) {\n await restoreDumpReplacing({\n connectionString: targetConnection,\n inputFile: localFile,\n objects,\n noOwner: args[\"--no-owner\"],\n inheritStdio: true\n });\n } else {\n await restoreDump({\n connectionString: targetConnection,\n inputFile: localFile,\n clean: args[\"--clean\"],\n noOwner: args[\"--no-owner\"],\n // Fail loudly by default so a skipped GRANT never leaves RLS off.\n exitOnError: !args[\"--continue-on-error\"],\n inheritStdio: true\n });\n }\n } catch (err) {\n if (err instanceof BackupToolError) throw err;\n if (err instanceof CleanRestoreFailed) {\n const { message, hint } = describeCleanRestoreFailure(targetDb ?? \"the target database\", err, rolesApplied);\n throw new BackupToolError(message, hint);\n }\n // pg_restore has printed its own error above; execa's repeats the\n // command line, which says nothing the reader can act on.\n throw new BackupToolError(\n `pg_restore stopped on the error above. What it restored before that stays in \"${targetDb ?? \"the target database\"}\".`,\n rolesApplied > 0\n ? `The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay too.`\n : undefined\n );\n }\n\n print(\"\");\n print(chalk.green(` ✓ Restore completed into \"${targetDb ?? \"the target database\"}\".`));\n print(\"\");\n } catch (err) {\n reportError(err);\n // An exit code, not `process.exit`: exiting here skipped the `finally`\n // below, and a failed restore from object storage left its downloaded\n // dump, every row of the database, in the temp directory.\n process.exitCode = 1;\n } finally {\n if (cleanupTemp && typeof localFile! === \"string\" && fs.existsSync(localFile!)) {\n fs.rmSync(path.dirname(localFile!), { recursive: true, force: true });\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backups list\n// ─────────────────────────────────────────────────────────────────────────\nconst BACKUPS_ACTIONS = [\"list\"] as const;\n\n/** What `db backups <action>` says of an action it does not have: the sentence every `db` command says. */\nexport function unknownBackupsAction(action: string): string {\n const near = closestWord(action, BACKUPS_ACTIONS);\n return near\n ? `Unknown db backups command \"${action}\" — did you mean \\`${near}\\`? Run \\`rebase db backups --help\\` for the rest.`\n : `Unknown db backups command \"${action}\". Run \\`rebase db backups --help\\` for the ones there are.`;\n}\n\nexport async function backupsCommand(rawArgs: string[]): Promise<void> {\n const action = rawArgs[2];\n if (!action || action === \"--help\") {\n printBackupsHelp();\n return;\n }\n if (action !== \"list\") {\n outError(chalk.red(`✗ ${unknownBackupsAction(action)}`));\n process.exit(1);\n }\n\n const args = parseCommandFlags(\n { \"--out\": String, \"--output\": \"--out\", \"-o\": \"--out\" },\n rawArgs.slice(3),\n \"db backups list\"\n );\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n try {\n const storage = await resolveStorageForDestination(dest, process.env);\n const backups = await listBackups(dest, storage ?? undefined);\n print(\"\");\n if (backups.length === 0) {\n print(chalk.gray(` No backups found at ${out}.`));\n await mentionBackendBackups(out, args[\"--out\"]);\n } else {\n print(chalk.bold(` 💾 ${backups.length} backup(s) at ${out}:`));\n print(\"\");\n for (const b of backups) {\n const when = b.createdAt ? b.createdAt.toISOString() : \"unknown date\";\n const name = dest.kind === \"local\" ? path.basename(b.key) : b.key;\n // An empty file is called out rather than listed as a peer of\n // the real ones. Older failures could leave a 0-byte dump here\n // (fixed at the source now), and retention protects the newest\n // by date whatever they contain — so a corpse left in place can\n // hold a `keepMinimum` slot against a backup that matters.\n const empty = b.sizeBytes === 0;\n const size = b.sizeBytes === undefined ? \"\" : ` — ${formatBytes(b.sizeBytes)}`;\n if (empty) {\n print(` ${chalk.red(\"○\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}`)}${chalk.red(\" — EMPTY, not restorable\")}`);\n } else {\n print(` ${chalk.green(\"●\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}${size}`)}`);\n }\n }\n if (backups.some(b => b.sizeBytes === 0)) {\n print(\"\");\n print(chalk.yellow(\" ⚠ Empty files above are leftovers from a failed backup. Delete them:\"));\n print(chalk.gray(\" they count as recent backups for retention but restore nothing.\"));\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n/**\n * Point at `<backend>/backups` when the default listing is empty and that\n * directory holds dumps.\n *\n * Earlier releases resolved the default there, so after an upgrade the\n * backups a project already has are one directory away from the listing.\n */\nasync function mentionBackendBackups(listed: string, flag: string | undefined): Promise<void> {\n if (flag || process.env.BACKUP_DESTINATION?.trim()) return;\n const backendBackups = path.join(process.cwd(), \"backups\");\n if (path.resolve(listed) === backendBackups) return;\n const found = await listBackups({ kind: \"local\", path: backendBackups }).catch(() => []);\n if (found.length === 0) return;\n print(chalk.gray(` ${found.length} backup(s) are in ${backendBackups}, where earlier releases of`));\n print(chalk.gray(` \\`rebase db backup\\` wrote by default. List them with:`));\n print(chalk.gray(` rebase db backups list --out ${path.relative(invocationDir(), backendBackups) || \".\"}`));\n}\n\n/**\n * Verify a freshly written dump; abort the command if it looks corrupt.\n *\n * Discards the artifact on the way out. Refusing to *report* success was never\n * enough on its own: the file stayed on disk, `rebase db backups list` showed\n * it as an ordinary entry, and retention — which ranks by timestamp and never\n * looks at size — would protect it as one of the `keepMinimum` newest while\n * pruning a real backup underneath it. The roles sidecar goes too; the two are\n * uploaded and pruned as a pair, so half a pair is not a backup either.\n */\nasync function assertDumpValid(localFile: string): Promise<void> {\n const check = await validateDump(localFile);\n if (!check.ok) {\n discardPartialDump(globalsFileForDump(localFile));\n discardPartialDump(localFile);\n throw new BackupToolError(\n `The backup failed validation and was discarded: ${check.reason}`,\n \"The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.\"\n );\n }\n}\n\n/**\n * Say why a backup command failed, with no password in it.\n *\n * What reaches here is often a client tool's failure, and execa's message\n * repeats the tool's command line. The tools get the password through\n * `PGPASSWORD` now, so it is not on that line, but a connection string can\n * still arrive inside a message from elsewhere; this is the last place to\n * stop it reaching a terminal or a CI log.\n */\nfunction reportError(err: unknown): void {\n if (err instanceof BackupToolError) {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err.message)}`));\n if (err.hint) outError(chalk.gray(` ${redactConnectionPasswords(err.hint)}`));\n } else {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err instanceof Error ? err.message : String(err))}`));\n }\n}\n\nfunction printBackupHelp(): void {\n print(`\n${chalk.bold(\"rebase db backup\")} — Create a database backup (pg_dump, custom format)\n\n${chalk.green.bold(\"Usage\")}\n rebase db backup [--out <path|s3://bucket/prefix>] [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--out, -o\")} <dest> Local path or s3://…/gs://… URL (default: ./backups)\n ${chalk.blue(\"--exclude-schema\")} <s> Exclude a schema (repeatable). Never rebase: a backup\n without it cannot be restored\n ${chalk.blue(\"--no-owner\")} Omit ownership commands from the dump\n ${chalk.blue(\"--enable-row-security\")} Dump as an admin subject instead of failing on RLS\n ${chalk.red(\"(may produce a partial dump — see below)\")}\n ${chalk.blue(\"--row-security-role\")} <r> Role to read as with the flag above (default: admin)\n\n${chalk.green.bold(\"Row-level security\")}\n On a managed Postgres the dumping role usually owns nothing and has no\n BYPASSRLS, so pg_dump refuses:\n\n ERROR: query would be affected by row-level security policy for table \"...\"\n\n That refusal is the safe behaviour. --enable-row-security replaces it by\n reading as an admin subject: Rebase sets app.uid/app.user_roles so the\n generated admin_full_access policy admits the dump. The dump then contains\n exactly what those policies admit ${chalk.red(\"and no error is raised for what they do not\")} —\n a table whose policies lack an admin rule comes out short, silently.\n\n Granting the dumping role BYPASSRLS is the option that keeps a backup\n meaning \"every row\".\n\n${chalk.green.bold(\"Notes\")}\n Backups may contain secrets and PII. Use private storage destinations and\n enable encryption-at-rest. See docs/backups.md.\n`);\n}\n\nfunction printRestoreHelp(): void {\n print(`\n${chalk.bold(\"rebase db restore\")} — Restore a database from a backup (pg_restore)\n\n${chalk.green.bold(\"Usage\")}\n rebase db restore <backup> [options]\n\n${chalk.green.bold(\"Arguments\")}\n <backup> Local .dump file, or s3://…/gs://… object key\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--target-db\")} <name> Restore into this database instead of DATABASE_URL's\n ${chalk.blue(\"--create-db\")} Create the target database first if it doesn't exist\n ${chalk.blue(\"--clean\")} Replace what the backup holds, in one transaction with\n the restore (runs the dump through psql)\n ${chalk.blue(\"--no-owner\")} Ignore ownership from the dump\n ${chalk.blue(\"--continue-on-error\")} Log and continue past errors ${chalk.red(\"(may leave RLS un-enforced!)\")}\n ${chalk.blue(\"--yes, -y\")} Skip the interactive confirmation ${chalk.red(\"(destructive!)\")}\n\n${chalk.red.bold(\"Warning\")}\n Restore is destructive and never runs automatically. Without --yes it\n asks for a typed 'yes' on a terminal, and with no terminal to ask on it\n refuses. Prefer --create-db/--target-db to restore into a fresh database\n rather than overwriting a live one. Into a database that already holds\n what the backup creates, it needs --clean, and refuses before changing\n anything without it. --clean drops each schema the backup creates whole,\n with what it holds that the backup does not (it names those first), and\n restores in the same transaction: a restore that stops changes nothing.\n\n By default the restore aborts on the first error (--exit-on-error) so a\n skipped GRANT never silently leaves RLS un-enforced. Roles are recreated\n from the backup's .globals.sql sidecar first; keep that file next to the\n dump. Use --continue-on-error only when you understand the consequences.\n`);\n}\n\nfunction printBackupsHelp(): void {\n print(`\n${chalk.bold(\"rebase db backups\")} — Manage stored backups\n\n${chalk.green.bold(\"Usage\")}\n rebase db backups list [--out <path|s3://bucket/prefix>]\n rebase db backup list [--out <path|s3://bucket/prefix>] ${chalk.gray(\"(the same thing)\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,SAAS,YAAY,OAAuB;CACxC,IAAI,QAAQ,MAAM,OAAO,GAAG,MAAM;CAClC,IAAI,QAAQ,OAAO,MAAM,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,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BAAmB,EAAE;;EAEhC,MAAM,MAAM,KAAK,OAAO,EAAE;;;EAG1B,MAAM,MAAM,KAAK,WAAW,EAAE;;;EAG9B,MAAM,MAAM,KAAK,SAAS,EAAE;IAC1B,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,SAAS,EAAE;;IAEtB,MAAM,KAAK,YAAY,EAAE;IACzB,MAAM,KAAK,qBAAqB,EAAE,oCAAoC,MAAM,IAAI,8BAA8B,EAAE;IAChH,MAAM,KAAK,WAAW,EAAE,mDAAmD,MAAM,IAAI,gBAAgB,EAAE;;EAEzG,MAAM,IAAI,KAAK,SAAS,EAAE;;;;;;;;;;;;;;CAc3B;AACD;AAEA,SAAS,mBAAyB;CAC9B,IAAM;EACR,MAAM,KAAK,mBAAmB,EAAE;;EAEhC,MAAM,MAAM,KAAK,OAAO,EAAE;;+DAEmC,MAAM,KAAK,kBAAkB,EAAE;CAC7F;AACD"}
1
+ {"version":3,"file":"backup-cli-B2CAn9fR.js","names":[],"sources":["../src/backup/backup-cli.ts"],"sourcesContent":["/**\n * CLI handlers for `rebase db backup`, `rebase db restore`, and\n * `rebase db backups list`. Kept out of the main `cli.ts` dispatcher so the\n * backup surface stays self-contained.\n */\nimport type arg from \"arg\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport chalk from \"chalk\";\n// Aliased: `out` is already a local in two of the commands below (the `--out`\n// backup destination).\nimport { out as print, outWarn, outError } from \"../cli-output\";\nimport { closestWord, parseCommandFlags } from \"../cli-flags\";\nimport { redactConnectionPasswords } from \"../utils/connection-string\";\nimport { promptConfirm } from \"../cli-prompt\";\nimport { checkDatabaseConnectivity } from \"../cli-errors\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport {\n BackupDestination,\n globalsFileForDump,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString,\n withDatabaseName\n} from \"./pg-tools\";\nimport {\n applyGlobals,\n BackupToolError,\n CleanRestoreFailed,\n createDump,\n discardPartialDump,\n ensureDatabaseExists,\n findCleanExtras,\n findRestoreConflicts,\n listBackups,\n preflight,\n readDumpObjects,\n restoreDump,\n restoreDumpReplacing,\n uploadBackup,\n validateDump\n} from \"./backup-service\";\nimport { resolvePgBinary } from \"./pg-binary\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n\n/** A web stream's chunks, for piping into a file. */\nasync function* webChunks(stream: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * The controller for an object-storage destination, or `null` for a local one.\n *\n * Built by `backupStorageFromEnv` from `@rebasepro/server` — the function the\n * Backups panel's routes use — so the CLI and the panel read a bucket the same\n * way. This file had its own copy, and the two had already drifted once\n * (`S3_FORCE_PATH_STYLE` read as `=== \"true\"`, so a MinIO backup addressed the\n * bucket as a host).\n *\n * Exported for its test.\n */\nexport async function resolveStorageForDestination(\n dest: BackupDestination,\n env: Record<string, string | undefined>\n): Promise<StorageController | null> {\n if (dest.kind === \"local\") return null;\n const { backupStorageFromEnv } = await import(\"@rebasepro/server\");\n try {\n return backupStorageFromEnv(dest, env);\n } catch (error) {\n throw new BackupToolError(\n error instanceof Error ? error.message : String(error),\n \"Set the same S3_* variables your backend uses for storage.\"\n );\n }\n}\n\n/**\n * The directory `rebase` was run from, which `rebase` puts here for the driver.\n *\n * The driver runs in the project's `backend/`, so a relative path resolved\n * against its own working directory named a different place from the one the\n * user typed it in: `rebase db backup --out ./backups` wrote to `<root>/backups`\n * (the CLI resolves explicit paths itself) while `rebase db backups list`\n * looked in `<root>/backend/backups`. Spelled the same in\n * `packages/cli/src/commands/db.ts`.\n */\nexport const INVOCATION_CWD_ENV = \"REBASE_INVOCATION_CWD\";\n\n/** Where a relative path the user typed is relative to: where they ran `rebase`. */\nexport function invocationDir(env: Readonly<Record<string, string | undefined>> = process.env): string {\n const dir = env[INVOCATION_CWD_ENV]?.trim();\n return dir && path.isAbsolute(dir) ? dir : process.cwd();\n}\n\n/**\n * Where `db backup` writes and `db backups list` reads, by one rule.\n *\n * - `--out` is relative to where `rebase` was run, like any path typed on a\n * command line.\n * - `BACKUP_DESTINATION` is relative to the backend directory, because the\n * server reads the same variable there: the Backups panel and the scheduled\n * backup have to find what the CLI wrote.\n * - With neither, `./backups` where `rebase` was run, as the help says.\n *\n * An `s3://` or `gs://` destination is returned as given.\n */\nexport function resolveBackupLocation(opts: {\n flag?: string;\n configured?: string;\n invocationDir: string;\n backendDir: string;\n}): string {\n const flag = opts.flag?.trim();\n if (flag) return isRemoteDestination(flag) ? flag : path.resolve(opts.invocationDir, flag);\n const configured = opts.configured?.trim();\n if (configured) return isRemoteDestination(configured) ? configured : path.resolve(opts.backendDir, configured);\n return path.join(opts.invocationDir, \"backups\");\n}\n\nfunction isRemoteDestination(value: string): boolean {\n return parseBackupDestination(value).kind !== \"local\";\n}\n\n/** {@link resolveBackupLocation} for this process. */\nfunction backupLocation(flag: string | undefined): string {\n return resolveBackupLocation({\n flag,\n configured: process.env.BACKUP_DESTINATION,\n invocationDir: invocationDir(),\n backendDir: process.cwd()\n });\n}\n\nfunction requireConnection(): string {\n const conn = resolveConnectionString(process.env);\n if (!conn) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return conn;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backup\n// ─────────────────────────────────────────────────────────────────────────\nconst BACKUP_FLAGS = {\n \"--out\": String,\n // The same alias `build` and `cloud env pull` carry. `--output` is the\n // canonical spelling in this CLI, and `rebase db backup --output ./backups`\n // has to write there.\n \"--output\": \"--out\",\n \"--exclude-schema\": [String],\n \"--no-owner\": Boolean,\n \"--enable-row-security\": Boolean,\n \"--row-security-role\": String,\n \"-o\": \"--out\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db backup …` line. An undeclared flag is refused (see\n * `parseCommandFlags`), and so is a positional: `rebase db backup ./backups`\n * means `--out ./backups`, and taken as nothing it wrote to the default\n * directory.\n */\nexport function parseBackupLine(rawArgs: string[]) {\n const args = parseCommandFlags(BACKUP_FLAGS, rawArgs.slice(2), \"db backup\");\n const [stray] = args._;\n if (stray !== undefined) {\n throw new Error(\n `\\`rebase db backup\\` takes no argument \"${stray}\". Nothing was run. ` +\n `To choose where the backup goes, pass --out ${stray}.`\n );\n }\n const dropsRebase = (args[\"--exclude-schema\"] ?? []).find(excludesRebaseSchema);\n if (dropsRebase !== undefined) {\n throw new Error(\n `--exclude-schema ${dropsRebase} leaves out the rebase schema, and a backup without it cannot be restored: ` +\n \"it holds the users, roles and the functions every policy calls. Nothing was run.\"\n );\n }\n return args;\n}\n\n/**\n * Whether a `pg_dump --exclude-schema` pattern matches the `rebase` schema, by\n * pg_dump's own rules: `*` and `?` are wildcards, an unquoted name is folded\n * to lower case and a double-quoted one is taken as written, and a\n * `<database>.<schema>` pattern is matched on its schema.\n */\nexport function excludesRebaseSchema(pattern: string): boolean {\n let source = \"\";\n let quoted = false;\n for (const char of pattern) {\n if (char === \"\\\"\") {\n quoted = !quoted;\n } else if (char === \".\" && !quoted) {\n // What came before was the database: the schema is what follows.\n source = \"\";\n } else if (char === \"*\" && !quoted) {\n source += \".*\";\n } else if (char === \"?\" && !quoted) {\n source += \".\";\n } else {\n const literal = quoted ? char : char.toLowerCase();\n source += literal.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n }\n return new RegExp(`^(?:${source})$`).test(\"rebase\");\n}\n\nexport async function backupCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printBackupHelp();\n return;\n }\n const args = parseBackupLine(rawArgs);\n\n const connectionString = requireConnection();\n const dbName = parseDbNameFromUrl(connectionString) ?? \"database\";\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n print(\"\");\n print(chalk.bold(\" 💾 Rebase DB Backup\"));\n print(chalk.gray(` Database: ${dbName}`));\n print(chalk.gray(` Destination: ${out}`));\n print(\"\");\n\n // A database that is not running is said the way `db push` says it — the\n // host, the port and what to start — before pg_dump's version probe meets\n // it as a bare `connect ECONNREFUSED`.\n await checkDatabaseConnectivity(connectionString);\n\n // Version pre-flight (doctor-style).\n const pf = await preflight(\"pg_dump\", connectionString);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n print(chalk.gray(` Using pg_dump ${pf.toolMajor} against server ${pf.serverMajor}.`));\n\n // Opt-in, and loud. With row security on, pg_dump stops refusing to read\n // rows it cannot see and starts leaving them out — an exit-0 backup that\n // is quietly short. Anyone choosing that should know they chose it.\n const rowSecurity = args[\"--enable-row-security\"]\n ? { uid: \"rebase-db-backup\", roles: [args[\"--row-security-role\"] || \"admin\"] }\n : undefined;\n\n if (rowSecurity) {\n outWarn(\"\");\n outWarn(chalk.yellow(\" ⚠ Dumping with row-level security ON.\"));\n outWarn(chalk.gray(` Reading as roles [${rowSecurity.roles.join(\", \")}], which satisfies the generated`));\n outWarn(chalk.gray(\" `admin_full_access` policy. This backup contains exactly the rows those\"));\n outWarn(chalk.gray(\" policies admit — a table whose policies have no admin rule comes out short,\"));\n outWarn(chalk.gray(\" and pg_dump will not say so. Prefer granting the dumping role BYPASSRLS.\"));\n outWarn(\"\");\n }\n\n try {\n if (dest.kind === \"local\") {\n // Honour an explicit `…/name.dump` path; otherwise treat it as a\n // directory and auto-name the file.\n const explicitFile = dest.path.endsWith(\".dump\");\n const dump = await createDump({\n connectionString,\n dbName,\n outDir: explicitFile ? path.dirname(dest.path) : dest.path,\n fileName: explicitFile ? path.basename(dest.path) : undefined,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n await assertDumpValid(dump.localFile);\n print(\"\");\n print(chalk.green(` ✓ Backup written to ${dump.localFile} (${formatBytes(dump.sizeBytes)})`));\n if (dump.globalsFile) {\n print(chalk.gray(` ✓ Roles captured to ${dump.globalsFile} (needed so RLS survives a restore).`));\n }\n } else {\n const storage = await resolveStorageForDestination(dest, process.env);\n const dump = await createDump({\n connectionString,\n dbName,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n try {\n await assertDumpValid(dump.localFile);\n const uploaded = await uploadBackup(storage!, dump.localFile, dest);\n print(\"\");\n print(chalk.green(` ✓ Backup uploaded to ${uploaded.storageUrl} (${formatBytes(dump.sizeBytes)})`));\n // Upload the roles sidecar next to the dump so a restore can\n // recreate roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const globalsUpload = await uploadBackup(storage!, dump.globalsFile, dest);\n print(chalk.gray(` ✓ Roles uploaded to ${globalsUpload.storageUrl} (needed so RLS survives a restore).`));\n }\n print(chalk.gray(\" Ensure this bucket is private — backups may contain secrets and PII.\"));\n } finally {\n if (fs.existsSync(dump.localFile)) fs.unlinkSync(dump.localFile);\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) fs.unlinkSync(dump.globalsFile);\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db restore <backup>\n// ─────────────────────────────────────────────────────────────────────────\nconst RESTORE_FLAGS = {\n \"--target-db\": String,\n \"--create-db\": Boolean,\n \"--clean\": Boolean,\n \"--no-owner\": Boolean,\n \"--continue-on-error\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db restore …` line; the one positional is the backup.\n *\n * Strict, because this is the command where a typo costs most: parsed\n * permissively, `--targt-db x` became a second positional, the target fell\n * back to DATABASE_URL's own database, and the restore ran against the live\n * one.\n */\nexport function parseRestoreLine(rawArgs: string[]) {\n const args = parseCommandFlags(RESTORE_FLAGS, rawArgs.slice(2), \"db restore\");\n if (args._.length > 1) {\n throw new Error(\n `\\`rebase db restore\\` restores one backup, and was given ${args._.length}: ` +\n `${args._.map(word => `\"${word}\"`).join(\", \")}. Nothing was run.`\n );\n }\n return args;\n}\n\n/**\n * The restore's one question, asked before anything can change.\n *\n * `--yes` skips it. On a terminal it asks for a typed 'yes'. With no terminal\n * nobody can answer, and the refusal says to pass `--yes`, as `db reset`,\n * `db pull` and `db branch prune` do: \"Aborted. No changes were made.\" alone\n * read as though someone had answered no.\n *\n * @returns whether to go on. When not, it has said why.\n */\nexport async function confirmRestore(opts: {\n target: string;\n yes: boolean;\n interactive: boolean;\n ask: (question: string) => Promise<boolean>;\n}): Promise<boolean> {\n if (opts.yes) return true;\n outWarn(chalk.yellow(` ⚠️ This will restore into \"${opts.target}\" and may overwrite existing data.`));\n if (!opts.interactive) {\n outError(chalk.red(\" ✗ Nothing was restored: there is no terminal to confirm on.\"));\n outError(chalk.gray(` Re-run with --yes to restore into \"${opts.target}\".`));\n return false;\n }\n const confirmed = await opts.ask(chalk.yellow(\" Type 'yes' to continue: \"));\n if (!confirmed) print(chalk.gray(\" Aborted. No changes were made.\"));\n return confirmed;\n}\n\n/** How many of the conflicting objects a refusal names before counting the rest. */\nconst CONFLICTS_NAMED = 5;\n\n/**\n * What `db restore` says when the target already holds what the backup\n * creates, and the two ways round it: `--clean` replaces them with the\n * backup's copy, a new database restores beside them.\n *\n * `line` is the rest of what the user typed — the database it names, `--yes`,\n * `--no-owner` — which both commands keep, so the one copied runs against the\n * same database and does not stop again to ask. `--target-db` goes on the\n * `--clean` one only: the other names a new database.\n */\nexport function describeRestoreConflict(\n target: string,\n backupArg: string,\n conflicts: readonly string[],\n line: { targetDb?: string; carried?: readonly string[] } = {}\n): { message: string; hint: string } {\n const named = conflicts.slice(0, CONFLICTS_NAMED).join(\", \");\n const more = conflicts.length > CONFLICTS_NAMED ? `, and ${conflicts.length - CONFLICTS_NAMED} more` : \"\";\n const carried = line.carried?.length ? ` ${line.carried.join(\" \")}` : \"\";\n const sameTarget = line.targetDb ? ` --target-db ${line.targetDb}` : \"\";\n return {\n message: `\"${target}\" already holds ${named}${more}, which this backup creates. ` +\n \"Without --clean, pg_restore stops at the first of them. Nothing was restored or changed.\",\n hint: [\n `To replace them with the backup's copy: rebase db restore ${backupArg}${sameTarget} --clean${carried}`,\n `To restore beside them, in a new database: rebase db restore ${backupArg} --create-db --target-db <new name>${carried}`\n ].join(\"\\n \")\n };\n}\n\n/** How many of the objects `--clean` drops beyond the backup's own it names before counting the rest. */\nconst EXTRAS_NAMED = 10;\n\n/**\n * What `restore --clean` says, before it asks, about what it drops that the\n * backup does not hold — see `findCleanExtras`. Nothing when there is none.\n */\nexport function describeCleanExtras(schemas: readonly string[], extras: readonly string[]): string[] {\n if (extras.length === 0) return [];\n const replaced = schemas.filter((schema) => schema !== \"public\");\n const lead = replaced.length > 0\n ? `--clean replaces ${replaced.length === 1 ? \"schema\" : \"schemas\"} ${replaced.join(\", \")} whole, so it also drops what this backup does not hold:`\n : \"--clean also drops what this backup does not hold:\";\n return [\n lead,\n ...extras.slice(0, EXTRAS_NAMED).map((extra) => ` ${extra}`),\n ...(extras.length > EXTRAS_NAMED ? [` and ${extras.length - EXTRAS_NAMED} more`] : [])\n ];\n}\n\n/**\n * What a `restore --clean` that stopped says: it ran as one transaction, so\n * nothing changed. The cluster roles the sidecar recreated are the exception,\n * and are said to be.\n */\nexport function describeCleanRestoreFailure(\n target: string,\n failure: { tool: \"pg_restore\" | \"psql\"; lockTimeout: boolean },\n rolesApplied: number\n): { message: string; hint?: string } {\n const why = failure.tool === \"pg_restore\"\n ? \"pg_restore could not read the whole backup\"\n : failure.lockTimeout\n ? `it waited too long for a lock on \"${target}\"`\n : \"a statement failed\";\n const hints = [\n ...(failure.lockTimeout\n ? [\"Something holds a lock on it — usually a `rebase dev` serving from it. Stop that, then restore again.\"]\n : []),\n ...(rolesApplied > 0\n ? [`The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay.`]\n : [])\n ];\n return {\n message: `Nothing was restored or changed: the restore ran as one transaction, and it was rolled back when ${why} (above). ` +\n `\"${target}\" holds what it held before.`,\n hint: hints.length > 0 ? hints.join(\"\\n \") : undefined\n };\n}\n\nexport async function restoreCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printRestoreHelp();\n return;\n }\n const args = parseRestoreLine(rawArgs);\n\n const backupArg = args._[0];\n if (!backupArg) {\n printRestoreHelp();\n process.exit(1);\n }\n\n const baseConnection = requireConnection();\n\n // Choose the target connection: an explicit --target-db swaps the database\n // name so the live one isn't clobbered. Without it the target is\n // DATABASE_URL's own database, and `--create-db` only creates it when it is\n // missing.\n const targetDb = args[\"--target-db\"] ?? parseDbNameFromUrl(baseConnection) ?? undefined;\n const targetConnection = args[\"--target-db\"]\n ? withDatabaseName(baseConnection, args[\"--target-db\"])\n : baseConnection;\n\n print(\"\");\n print(chalk.bold(\" ♻️ Rebase DB Restore\"));\n print(chalk.gray(` Source: ${backupArg}`));\n print(chalk.gray(` Target: ${targetDb ?? \"(from DATABASE_URL)\"}`));\n print(\"\");\n\n // Before anything is downloaded, and in `db push`'s words: see backupCommand.\n await checkDatabaseConnectivity(baseConnection);\n\n // Resolve the local file to restore from (download object-storage keys).\n // Also resolve the `.globals.sql` roles sidecar so cluster roles can be\n // recreated before the restore — without them the dump's GRANT/RLS\n // statements fail and RLS is silently lost.\n let localFile: string;\n let globalsSql: string | null = null;\n let cleanupTemp = false;\n try {\n if (/^(s3|gs):\\/\\//.test(backupArg)) {\n const dest = parseBackupDestination(backupArg.replace(/\\/[^/]+$/, \"\"));\n const storage = await resolveStorageForDestination(dest, process.env);\n if (!storage) throw new BackupToolError(\"Could not resolve storage for the given URL.\");\n const key = backupArg.replace(/^(s3|gs):\\/\\/[^/]+\\//, \"\");\n const bucket = backupArg.replace(/^(s3|gs):\\/\\/([^/]+)\\/.*$/, \"$2\");\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-restore-\"));\n localFile = path.join(tmpDir, path.basename(key));\n cleanupTemp = true;\n // Streamed to disk: buffered, a dump was held twice in memory and\n // one over 2 GiB could not be written in one call at all.\n const object = storage.getObjectStream\n ? await storage.getObjectStream(key, { bucket })\n : await storage.getObject(key, bucket).then((file) => file && { stream: file.stream() });\n if (!object) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);\n await pipeline(Readable.from(webChunks(object.stream)), fs.createWriteStream(localFile));\n const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);\n if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString(\"utf-8\");\n } else {\n localFile = path.resolve(invocationDir(), backupArg);\n if (!fs.existsSync(localFile)) throw new BackupToolError(`Backup file not found: ${localFile}`);\n const globalsPath = globalsFileForDump(localFile);\n if (fs.existsSync(globalsPath)) globalsSql = fs.readFileSync(globalsPath, \"utf-8\");\n }\n\n // Version pre-flight. Check against the base connection — the server\n // version is identical for every database, and the target may not\n // exist yet when --create-db is used.\n // Thrown, not exited, from here down: an exit skipped the `finally`\n // that removes a dump downloaded from object storage.\n const pf = await preflight(\"pg_restore\", baseConnection);\n if (!pf.compatible) throw new BackupToolError(pf.reason ?? \"pg_restore cannot restore into this server.\");\n\n // `--create-db` needs a name before anything else can be decided.\n if (args[\"--create-db\"] && !targetDb) {\n throw new BackupToolError(\"--create-db requires a resolvable target database name (use --target-db).\");\n }\n\n // Destructive-action gate. Restores overwrite data; never run without\n // an explicit yes (interactive confirmation or --yes).\n //\n // Ahead of `--create-db`, not after it. Creating the database first\n // meant an aborted run had already changed the cluster, while printing\n // \"No changes were made\" — and it left an empty database behind that a\n // second, confirmed run then reported as \"already exists\". The gate is\n // now the first thing that can stop the command, so its own message is\n // true whichever way the answer goes.\n // Before the question and before anything is applied, roles included:\n // without --clean, pg_restore stops at the first object the target\n // already has, and said so in its own words and execa's, after the\n // roles had run. A target that does not exist yet holds nothing.\n const objects = await readDumpObjects(localFile);\n if (!args[\"--clean\"]) {\n const conflicts = await findRestoreConflicts(targetConnection, objects);\n if (conflicts.length > 0) {\n const { message, hint } = describeRestoreConflict(targetDb ?? \"the target database\", backupArg, conflicts, {\n targetDb: args[\"--target-db\"],\n carried: [\n ...(args[\"--database-url\"] ? [\"--database-url\", `\"${args[\"--database-url\"]}\"`] : []),\n ...(args[\"--docker\"] ? [\"--docker\"] : []),\n ...(args[\"--no-owner\"] ? [\"--no-owner\"] : []),\n ...(args[\"--yes\"] ? [\"--yes\"] : [])\n ]\n });\n throw new BackupToolError(message, hint);\n }\n }\n\n // `--clean` replaces the backup's schemas whole, in one transaction\n // with the restore — see `restoreDumpReplacing`. `--continue-on-error`\n // asks for the opposite of one transaction, and gets pg_restore's own\n // `--clean`, statement by statement, as it asked.\n const replacing = args[\"--clean\"] === true && args[\"--continue-on-error\"] !== true;\n if (replacing) {\n if (!resolvePgBinary(\"psql\")) {\n throw new BackupToolError(\n \"Could not find the 'psql' binary, which runs a --clean restore as one transaction. Nothing was restored or changed.\",\n \"Install the PostgreSQL client tools (they ship psql beside pg_restore), or set PSQL_PATH to its full path.\"\n );\n }\n const extras = describeCleanExtras(objects.schemas, await findCleanExtras(targetConnection, objects));\n if (extras.length > 0) {\n outWarn(chalk.yellow(` ⚠️ ${extras[0]}`));\n for (const extra of extras.slice(1)) outWarn(chalk.yellow(` ${extra}`));\n }\n }\n\n const confirmed = await confirmRestore({\n target: targetDb ?? \"the target database\",\n yes: args[\"--yes\"] === true,\n interactive: process.stdin.isTTY === true,\n ask: promptConfirm\n });\n if (!confirmed) {\n // An exit code, so the `finally` still removes a downloaded dump.\n process.exitCode = 1;\n return;\n }\n\n // Create the target database when requested.\n if (args[\"--create-db\"]) {\n const created = await ensureDatabaseExists(baseConnection, targetDb!);\n print(chalk.gray(created ? ` ✓ Created database \"${targetDb}\".` : ` • Database \"${targetDb}\" already exists.`));\n }\n\n // Recreate cluster roles before restoring so GRANT/RLS statements in\n // the dump apply. Best-effort and idempotent (see applyGlobals).\n let rolesApplied = 0;\n if (globalsSql) {\n print(chalk.gray(\" Recreating cluster roles from the backup's roles sidecar…\"));\n const { applied, skipped } = await applyGlobals(\n targetConnection,\n globalsSql,\n (m) => print(chalk.gray(m))\n );\n rolesApplied = applied;\n print(chalk.gray(` ✓ Roles: ${applied} applied, ${skipped} skipped (already present or not permitted).`));\n } else {\n outWarn(chalk.yellow(\" ⚠️ No roles sidecar (.globals.sql) accompanies this backup.\"));\n outWarn(chalk.yellow(\" If the dump grants to roles that don't exist (e.g. rebase_user), the restore\"));\n outWarn(chalk.yellow(\" will fail — recreate those roles first, or use a backup that includes its globals.\"));\n }\n\n try {\n if (replacing) {\n await restoreDumpReplacing({\n connectionString: targetConnection,\n inputFile: localFile,\n objects,\n noOwner: args[\"--no-owner\"],\n inheritStdio: true\n });\n } else {\n await restoreDump({\n connectionString: targetConnection,\n inputFile: localFile,\n clean: args[\"--clean\"],\n noOwner: args[\"--no-owner\"],\n // Fail loudly by default so a skipped GRANT never leaves RLS off.\n exitOnError: !args[\"--continue-on-error\"],\n inheritStdio: true\n });\n }\n } catch (err) {\n if (err instanceof BackupToolError) throw err;\n if (err instanceof CleanRestoreFailed) {\n const { message, hint } = describeCleanRestoreFailure(targetDb ?? \"the target database\", err, rolesApplied);\n throw new BackupToolError(message, hint);\n }\n // pg_restore has printed its own error above; execa's repeats the\n // command line, which says nothing the reader can act on.\n throw new BackupToolError(\n `pg_restore stopped on the error above. What it restored before that stays in \"${targetDb ?? \"the target database\"}\".`,\n rolesApplied > 0\n ? `The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay too.`\n : undefined\n );\n }\n\n print(\"\");\n print(chalk.green(` ✓ Restore completed into \"${targetDb ?? \"the target database\"}\".`));\n print(\"\");\n } catch (err) {\n reportError(err);\n // An exit code, not `process.exit`: exiting here skipped the `finally`\n // below, and a failed restore from object storage left its downloaded\n // dump, every row of the database, in the temp directory.\n process.exitCode = 1;\n } finally {\n if (cleanupTemp && typeof localFile! === \"string\" && fs.existsSync(localFile!)) {\n fs.rmSync(path.dirname(localFile!), { recursive: true, force: true });\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backups list\n// ─────────────────────────────────────────────────────────────────────────\nconst BACKUPS_ACTIONS = [\"list\"] as const;\n\n/** What `db backups <action>` says of an action it does not have: the sentence every `db` command says. */\nexport function unknownBackupsAction(action: string): string {\n const near = closestWord(action, BACKUPS_ACTIONS);\n return near\n ? `Unknown db backups command \"${action}\" — did you mean \\`${near}\\`? Run \\`rebase db backups --help\\` for the rest.`\n : `Unknown db backups command \"${action}\". Run \\`rebase db backups --help\\` for the ones there are.`;\n}\n\nexport async function backupsCommand(rawArgs: string[]): Promise<void> {\n const action = rawArgs[2];\n if (!action || action === \"--help\") {\n printBackupsHelp();\n return;\n }\n if (action !== \"list\") {\n outError(chalk.red(`✗ ${unknownBackupsAction(action)}`));\n process.exit(1);\n }\n\n const args = parseCommandFlags(\n { \"--out\": String, \"--output\": \"--out\", \"-o\": \"--out\" },\n rawArgs.slice(3),\n \"db backups list\"\n );\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n try {\n const storage = await resolveStorageForDestination(dest, process.env);\n const backups = await listBackups(dest, storage ?? undefined);\n print(\"\");\n if (backups.length === 0) {\n print(chalk.gray(` No backups found at ${out}.`));\n await mentionBackendBackups(out, args[\"--out\"]);\n } else {\n print(chalk.bold(` 💾 ${backups.length} backup(s) at ${out}:`));\n print(\"\");\n for (const b of backups) {\n const when = b.createdAt ? b.createdAt.toISOString() : \"unknown date\";\n const name = dest.kind === \"local\" ? path.basename(b.key) : b.key;\n // An empty file is called out rather than listed as a peer of\n // the real ones. Older failures could leave a 0-byte dump here\n // (fixed at the source now), and retention protects the newest\n // by date whatever they contain — so a corpse left in place can\n // hold a `keepMinimum` slot against a backup that matters.\n const empty = b.sizeBytes === 0;\n const size = b.sizeBytes === undefined ? \"\" : ` — ${formatBytes(b.sizeBytes)}`;\n if (empty) {\n print(` ${chalk.red(\"○\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}`)}${chalk.red(\" — EMPTY, not restorable\")}`);\n } else {\n print(` ${chalk.green(\"●\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}${size}`)}`);\n }\n }\n if (backups.some(b => b.sizeBytes === 0)) {\n print(\"\");\n print(chalk.yellow(\" ⚠ Empty files above are leftovers from a failed backup. Delete them:\"));\n print(chalk.gray(\" they count as recent backups for retention but restore nothing.\"));\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n/**\n * Point at `<backend>/backups` when the default listing is empty and that\n * directory holds dumps.\n *\n * Earlier releases resolved the default there, so after an upgrade the\n * backups a project already has are one directory away from the listing.\n */\nasync function mentionBackendBackups(listed: string, flag: string | undefined): Promise<void> {\n if (flag || process.env.BACKUP_DESTINATION?.trim()) return;\n const backendBackups = path.join(process.cwd(), \"backups\");\n if (path.resolve(listed) === backendBackups) return;\n const found = await listBackups({ kind: \"local\", path: backendBackups }).catch(() => []);\n if (found.length === 0) return;\n print(chalk.gray(` ${found.length} backup(s) are in ${backendBackups}, where earlier releases of`));\n print(chalk.gray(` \\`rebase db backup\\` wrote by default. List them with:`));\n print(chalk.gray(` rebase db backups list --out ${path.relative(invocationDir(), backendBackups) || \".\"}`));\n}\n\n/**\n * Verify a freshly written dump; abort the command if it looks corrupt.\n *\n * Discards the artifact on the way out. Refusing to *report* success was never\n * enough on its own: the file stayed on disk, `rebase db backups list` showed\n * it as an ordinary entry, and retention — which ranks by timestamp and never\n * looks at size — would protect it as one of the `keepMinimum` newest while\n * pruning a real backup underneath it. The roles sidecar goes too; the two are\n * uploaded and pruned as a pair, so half a pair is not a backup either.\n */\nasync function assertDumpValid(localFile: string): Promise<void> {\n const check = await validateDump(localFile);\n if (!check.ok) {\n discardPartialDump(globalsFileForDump(localFile));\n discardPartialDump(localFile);\n throw new BackupToolError(\n `The backup failed validation and was discarded: ${check.reason}`,\n \"The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.\"\n );\n }\n}\n\n/**\n * Say why a backup command failed, with no password in it.\n *\n * What reaches here is often a client tool's failure, and execa's message\n * repeats the tool's command line. The tools get the password through\n * `PGPASSWORD` now, so it is not on that line, but a connection string can\n * still arrive inside a message from elsewhere; this is the last place to\n * stop it reaching a terminal or a CI log.\n */\nfunction reportError(err: unknown): void {\n if (err instanceof BackupToolError) {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err.message)}`));\n if (err.hint) outError(chalk.gray(` ${redactConnectionPasswords(err.hint)}`));\n } else {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err instanceof Error ? err.message : String(err))}`));\n }\n}\n\nfunction printBackupHelp(): void {\n print(`\n${chalk.bold(\"rebase db backup\")} — Create a database backup (pg_dump, custom format)\n\n${chalk.green.bold(\"Usage\")}\n rebase db backup [--out <path|s3://bucket/prefix>] [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--out, -o\")} <dest> Local path or s3://…/gs://… URL (default: ./backups)\n ${chalk.blue(\"--exclude-schema\")} <s> Exclude a schema (repeatable). Never rebase: a backup\n without it cannot be restored\n ${chalk.blue(\"--no-owner\")} Omit ownership commands from the dump\n ${chalk.blue(\"--enable-row-security\")} Dump as an admin subject instead of failing on RLS\n ${chalk.red(\"(may produce a partial dump — see below)\")}\n ${chalk.blue(\"--row-security-role\")} <r> Role to read as with the flag above (default: admin)\n\n${chalk.green.bold(\"Row-level security\")}\n On a managed Postgres the dumping role usually owns nothing and has no\n BYPASSRLS, so pg_dump refuses:\n\n ERROR: query would be affected by row-level security policy for table \"...\"\n\n That refusal is the safe behaviour. --enable-row-security replaces it by\n reading as an admin subject: Rebase sets app.uid/app.user_roles so the\n generated admin_full_access policy admits the dump. The dump then contains\n exactly what those policies admit ${chalk.red(\"and no error is raised for what they do not\")} —\n a table whose policies lack an admin rule comes out short, silently.\n\n Granting the dumping role BYPASSRLS is the option that keeps a backup\n meaning \"every row\".\n\n${chalk.green.bold(\"Notes\")}\n Backups may contain secrets and PII. Use private storage destinations and\n enable encryption-at-rest. See docs/backups.md.\n`);\n}\n\nfunction printRestoreHelp(): void {\n print(`\n${chalk.bold(\"rebase db restore\")} — Restore a database from a backup (pg_restore)\n\n${chalk.green.bold(\"Usage\")}\n rebase db restore <backup> [options]\n\n${chalk.green.bold(\"Arguments\")}\n <backup> Local .dump file, or s3://…/gs://… object key\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--target-db\")} <name> Restore into this database instead of DATABASE_URL's\n ${chalk.blue(\"--create-db\")} Create the target database first if it doesn't exist\n ${chalk.blue(\"--clean\")} Replace what the backup holds, in one transaction with\n the restore (runs the dump through psql)\n ${chalk.blue(\"--no-owner\")} Ignore ownership from the dump\n ${chalk.blue(\"--continue-on-error\")} Log and continue past errors ${chalk.red(\"(may leave RLS un-enforced!)\")}\n ${chalk.blue(\"--yes, -y\")} Skip the interactive confirmation ${chalk.red(\"(destructive!)\")}\n\n${chalk.red.bold(\"Warning\")}\n Restore is destructive and never runs automatically. Without --yes it\n asks for a typed 'yes' on a terminal, and with no terminal to ask on it\n refuses. Prefer --create-db/--target-db to restore into a fresh database\n rather than overwriting a live one. Into a database that already holds\n what the backup creates, it needs --clean, and refuses before changing\n anything without it. --clean drops each schema the backup creates whole,\n with what it holds that the backup does not (it names those first), and\n restores in the same transaction: a restore that stops changes nothing.\n\n By default the restore aborts on the first error (--exit-on-error) so a\n skipped GRANT never silently leaves RLS un-enforced. Roles are recreated\n from the backup's .globals.sql sidecar first; keep that file next to the\n dump. Use --continue-on-error only when you understand the consequences.\n`);\n}\n\nfunction printBackupsHelp(): void {\n print(`\n${chalk.bold(\"rebase db backups\")} — Manage stored backups\n\n${chalk.green.bold(\"Usage\")}\n rebase db backups list [--out <path|s3://bucket/prefix>]\n rebase db backup list [--out <path|s3://bucket/prefix>] ${chalk.gray(\"(the same thing)\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;AA+CA,SAAS,YAAY,OAAuB;CACxC,IAAI,QAAQ,MAAM,OAAO,GAAG,MAAM;CAClC,IAAI,QAAQ,OAAO,MAAM,OAAO,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;CAC7D,IAAI,QAAQ,OAAO,OAAO,MAAM,OAAO,IAAI,SAAS,OAAO,MAAA,CAAO,QAAQ,CAAC,EAAE;CAC7E,OAAO,IAAI,SAAS,OAAO,OAAO,MAAA,CAAO,QAAQ,CAAC,EAAE;AACxD;;AAGA,gBAAgB,UAAU,QAAgE;CACtF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI;EACA,SAAS;GACL,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MAAM;GACV,MAAM;EACV;CACJ,UAAU;EACN,OAAO,YAAY;CACvB;AACJ;;;;;;;;;;;;AAaA,eAAsB,6BAClB,MACA,KACiC;CACjC,IAAI,KAAK,SAAS,SAAS,OAAO;CAClC,MAAM,EAAE,yBAAyB,MAAM,OAAO;CAC9C,IAAI;EACA,OAAO,qBAAqB,MAAM,GAAG;CACzC,SAAS,OAAO;EACZ,MAAM,IAAI,gBACN,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrD,4DACJ;CACJ;AACJ;;;;;;;;;;;AAYA,IAAa,qBAAqB;;AAGlC,SAAgB,cAAc,MAAoD,QAAQ,KAAa;CACnG,MAAM,MAAM,IAAI,mBAAmB,EAAE,KAAK;CAC1C,OAAO,OAAO,KAAK,WAAW,GAAG,IAAI,MAAM,QAAQ,IAAI;AAC3D;;;;;;;;;;;;;AAcA,SAAgB,sBAAsB,MAK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AAM,KAAK,kBAAkB,EAAE;;IAE/B,MAAM,KAAK,YAAY,EAAE;IACzB,MAAM,KAAK,uBAAuB,EAAE;+BACT,MAAM,IAAI,0CAA0C,EAAE;IACjF,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,oBAAoB,EAAE;;;;;;;;;sCASH,MAAM,IAAI,6CAA6C,EAAE;;;;;;EAM7F,MAAM,MAAM,KAAK,OAAO,EAAE;;;CAG3B;AACD;AAEA,SAAS,mBAAyB;CAC9B,IAAM;EACR,MAAM,KAAK,mBAAmB,EAAE;;EAEhC,MAAM,MAAM,KAAK,OAAO,EAAE;;;EAG1B,MAAM,MAAM,KAAK,WAAW,EAAE;;;EAG9B,MAAM,MAAM,KAAK,SAAS,EAAE;IAC1B,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,SAAS,EAAE;;IAEtB,MAAM,KAAK,YAAY,EAAE;IACzB,MAAM,KAAK,qBAAqB,EAAE,oCAAoC,MAAM,IAAI,8BAA8B,EAAE;IAChH,MAAM,KAAK,WAAW,EAAE,mDAAmD,MAAM,IAAI,gBAAgB,EAAE;;EAEzG,MAAM,IAAI,KAAK,SAAS,EAAE;;;;;;;;;;;;;;CAc3B;AACD;AAEA,SAAS,mBAAyB;CAC9B,IAAM;EACR,MAAM,KAAK,mBAAmB,EAAE;;EAEhC,MAAM,MAAM,KAAK,OAAO,EAAE;;+DAEmC,MAAM,KAAK,kBAAkB,EAAE;CAC7F;AACD"}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { n as __exportAll } from "./rolldown-runtime-V7rFbMRe.js";
4
- import { Q as forLibpq, R as resolveLocalBin, et as splitPassword } from "./cli-errors-CJTKAKax.js";
4
+ import { $ as forLibpq, tt as splitPassword, z as resolveLocalBin } from "./cli-errors-DwQnNATs.js";
5
5
  import { o as execa } from "./rls-bootstrap-sql-Bd-hJk08.js";
6
6
  import path from "path";
7
7
  import fs from "fs";
@@ -239,6 +239,10 @@ function buildPgRestoreListArgs(inputFile) {
239
239
  var TOC_ENTRY = /^\d+;\s+\d+\s+\d+\s+(SCHEMA|TABLE)\s+(?!DATA\s)(\S+)\s+(.+)\s+(\S+)$/;
240
240
  /** A TOC entry for a relation of any kind. `TABLE DATA`, `SEQUENCE SET` and `SEQUENCE OWNED BY` are not relations. */
241
241
  var TOC_RELATION = /^\d+;\s+\d+\s+\d+\s+(?:FOREIGN TABLE|MATERIALIZED VIEW|TABLE|VIEW|SEQUENCE)\s+(?!DATA\s|SET\s|OWNED BY\s)(\S+)\s+(.+)\s+(\S+)$/;
242
+ /** A function's TOC entry: its tag is the name and the argument types, `two(integer, text)`. */
243
+ var TOC_ROUTINE = /^\d+;\s+\d+\s+\d+\s+(?:FUNCTION|PROCEDURE|AGGREGATE)\s+(\S+)\s+(.+?)\(.*\)\s+\S+$/;
244
+ /** A type's or a domain's TOC entry. */
245
+ var TOC_TYPE = /^\d+;\s+\d+\s+\d+\s+(?:TYPE|DOMAIN)\s+(\S+)\s+(.+)\s+(\S+)$/;
242
246
  /**
243
247
  * The schemas and tables in `pg_restore --list` output: the objects a
244
248
  * restore without `--clean` fails on when the target already has them.
@@ -246,13 +250,17 @@ var TOC_RELATION = /^\d+;\s+\d+\s+\d+\s+(?:FOREIGN TABLE|MATERIALIZED VIEW|TABLE
246
250
  * A TOC line ends in the object's owner, after its namespace and its name;
247
251
  * a schema's namespace is `-`. The name is what lies between the two, so a
248
252
  * name with a space in it (`Odd Name`) reads whole. `TABLE DATA` and every
249
- * other kind of entry are not objects of their own here.
253
+ * other kind of entry are not objects of their own here. Its relations,
254
+ * functions and types are read too, for what `restore --clean` would drop
255
+ * that the dump does not hold (`findCleanExtras`).
250
256
  */
251
257
  function parseDumpObjects(list) {
252
258
  const objects = {
253
259
  schemas: [],
254
260
  tables: [],
255
- relations: []
261
+ relations: [],
262
+ routines: [],
263
+ types: []
256
264
  };
257
265
  for (const line of list.split("\n")) {
258
266
  const trimmed = line.trim();
@@ -261,6 +269,16 @@ function parseDumpObjects(list) {
261
269
  schema: relation[1],
262
270
  name: relation[2]
263
271
  });
272
+ const routine = TOC_ROUTINE.exec(trimmed);
273
+ if (routine) objects.routines.push({
274
+ schema: routine[1],
275
+ name: routine[2]
276
+ });
277
+ const type = TOC_TYPE.exec(trimmed);
278
+ if (type) objects.types.push({
279
+ schema: type[1],
280
+ name: type[2]
281
+ });
264
282
  const entry = TOC_ENTRY.exec(trimmed);
265
283
  if (!entry) continue;
266
284
  const [, kind, namespace, name] = entry;
@@ -929,15 +947,21 @@ async function restoreDumpReplacing(opts) {
929
947
  }
930
948
  /**
931
949
  * What `restore --clean` drops that the backup does not hold, so it can say
932
- * so before it runs: the tables and views in a schema the backup replaces
933
- * whole that it has no copy of, and the views and foreign keys elsewhere that
934
- * reference one of the relations it replaces. As `<kind> <name>`.
950
+ * so before it runs: what a schema the backup replaces whole holds that it has
951
+ * no copy of — tables, views, sequences, functions, procedures, aggregates,
952
+ * types and domains — and the views and foreign keys elsewhere that reference
953
+ * one of the relations it replaces. As `<kind> <name>`.
954
+ *
955
+ * A function is matched by its name, so an overload the backup lacks beside
956
+ * one it holds is not named. Sequences a column owns go with their table,
957
+ * and what an extension owns with the extension, so neither is named.
935
958
  *
936
959
  * None for a database that does not exist yet.
937
960
  */
938
961
  async function findCleanExtras(connectionString, objects) {
939
962
  const schemas = objects.schemas.filter((schema) => schema !== "public");
940
963
  if (schemas.length === 0 && objects.relations.length === 0) return [];
964
+ const { routines, types } = objects;
941
965
  const { Client } = await import("pg");
942
966
  const client = new Client({ connectionString });
943
967
  try {
@@ -956,13 +980,42 @@ async function findCleanExtras(connectionString, objects) {
956
980
  )
957
981
  SELECT kind, name FROM (
958
982
  SELECT CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view'
959
- WHEN 'f' THEN 'foreign table' ELSE 'table' END AS kind,
983
+ WHEN 'f' THEN 'foreign table' WHEN 'S' THEN 'sequence' ELSE 'table' END AS kind,
960
984
  n.nspname || '.' || c.relname AS name
961
985
  FROM pg_class c
962
986
  JOIN pg_namespace n ON n.oid = c.relnamespace
963
987
  WHERE n.nspname = ANY($1::text[])
964
- AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
988
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
965
989
  AND c.oid NOT IN (SELECT oid FROM dumped)
990
+ AND NOT (c.relkind = 'S' AND EXISTS (
991
+ SELECT 1 FROM pg_depend owner
992
+ WHERE owner.classid = 'pg_class'::regclass AND owner.objid = c.oid
993
+ AND owner.deptype IN ('a', 'i')))
994
+ UNION
995
+ SELECT CASE p.prokind WHEN 'p' THEN 'procedure' WHEN 'a' THEN 'aggregate' ELSE 'function' END,
996
+ n.nspname || '.' || p.proname
997
+ FROM pg_proc p
998
+ JOIN pg_namespace n ON n.oid = p.pronamespace
999
+ WHERE n.nspname = ANY($1::text[])
1000
+ AND (n.nspname, p.proname) NOT IN (SELECT * FROM unnest($4::text[], $5::text[]))
1001
+ AND NOT EXISTS (
1002
+ SELECT 1 FROM pg_depend owner
1003
+ WHERE owner.classid = 'pg_proc'::regclass AND owner.objid = p.oid
1004
+ AND owner.deptype IN ('e', 'i'))
1005
+ UNION
1006
+ SELECT CASE t.typtype WHEN 'd' THEN 'domain' ELSE 'type' END,
1007
+ n.nspname || '.' || t.typname
1008
+ FROM pg_type t
1009
+ JOIN pg_namespace n ON n.oid = t.typnamespace
1010
+ WHERE n.nspname = ANY($1::text[])
1011
+ AND (t.typtype IN ('e', 'd', 'r')
1012
+ OR (t.typtype = 'c' AND EXISTS (
1013
+ SELECT 1 FROM pg_class tc WHERE tc.oid = t.typrelid AND tc.relkind = 'c')))
1014
+ AND (n.nspname, t.typname) NOT IN (SELECT * FROM unnest($6::text[], $7::text[]))
1015
+ AND NOT EXISTS (
1016
+ SELECT 1 FROM pg_depend owner
1017
+ WHERE owner.classid = 'pg_type'::regclass AND owner.objid = t.oid
1018
+ AND owner.deptype = 'e')
966
1019
  UNION
967
1020
  SELECT 'view', vn.nspname || '.' || v.relname
968
1021
  FROM pg_depend dep
@@ -985,7 +1038,11 @@ async function findCleanExtras(connectionString, objects) {
985
1038
  ORDER BY name`, [
986
1039
  schemas,
987
1040
  objects.relations.map((r) => r.schema),
988
- objects.relations.map((r) => r.name)
1041
+ objects.relations.map((r) => r.name),
1042
+ routines.map((r) => r.schema),
1043
+ routines.map((r) => r.name),
1044
+ types.map((t) => t.schema),
1045
+ types.map((t) => t.name)
989
1046
  ]);
990
1047
  return rows.map((row) => `${row.kind} ${row.name}`);
991
1048
  } finally {
@@ -1134,4 +1191,4 @@ async function pruneBackups(dest, options, storage) {
1134
1191
  //#endregion
1135
1192
  export { buildPgRestoreScriptArgs as A, parseDbNameFromUrl as B, selectBackupsToPrune as C, buildPgDumpallGlobalsArgs as D, buildPgDumpArgs as E, diagnoseRowSecurityDumpFailure as F, splitGlobalsStatements as G, parsePgToolMajor as H, globalsFileForDump as I, withDatabaseName as K, joinStorageKey as L, buildRowSecurityPgOptions as M, checkToolServerCompatibility as N, buildPgRestoreArgs as O, cleanRestorePrelude as P, parseBackupDestination as R, resolvePgBinary as S, buildBackupFilename as T, resolveConnectionString as U, parseDumpObjects as V, serverVersionNumToMajor as W, restoreDump as _, createDump as a, validateDump as b, ensureDatabaseExists as c, getServerVersionMajor as d, listBackups as f, resetSharedSession as g, readDumpObjects as h, backup_service_exports as i, buildPsqlScriptArgs as j, buildPgRestoreListArgs as k, findCleanExtras as l, pruneBackups as m, CleanRestoreFailed as n, detectToolMajor as o, preflight as p, applyGlobals as r, discardPartialDump as s, BackupToolError as t, findRestoreConflicts as u, restoreDumpReplacing as v, CLEAN_LOCK_TIMEOUT as w, pgToolVariable as x, uploadBackup as y, parseBackupTimestamp as z };
1136
1193
 
1137
- //# sourceMappingURL=backup-service-DytMimsL.js.map
1194
+ //# sourceMappingURL=backup-service-Bb39plam.js.map