@newcode-team/sync 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -59,6 +59,7 @@ Every failure or abort exits with 1. Ctrl+C on a prompt aborts.
|
|
|
59
59
|
- The migration history comes along when its table lives in a synced schema, so no migrate run is needed afterwards. Drizzle keeps it in `drizzle`: add that schema.
|
|
60
60
|
- The dump goes to a temporary folder that is always removed, also after Ctrl+C.
|
|
61
61
|
- Passwords reach `pg_dump` and `psql` through `PGPASSWORD`, never as process arguments.
|
|
62
|
+
- A URL with `sslmode=verify-full` and no root certificate, in the URL, in `PGSSLROOTCERT` or at `~/.postgresql/root.crt`, is verified against the system's trusted roots (`sslrootcert=system`, libpq 16 or later), like Node's `pg` does. So hosted Postgres such as PlanetScale or Neon needs no certificate file, and only that side changes.
|
|
62
63
|
|
|
63
64
|
Doesn't copy roles, extensions or other schemas, and doesn't touch the source.
|
|
64
65
|
|
package/dist/cli.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from "commander";
|
|
3
3
|
import { confirmEnvironment, listEnvironments } from "@newcode-team/env";
|
|
4
|
-
import { c as loadSyncConfig, d as SyncError, f as errorMessage, i as planDatabaseSync, l as switchedOff, o as postgresTools, r as rcloneTools, s as requireTools, t as planS3Sync } from "./sync-
|
|
4
|
+
import { c as loadSyncConfig, d as SyncError, f as errorMessage, i as planDatabaseSync, l as switchedOff, o as postgresTools, r as rcloneTools, s as requireTools, t as planS3Sync } from "./sync-bv5bfhtZ.mjs";
|
|
5
5
|
// package.json
|
|
6
|
-
var version = "0.2.
|
|
6
|
+
var version = "0.2.1";
|
|
7
7
|
// src/lib/prompt.ts
|
|
8
8
|
/**
|
|
9
9
|
* Prompts read the terminal and write to stderr, like newenv's, so stdout stays the command's
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { d as SyncError, u as sync, a as syncDatabase, n as syncS3 } from "./sync-
|
|
1
|
+
export { d as SyncError, u as sync, a as syncDatabase, n as syncS3 } from "./sync-bv5bfhtZ.mjs";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { loadConfig } from "@newcode-team/config";
|
|
2
2
|
import { spawn, spawnSync } from "node:child_process";
|
|
3
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
-
import { devNull, tmpdir } from "node:os";
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { devNull, homedir, tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { loadEnvironment } from "@newcode-team/env";
|
|
7
7
|
// src/lib/errors.ts
|
|
@@ -223,6 +223,22 @@ const libpqVariables = [
|
|
|
223
223
|
"PGSERVICE"
|
|
224
224
|
];
|
|
225
225
|
/**
|
|
226
|
+
* Where libpq looks for a root certificate when neither the URL nor PGSSLROOTCERT names one
|
|
227
|
+
*/
|
|
228
|
+
function defaultRootCertificate() {
|
|
229
|
+
return process.platform === "win32" ? join(process.env.APPDATA ?? homedir(), "postgresql", "root.crt") : join(homedir(), ".postgresql", "root.crt");
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Whether libpq should check the server against the system's trusted roots. With
|
|
233
|
+
* `sslmode=verify-full` libpq wants a root certificate file and fails without one, while hosted
|
|
234
|
+
* Postgres, such as PlanetScale or Neon, uses public certificates that the system's roots verify,
|
|
235
|
+
* as Node's `pg` does. A root certificate the user set up, in the URL, in PGSSLROOTCERT or at
|
|
236
|
+
* libpq's default path, is left alone
|
|
237
|
+
*/
|
|
238
|
+
function useSystemRoots(url, env) {
|
|
239
|
+
return (url.searchParams.get("sslmode") ?? env.PGSSLMODE) === "verify-full" && !url.searchParams.has("sslrootcert") && !env.PGSSLROOTCERT && !existsSync(defaultRootCertificate());
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
226
242
|
* The URL to pass to pg_dump and psql, and the environment to run them with. The password goes
|
|
227
243
|
* through PGPASSWORD, so it's never a process argument that `ps` shows
|
|
228
244
|
*/
|
|
@@ -232,6 +248,7 @@ function connection(url) {
|
|
|
232
248
|
withoutPassword.searchParams.delete("password");
|
|
233
249
|
const password = url.password ? decodeURIComponent(url.password) : url.searchParams.get("password") ?? void 0;
|
|
234
250
|
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !libpqVariables.includes(key)));
|
|
251
|
+
if (useSystemRoots(url, env)) withoutPassword.searchParams.set("sslrootcert", "system");
|
|
235
252
|
return {
|
|
236
253
|
dbname: withoutPassword.href,
|
|
237
254
|
env: password === void 0 ? env : {
|
|
@@ -509,4 +526,4 @@ async function syncS3(options) {
|
|
|
509
526
|
}
|
|
510
527
|
export { syncDatabase as a, loadSyncConfig as c, SyncError as d, errorMessage as f, planDatabaseSync as i, switchedOff as l, syncS3 as n, postgresTools as o, rcloneTools as r, requireTools as s, planS3Sync as t, sync as u };
|
|
511
528
|
|
|
512
|
-
//# sourceMappingURL=sync-
|
|
529
|
+
//# sourceMappingURL=sync-bv5bfhtZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-bv5bfhtZ.mjs","names":[],"sources":["../src/lib/errors.ts","../src/lib/config.ts","../src/lib/process.ts","../src/commands/database/helpers.ts","../src/commands/database/sync.ts","../src/commands/s3/helpers.ts","../src/commands/s3/sync.ts"],"sourcesContent":["/**\n * A refusal or failure: an invalid config section, a missing tool or variable, the same source and\n * target, a command that failed. Messages never hold a URL, password or key.\n */\nexport class SyncError extends Error {\n override name = \"SyncError\";\n}\n\n/**\n * What the command prints for an error. Ctrl+C on a prompt is an abort\n */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.name === \"ExitPromptError\" ? \"Aborted.\" : error.message;\n }\n return String(error);\n}\n","import { loadConfig } from \"@newcode-team/config\";\nimport { SyncError } from \"./errors\";\n\nexport type Provider = \"auto\" | \"cloudflare\" | \"other\";\n\n/**\n * The variables that hold the database connection, per environment\n */\nexport interface DatabaseConfig {\n /**\n * Variable with the postgres:// URL. Default: `\"DATABASE_URL\"`\n */\n url?: string;\n /**\n * Schemas that are copied, and replaced in the target. Default: `[\"public\"]`. A Drizzle project\n * adds `\"drizzle\"` to bring its migration history along\n */\n schemas?: string[];\n}\n\n/**\n * The variables that hold the S3 bucket, per environment\n */\nexport interface S3Config {\n /**\n * Variable with the endpoint URL. Default: `\"S3_ENDPOINT\"`\n */\n endpoint?: string;\n /**\n * Variable with the access key ID. Default: `\"S3_ACCESS_KEY_ID\"`\n */\n accessKeyId?: string;\n /**\n * Variable with the secret access key. Default: `\"S3_SECRET_ACCESS_KEY\"`\n */\n secretAccessKey?: string;\n /**\n * Variable with the bucket name. Default: `\"S3_BUCKET\"`\n */\n bucket?: string;\n /**\n * `\"auto\"`: Cloudflare R2 when the endpoint is on r2.cloudflarestorage.com, otherwise generic S3.\n * Default: `\"auto\"`\n */\n provider?: Provider;\n}\n\n/**\n * The `sync` section of newcode.config.ts. Settings name variables, never hold their values\n */\nexport interface SyncConfig {\n /**\n * `false` switches the database sync off\n */\n database?: DatabaseConfig | false;\n /**\n * `false` switches the S3 sync off\n */\n s3?: S3Config | false;\n}\n\nexport interface ResolvedSyncConfig {\n database: Required<DatabaseConfig> | false;\n s3: Required<S3Config> | false;\n}\n\ndeclare module \"@newcode-team/config\" {\n interface Config {\n sync?: SyncConfig;\n }\n}\n\n/**\n * The `sync` section of newcode.config.ts. Returns its input: it types the section and adds `sync`\n * to `Config`\n */\nexport const sync = (section: SyncConfig): SyncConfig => section;\n\nexport const defaults = {\n database: { url: \"DATABASE_URL\", schemas: [\"public\"] },\n s3: {\n endpoint: \"S3_ENDPOINT\",\n accessKeyId: \"S3_ACCESS_KEY_ID\",\n secretAccessKey: \"S3_SECRET_ACCESS_KEY\",\n bucket: \"S3_BUCKET\",\n provider: \"auto\",\n },\n} as const satisfies ResolvedSyncConfig;\n\nconst variableName = /^[A-Za-z_]\\w*$/;\n// Plain identifiers only, so they need no escaping in pg_dump patterns or SQL\nconst schemaName = /^[A-Za-z_][\\w$]*$/;\nconst providers: Provider[] = [\"auto\", \"cloudflare\", \"other\"];\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction checkKeys(path: string, value: Record<string, unknown>, known: string[]): void {\n const unknown = Object.keys(value).find((key) => !known.includes(key));\n if (unknown !== undefined) {\n throw new SyncError(`${path}.${unknown} is not a known key. Known: ${known.join(\", \")}`);\n }\n}\n\n// Never repeats the value: a mistake here is often a URL or key pasted in place of its name\nfunction checkVariable(path: string, value: unknown): void {\n if (value !== undefined && (typeof value !== \"string\" || !variableName.test(value))) {\n throw new SyncError(`${path} must be a variable name, such as \"DATABASE_URL\"`);\n }\n}\n\nfunction resolveDatabaseSection(value: unknown): ResolvedSyncConfig[\"database\"] {\n if (value === false) {\n return false;\n }\n if (value === undefined) {\n return { ...defaults.database, schemas: [...defaults.database.schemas] };\n }\n if (!isObject(value)) {\n throw new SyncError(\"sync.database must be false or an object\");\n }\n\n checkKeys(\"sync.database\", value, [\"url\", \"schemas\"]);\n checkVariable(\"sync.database.url\", value.url);\n const { schemas } = value;\n if (\n schemas !== undefined &&\n (!Array.isArray(schemas) ||\n schemas.length === 0 ||\n !schemas.every((schema) => typeof schema === \"string\" && schemaName.test(schema)))\n ) {\n throw new SyncError(\"sync.database.schemas must be a non-empty list of names\");\n }\n return { ...resolveDatabaseSection(undefined), ...value } as Required<DatabaseConfig>;\n}\n\nfunction resolveS3Section(value: unknown): ResolvedSyncConfig[\"s3\"] {\n if (value === false) {\n return false;\n }\n if (value === undefined) {\n return { ...defaults.s3 };\n }\n if (!isObject(value)) {\n throw new SyncError(\"sync.s3 must be false or an object\");\n }\n\n const variables = [\"endpoint\", \"accessKeyId\", \"secretAccessKey\", \"bucket\"];\n checkKeys(\"sync.s3\", value, [...variables, \"provider\"]);\n variables.forEach((key) => {\n checkVariable(`sync.s3.${key}`, value[key]);\n });\n if (value.provider !== undefined && !providers.includes(value.provider as Provider)) {\n throw new SyncError('sync.s3.provider must be \"auto\", \"cloudflare\" or \"other\"');\n }\n return { ...defaults.s3, ...value } as Required<S3Config>;\n}\n\n/**\n * Checks the section and fills in the defaults. Throws a `SyncError` with the path of the first\n * problem\n */\nexport function resolveSyncConfig(section: unknown = {}): ResolvedSyncConfig {\n if (!isObject(section)) {\n throw new SyncError(\"sync must be an object\");\n }\n checkKeys(\"sync\", section, [\"database\", \"s3\"]);\n return { database: resolveDatabaseSection(section.database), s3: resolveS3Section(section.s3) };\n}\n\n/**\n * The refusal for a part that is switched off with `false`\n */\nexport const switchedOff = (part: keyof ResolvedSyncConfig): SyncError =>\n new SyncError(\n `The ${part === \"s3\" ? \"S3\" : \"database\"} sync is off: sync.${part} is false in newcode.config.ts.`,\n );\n\n/**\n * The `sync` section of the project's newcode.config.ts, found from cwd up, checked and with the\n * defaults\n */\nexport async function loadSyncConfig(cwd: string): Promise<ResolvedSyncConfig> {\n return resolveSyncConfig((await loadConfig({ cwd })).sync);\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport { SyncError } from \"./errors\";\n\n/**\n * Tools a sync needs, and how to install them\n */\nexport interface Tools {\n names: string[];\n hint: string;\n}\n\n/**\n * Throws a `SyncError` with the install hint when one of the tools can't be started\n */\nexport function requireTools({ names, hint }: Tools): void {\n const missing = names.filter(\n (name) =>\n (spawnSync(name, [\"--version\"], { stdio: \"ignore\" }).error as NodeJS.ErrnoException)?.code ===\n \"ENOENT\",\n );\n if (missing.length > 0) {\n throw new SyncError(`${missing.join(\", \")} not found. ${hint}`);\n }\n}\n\nexport interface RunToolOptions {\n env: NodeJS.ProcessEnv;\n /**\n * Returns stdout instead of passing it through\n */\n capture?: boolean;\n}\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * Runs a tool and waits for it. Its stderr, and stdout unless captured, go to the terminal. A\n * failure throws a `SyncError` naming only the tool: the tool already printed what went wrong, and\n * its arguments aren't repeated.\n *\n * Signals are forwarded like newenv does: in a terminal, Ctrl+C and hangups already reach the tool,\n * so only SIGTERM is forwarded there. Node keeps running until the tool exits, so callers clean up.\n */\nexport function runTool(\n command: string,\n args: string[],\n { env, capture = false }: RunToolOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n env,\n stdio: [\"ignore\", capture ? \"pipe\" : \"inherit\", \"inherit\"],\n });\n const output: Buffer[] = [];\n child.stdout?.on(\"data\", (chunk: Buffer) => output.push(chunk));\n\n const forward = (signal: NodeJS.Signals) => {\n if (signal === \"SIGTERM\" || !process.stdin.isTTY) {\n child.kill(signal);\n }\n };\n const stopForwarding = () => {\n signals.forEach((signal) => {\n process.off(signal, forward);\n });\n };\n signals.forEach((signal) => {\n process.on(signal, forward);\n });\n\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n stopForwarding();\n reject(\n new SyncError(\n error.code === \"ENOENT\"\n ? `${command} not found.`\n : `${command} could not start: ${error.message}`,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n stopForwarding();\n if (code === 0) {\n resolve(Buffer.concat(output).toString());\n } else {\n reject(new SyncError(signal ? `${command} stopped by ${signal}.` : `${command} failed.`));\n }\n });\n });\n}\n","import { existsSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { devNull, homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { loadEnvironment } from \"@newcode-team/env\";\nimport type { DatabaseConfig } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport { runTool, type Tools } from \"../../lib/process\";\n\nexport const postgresTools: Tools = {\n names: [\"pg_dump\", \"pg_restore\", \"psql\"],\n hint: \"macOS: install Postgres.app (https://postgresapp.com) and add its bin folder to PATH, or brew install libpq. Other systems: https://www.postgresql.org/download/\",\n};\n\n/**\n * A database that is in no environment\n */\nexport interface CustomDatabase {\n /**\n * A postgres:// or postgresql:// URL\n */\n url: string;\n}\n\n/**\n * An environment name, or a custom database\n */\nexport type DatabaseSide = string | CustomDatabase;\n\nexport interface Database {\n /**\n * The environment name, or `custom`\n */\n label: string;\n url: URL;\n}\n\n/**\n * Parses a postgres URL. The message names where it came from, never the value\n */\nexport function parseDatabaseUrl(value: string, from: string): URL {\n const url = URL.parse(value);\n if (!url || ![\"postgres:\", \"postgresql:\"].includes(url.protocol) || !url.hostname) {\n throw new SyncError(`${from} is not a postgres:// or postgresql:// URL.`);\n }\n return url;\n}\n\n/**\n * The URL of an environment, read from the configured variable, or of a custom database\n */\nexport async function resolveDatabase(\n side: DatabaseSide,\n config: Required<DatabaseConfig>,\n cwd: string,\n): Promise<Database> {\n if (typeof side !== \"string\") {\n return { label: \"custom\", url: parseDatabaseUrl(side.url, \"The custom database URL\") };\n }\n\n const environment = await loadEnvironment(side, { cwd });\n // require() has checked the key\n const { [config.url]: value = \"\" } = environment.require(config.url);\n return { label: side, url: parseDatabaseUrl(value, `${config.url} of environment \"${side}\"`) };\n}\n\n/**\n * Environment, host and database, without the user and password\n */\nexport const describeDatabase = ({ label, url }: Database): string =>\n `${label} (${url.host}${url.pathname})`;\n\n/**\n * Same host, port and database name\n */\nexport function sameDatabase(a: Database, b: Database): boolean {\n const key = ({ url }: Database) =>\n [url.hostname.toLowerCase(), url.port || \"5432\", decodeURIComponent(url.pathname)].join(\" \");\n return key(a) === key(b);\n}\n\n// libpq reads these from the environment, and would fill in what a URL leaves out\nconst libpqVariables = [\n \"PGHOST\",\n \"PGHOSTADDR\",\n \"PGPORT\",\n \"PGDATABASE\",\n \"PGUSER\",\n \"PGPASSWORD\",\n \"PGSERVICE\",\n];\n\n/**\n * Where libpq looks for a root certificate when neither the URL nor PGSSLROOTCERT names one\n */\nexport function defaultRootCertificate(): string {\n return process.platform === \"win32\"\n ? join(process.env.APPDATA ?? homedir(), \"postgresql\", \"root.crt\")\n : join(homedir(), \".postgresql\", \"root.crt\");\n}\n\n/**\n * Whether libpq should check the server against the system's trusted roots. With\n * `sslmode=verify-full` libpq wants a root certificate file and fails without one, while hosted\n * Postgres, such as PlanetScale or Neon, uses public certificates that the system's roots verify,\n * as Node's `pg` does. A root certificate the user set up, in the URL, in PGSSLROOTCERT or at\n * libpq's default path, is left alone\n */\nexport function useSystemRoots(url: URL, env: NodeJS.ProcessEnv): boolean {\n const mode = url.searchParams.get(\"sslmode\") ?? env.PGSSLMODE;\n return (\n mode === \"verify-full\" &&\n !url.searchParams.has(\"sslrootcert\") &&\n !env.PGSSLROOTCERT &&\n !existsSync(defaultRootCertificate())\n );\n}\n\n/**\n * The URL to pass to pg_dump and psql, and the environment to run them with. The password goes\n * through PGPASSWORD, so it's never a process argument that `ps` shows\n */\nexport function connection(url: URL): { dbname: string; env: NodeJS.ProcessEnv } {\n const withoutPassword = new URL(url.href);\n withoutPassword.password = \"\";\n withoutPassword.searchParams.delete(\"password\");\n const password = url.password\n ? decodeURIComponent(url.password)\n : (url.searchParams.get(\"password\") ?? undefined);\n\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !libpqVariables.includes(key)),\n );\n // In this side's URL only: PGSSLROOTCERT=system would make every side require SSL, also a local\n // Postgres without it. Needs libpq 16 or later\n if (useSystemRoots(url, env)) {\n withoutPassword.searchParams.set(\"sslrootcert\", \"system\");\n }\n return {\n dbname: withoutPassword.href,\n env: password === undefined ? env : { ...env, PGPASSWORD: password },\n };\n}\n\n/**\n * Runs SQL with psql and returns the rows, tab-separated\n */\nfunction query(url: URL, sql: string): Promise<string> {\n const { dbname, env } = connection(url);\n return runTool(\n \"psql\",\n [\n \"--no-psqlrc\",\n \"--quiet\",\n \"--no-align\",\n \"--tuples-only\",\n \"--field-separator=\\t\",\n \"--set=ON_ERROR_STOP=1\",\n `--command=${sql}`,\n `--dbname=${dbname}`,\n ],\n { env, capture: true },\n );\n}\n\n/**\n * Refuses when pg_dump is an older major version than the source server: it can't dump it\n */\nexport async function checkVersion(source: Database): Promise<void> {\n const version = await runTool(\"pg_dump\", [\"--version\"], { env: process.env, capture: true });\n const dump = Number(/\\)\\s*(\\d+)/.exec(version)?.[1]);\n const server = Math.floor(Number(await query(source.url, \"SHOW server_version_num\")) / 10000);\n if (dump < server) {\n throw new SyncError(\n `pg_dump ${dump} is older than the source server, Postgres ${server}. Install pg_dump ${server} or later. ${postgresTools.hint}`,\n );\n }\n}\n\n/**\n * A row estimate for the dry run, e.g. `~1 row`\n */\nexport function describeRowEstimate(estimate: string): string {\n const count = estimate === \"\" ? -1 : Number(estimate);\n return count < 0 ? \"row count unknown\" : `~${count} ${count === 1 ? \"row\" : \"rows\"}`;\n}\n\n/**\n * Lists the target's tables in the schemas, with row estimates. Changes nothing. Schema names are\n * plain identifiers (see lib/config.ts), so they need no escaping\n */\nexport async function listTables(\n target: Database,\n schemas: string[],\n log: (message: string) => void,\n): Promise<void> {\n // reltuples stays -1 until a table is analyzed, as after a restore. The statistics' live row\n // count is kept up to date on every write, and costs no count(*) on a large table\n const rows = await query(\n target.url,\n `SELECT n.nspname || '.' || c.relname, CASE WHEN c.reltuples >= 0 THEN c.reltuples::bigint ELSE s.n_live_tup END FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition AND n.nspname IN (${schemas.map((schema) => `'${schema}'`).join(\", \")}) ORDER BY 1`,\n );\n const tables = rows\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\")\n .map((line) => {\n const [name = \"\", estimate = \"\"] = line.split(\"\\t\");\n return ` ${name} ${describeRowEstimate(estimate)}`;\n });\n log(\n tables.length > 0\n ? `Would replace these tables of ${describeDatabase(target)}:\\n${tables.join(\"\\n\")}`\n : `No tables in ${schemas.join(\", \")} of ${describeDatabase(target)} yet.`,\n );\n log(\"Dry run: nothing changed.\");\n}\n\n/**\n * Dumps the schemas of the source and restores them into the target in one transaction\n */\nexport async function copyDatabase(\n source: Database,\n target: Database,\n schemas: string[],\n log: (message: string) => void,\n): Promise<void> {\n const dir = mkdtempSync(join(tmpdir(), \"newsync-\"));\n // Ctrl+C stops the running tool and no further one starts. Node keeps running until the dump is\n // removed\n let interrupted = false;\n const interrupt = () => {\n interrupted = true;\n };\n const step = async (command: string, args: string[], env: NodeJS.ProcessEnv) => {\n if (interrupted) {\n throw new SyncError(\"Aborted.\");\n }\n await runTool(command, args, { env }).catch((error: unknown) => {\n throw interrupted ? new SyncError(\"Aborted.\") : error;\n });\n };\n process.on(\"SIGINT\", interrupt);\n\n try {\n const dumpFile = join(dir, \"source.dump\");\n const sqlFile = join(dir, \"source.sql\");\n\n // Only the configured schemas: hosting providers keep their own extensions in other schemas,\n // which a local Postgres can't install\n log(`Dumping ${describeDatabase(source)}...`);\n const from = connection(source.url);\n await step(\n \"pg_dump\",\n [\n ...schemas.map((schema) => `--schema=\"${schema}\"`),\n \"--format=custom\",\n \"--no-owner\",\n \"--no-privileges\",\n `--file=${dumpFile}`,\n `--dbname=${from.dbname}`,\n ],\n from.env,\n );\n await step(\n \"pg_restore\",\n [\"--no-owner\", \"--no-privileges\", `--file=${sqlFile}`, dumpFile],\n process.env,\n );\n\n // Dropping with CASCADE also removes tables that only exist in the target. Drop and restore run\n // in one transaction, so a failed restore leaves the target as it was\n log(`Restoring into ${describeDatabase(target)}...`);\n const to = connection(target.url);\n const drop = schemas.map((schema) => `DROP SCHEMA IF EXISTS \"${schema}\" CASCADE;`);\n await step(\n \"psql\",\n [\n \"--no-psqlrc\",\n \"--quiet\",\n \"--single-transaction\",\n \"--set=ON_ERROR_STOP=1\",\n `--output=${devNull}`,\n `--command=SET client_min_messages = warning; ${drop.join(\" \")}`,\n `--file=${sqlFile}`,\n `--dbname=${to.dbname}`,\n ],\n to.env,\n );\n // Migration history comes along only when its table is in one of the schemas\n const one = schemas.length === 1;\n log(\n `Done. ${one ? \"Schema\" : \"Schemas\"} ${schemas.join(\", \")} of ${describeDatabase(target)} now ${one ? \"matches\" : \"match\"} the source.`,\n );\n } finally {\n process.off(\"SIGINT\", interrupt);\n rmSync(dir, { recursive: true, force: true });\n }\n}\n","import { loadSyncConfig, switchedOff } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { SyncOptions, SyncPlan } from \"../../lib/plan\";\nimport { requireTools } from \"../../lib/process\";\nimport {\n checkVersion,\n copyDatabase,\n type DatabaseSide,\n describeDatabase,\n listTables,\n postgresTools,\n resolveDatabase,\n sameDatabase,\n} from \"./helpers\";\n\nexport type { CustomDatabase, DatabaseSide } from \"./helpers\";\n\nexport type SyncDatabaseOptions = SyncOptions<DatabaseSide>;\n\n/**\n * Checks the tools, both databases and the pg_dump version, without changing anything\n */\nexport async function planDatabaseSync({\n source: sourceSide,\n target: targetSide,\n dryRun = false,\n cwd = process.cwd(),\n log = console.log,\n}: SyncDatabaseOptions): Promise<SyncPlan> {\n const { database: config } = await loadSyncConfig(cwd);\n if (!config) {\n throw switchedOff(\"database\");\n }\n requireTools(postgresTools);\n\n const source = await resolveDatabase(sourceSide, config, cwd);\n const target = await resolveDatabase(targetSide, config, cwd);\n if (sameDatabase(source, target)) {\n throw new SyncError(`Source and target are the same database: ${describeDatabase(target)}.`);\n }\n await checkVersion(source);\n\n const { schemas } = config;\n return {\n source: describeDatabase(source),\n target: describeDatabase(target),\n question: `Replace ${schemas.length === 1 ? \"schema\" : \"schemas\"} ${schemas.join(\", \")} of ${describeDatabase(target)}`,\n run: () =>\n dryRun ? listTables(target, schemas, log) : copyDatabase(source, target, schemas, log),\n };\n}\n\n/**\n * Replaces the configured schemas of the target database with a copy of the source's. Doesn't\n * ask: a script confirms first, e.g. with `confirmEnvironment` from @newcode-team/env\n */\nexport async function syncDatabase(options: SyncDatabaseOptions): Promise<void> {\n await (await planDatabaseSync(options)).run();\n}\n","import { loadEnvironment } from \"@newcode-team/env\";\nimport type { Provider, S3Config } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { Tools } from \"../../lib/process\";\n\nexport const rcloneTools: Tools = {\n names: [\"rclone\"],\n hint: \"macOS: brew install rclone. Other systems: https://rclone.org/install/\",\n};\n\n/**\n * A bucket that is in no environment\n */\nexport interface CustomBucket {\n /**\n * An http:// or https:// URL\n */\n endpoint: string;\n accessKeyId: string;\n secretAccessKey: string;\n bucket: string;\n /**\n * Default: `\"auto\"`\n */\n provider?: Provider;\n}\n\n/**\n * An environment name, or a custom bucket\n */\nexport type BucketSide = string | CustomBucket;\n\nexport interface Bucket {\n /**\n * The environment name, or `custom`\n */\n label: string;\n endpoint: URL;\n accessKeyId: string;\n secretAccessKey: string;\n bucket: string;\n provider: Provider;\n}\n\n/**\n * Parses an S3 endpoint. The message names where it came from, never the value\n */\nexport function parseEndpoint(value: string, from: string): URL {\n const url = URL.parse(value);\n if (!url || ![\"http:\", \"https:\"].includes(url.protocol)) {\n throw new SyncError(`${from} is not an http:// or https:// URL.`);\n }\n return url;\n}\n\n/**\n * The bucket of an environment, read from the configured variables, or a custom bucket\n */\nexport async function resolveBucket(\n side: BucketSide,\n config: Required<S3Config>,\n cwd: string,\n): Promise<Bucket> {\n if (typeof side !== \"string\") {\n const missing = ([\"accessKeyId\", \"secretAccessKey\", \"bucket\"] as const).filter(\n (key) => !side[key],\n );\n if (missing.length > 0) {\n throw new SyncError(`The custom bucket misses ${missing.join(\", \")}.`);\n }\n return {\n ...side,\n label: \"custom\",\n endpoint: parseEndpoint(side.endpoint, \"The custom endpoint\"),\n provider: side.provider ?? \"auto\",\n };\n }\n\n const environment = await loadEnvironment(side, { cwd });\n const values = environment.require(\n config.endpoint,\n config.accessKeyId,\n config.secretAccessKey,\n config.bucket,\n );\n // require() has checked every key\n const value = (key: string) => values[key] ?? \"\";\n return {\n label: side,\n endpoint: parseEndpoint(value(config.endpoint), `${config.endpoint} of environment \"${side}\"`),\n accessKeyId: value(config.accessKeyId),\n secretAccessKey: value(config.secretAccessKey),\n bucket: value(config.bucket),\n provider: config.provider,\n };\n}\n\n/**\n * Environment, bucket and host, without the keys\n */\nexport const describeBucket = ({ label, bucket, endpoint }: Bucket): string =>\n `${label} (${bucket} on ${endpoint.host})`;\n\n/**\n * Same bucket on the same endpoint\n */\nexport const sameBucket = (a: Bucket, b: Bucket): boolean =>\n a.endpoint.host.toLowerCase() === b.endpoint.host.toLowerCase() && a.bucket === b.bucket;\n\nconst endpointKey = ({ endpoint }: Bucket) => endpoint.href.replace(/\\/$/, \"\").toLowerCase();\n\n/**\n * Both buckets reachable with one endpoint and one key, e.g. production to staging on R2: then one\n * rclone remote, and the provider copies the files itself. Otherwise they stream through this\n * machine\n */\nexport const sameRemote = (a: Bucket, b: Bucket): boolean =>\n endpointKey(a) === endpointKey(b) &&\n a.accessKeyId === b.accessKeyId &&\n a.secretAccessKey === b.secretAccessKey;\n\n/**\n * Cloudflare for R2, otherwise generic S3\n */\nexport function rcloneProvider({ provider, endpoint }: Bucket): \"Cloudflare\" | \"Other\" {\n if (provider === \"auto\") {\n return endpoint.hostname.toLowerCase().endsWith(\".r2.cloudflarestorage.com\")\n ? \"Cloudflare\"\n : \"Other\";\n }\n return provider === \"cloudflare\" ? \"Cloudflare\" : \"Other\";\n}\n\n// rclone reads a remote from RCLONE_CONFIG_<NAME>_* variables, so the keys are never process\n// arguments that `ps` shows, nor in an rclone.conf on disk\nfunction remoteEnv(name: string, bucket: Bucket): Record<string, string> {\n const prefix = `RCLONE_CONFIG_${name.toUpperCase()}`;\n return {\n [`${prefix}_TYPE`]: \"s3\",\n [`${prefix}_PROVIDER`]: rcloneProvider(bucket),\n [`${prefix}_REGION`]: \"auto\",\n [`${prefix}_ENDPOINT`]: bucket.endpoint.href.replace(/\\/$/, \"\"),\n [`${prefix}_ACCESS_KEY_ID`]: bucket.accessKeyId,\n [`${prefix}_SECRET_ACCESS_KEY`]: bucket.secretAccessKey,\n [`${prefix}_ENV_AUTH`]: \"false\",\n // R2 tokens are often scoped to a few buckets and may not create or check buckets\n [`${prefix}_NO_CHECK_BUCKET`]: \"true\",\n };\n}\n\n/**\n * The rclone source and target paths, and the variables that define their remotes\n */\nexport function remotes(\n source: Bucket,\n target: Bucket,\n): { source: string; target: string; env: Record<string, string> } {\n const one = sameRemote(source, target);\n return {\n source: `${one ? \"newsync_target\" : \"newsync_source\"}:${source.bucket}`,\n target: `newsync_target:${target.bucket}`,\n env: {\n ...remoteEnv(\"newsync_target\", target),\n ...(one ? {} : remoteEnv(\"newsync_source\", source)),\n },\n };\n}\n","import { loadSyncConfig, switchedOff } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { SyncOptions, SyncPlan } from \"../../lib/plan\";\nimport { requireTools, runTool } from \"../../lib/process\";\nimport {\n type BucketSide,\n describeBucket,\n rcloneTools,\n remotes,\n resolveBucket,\n sameBucket,\n} from \"./helpers\";\n\nexport type { BucketSide, CustomBucket } from \"./helpers\";\n\nexport type SyncS3Options = SyncOptions<BucketSide>;\n\n/**\n * Checks the tool and both buckets, without changing anything\n */\nexport async function planS3Sync({\n source: sourceSide,\n target: targetSide,\n dryRun = false,\n cwd = process.cwd(),\n log = console.log,\n}: SyncS3Options): Promise<SyncPlan> {\n const { s3: config } = await loadSyncConfig(cwd);\n if (!config) {\n throw switchedOff(\"s3\");\n }\n requireTools(rcloneTools);\n\n const source = await resolveBucket(sourceSide, config, cwd);\n const target = await resolveBucket(targetSide, config, cwd);\n if (sameBucket(source, target)) {\n throw new SyncError(`Source and target are the same bucket: ${describeBucket(target)}.`);\n }\n\n const paths = remotes(source, target);\n return {\n source: describeBucket(source),\n target: describeBucket(target),\n question: `Overwrite ${describeBucket(target)} and delete its files that aren't in the source`,\n async run() {\n log(dryRun ? \"Comparing buckets...\" : `Syncing ${describeBucket(target)}...`);\n // sync copies new and changed files, skips unchanged ones (size and modification time) and\n // deletes files that only exist in the target. Deleting comes last and is skipped after an\n // error, so a failed sync never leaves the target with fewer files\n await runTool(\n \"rclone\",\n [\n \"sync\",\n paths.source,\n paths.target,\n // One listing request per bucket instead of one per folder: fewer R2 class A operations\n \"--fast-list\",\n \"--delete-after\",\n \"--stats-one-line\",\n ...(dryRun ? [\"--dry-run\"] : process.stdout.isTTY ? [\"--progress\"] : []),\n ],\n { env: { ...process.env, ...paths.env } },\n );\n log(\n dryRun\n ? \"Dry run: nothing changed.\"\n : `Done. ${describeBucket(target)} now has the files of the source.`,\n );\n },\n };\n}\n\n/**\n * Makes the target bucket an exact copy of the source bucket. Doesn't ask: a script confirms\n * first, e.g. with `confirmEnvironment` from @newcode-team/env\n */\nexport async function syncS3(options: SyncS3Options): Promise<void> {\n await (await planS3Sync(options)).run();\n}\n"],"mappings":";;;;;;;;;;;AAIA,IAAa,YAAb,cAA+B,MAAM;CAC1B,OAAO;AAClB;;;;AAKA,SAAgB,aAAa,OAAwB;CACnD,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,oBAAoB,aAAa,MAAM;CAE/D,OAAO,OAAO,KAAK;AACrB;;;;;;AC4DA,MAAa,QAAQ,YAAoC;AAEzD,MAAa,WAAW;CACtB,UAAU;EAAE,KAAK;EAAgB,SAAS,CAAC,QAAQ;CAAE;CACrD,IAAI;EACF,UAAU;EACV,aAAa;EACb,iBAAiB;EACjB,QAAQ;EACR,UAAU;CACZ;AACF;AAEA,MAAM,eAAe;AAErB,MAAM,aAAa;AACnB,MAAM,YAAwB;CAAC;CAAQ;CAAc;AAAO;AAE5D,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,SAAS,UAAU,MAAc,OAAgC,OAAuB;CACtF,MAAM,UAAU,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,CAAC,MAAM,SAAS,GAAG,CAAC;CACrE,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,UAAU,GAAG,KAAK,GAAG,QAAQ,8BAA8B,MAAM,KAAK,IAAI,GAAG;AAE3F;AAGA,SAAS,cAAc,MAAc,OAAsB;CACzD,IAAI,UAAU,KAAA,MAAc,OAAO,UAAU,YAAY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AM,QACJ,UACA;IACE;IACA,MAAM;IACN,MAAM;IAEN;IACA;IACA;IACA,GAAI,SAAS,CAAC,WAAW,IAAI,QAAQ,OAAO,QAAQ,CAAC,YAAY,IAAI,CAAC;GACxE,GACA,EAAE,KAAK;IAAE,GAAG,QAAQ;IAAK,GAAG,MAAM;GAAI,EAAE,CAC1C;GACA,IACE,SACI,8BACA,SAAS,eAAe,MAAM,EAAE,kCACtC;EACF;CACF;AACF;;;;;AAMA,eAAsB,OAAO,SAAuC;CAClE,OAAO,MAAM,WAAW,OAAO,EAAA,CAAG,IAAI;AACxC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@newcode-team/sync",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Copy databases and files between environments",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -28,12 +28,12 @@
|
|
|
28
28
|
"@inquirer/input": "^5.2.0",
|
|
29
29
|
"@inquirer/password": "^5.3.1",
|
|
30
30
|
"@inquirer/select": "^5.3.1",
|
|
31
|
-
"@newcode-team/env": "^0.2.
|
|
31
|
+
"@newcode-team/env": "^0.2.1",
|
|
32
32
|
"commander": "^15.1.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@arethetypeswrong/core": "^0.18.5",
|
|
36
|
-
"@newcode-team/config": "0.2.
|
|
36
|
+
"@newcode-team/config": "0.2.1",
|
|
37
37
|
"@types/node": "^24.19.2",
|
|
38
38
|
"publint": "^0.3.25",
|
|
39
39
|
"tsdown": "^0.23.7",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"vitest": "^5.1.0"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@newcode-team/config": "^0.2.
|
|
45
|
+
"@newcode-team/config": "^0.2.1"
|
|
46
46
|
},
|
|
47
47
|
"publishConfig": {
|
|
48
48
|
"access": "public"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sync-C6BM27_L.mjs","names":[],"sources":["../src/lib/errors.ts","../src/lib/config.ts","../src/lib/process.ts","../src/commands/database/helpers.ts","../src/commands/database/sync.ts","../src/commands/s3/helpers.ts","../src/commands/s3/sync.ts"],"sourcesContent":["/**\n * A refusal or failure: an invalid config section, a missing tool or variable, the same source and\n * target, a command that failed. Messages never hold a URL, password or key.\n */\nexport class SyncError extends Error {\n override name = \"SyncError\";\n}\n\n/**\n * What the command prints for an error. Ctrl+C on a prompt is an abort\n */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.name === \"ExitPromptError\" ? \"Aborted.\" : error.message;\n }\n return String(error);\n}\n","import { loadConfig } from \"@newcode-team/config\";\nimport { SyncError } from \"./errors\";\n\nexport type Provider = \"auto\" | \"cloudflare\" | \"other\";\n\n/**\n * The variables that hold the database connection, per environment\n */\nexport interface DatabaseConfig {\n /**\n * Variable with the postgres:// URL. Default: `\"DATABASE_URL\"`\n */\n url?: string;\n /**\n * Schemas that are copied, and replaced in the target. Default: `[\"public\"]`. A Drizzle project\n * adds `\"drizzle\"` to bring its migration history along\n */\n schemas?: string[];\n}\n\n/**\n * The variables that hold the S3 bucket, per environment\n */\nexport interface S3Config {\n /**\n * Variable with the endpoint URL. Default: `\"S3_ENDPOINT\"`\n */\n endpoint?: string;\n /**\n * Variable with the access key ID. Default: `\"S3_ACCESS_KEY_ID\"`\n */\n accessKeyId?: string;\n /**\n * Variable with the secret access key. Default: `\"S3_SECRET_ACCESS_KEY\"`\n */\n secretAccessKey?: string;\n /**\n * Variable with the bucket name. Default: `\"S3_BUCKET\"`\n */\n bucket?: string;\n /**\n * `\"auto\"`: Cloudflare R2 when the endpoint is on r2.cloudflarestorage.com, otherwise generic S3.\n * Default: `\"auto\"`\n */\n provider?: Provider;\n}\n\n/**\n * The `sync` section of newcode.config.ts. Settings name variables, never hold their values\n */\nexport interface SyncConfig {\n /**\n * `false` switches the database sync off\n */\n database?: DatabaseConfig | false;\n /**\n * `false` switches the S3 sync off\n */\n s3?: S3Config | false;\n}\n\nexport interface ResolvedSyncConfig {\n database: Required<DatabaseConfig> | false;\n s3: Required<S3Config> | false;\n}\n\ndeclare module \"@newcode-team/config\" {\n interface Config {\n sync?: SyncConfig;\n }\n}\n\n/**\n * The `sync` section of newcode.config.ts. Returns its input: it types the section and adds `sync`\n * to `Config`\n */\nexport const sync = (section: SyncConfig): SyncConfig => section;\n\nexport const defaults = {\n database: { url: \"DATABASE_URL\", schemas: [\"public\"] },\n s3: {\n endpoint: \"S3_ENDPOINT\",\n accessKeyId: \"S3_ACCESS_KEY_ID\",\n secretAccessKey: \"S3_SECRET_ACCESS_KEY\",\n bucket: \"S3_BUCKET\",\n provider: \"auto\",\n },\n} as const satisfies ResolvedSyncConfig;\n\nconst variableName = /^[A-Za-z_]\\w*$/;\n// Plain identifiers only, so they need no escaping in pg_dump patterns or SQL\nconst schemaName = /^[A-Za-z_][\\w$]*$/;\nconst providers: Provider[] = [\"auto\", \"cloudflare\", \"other\"];\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction checkKeys(path: string, value: Record<string, unknown>, known: string[]): void {\n const unknown = Object.keys(value).find((key) => !known.includes(key));\n if (unknown !== undefined) {\n throw new SyncError(`${path}.${unknown} is not a known key. Known: ${known.join(\", \")}`);\n }\n}\n\n// Never repeats the value: a mistake here is often a URL or key pasted in place of its name\nfunction checkVariable(path: string, value: unknown): void {\n if (value !== undefined && (typeof value !== \"string\" || !variableName.test(value))) {\n throw new SyncError(`${path} must be a variable name, such as \"DATABASE_URL\"`);\n }\n}\n\nfunction resolveDatabaseSection(value: unknown): ResolvedSyncConfig[\"database\"] {\n if (value === false) {\n return false;\n }\n if (value === undefined) {\n return { ...defaults.database, schemas: [...defaults.database.schemas] };\n }\n if (!isObject(value)) {\n throw new SyncError(\"sync.database must be false or an object\");\n }\n\n checkKeys(\"sync.database\", value, [\"url\", \"schemas\"]);\n checkVariable(\"sync.database.url\", value.url);\n const { schemas } = value;\n if (\n schemas !== undefined &&\n (!Array.isArray(schemas) ||\n schemas.length === 0 ||\n !schemas.every((schema) => typeof schema === \"string\" && schemaName.test(schema)))\n ) {\n throw new SyncError(\"sync.database.schemas must be a non-empty list of names\");\n }\n return { ...resolveDatabaseSection(undefined), ...value } as Required<DatabaseConfig>;\n}\n\nfunction resolveS3Section(value: unknown): ResolvedSyncConfig[\"s3\"] {\n if (value === false) {\n return false;\n }\n if (value === undefined) {\n return { ...defaults.s3 };\n }\n if (!isObject(value)) {\n throw new SyncError(\"sync.s3 must be false or an object\");\n }\n\n const variables = [\"endpoint\", \"accessKeyId\", \"secretAccessKey\", \"bucket\"];\n checkKeys(\"sync.s3\", value, [...variables, \"provider\"]);\n variables.forEach((key) => {\n checkVariable(`sync.s3.${key}`, value[key]);\n });\n if (value.provider !== undefined && !providers.includes(value.provider as Provider)) {\n throw new SyncError('sync.s3.provider must be \"auto\", \"cloudflare\" or \"other\"');\n }\n return { ...defaults.s3, ...value } as Required<S3Config>;\n}\n\n/**\n * Checks the section and fills in the defaults. Throws a `SyncError` with the path of the first\n * problem\n */\nexport function resolveSyncConfig(section: unknown = {}): ResolvedSyncConfig {\n if (!isObject(section)) {\n throw new SyncError(\"sync must be an object\");\n }\n checkKeys(\"sync\", section, [\"database\", \"s3\"]);\n return { database: resolveDatabaseSection(section.database), s3: resolveS3Section(section.s3) };\n}\n\n/**\n * The refusal for a part that is switched off with `false`\n */\nexport const switchedOff = (part: keyof ResolvedSyncConfig): SyncError =>\n new SyncError(\n `The ${part === \"s3\" ? \"S3\" : \"database\"} sync is off: sync.${part} is false in newcode.config.ts.`,\n );\n\n/**\n * The `sync` section of the project's newcode.config.ts, found from cwd up, checked and with the\n * defaults\n */\nexport async function loadSyncConfig(cwd: string): Promise<ResolvedSyncConfig> {\n return resolveSyncConfig((await loadConfig({ cwd })).sync);\n}\n","import { spawn, spawnSync } from \"node:child_process\";\nimport { SyncError } from \"./errors\";\n\n/**\n * Tools a sync needs, and how to install them\n */\nexport interface Tools {\n names: string[];\n hint: string;\n}\n\n/**\n * Throws a `SyncError` with the install hint when one of the tools can't be started\n */\nexport function requireTools({ names, hint }: Tools): void {\n const missing = names.filter(\n (name) =>\n (spawnSync(name, [\"--version\"], { stdio: \"ignore\" }).error as NodeJS.ErrnoException)?.code ===\n \"ENOENT\",\n );\n if (missing.length > 0) {\n throw new SyncError(`${missing.join(\", \")} not found. ${hint}`);\n }\n}\n\nexport interface RunToolOptions {\n env: NodeJS.ProcessEnv;\n /**\n * Returns stdout instead of passing it through\n */\n capture?: boolean;\n}\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * Runs a tool and waits for it. Its stderr, and stdout unless captured, go to the terminal. A\n * failure throws a `SyncError` naming only the tool: the tool already printed what went wrong, and\n * its arguments aren't repeated.\n *\n * Signals are forwarded like newenv does: in a terminal, Ctrl+C and hangups already reach the tool,\n * so only SIGTERM is forwarded there. Node keeps running until the tool exits, so callers clean up.\n */\nexport function runTool(\n command: string,\n args: string[],\n { env, capture = false }: RunToolOptions,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n env,\n stdio: [\"ignore\", capture ? \"pipe\" : \"inherit\", \"inherit\"],\n });\n const output: Buffer[] = [];\n child.stdout?.on(\"data\", (chunk: Buffer) => output.push(chunk));\n\n const forward = (signal: NodeJS.Signals) => {\n if (signal === \"SIGTERM\" || !process.stdin.isTTY) {\n child.kill(signal);\n }\n };\n const stopForwarding = () => {\n signals.forEach((signal) => {\n process.off(signal, forward);\n });\n };\n signals.forEach((signal) => {\n process.on(signal, forward);\n });\n\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n stopForwarding();\n reject(\n new SyncError(\n error.code === \"ENOENT\"\n ? `${command} not found.`\n : `${command} could not start: ${error.message}`,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n stopForwarding();\n if (code === 0) {\n resolve(Buffer.concat(output).toString());\n } else {\n reject(new SyncError(signal ? `${command} stopped by ${signal}.` : `${command} failed.`));\n }\n });\n });\n}\n","import { mkdtempSync, rmSync } from \"node:fs\";\nimport { devNull, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { loadEnvironment } from \"@newcode-team/env\";\nimport type { DatabaseConfig } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport { runTool, type Tools } from \"../../lib/process\";\n\nexport const postgresTools: Tools = {\n names: [\"pg_dump\", \"pg_restore\", \"psql\"],\n hint: \"macOS: install Postgres.app (https://postgresapp.com) and add its bin folder to PATH, or brew install libpq. Other systems: https://www.postgresql.org/download/\",\n};\n\n/**\n * A database that is in no environment\n */\nexport interface CustomDatabase {\n /**\n * A postgres:// or postgresql:// URL\n */\n url: string;\n}\n\n/**\n * An environment name, or a custom database\n */\nexport type DatabaseSide = string | CustomDatabase;\n\nexport interface Database {\n /**\n * The environment name, or `custom`\n */\n label: string;\n url: URL;\n}\n\n/**\n * Parses a postgres URL. The message names where it came from, never the value\n */\nexport function parseDatabaseUrl(value: string, from: string): URL {\n const url = URL.parse(value);\n if (!url || ![\"postgres:\", \"postgresql:\"].includes(url.protocol) || !url.hostname) {\n throw new SyncError(`${from} is not a postgres:// or postgresql:// URL.`);\n }\n return url;\n}\n\n/**\n * The URL of an environment, read from the configured variable, or of a custom database\n */\nexport async function resolveDatabase(\n side: DatabaseSide,\n config: Required<DatabaseConfig>,\n cwd: string,\n): Promise<Database> {\n if (typeof side !== \"string\") {\n return { label: \"custom\", url: parseDatabaseUrl(side.url, \"The custom database URL\") };\n }\n\n const environment = await loadEnvironment(side, { cwd });\n // require() has checked the key\n const { [config.url]: value = \"\" } = environment.require(config.url);\n return { label: side, url: parseDatabaseUrl(value, `${config.url} of environment \"${side}\"`) };\n}\n\n/**\n * Environment, host and database, without the user and password\n */\nexport const describeDatabase = ({ label, url }: Database): string =>\n `${label} (${url.host}${url.pathname})`;\n\n/**\n * Same host, port and database name\n */\nexport function sameDatabase(a: Database, b: Database): boolean {\n const key = ({ url }: Database) =>\n [url.hostname.toLowerCase(), url.port || \"5432\", decodeURIComponent(url.pathname)].join(\" \");\n return key(a) === key(b);\n}\n\n// libpq reads these from the environment, and would fill in what a URL leaves out\nconst libpqVariables = [\n \"PGHOST\",\n \"PGHOSTADDR\",\n \"PGPORT\",\n \"PGDATABASE\",\n \"PGUSER\",\n \"PGPASSWORD\",\n \"PGSERVICE\",\n];\n\n/**\n * The URL to pass to pg_dump and psql, and the environment to run them with. The password goes\n * through PGPASSWORD, so it's never a process argument that `ps` shows\n */\nexport function connection(url: URL): { dbname: string; env: NodeJS.ProcessEnv } {\n const withoutPassword = new URL(url.href);\n withoutPassword.password = \"\";\n withoutPassword.searchParams.delete(\"password\");\n const password = url.password\n ? decodeURIComponent(url.password)\n : (url.searchParams.get(\"password\") ?? undefined);\n\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !libpqVariables.includes(key)),\n );\n return {\n dbname: withoutPassword.href,\n env: password === undefined ? env : { ...env, PGPASSWORD: password },\n };\n}\n\n/**\n * Runs SQL with psql and returns the rows, tab-separated\n */\nfunction query(url: URL, sql: string): Promise<string> {\n const { dbname, env } = connection(url);\n return runTool(\n \"psql\",\n [\n \"--no-psqlrc\",\n \"--quiet\",\n \"--no-align\",\n \"--tuples-only\",\n \"--field-separator=\\t\",\n \"--set=ON_ERROR_STOP=1\",\n `--command=${sql}`,\n `--dbname=${dbname}`,\n ],\n { env, capture: true },\n );\n}\n\n/**\n * Refuses when pg_dump is an older major version than the source server: it can't dump it\n */\nexport async function checkVersion(source: Database): Promise<void> {\n const version = await runTool(\"pg_dump\", [\"--version\"], { env: process.env, capture: true });\n const dump = Number(/\\)\\s*(\\d+)/.exec(version)?.[1]);\n const server = Math.floor(Number(await query(source.url, \"SHOW server_version_num\")) / 10000);\n if (dump < server) {\n throw new SyncError(\n `pg_dump ${dump} is older than the source server, Postgres ${server}. Install pg_dump ${server} or later. ${postgresTools.hint}`,\n );\n }\n}\n\n/**\n * A row estimate for the dry run, e.g. `~1 row`\n */\nexport function describeRowEstimate(estimate: string): string {\n const count = estimate === \"\" ? -1 : Number(estimate);\n return count < 0 ? \"row count unknown\" : `~${count} ${count === 1 ? \"row\" : \"rows\"}`;\n}\n\n/**\n * Lists the target's tables in the schemas, with row estimates. Changes nothing. Schema names are\n * plain identifiers (see lib/config.ts), so they need no escaping\n */\nexport async function listTables(\n target: Database,\n schemas: string[],\n log: (message: string) => void,\n): Promise<void> {\n // reltuples stays -1 until a table is analyzed, as after a restore. The statistics' live row\n // count is kept up to date on every write, and costs no count(*) on a large table\n const rows = await query(\n target.url,\n `SELECT n.nspname || '.' || c.relname, CASE WHEN c.reltuples >= 0 THEN c.reltuples::bigint ELSE s.n_live_tup END FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition AND n.nspname IN (${schemas.map((schema) => `'${schema}'`).join(\", \")}) ORDER BY 1`,\n );\n const tables = rows\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\")\n .map((line) => {\n const [name = \"\", estimate = \"\"] = line.split(\"\\t\");\n return ` ${name} ${describeRowEstimate(estimate)}`;\n });\n log(\n tables.length > 0\n ? `Would replace these tables of ${describeDatabase(target)}:\\n${tables.join(\"\\n\")}`\n : `No tables in ${schemas.join(\", \")} of ${describeDatabase(target)} yet.`,\n );\n log(\"Dry run: nothing changed.\");\n}\n\n/**\n * Dumps the schemas of the source and restores them into the target in one transaction\n */\nexport async function copyDatabase(\n source: Database,\n target: Database,\n schemas: string[],\n log: (message: string) => void,\n): Promise<void> {\n const dir = mkdtempSync(join(tmpdir(), \"newsync-\"));\n // Ctrl+C stops the running tool and no further one starts. Node keeps running until the dump is\n // removed\n let interrupted = false;\n const interrupt = () => {\n interrupted = true;\n };\n const step = async (command: string, args: string[], env: NodeJS.ProcessEnv) => {\n if (interrupted) {\n throw new SyncError(\"Aborted.\");\n }\n await runTool(command, args, { env }).catch((error: unknown) => {\n throw interrupted ? new SyncError(\"Aborted.\") : error;\n });\n };\n process.on(\"SIGINT\", interrupt);\n\n try {\n const dumpFile = join(dir, \"source.dump\");\n const sqlFile = join(dir, \"source.sql\");\n\n // Only the configured schemas: hosting providers keep their own extensions in other schemas,\n // which a local Postgres can't install\n log(`Dumping ${describeDatabase(source)}...`);\n const from = connection(source.url);\n await step(\n \"pg_dump\",\n [\n ...schemas.map((schema) => `--schema=\"${schema}\"`),\n \"--format=custom\",\n \"--no-owner\",\n \"--no-privileges\",\n `--file=${dumpFile}`,\n `--dbname=${from.dbname}`,\n ],\n from.env,\n );\n await step(\n \"pg_restore\",\n [\"--no-owner\", \"--no-privileges\", `--file=${sqlFile}`, dumpFile],\n process.env,\n );\n\n // Dropping with CASCADE also removes tables that only exist in the target. Drop and restore run\n // in one transaction, so a failed restore leaves the target as it was\n log(`Restoring into ${describeDatabase(target)}...`);\n const to = connection(target.url);\n const drop = schemas.map((schema) => `DROP SCHEMA IF EXISTS \"${schema}\" CASCADE;`);\n await step(\n \"psql\",\n [\n \"--no-psqlrc\",\n \"--quiet\",\n \"--single-transaction\",\n \"--set=ON_ERROR_STOP=1\",\n `--output=${devNull}`,\n `--command=SET client_min_messages = warning; ${drop.join(\" \")}`,\n `--file=${sqlFile}`,\n `--dbname=${to.dbname}`,\n ],\n to.env,\n );\n // Migration history comes along only when its table is in one of the schemas\n const one = schemas.length === 1;\n log(\n `Done. ${one ? \"Schema\" : \"Schemas\"} ${schemas.join(\", \")} of ${describeDatabase(target)} now ${one ? \"matches\" : \"match\"} the source.`,\n );\n } finally {\n process.off(\"SIGINT\", interrupt);\n rmSync(dir, { recursive: true, force: true });\n }\n}\n","import { loadSyncConfig, switchedOff } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { SyncOptions, SyncPlan } from \"../../lib/plan\";\nimport { requireTools } from \"../../lib/process\";\nimport {\n checkVersion,\n copyDatabase,\n type DatabaseSide,\n describeDatabase,\n listTables,\n postgresTools,\n resolveDatabase,\n sameDatabase,\n} from \"./helpers\";\n\nexport type { CustomDatabase, DatabaseSide } from \"./helpers\";\n\nexport type SyncDatabaseOptions = SyncOptions<DatabaseSide>;\n\n/**\n * Checks the tools, both databases and the pg_dump version, without changing anything\n */\nexport async function planDatabaseSync({\n source: sourceSide,\n target: targetSide,\n dryRun = false,\n cwd = process.cwd(),\n log = console.log,\n}: SyncDatabaseOptions): Promise<SyncPlan> {\n const { database: config } = await loadSyncConfig(cwd);\n if (!config) {\n throw switchedOff(\"database\");\n }\n requireTools(postgresTools);\n\n const source = await resolveDatabase(sourceSide, config, cwd);\n const target = await resolveDatabase(targetSide, config, cwd);\n if (sameDatabase(source, target)) {\n throw new SyncError(`Source and target are the same database: ${describeDatabase(target)}.`);\n }\n await checkVersion(source);\n\n const { schemas } = config;\n return {\n source: describeDatabase(source),\n target: describeDatabase(target),\n question: `Replace ${schemas.length === 1 ? \"schema\" : \"schemas\"} ${schemas.join(\", \")} of ${describeDatabase(target)}`,\n run: () =>\n dryRun ? listTables(target, schemas, log) : copyDatabase(source, target, schemas, log),\n };\n}\n\n/**\n * Replaces the configured schemas of the target database with a copy of the source's. Doesn't\n * ask: a script confirms first, e.g. with `confirmEnvironment` from @newcode-team/env\n */\nexport async function syncDatabase(options: SyncDatabaseOptions): Promise<void> {\n await (await planDatabaseSync(options)).run();\n}\n","import { loadEnvironment } from \"@newcode-team/env\";\nimport type { Provider, S3Config } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { Tools } from \"../../lib/process\";\n\nexport const rcloneTools: Tools = {\n names: [\"rclone\"],\n hint: \"macOS: brew install rclone. Other systems: https://rclone.org/install/\",\n};\n\n/**\n * A bucket that is in no environment\n */\nexport interface CustomBucket {\n /**\n * An http:// or https:// URL\n */\n endpoint: string;\n accessKeyId: string;\n secretAccessKey: string;\n bucket: string;\n /**\n * Default: `\"auto\"`\n */\n provider?: Provider;\n}\n\n/**\n * An environment name, or a custom bucket\n */\nexport type BucketSide = string | CustomBucket;\n\nexport interface Bucket {\n /**\n * The environment name, or `custom`\n */\n label: string;\n endpoint: URL;\n accessKeyId: string;\n secretAccessKey: string;\n bucket: string;\n provider: Provider;\n}\n\n/**\n * Parses an S3 endpoint. The message names where it came from, never the value\n */\nexport function parseEndpoint(value: string, from: string): URL {\n const url = URL.parse(value);\n if (!url || ![\"http:\", \"https:\"].includes(url.protocol)) {\n throw new SyncError(`${from} is not an http:// or https:// URL.`);\n }\n return url;\n}\n\n/**\n * The bucket of an environment, read from the configured variables, or a custom bucket\n */\nexport async function resolveBucket(\n side: BucketSide,\n config: Required<S3Config>,\n cwd: string,\n): Promise<Bucket> {\n if (typeof side !== \"string\") {\n const missing = ([\"accessKeyId\", \"secretAccessKey\", \"bucket\"] as const).filter(\n (key) => !side[key],\n );\n if (missing.length > 0) {\n throw new SyncError(`The custom bucket misses ${missing.join(\", \")}.`);\n }\n return {\n ...side,\n label: \"custom\",\n endpoint: parseEndpoint(side.endpoint, \"The custom endpoint\"),\n provider: side.provider ?? \"auto\",\n };\n }\n\n const environment = await loadEnvironment(side, { cwd });\n const values = environment.require(\n config.endpoint,\n config.accessKeyId,\n config.secretAccessKey,\n config.bucket,\n );\n // require() has checked every key\n const value = (key: string) => values[key] ?? \"\";\n return {\n label: side,\n endpoint: parseEndpoint(value(config.endpoint), `${config.endpoint} of environment \"${side}\"`),\n accessKeyId: value(config.accessKeyId),\n secretAccessKey: value(config.secretAccessKey),\n bucket: value(config.bucket),\n provider: config.provider,\n };\n}\n\n/**\n * Environment, bucket and host, without the keys\n */\nexport const describeBucket = ({ label, bucket, endpoint }: Bucket): string =>\n `${label} (${bucket} on ${endpoint.host})`;\n\n/**\n * Same bucket on the same endpoint\n */\nexport const sameBucket = (a: Bucket, b: Bucket): boolean =>\n a.endpoint.host.toLowerCase() === b.endpoint.host.toLowerCase() && a.bucket === b.bucket;\n\nconst endpointKey = ({ endpoint }: Bucket) => endpoint.href.replace(/\\/$/, \"\").toLowerCase();\n\n/**\n * Both buckets reachable with one endpoint and one key, e.g. production to staging on R2: then one\n * rclone remote, and the provider copies the files itself. Otherwise they stream through this\n * machine\n */\nexport const sameRemote = (a: Bucket, b: Bucket): boolean =>\n endpointKey(a) === endpointKey(b) &&\n a.accessKeyId === b.accessKeyId &&\n a.secretAccessKey === b.secretAccessKey;\n\n/**\n * Cloudflare for R2, otherwise generic S3\n */\nexport function rcloneProvider({ provider, endpoint }: Bucket): \"Cloudflare\" | \"Other\" {\n if (provider === \"auto\") {\n return endpoint.hostname.toLowerCase().endsWith(\".r2.cloudflarestorage.com\")\n ? \"Cloudflare\"\n : \"Other\";\n }\n return provider === \"cloudflare\" ? \"Cloudflare\" : \"Other\";\n}\n\n// rclone reads a remote from RCLONE_CONFIG_<NAME>_* variables, so the keys are never process\n// arguments that `ps` shows, nor in an rclone.conf on disk\nfunction remoteEnv(name: string, bucket: Bucket): Record<string, string> {\n const prefix = `RCLONE_CONFIG_${name.toUpperCase()}`;\n return {\n [`${prefix}_TYPE`]: \"s3\",\n [`${prefix}_PROVIDER`]: rcloneProvider(bucket),\n [`${prefix}_REGION`]: \"auto\",\n [`${prefix}_ENDPOINT`]: bucket.endpoint.href.replace(/\\/$/, \"\"),\n [`${prefix}_ACCESS_KEY_ID`]: bucket.accessKeyId,\n [`${prefix}_SECRET_ACCESS_KEY`]: bucket.secretAccessKey,\n [`${prefix}_ENV_AUTH`]: \"false\",\n // R2 tokens are often scoped to a few buckets and may not create or check buckets\n [`${prefix}_NO_CHECK_BUCKET`]: \"true\",\n };\n}\n\n/**\n * The rclone source and target paths, and the variables that define their remotes\n */\nexport function remotes(\n source: Bucket,\n target: Bucket,\n): { source: string; target: string; env: Record<string, string> } {\n const one = sameRemote(source, target);\n return {\n source: `${one ? \"newsync_target\" : \"newsync_source\"}:${source.bucket}`,\n target: `newsync_target:${target.bucket}`,\n env: {\n ...remoteEnv(\"newsync_target\", target),\n ...(one ? {} : remoteEnv(\"newsync_source\", source)),\n },\n };\n}\n","import { loadSyncConfig, switchedOff } from \"../../lib/config\";\nimport { SyncError } from \"../../lib/errors\";\nimport type { SyncOptions, SyncPlan } from \"../../lib/plan\";\nimport { requireTools, runTool } from \"../../lib/process\";\nimport {\n type BucketSide,\n describeBucket,\n rcloneTools,\n remotes,\n resolveBucket,\n sameBucket,\n} from \"./helpers\";\n\nexport type { BucketSide, CustomBucket } from \"./helpers\";\n\nexport type SyncS3Options = SyncOptions<BucketSide>;\n\n/**\n * Checks the tool and both buckets, without changing anything\n */\nexport async function planS3Sync({\n source: sourceSide,\n target: targetSide,\n dryRun = false,\n cwd = process.cwd(),\n log = console.log,\n}: SyncS3Options): Promise<SyncPlan> {\n const { s3: config } = await loadSyncConfig(cwd);\n if (!config) {\n throw switchedOff(\"s3\");\n }\n requireTools(rcloneTools);\n\n const source = await resolveBucket(sourceSide, config, cwd);\n const target = await resolveBucket(targetSide, config, cwd);\n if (sameBucket(source, target)) {\n throw new SyncError(`Source and target are the same bucket: ${describeBucket(target)}.`);\n }\n\n const paths = remotes(source, target);\n return {\n source: describeBucket(source),\n target: describeBucket(target),\n question: `Overwrite ${describeBucket(target)} and delete its files that aren't in the source`,\n async run() {\n log(dryRun ? \"Comparing buckets...\" : `Syncing ${describeBucket(target)}...`);\n // sync copies new and changed files, skips unchanged ones (size and modification time) and\n // deletes files that only exist in the target. Deleting comes last and is skipped after an\n // error, so a failed sync never leaves the target with fewer files\n await runTool(\n \"rclone\",\n [\n \"sync\",\n paths.source,\n paths.target,\n // One listing request per bucket instead of one per folder: fewer R2 class A operations\n \"--fast-list\",\n \"--delete-after\",\n \"--stats-one-line\",\n ...(dryRun ? [\"--dry-run\"] : process.stdout.isTTY ? [\"--progress\"] : []),\n ],\n { env: { ...process.env, ...paths.env } },\n );\n log(\n dryRun\n ? \"Dry run: nothing changed.\"\n : `Done. ${describeBucket(target)} now has the files of the source.`,\n );\n },\n };\n}\n\n/**\n * Makes the target bucket an exact copy of the source bucket. Doesn't ask: a script confirms\n * first, e.g. with `confirmEnvironment` from @newcode-team/env\n */\nexport async function syncS3(options: SyncS3Options): Promise<void> {\n await (await planS3Sync(options)).run();\n}\n"],"mappings":";;;;;;;;;;;AAIA,IAAa,YAAb,cAA+B,MAAM;CAC1B,OAAO;AAClB;;;;AAKA,SAAgB,aAAa,OAAwB;CACnD,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,oBAAoB,aAAa,MAAM;CAE/D,OAAO,OAAO,KAAK;AACrB;;;;;;AC4DA,MAAa,QAAQ,YAAoC;AAEzD,MAAa,WAAW;CACtB,UAAU;EAAE,KAAK;EAAgB,SAAS,CAAC,QAAQ;CAAE;CACrD,IAAI;EACF,UAAU;EACV,aAAa;EACb,iBAAiB;EACjB,QAAQ;EACR,UAAU;CACZ;AACF;AAEA,MAAM,eAAe;AAErB,MAAM,aAAa;AACnB,MAAM,YAAwB;CAAC;CAAQ;CAAc;AAAO;AAE5D,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,SAAS,UAAU,MAAc,OAAgC,OAAuB;CACtF,MAAM,UAAU,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,CAAC,MAAM,SAAS,GAAG,CAAC;CACrE,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,UAAU,GAAG,KAAK,GAAG,QAAQ,8BAA8B,MAAM,KAAK,IAAI,GAAG;AAE3F;AAGA,SAAS,cAAc,MAAc,OAAsB;CACzD,IAAI,UAAU,KAAA,MAAc,OAAO,UAAU,YAAY,CAAC,aAAa,KAAK,KAAK,IAC/E,MAAM,IAAI,UAAU,GAAG,KAAK,iDAAiD;AAEjF;AAEA,SAAS,uBAAuB,OAAgD;CAC9E,IAAI,UAAU,OACZ,OAAO;CAET,IAAI,UAAU,KAAA,GAC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