@newcode-team/sync 0.0.0 → 0.2.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.
- package/README.md +174 -2
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +164 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.d.mts +140 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1 -0
- package/dist/sync-C6BM27_L.mjs +512 -0
- package/dist/sync-C6BM27_L.mjs.map +1 -0
- package/package.json +59 -2
package/README.md
CHANGED
|
@@ -1,3 +1,175 @@
|
|
|
1
|
-
#
|
|
1
|
+
# newsync
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Copies a database or an S3 bucket from one environment to another, such as production to staging or staging to local. Both sides load through [`@newcode-team/env`](../env), so nobody pastes URLs or keys for the usual cases.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add -D @newcode-team/sync @newcode-team/env @newcode-team/config
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"scripts": {
|
|
12
|
+
"db:sync": "newsync db",
|
|
13
|
+
"s3:sync": "newsync s3"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Both at once: `newsync s3 production staging && newsync db production staging`. The bucket goes first: a failed S3 sync deletes nothing, so the target still works with its old database. Each asks its own confirmation.
|
|
19
|
+
|
|
20
|
+
Requires Node 24+, plus `pg_dump`, `pg_restore` and `psql` for the database and `rclone` for S3:
|
|
21
|
+
|
|
22
|
+
| System | Install |
|
|
23
|
+
|---|---|
|
|
24
|
+
| macOS | [Postgres.app](https://postgresapp.com) (add its `bin` folder to `PATH`) or `brew install libpq`, and `brew install rclone` |
|
|
25
|
+
| Other | [PostgreSQL client](https://www.postgresql.org/download/) and [rclone](https://rclone.org/install/) |
|
|
26
|
+
|
|
27
|
+
`pg_dump` must be at least the major version of the source server.
|
|
28
|
+
|
|
29
|
+
## Commands
|
|
30
|
+
|
|
31
|
+
| Command | Does |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `newsync db <source> <target>` | Replaces the target database's schemas with a copy of the source's |
|
|
34
|
+
| `newsync s3 <source> <target>` | Makes the target S3 bucket an exact copy of the source bucket |
|
|
35
|
+
| `--dry-run` | Changes nothing: `s3` lists what would be copied and deleted, `db` checks both connections and lists the tables that would be replaced |
|
|
36
|
+
|
|
37
|
+
`<source>` and `<target>` are environment names (a `.envs/.env.<name>` file) or `custom`. A missing one is asked, with a list of the environments plus `custom`. `custom` asks for a database URL, or an endpoint, keys and bucket, with the secrets masked.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm db:sync production staging
|
|
41
|
+
pnpm s3:sync staging local --dry-run
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Every sync
|
|
45
|
+
|
|
46
|
+
1. **Tools:** checked first, with an install hint when one is missing.
|
|
47
|
+
2. **Both sides:** loaded with `loadEnvironment(name)`, the same files and checks as `newenv`, and the configured variables required. Or the custom prompts.
|
|
48
|
+
3. **Same target:** refused when source and target are the same database (host, port and name) or the same bucket on the same endpoint.
|
|
49
|
+
4. **Shows** `source → target` as environment, host and database or bucket, such as `staging (db.example.com/app)`. Never a user, password or key.
|
|
50
|
+
5. **Confirms** with the target environment's own rule from the `env` section: production types its name, local doesn't ask, others ask y/N. A custom target always asks y/N. A question without a terminal aborts, so agents and CI can't confirm by accident. The source is only read and never asks. `--dry-run` doesn't ask.
|
|
51
|
+
|
|
52
|
+
Every failure or abort exits with 1. Ctrl+C on a prompt aborts.
|
|
53
|
+
|
|
54
|
+
### Database
|
|
55
|
+
|
|
56
|
+
- `pg_dump` of the configured schemas only (custom format, no owner, no privileges). Hosting providers keep their own extensions in other schemas, which a local Postgres can't install.
|
|
57
|
+
- Refuses when `pg_dump` is an older major version than the source server, before dumping.
|
|
58
|
+
- Restores in one transaction: drops the configured schemas with `CASCADE`, then loads the dump. A failure leaves the target untouched. After a success, tables that only existed in the target are gone.
|
|
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
|
+
- The dump goes to a temporary folder that is always removed, also after Ctrl+C.
|
|
61
|
+
- Passwords reach `pg_dump` and `psql` through `PGPASSWORD`, never as process arguments.
|
|
62
|
+
|
|
63
|
+
Doesn't copy roles, extensions or other schemas, and doesn't touch the source.
|
|
64
|
+
|
|
65
|
+
### S3
|
|
66
|
+
|
|
67
|
+
Any S3-compatible storage: Cloudflare R2, AWS S3, RustFS, MinIO, …
|
|
68
|
+
|
|
69
|
+
- `rclone sync`: copies new and changed files, skips unchanged ones (size and modification time), and deletes files that only exist in the target.
|
|
70
|
+
- Same endpoint and keys on both sides, such as production → staging on R2: one rclone remote, and R2 copies server-side. Otherwise, such as staging → the local container: two remotes, streaming through this machine.
|
|
71
|
+
- Keys reach rclone through `RCLONE_CONFIG_*` variables, never as arguments or an `rclone.conf` on disk.
|
|
72
|
+
- Deleting comes last and is skipped after an error, so a failed sync never leaves the target with fewer files.
|
|
73
|
+
|
|
74
|
+
Doesn't create buckets, or copy bucket settings such as CORS rules or policies.
|
|
75
|
+
|
|
76
|
+
## Config
|
|
77
|
+
|
|
78
|
+
Optional. The `sync` section of `newcode.config.ts`, the config file all NewCode tools share. The values below are the defaults, so a project that uses these variable names needs no section:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { defineConfig } from "@newcode-team/config";
|
|
82
|
+
import { sync } from "@newcode-team/sync";
|
|
83
|
+
|
|
84
|
+
export default defineConfig({
|
|
85
|
+
sync: sync({
|
|
86
|
+
database: { url: "DATABASE_URL", schemas: ["public"] },
|
|
87
|
+
s3: {
|
|
88
|
+
endpoint: "S3_ENDPOINT",
|
|
89
|
+
accessKeyId: "S3_ACCESS_KEY_ID",
|
|
90
|
+
secretAccessKey: "S3_SECRET_ACCESS_KEY",
|
|
91
|
+
bucket: "S3_BUCKET",
|
|
92
|
+
provider: "auto",
|
|
93
|
+
},
|
|
94
|
+
}),
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Settings name variables in `.envs/`, never hold their values. `sync()` returns the section as is: importing it types the section and adds the `sync` key to the config, so a typo is an error. The section is also checked when loaded, with the path in the message, such as `sync.database.schemas must be a non-empty list of names`.
|
|
99
|
+
|
|
100
|
+
| Key | Default | Does |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| `database` | | `false` switches the database sync off |
|
|
103
|
+
| `database.url` | `"DATABASE_URL"` | Variable with the `postgres://` URL |
|
|
104
|
+
| `database.schemas` | `["public"]` | Schemas that are copied and replaced. A Drizzle project: `["public", "drizzle"]` |
|
|
105
|
+
| `s3` | | `false` switches the S3 sync off |
|
|
106
|
+
| `s3.endpoint` | `"S3_ENDPOINT"` | Variable with the `http(s)://` endpoint |
|
|
107
|
+
| `s3.accessKeyId` | `"S3_ACCESS_KEY_ID"` | Variable with the access key ID |
|
|
108
|
+
| `s3.secretAccessKey` | `"S3_SECRET_ACCESS_KEY"` | Variable with the secret access key |
|
|
109
|
+
| `s3.bucket` | `"S3_BUCKET"` | Variable with the bucket name |
|
|
110
|
+
| `s3.provider` | `"auto"` | `auto`: Cloudflare R2 when the endpoint is on `r2.cloudflarestorage.com`, otherwise generic S3. Or `cloudflare`, `other` |
|
|
111
|
+
|
|
112
|
+
Confirmation follows `environments.<name>.confirm` in the `env` section.
|
|
113
|
+
|
|
114
|
+
## Use in scripts
|
|
115
|
+
|
|
116
|
+
The same syncs, for scripts:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { confirmEnvironment } from "@newcode-team/env";
|
|
120
|
+
import { syncDatabase, syncS3 } from "@newcode-team/sync";
|
|
121
|
+
|
|
122
|
+
if (await confirmEnvironment("staging", "Overwrite staging with production")) {
|
|
123
|
+
await syncS3({ source: "production", target: "staging" });
|
|
124
|
+
await syncDatabase({ source: "production", target: "staging" });
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
| Function | Does |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `syncDatabase({ source, target, dryRun? })` | The database sync |
|
|
131
|
+
| `syncS3({ source, target, dryRun? })` | The S3 sync |
|
|
132
|
+
| `sync(section)` | The config section helper |
|
|
133
|
+
| `SyncError` | Thrown for every refusal and failure, with the command's messages |
|
|
134
|
+
|
|
135
|
+
- They don't ask: confirming stays in the command. **A script must confirm itself**, for example with `confirmEnvironment` as above.
|
|
136
|
+
- A side is an environment name, or a custom object: `{ url }` for a database, `{ endpoint, accessKeyId, secretAccessKey, bucket, provider? }` for S3.
|
|
137
|
+
- Both also take `{ cwd }`, default `process.cwd()`, and `log`, default `console.log`.
|
|
138
|
+
|
|
139
|
+
## Development
|
|
140
|
+
|
|
141
|
+
Part of the [NewCode tools](../..) monorepo, laid out like `@newcode-team/env`:
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
src/
|
|
145
|
+
cli.ts the newsync program, registers the commands
|
|
146
|
+
index.ts the public API
|
|
147
|
+
commands/
|
|
148
|
+
database/ command.ts (newsync db), sync.ts, helpers.ts (Postgres)
|
|
149
|
+
s3/ command.ts (newsync s3), sync.ts, helpers.ts (rclone)
|
|
150
|
+
lib/ config, errors, the command flow, processes, prompts
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- `command.ts` registers the command. Simple logic used once stays inline.
|
|
154
|
+
- `sync.ts` is the public API of the part, exported from `index.ts`.
|
|
155
|
+
- `helpers.ts` holds logic that is complex, reused or tested on its own.
|
|
156
|
+
- `lib/` never imports from `commands/`.
|
|
157
|
+
|
|
158
|
+
From the repository root:
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
pnpm build # tsdown, with publint and attw
|
|
162
|
+
pnpm test # Vitest, builds dist/ first for the CLI tests
|
|
163
|
+
pnpm lint # Oxlint
|
|
164
|
+
pnpm format # Oxfmt
|
|
165
|
+
pnpm typecheck
|
|
166
|
+
pnpm changeset # describe a change for the next release
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
The integration tests run against Postgres 18 and RustFS from `compose.yaml` at the repository root, and start them with `docker compose up`. They skip, with the reason, when Docker, `pg_dump` or `rclone` is missing.
|
|
170
|
+
|
|
171
|
+
Releases go through Changesets: merging to `main` opens a release PR, and merging that PR publishes to npm.
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from "commander";
|
|
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-C6BM27_L.mjs";
|
|
5
|
+
// package.json
|
|
6
|
+
var version = "0.2.0";
|
|
7
|
+
// src/lib/prompt.ts
|
|
8
|
+
/**
|
|
9
|
+
* Prompts read the terminal and write to stderr, like newenv's, so stdout stays the command's
|
|
10
|
+
*/
|
|
11
|
+
const terminal = {
|
|
12
|
+
input: process.stdin,
|
|
13
|
+
output: process.stderr
|
|
14
|
+
};
|
|
15
|
+
const CUSTOM = "custom";
|
|
16
|
+
/**
|
|
17
|
+
* Validates a required answer
|
|
18
|
+
*/
|
|
19
|
+
const required = (value) => value.trim() !== "" || "Required";
|
|
20
|
+
/**
|
|
21
|
+
* Validates a URL with one of the protocols
|
|
22
|
+
*/
|
|
23
|
+
const urlWithProtocol = (protocols, message) => (value) => protocols.includes(URL.parse(value)?.protocol ?? "") || message;
|
|
24
|
+
/**
|
|
25
|
+
* The environment given on the command line, or chosen from the environments plus custom
|
|
26
|
+
*/
|
|
27
|
+
async function chooseSide(side, given, environments, streams = terminal) {
|
|
28
|
+
const available = [...environments, CUSTOM];
|
|
29
|
+
if (given !== void 0) {
|
|
30
|
+
if (!available.includes(given)) throw new SyncError(`Unknown environment "${given}". Available: ${available.join(", ")}`);
|
|
31
|
+
if (given === "custom" && !streams.input.isTTY) throw new SyncError(`${side} ${CUSTOM} asks for the connection details: needs a terminal. In a script, pass a custom side to syncDatabase or syncS3.`);
|
|
32
|
+
return given;
|
|
33
|
+
}
|
|
34
|
+
if (!streams.input.isTTY) throw new SyncError(`${side} missing. Pass it as an argument (${available.join(", ")}), or run in a terminal to choose.`);
|
|
35
|
+
const { default: select } = await import("@inquirer/select");
|
|
36
|
+
return select({
|
|
37
|
+
message: `${side}:`,
|
|
38
|
+
choices: available.map((name) => ({
|
|
39
|
+
value: name,
|
|
40
|
+
name: name === "custom" ? `${CUSTOM} (enter the connection details)` : name
|
|
41
|
+
}))
|
|
42
|
+
}, streams);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* y/N for a custom target, which has no environment settings. Throws without a TTY, like
|
|
46
|
+
* `confirmEnvironment`, so agents and CI can't confirm by accident. Ctrl+C answers no
|
|
47
|
+
*/
|
|
48
|
+
async function confirmCustom(question, streams = terminal) {
|
|
49
|
+
if (!streams.input.isTTY) throw new SyncError(`${question}: needs confirmation, no TTY. Aborted.`);
|
|
50
|
+
const { default: confirm } = await import("@inquirer/confirm");
|
|
51
|
+
try {
|
|
52
|
+
return await confirm({
|
|
53
|
+
message: `${question}?`,
|
|
54
|
+
default: false
|
|
55
|
+
}, streams);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error instanceof Error && error.name === "ExitPromptError") return false;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// src/lib/flow.ts
|
|
62
|
+
const sourceDescription = `Environment to copy from, or ${CUSTOM}`;
|
|
63
|
+
const targetDescription = `Environment to overwrite, or ${CUSTOM}`;
|
|
64
|
+
/**
|
|
65
|
+
* The flow of every newsync command: checks the config and tools, chooses both sides, checks them,
|
|
66
|
+
* shows source → target, confirms with the target's rule and runs
|
|
67
|
+
*/
|
|
68
|
+
async function runSyncCommand(kind, [sourceName, targetName], { dryRun = false }) {
|
|
69
|
+
const cwd = process.cwd();
|
|
70
|
+
if ((await loadSyncConfig(cwd))[kind.part] === false) throw switchedOff(kind.part);
|
|
71
|
+
requireTools(kind.tools);
|
|
72
|
+
const environments = listEnvironments({ cwd });
|
|
73
|
+
const choose = async (side, given) => {
|
|
74
|
+
const name = await chooseSide(side, given, environments);
|
|
75
|
+
return {
|
|
76
|
+
name,
|
|
77
|
+
side: name === "custom" ? await kind.askCustom(side) : name
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
const source = await choose("Source", sourceName);
|
|
81
|
+
const target = await choose("Target", targetName);
|
|
82
|
+
const plan = await kind.plan({
|
|
83
|
+
source: source.side,
|
|
84
|
+
target: target.side,
|
|
85
|
+
dryRun,
|
|
86
|
+
cwd
|
|
87
|
+
});
|
|
88
|
+
console.log(`${plan.source} → ${plan.target}`);
|
|
89
|
+
if (!dryRun) {
|
|
90
|
+
if (!(target.name === "custom" ? await confirmCustom(plan.question) : await confirmEnvironment(target.name, plan.question, { cwd }))) throw new SyncError("Aborted.");
|
|
91
|
+
}
|
|
92
|
+
await plan.run();
|
|
93
|
+
}
|
|
94
|
+
// src/commands/database/command.ts
|
|
95
|
+
const database = {
|
|
96
|
+
part: "database",
|
|
97
|
+
tools: postgresTools,
|
|
98
|
+
async askCustom(side) {
|
|
99
|
+
const { default: password } = await import("@inquirer/password");
|
|
100
|
+
return { url: await password({
|
|
101
|
+
message: `${side} database URL:`,
|
|
102
|
+
mask: true,
|
|
103
|
+
validate: urlWithProtocol(["postgres:", "postgresql:"], "Must be a postgres:// or postgresql:// URL")
|
|
104
|
+
}, terminal) };
|
|
105
|
+
},
|
|
106
|
+
plan: planDatabaseSync
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* `newsync db [source] [target]`
|
|
110
|
+
*/
|
|
111
|
+
function dbCommand(program) {
|
|
112
|
+
program.command("db").description("Replace the target database's schemas with a copy of the source's").argument("[source]", sourceDescription).argument("[target]", targetDescription).option("--dry-run", "Check both connections and list the tables that would be replaced").action((source, target, options) => runSyncCommand(database, [source, target], options));
|
|
113
|
+
}
|
|
114
|
+
// src/commands/s3/command.ts
|
|
115
|
+
const s3 = {
|
|
116
|
+
part: "s3",
|
|
117
|
+
tools: rcloneTools,
|
|
118
|
+
async askCustom(side) {
|
|
119
|
+
const [{ default: input }, { default: password }] = await Promise.all([import("@inquirer/input"), import("@inquirer/password")]);
|
|
120
|
+
const endpoint = await input({
|
|
121
|
+
message: `${side} S3 endpoint:`,
|
|
122
|
+
validate: urlWithProtocol(["http:", "https:"], "Must be an http:// or https:// URL")
|
|
123
|
+
}, terminal);
|
|
124
|
+
const accessKeyId = await input({
|
|
125
|
+
message: `${side} access key ID:`,
|
|
126
|
+
validate: required
|
|
127
|
+
}, terminal);
|
|
128
|
+
const secretAccessKey = await password({
|
|
129
|
+
message: `${side} secret access key:`,
|
|
130
|
+
mask: true,
|
|
131
|
+
validate: required
|
|
132
|
+
}, terminal);
|
|
133
|
+
const bucket = await input({
|
|
134
|
+
message: `${side} bucket:`,
|
|
135
|
+
validate: required
|
|
136
|
+
}, terminal);
|
|
137
|
+
return {
|
|
138
|
+
endpoint: endpoint.trim(),
|
|
139
|
+
accessKeyId: accessKeyId.trim(),
|
|
140
|
+
secretAccessKey,
|
|
141
|
+
bucket: bucket.trim()
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
plan: planS3Sync
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* `newsync s3 [source] [target]`
|
|
148
|
+
*/
|
|
149
|
+
function s3Command(program) {
|
|
150
|
+
program.command("s3").description("Make the target S3 bucket an exact copy of the source bucket").argument("[source]", sourceDescription).argument("[target]", targetDescription).option("--dry-run", "List what would be copied and deleted").action((source, target, options) => runSyncCommand(s3, [source, target], options));
|
|
151
|
+
}
|
|
152
|
+
// src/cli.ts
|
|
153
|
+
const program = new Command("newsync").description("Copy a database or an S3 bucket from one environment to another").version(version, "-v, --version", "Show version").helpOption("-h, --help", "Show help").configureOutput({ outputError: (message, write) => write(`newsync: ${message.replace(/^error: /, "")}`) });
|
|
154
|
+
dbCommand(program);
|
|
155
|
+
s3Command(program);
|
|
156
|
+
try {
|
|
157
|
+
await program.parseAsync(process.argv.slice(2), { from: "user" });
|
|
158
|
+
} catch (error) {
|
|
159
|
+
console.error(`newsync: ${errorMessage(error)}`);
|
|
160
|
+
process.exitCode = 1;
|
|
161
|
+
}
|
|
162
|
+
export {};
|
|
163
|
+
|
|
164
|
+
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../package.json","../src/lib/prompt.ts","../src/lib/flow.ts","../src/commands/database/command.ts","../src/commands/s3/command.ts","../src/cli.ts"],"sourcesContent":["","import type { Readable, Writable } from \"node:stream\";\nimport { SyncError } from \"./errors\";\n\nexport interface Streams {\n input: Readable & { isTTY?: boolean };\n output: Writable;\n}\n\n/**\n * Prompts read the terminal and write to stderr, like newenv's, so stdout stays the command's\n */\nexport const terminal: Streams = { input: process.stdin, output: process.stderr };\n\nexport const CUSTOM = \"custom\";\n\nexport type Side = \"Source\" | \"Target\";\n\n/**\n * Validates a required answer\n */\nexport const required = (value: string): true | string => value.trim() !== \"\" || \"Required\";\n\n/**\n * Validates a URL with one of the protocols\n */\nexport const urlWithProtocol =\n (protocols: string[], message: string) =>\n (value: string): true | string =>\n protocols.includes(URL.parse(value)?.protocol ?? \"\") || message;\n\n/**\n * The environment given on the command line, or chosen from the environments plus custom\n */\nexport async function chooseSide(\n side: Side,\n given: string | undefined,\n environments: string[],\n streams: Streams = terminal,\n): Promise<string> {\n const available = [...environments, CUSTOM];\n if (given !== undefined) {\n if (!available.includes(given)) {\n throw new SyncError(`Unknown environment \"${given}\". Available: ${available.join(\", \")}`);\n }\n // Checked here: a prompt on a closed stdin never settles, and Node exits with a warning\n if (given === CUSTOM && !streams.input.isTTY) {\n throw new SyncError(\n `${side} ${CUSTOM} asks for the connection details: needs a terminal. In a script, pass a custom side to syncDatabase or syncS3.`,\n );\n }\n return given;\n }\n if (!streams.input.isTTY) {\n throw new SyncError(\n `${side} missing. Pass it as an argument (${available.join(\", \")}), or run in a terminal to choose.`,\n );\n }\n\n // Imported on demand, like newenv: most runs get their sides as arguments\n const { default: select } = await import(\"@inquirer/select\");\n return select(\n {\n message: `${side}:`,\n choices: available.map((name) => ({\n value: name,\n name: name === CUSTOM ? `${CUSTOM} (enter the connection details)` : name,\n })),\n },\n streams,\n );\n}\n\n/**\n * y/N for a custom target, which has no environment settings. Throws without a TTY, like\n * `confirmEnvironment`, so agents and CI can't confirm by accident. Ctrl+C answers no\n */\nexport async function confirmCustom(\n question: string,\n streams: Streams = terminal,\n): Promise<boolean> {\n if (!streams.input.isTTY) {\n throw new SyncError(`${question}: needs confirmation, no TTY. Aborted.`);\n }\n const { default: confirm } = await import(\"@inquirer/confirm\");\n try {\n return await confirm({ message: `${question}?`, default: false }, streams);\n } catch (error) {\n if (error instanceof Error && error.name === \"ExitPromptError\") {\n return false;\n }\n throw error;\n }\n}\n","import { confirmEnvironment, listEnvironments } from \"@newcode-team/env\";\nimport { loadSyncConfig, type ResolvedSyncConfig, switchedOff } from \"./config\";\nimport { SyncError } from \"./errors\";\nimport type { SyncOptions, SyncPlan } from \"./plan\";\nimport { requireTools, type Tools } from \"./process\";\nimport { chooseSide, confirmCustom, CUSTOM, type Side } from \"./prompt\";\n\nexport interface SyncCommandOptions {\n dryRun?: boolean;\n}\n\nexport const sourceDescription = `Environment to copy from, or ${CUSTOM}`;\nexport const targetDescription = `Environment to overwrite, or ${CUSTOM}`;\n\n/**\n * What a sync command plugs into the flow\n */\nexport interface SyncKind<Custom> {\n /**\n * Its key in the `sync` section\n */\n part: keyof ResolvedSyncConfig;\n tools: Tools;\n /**\n * Asks for the details of a custom side\n */\n askCustom(side: Side): Promise<Custom>;\n plan(options: SyncOptions<string | Custom>): Promise<SyncPlan>;\n}\n\n/**\n * The flow of every newsync command: checks the config and tools, chooses both sides, checks them,\n * shows source → target, confirms with the target's rule and runs\n */\nexport async function runSyncCommand<Custom>(\n kind: SyncKind<Custom>,\n [sourceName, targetName]: [string | undefined, string | undefined],\n { dryRun = false }: SyncCommandOptions,\n): Promise<void> {\n const cwd = process.cwd();\n if ((await loadSyncConfig(cwd))[kind.part] === false) {\n throw switchedOff(kind.part);\n }\n requireTools(kind.tools);\n\n const environments = listEnvironments({ cwd });\n const choose = async (side: Side, given: string | undefined) => {\n const name = await chooseSide(side, given, environments);\n return { name, side: name === CUSTOM ? await kind.askCustom(side) : name };\n };\n const source = await choose(\"Source\", sourceName);\n const target = await choose(\"Target\", targetName);\n\n // Every check runs before anything is asked or changed\n const plan = await kind.plan({ source: source.side, target: target.side, dryRun, cwd });\n console.log(`${plan.source} → ${plan.target}`);\n\n if (!dryRun) {\n // The target's own rule: production types its name, local doesn't ask. The source is only read\n const confirmed =\n target.name === CUSTOM\n ? await confirmCustom(plan.question)\n : await confirmEnvironment(target.name, plan.question, { cwd });\n if (!confirmed) {\n throw new SyncError(\"Aborted.\");\n }\n }\n\n await plan.run();\n}\n","import type { Command } from \"commander\";\nimport {\n runSyncCommand,\n type SyncCommandOptions,\n type SyncKind,\n sourceDescription,\n targetDescription,\n} from \"../../lib/flow\";\nimport { terminal, urlWithProtocol } from \"../../lib/prompt\";\nimport { type CustomDatabase, postgresTools } from \"./helpers\";\nimport { planDatabaseSync } from \"./sync\";\n\nconst database: SyncKind<CustomDatabase> = {\n part: \"database\",\n tools: postgresTools,\n // Masked: the URL holds the password\n async askCustom(side) {\n const { default: password } = await import(\"@inquirer/password\");\n const url = await password(\n {\n message: `${side} database URL:`,\n mask: true,\n validate: urlWithProtocol(\n [\"postgres:\", \"postgresql:\"],\n \"Must be a postgres:// or postgresql:// URL\",\n ),\n },\n terminal,\n );\n return { url };\n },\n plan: planDatabaseSync,\n};\n\n/**\n * `newsync db [source] [target]`\n */\nexport function dbCommand(program: Command): void {\n program\n .command(\"db\")\n .description(\"Replace the target database's schemas with a copy of the source's\")\n .argument(\"[source]\", sourceDescription)\n .argument(\"[target]\", targetDescription)\n .option(\"--dry-run\", \"Check both connections and list the tables that would be replaced\")\n .action((source: string | undefined, target: string | undefined, options: SyncCommandOptions) =>\n runSyncCommand(database, [source, target], options),\n );\n}\n","import type { Command } from \"commander\";\nimport {\n runSyncCommand,\n type SyncCommandOptions,\n type SyncKind,\n sourceDescription,\n targetDescription,\n} from \"../../lib/flow\";\nimport { required, terminal, urlWithProtocol } from \"../../lib/prompt\";\nimport { type CustomBucket, rcloneTools } from \"./helpers\";\nimport { planS3Sync } from \"./sync\";\n\nconst s3: SyncKind<CustomBucket> = {\n part: \"s3\",\n tools: rcloneTools,\n // The secret key is masked\n async askCustom(side) {\n const [{ default: input }, { default: password }] = await Promise.all([\n import(\"@inquirer/input\"),\n import(\"@inquirer/password\"),\n ]);\n const endpoint = await input(\n {\n message: `${side} S3 endpoint:`,\n validate: urlWithProtocol([\"http:\", \"https:\"], \"Must be an http:// or https:// URL\"),\n },\n terminal,\n );\n const accessKeyId = await input(\n { message: `${side} access key ID:`, validate: required },\n terminal,\n );\n const secretAccessKey = await password(\n { message: `${side} secret access key:`, mask: true, validate: required },\n terminal,\n );\n const bucket = await input({ message: `${side} bucket:`, validate: required }, terminal);\n return {\n endpoint: endpoint.trim(),\n accessKeyId: accessKeyId.trim(),\n secretAccessKey,\n bucket: bucket.trim(),\n };\n },\n plan: planS3Sync,\n};\n\n/**\n * `newsync s3 [source] [target]`\n */\nexport function s3Command(program: Command): void {\n program\n .command(\"s3\")\n .description(\"Make the target S3 bucket an exact copy of the source bucket\")\n .argument(\"[source]\", sourceDescription)\n .argument(\"[target]\", targetDescription)\n .option(\"--dry-run\", \"List what would be copied and deleted\")\n .action((source: string | undefined, target: string | undefined, options: SyncCommandOptions) =>\n runSyncCommand(s3, [source, target], options),\n );\n}\n","#!/usr/bin/env node\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { dbCommand } from \"./commands/database/command\";\nimport { s3Command } from \"./commands/s3/command\";\nimport { errorMessage } from \"./lib/errors\";\n\nconst program = new Command(\"newsync\")\n .description(\"Copy a database or an S3 bucket from one environment to another\")\n .version(version, \"-v, --version\", \"Show version\")\n .helpOption(\"-h, --help\", \"Show help\")\n .configureOutput({\n outputError: (message, write) => write(`newsync: ${message.replace(/^error: /, \"\")}`),\n });\n\ndbCommand(program);\ns3Command(program);\n\ntry {\n await program.parseAsync(process.argv.slice(2), { from: \"user\" });\n} catch (error) {\n console.error(`newsync: ${errorMessage(error)}`);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;ACWA,MAAa,WAAoB;CAAE,OAAO,QAAQ;CAAO,QAAQ,QAAQ;AAAO;AAEhF,MAAa,SAAS;;;;AAOtB,MAAa,YAAY,UAAiC,MAAM,KAAK,MAAM,MAAM;;;;AAKjF,MAAa,mBACV,WAAqB,aACrB,UACC,UAAU,SAAS,IAAI,MAAM,KAAK,CAAC,EAAE,YAAY,EAAE,KAAK;;;;AAK5D,eAAsB,WACpB,MACA,OACA,cACA,UAAmB,UACF;CACjB,MAAM,YAAY,CAAC,GAAG,cAAc,MAAM;CAC1C,IAAI,UAAU,KAAA,GAAW;EACvB,IAAI,CAAC,UAAU,SAAS,KAAK,GAC3B,MAAM,IAAI,UAAU,wBAAwB,MAAM,gBAAgB,UAAU,KAAK,IAAI,GAAG;EAG1F,IAAI,UAAA,YAAoB,CAAC,QAAQ,MAAM,OACrC,MAAM,IAAI,UACR,GAAG,KAAK,GAAG,OAAO,+GACpB;EAEF,OAAO;CACT;CACA,IAAI,CAAC,QAAQ,MAAM,OACjB,MAAM,IAAI,UACR,GAAG,KAAK,oCAAoC,UAAU,KAAK,IAAI,EAAE,mCACnE;CAIF,MAAM,EAAE,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,UAAU;EAAS,GACxE,QACF;EACA,MAAM,SAAS,MAAM,MAAM;GAAE,SAAS,GAAG,KAAK;GAAW,UAAU;EAAS,GAAG,QAAQ;EACvF,OAAO;GACL,UAAU,SAAS,KAAK;GACxB,aAAa,YAAY,KAAK;GAC9B;GACA,QAAQ,OAAO,KAAK;EACtB;CACF;CACA,MAAM;AACR;;;;AAKA,SAAgB,UAAU,SAAwB;CAChD,QACG,QAAQ,IAAI,CAAC,CACb,YAAY,8DAA8D,CAAC,CAC3E,SAAS,YAAY,iBAAiB,CAAC,CACvC,SAAS,YAAY,iBAAiB,CAAC,CACvC,OAAO,aAAa,uCAAuC,CAAC,CAC5D,QAAQ,QAA4B,QAA4B,YAC/D,eAAe,IAAI,CAAC,QAAQ,MAAM,GAAG,OAAO,CAC9C;AACJ;;ACrDA,MAAM,UAAU,IAAI,QAAQ,SAAS,CAAC,CACnC,YAAY,iEAAiE,CAAC,CAC9E,QAAQ,SAAS,iBAAiB,cAAc,CAAC,CACjD,WAAW,cAAc,WAAW,CAAC,CACrC,gBAAgB,EACf,cAAc,SAAS,UAAU,MAAM,YAAY,QAAQ,QAAQ,YAAY,EAAE,GAAG,EACtF,CAAC;AAEH,UAAU,OAAO;AACjB,UAAU,OAAO;AAEjB,IAAI;CACF,MAAM,QAAQ,WAAW,QAAQ,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,OAAO,CAAC;AAClE,SAAS,OAAO;CACd,QAAQ,MAAM,YAAY,aAAa,KAAK,GAAG;CAC/C,QAAQ,WAAW;AACrB"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
interface SyncOptions<Side> {
|
|
2
|
+
/**
|
|
3
|
+
* An environment name, or a custom side
|
|
4
|
+
*/
|
|
5
|
+
source: Side;
|
|
6
|
+
/**
|
|
7
|
+
* An environment name, or a custom side. Overwritten
|
|
8
|
+
*/
|
|
9
|
+
target: Side;
|
|
10
|
+
/**
|
|
11
|
+
* Shows what would change, and changes nothing
|
|
12
|
+
*/
|
|
13
|
+
dryRun?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Where newcode.config.ts and .envs/ are looked up. Default: `process.cwd()`
|
|
16
|
+
*/
|
|
17
|
+
cwd?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Progress messages. Default: `console.log`
|
|
20
|
+
*/
|
|
21
|
+
log?: (message: string) => void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A refusal or failure: an invalid config section, a missing tool or variable, the same source and
|
|
25
|
+
* target, a command that failed. Messages never hold a URL, password or key.
|
|
26
|
+
*/
|
|
27
|
+
export declare class SyncError extends Error {
|
|
28
|
+
name: string;
|
|
29
|
+
}
|
|
30
|
+
type Provider = "auto" | "cloudflare" | "other";
|
|
31
|
+
/**
|
|
32
|
+
* The variables that hold the database connection, per environment
|
|
33
|
+
*/
|
|
34
|
+
interface DatabaseConfig {
|
|
35
|
+
/**
|
|
36
|
+
* Variable with the postgres:// URL. Default: `"DATABASE_URL"`
|
|
37
|
+
*/
|
|
38
|
+
url?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Schemas that are copied, and replaced in the target. Default: `["public"]`. A Drizzle project
|
|
41
|
+
* adds `"drizzle"` to bring its migration history along
|
|
42
|
+
*/
|
|
43
|
+
schemas?: string[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The variables that hold the S3 bucket, per environment
|
|
47
|
+
*/
|
|
48
|
+
interface S3Config {
|
|
49
|
+
/**
|
|
50
|
+
* Variable with the endpoint URL. Default: `"S3_ENDPOINT"`
|
|
51
|
+
*/
|
|
52
|
+
endpoint?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Variable with the access key ID. Default: `"S3_ACCESS_KEY_ID"`
|
|
55
|
+
*/
|
|
56
|
+
accessKeyId?: string;
|
|
57
|
+
/**
|
|
58
|
+
* Variable with the secret access key. Default: `"S3_SECRET_ACCESS_KEY"`
|
|
59
|
+
*/
|
|
60
|
+
secretAccessKey?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Variable with the bucket name. Default: `"S3_BUCKET"`
|
|
63
|
+
*/
|
|
64
|
+
bucket?: string;
|
|
65
|
+
/**
|
|
66
|
+
* `"auto"`: Cloudflare R2 when the endpoint is on r2.cloudflarestorage.com, otherwise generic S3.
|
|
67
|
+
* Default: `"auto"`
|
|
68
|
+
*/
|
|
69
|
+
provider?: Provider;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The `sync` section of newcode.config.ts. Settings name variables, never hold their values
|
|
73
|
+
*/
|
|
74
|
+
interface SyncConfig {
|
|
75
|
+
/**
|
|
76
|
+
* `false` switches the database sync off
|
|
77
|
+
*/
|
|
78
|
+
database?: DatabaseConfig | false;
|
|
79
|
+
/**
|
|
80
|
+
* `false` switches the S3 sync off
|
|
81
|
+
*/
|
|
82
|
+
s3?: S3Config | false;
|
|
83
|
+
}
|
|
84
|
+
declare module "@newcode-team/config" {
|
|
85
|
+
interface Config {
|
|
86
|
+
sync?: SyncConfig;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The `sync` section of newcode.config.ts. Returns its input: it types the section and adds `sync`
|
|
91
|
+
* to `Config`
|
|
92
|
+
*/
|
|
93
|
+
export declare const sync: (section: SyncConfig) => SyncConfig;
|
|
94
|
+
/**
|
|
95
|
+
* A database that is in no environment
|
|
96
|
+
*/
|
|
97
|
+
interface CustomDatabase {
|
|
98
|
+
/**
|
|
99
|
+
* A postgres:// or postgresql:// URL
|
|
100
|
+
*/
|
|
101
|
+
url: string;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* An environment name, or a custom database
|
|
105
|
+
*/
|
|
106
|
+
type DatabaseSide = string | CustomDatabase;
|
|
107
|
+
type SyncDatabaseOptions = SyncOptions<DatabaseSide>;
|
|
108
|
+
/**
|
|
109
|
+
* Replaces the configured schemas of the target database with a copy of the source's. Doesn't
|
|
110
|
+
* ask: a script confirms first, e.g. with `confirmEnvironment` from @newcode-team/env
|
|
111
|
+
*/
|
|
112
|
+
export declare function syncDatabase(options: SyncDatabaseOptions): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* A bucket that is in no environment
|
|
115
|
+
*/
|
|
116
|
+
interface CustomBucket {
|
|
117
|
+
/**
|
|
118
|
+
* An http:// or https:// URL
|
|
119
|
+
*/
|
|
120
|
+
endpoint: string;
|
|
121
|
+
accessKeyId: string;
|
|
122
|
+
secretAccessKey: string;
|
|
123
|
+
bucket: string;
|
|
124
|
+
/**
|
|
125
|
+
* Default: `"auto"`
|
|
126
|
+
*/
|
|
127
|
+
provider?: Provider;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* An environment name, or a custom bucket
|
|
131
|
+
*/
|
|
132
|
+
type BucketSide = string | CustomBucket;
|
|
133
|
+
type SyncS3Options = SyncOptions<BucketSide>;
|
|
134
|
+
/**
|
|
135
|
+
* Makes the target bucket an exact copy of the source bucket. Doesn't ask: a script confirms
|
|
136
|
+
* first, e.g. with `confirmEnvironment` from @newcode-team/env
|
|
137
|
+
*/
|
|
138
|
+
export declare function syncS3(options: SyncS3Options): Promise<void>;
|
|
139
|
+
export type { BucketSide, CustomBucket, CustomDatabase, DatabaseConfig, DatabaseSide, Provider, S3Config, SyncConfig, SyncDatabaseOptions, SyncS3Options };
|
|
140
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/plan.ts","../src/lib/errors.ts","../src/lib/config.ts","../src/commands/database/helpers.ts","../src/commands/database/sync.ts","../src/commands/s3/helpers.ts","../src/commands/s3/sync.ts"],"mappings":"A,UAAiB,YAAY;;;;EAI3B,QAAQ;;;;EAIR,QAAQ;;;;EAIR;;;;EAIA;;;;EAIA,OAAO;;;;;;qBChBI,kBAAkB;EACpB;;KCFC;;;;UAKK;;;;EAIf;;;;;EAKA;;;;;UAMe;;;;EAIf;;;;EAIA;;;;EAIA;;;;EAIA;;;;;EAKA,WAAW;;;;;UAMI;;;;EAIf,WAAW;;;;EAIX,KAAK;;;YASK;IACR,OAAO;;;;;;;qBAQE,OAAQ,SAAS,eAAa;;;;UC5D1B;;;;EAIf;;;;;KAMU,wBAAwB;KCTxB,sBAAsB,YAAY;;;;;wBAuCxB,aAAa,SAAS,sBAAsB;;;;UC3CjD;;;;EAIf;EACA;EACA;EACA;;;;EAIA,WAAW;;;;;KAMD,sBAAsB;KCftB,gBAAgB,YAAY;;;;;wBA6DlB,OAAO,SAAS,gBAAgB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { d as SyncError, u as sync, a as syncDatabase, n as syncS3 } from "./sync-C6BM27_L.mjs";
|
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { loadConfig } from "@newcode-team/config";
|
|
2
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { devNull, tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { loadEnvironment } from "@newcode-team/env";
|
|
7
|
+
// src/lib/errors.ts
|
|
8
|
+
/**
|
|
9
|
+
* A refusal or failure: an invalid config section, a missing tool or variable, the same source and
|
|
10
|
+
* target, a command that failed. Messages never hold a URL, password or key.
|
|
11
|
+
*/
|
|
12
|
+
var SyncError = class extends Error {
|
|
13
|
+
name = "SyncError";
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* What the command prints for an error. Ctrl+C on a prompt is an abort
|
|
17
|
+
*/
|
|
18
|
+
function errorMessage(error) {
|
|
19
|
+
if (error instanceof Error) return error.name === "ExitPromptError" ? "Aborted." : error.message;
|
|
20
|
+
return String(error);
|
|
21
|
+
}
|
|
22
|
+
// src/lib/config.ts
|
|
23
|
+
/**
|
|
24
|
+
* The `sync` section of newcode.config.ts. Returns its input: it types the section and adds `sync`
|
|
25
|
+
* to `Config`
|
|
26
|
+
*/
|
|
27
|
+
const sync = (section) => section;
|
|
28
|
+
const defaults = {
|
|
29
|
+
database: {
|
|
30
|
+
url: "DATABASE_URL",
|
|
31
|
+
schemas: ["public"]
|
|
32
|
+
},
|
|
33
|
+
s3: {
|
|
34
|
+
endpoint: "S3_ENDPOINT",
|
|
35
|
+
accessKeyId: "S3_ACCESS_KEY_ID",
|
|
36
|
+
secretAccessKey: "S3_SECRET_ACCESS_KEY",
|
|
37
|
+
bucket: "S3_BUCKET",
|
|
38
|
+
provider: "auto"
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const variableName = /^[A-Za-z_]\w*$/;
|
|
42
|
+
const schemaName = /^[A-Za-z_][\w$]*$/;
|
|
43
|
+
const providers = [
|
|
44
|
+
"auto",
|
|
45
|
+
"cloudflare",
|
|
46
|
+
"other"
|
|
47
|
+
];
|
|
48
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
49
|
+
function checkKeys(path, value, known) {
|
|
50
|
+
const unknown = Object.keys(value).find((key) => !known.includes(key));
|
|
51
|
+
if (unknown !== void 0) throw new SyncError(`${path}.${unknown} is not a known key. Known: ${known.join(", ")}`);
|
|
52
|
+
}
|
|
53
|
+
function checkVariable(path, value) {
|
|
54
|
+
if (value !== void 0 && (typeof value !== "string" || !variableName.test(value))) throw new SyncError(`${path} must be a variable name, such as "DATABASE_URL"`);
|
|
55
|
+
}
|
|
56
|
+
function resolveDatabaseSection(value) {
|
|
57
|
+
if (value === false) return false;
|
|
58
|
+
if (value === void 0) return {
|
|
59
|
+
...defaults.database,
|
|
60
|
+
schemas: [...defaults.database.schemas]
|
|
61
|
+
};
|
|
62
|
+
if (!isObject(value)) throw new SyncError("sync.database must be false or an object");
|
|
63
|
+
checkKeys("sync.database", value, ["url", "schemas"]);
|
|
64
|
+
checkVariable("sync.database.url", value.url);
|
|
65
|
+
const { schemas } = value;
|
|
66
|
+
if (schemas !== void 0 && (!Array.isArray(schemas) || schemas.length === 0 || !schemas.every((schema) => typeof schema === "string" && schemaName.test(schema)))) throw new SyncError("sync.database.schemas must be a non-empty list of names");
|
|
67
|
+
return {
|
|
68
|
+
...resolveDatabaseSection(void 0),
|
|
69
|
+
...value
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function resolveS3Section(value) {
|
|
73
|
+
if (value === false) return false;
|
|
74
|
+
if (value === void 0) return { ...defaults.s3 };
|
|
75
|
+
if (!isObject(value)) throw new SyncError("sync.s3 must be false or an object");
|
|
76
|
+
const variables = [
|
|
77
|
+
"endpoint",
|
|
78
|
+
"accessKeyId",
|
|
79
|
+
"secretAccessKey",
|
|
80
|
+
"bucket"
|
|
81
|
+
];
|
|
82
|
+
checkKeys("sync.s3", value, [...variables, "provider"]);
|
|
83
|
+
variables.forEach((key) => {
|
|
84
|
+
checkVariable(`sync.s3.${key}`, value[key]);
|
|
85
|
+
});
|
|
86
|
+
if (value.provider !== void 0 && !providers.includes(value.provider)) throw new SyncError("sync.s3.provider must be \"auto\", \"cloudflare\" or \"other\"");
|
|
87
|
+
return {
|
|
88
|
+
...defaults.s3,
|
|
89
|
+
...value
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Checks the section and fills in the defaults. Throws a `SyncError` with the path of the first
|
|
94
|
+
* problem
|
|
95
|
+
*/
|
|
96
|
+
function resolveSyncConfig(section = {}) {
|
|
97
|
+
if (!isObject(section)) throw new SyncError("sync must be an object");
|
|
98
|
+
checkKeys("sync", section, ["database", "s3"]);
|
|
99
|
+
return {
|
|
100
|
+
database: resolveDatabaseSection(section.database),
|
|
101
|
+
s3: resolveS3Section(section.s3)
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The refusal for a part that is switched off with `false`
|
|
106
|
+
*/
|
|
107
|
+
const switchedOff = (part) => new SyncError(`The ${part === "s3" ? "S3" : "database"} sync is off: sync.${part} is false in newcode.config.ts.`);
|
|
108
|
+
/**
|
|
109
|
+
* The `sync` section of the project's newcode.config.ts, found from cwd up, checked and with the
|
|
110
|
+
* defaults
|
|
111
|
+
*/
|
|
112
|
+
async function loadSyncConfig(cwd) {
|
|
113
|
+
return resolveSyncConfig((await loadConfig({ cwd })).sync);
|
|
114
|
+
}
|
|
115
|
+
// src/lib/process.ts
|
|
116
|
+
/**
|
|
117
|
+
* Throws a `SyncError` with the install hint when one of the tools can't be started
|
|
118
|
+
*/
|
|
119
|
+
function requireTools({ names, hint }) {
|
|
120
|
+
const missing = names.filter((name) => spawnSync(name, ["--version"], { stdio: "ignore" }).error?.code === "ENOENT");
|
|
121
|
+
if (missing.length > 0) throw new SyncError(`${missing.join(", ")} not found. ${hint}`);
|
|
122
|
+
}
|
|
123
|
+
const signals = [
|
|
124
|
+
"SIGINT",
|
|
125
|
+
"SIGTERM",
|
|
126
|
+
"SIGHUP"
|
|
127
|
+
];
|
|
128
|
+
/**
|
|
129
|
+
* Runs a tool and waits for it. Its stderr, and stdout unless captured, go to the terminal. A
|
|
130
|
+
* failure throws a `SyncError` naming only the tool: the tool already printed what went wrong, and
|
|
131
|
+
* its arguments aren't repeated.
|
|
132
|
+
*
|
|
133
|
+
* Signals are forwarded like newenv does: in a terminal, Ctrl+C and hangups already reach the tool,
|
|
134
|
+
* so only SIGTERM is forwarded there. Node keeps running until the tool exits, so callers clean up.
|
|
135
|
+
*/
|
|
136
|
+
function runTool(command, args, { env, capture = false }) {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
const child = spawn(command, args, {
|
|
139
|
+
env,
|
|
140
|
+
stdio: [
|
|
141
|
+
"ignore",
|
|
142
|
+
capture ? "pipe" : "inherit",
|
|
143
|
+
"inherit"
|
|
144
|
+
]
|
|
145
|
+
});
|
|
146
|
+
const output = [];
|
|
147
|
+
child.stdout?.on("data", (chunk) => output.push(chunk));
|
|
148
|
+
const forward = (signal) => {
|
|
149
|
+
if (signal === "SIGTERM" || !process.stdin.isTTY) child.kill(signal);
|
|
150
|
+
};
|
|
151
|
+
const stopForwarding = () => {
|
|
152
|
+
signals.forEach((signal) => {
|
|
153
|
+
process.off(signal, forward);
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
signals.forEach((signal) => {
|
|
157
|
+
process.on(signal, forward);
|
|
158
|
+
});
|
|
159
|
+
child.on("error", (error) => {
|
|
160
|
+
stopForwarding();
|
|
161
|
+
reject(new SyncError(error.code === "ENOENT" ? `${command} not found.` : `${command} could not start: ${error.message}`));
|
|
162
|
+
});
|
|
163
|
+
child.on("close", (code, signal) => {
|
|
164
|
+
stopForwarding();
|
|
165
|
+
if (code === 0) resolve(Buffer.concat(output).toString());
|
|
166
|
+
else reject(new SyncError(signal ? `${command} stopped by ${signal}.` : `${command} failed.`));
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
// src/commands/database/helpers.ts
|
|
171
|
+
const postgresTools = {
|
|
172
|
+
names: [
|
|
173
|
+
"pg_dump",
|
|
174
|
+
"pg_restore",
|
|
175
|
+
"psql"
|
|
176
|
+
],
|
|
177
|
+
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/"
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* Parses a postgres URL. The message names where it came from, never the value
|
|
181
|
+
*/
|
|
182
|
+
function parseDatabaseUrl(value, from) {
|
|
183
|
+
const url = URL.parse(value);
|
|
184
|
+
if (!url || !["postgres:", "postgresql:"].includes(url.protocol) || !url.hostname) throw new SyncError(`${from} is not a postgres:// or postgresql:// URL.`);
|
|
185
|
+
return url;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The URL of an environment, read from the configured variable, or of a custom database
|
|
189
|
+
*/
|
|
190
|
+
async function resolveDatabase(side, config, cwd) {
|
|
191
|
+
if (typeof side !== "string") return {
|
|
192
|
+
label: "custom",
|
|
193
|
+
url: parseDatabaseUrl(side.url, "The custom database URL")
|
|
194
|
+
};
|
|
195
|
+
const { [config.url]: value = "" } = (await loadEnvironment(side, { cwd })).require(config.url);
|
|
196
|
+
return {
|
|
197
|
+
label: side,
|
|
198
|
+
url: parseDatabaseUrl(value, `${config.url} of environment "${side}"`)
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Environment, host and database, without the user and password
|
|
203
|
+
*/
|
|
204
|
+
const describeDatabase = ({ label, url }) => `${label} (${url.host}${url.pathname})`;
|
|
205
|
+
/**
|
|
206
|
+
* Same host, port and database name
|
|
207
|
+
*/
|
|
208
|
+
function sameDatabase(a, b) {
|
|
209
|
+
const key = ({ url }) => [
|
|
210
|
+
url.hostname.toLowerCase(),
|
|
211
|
+
url.port || "5432",
|
|
212
|
+
decodeURIComponent(url.pathname)
|
|
213
|
+
].join(" ");
|
|
214
|
+
return key(a) === key(b);
|
|
215
|
+
}
|
|
216
|
+
const libpqVariables = [
|
|
217
|
+
"PGHOST",
|
|
218
|
+
"PGHOSTADDR",
|
|
219
|
+
"PGPORT",
|
|
220
|
+
"PGDATABASE",
|
|
221
|
+
"PGUSER",
|
|
222
|
+
"PGPASSWORD",
|
|
223
|
+
"PGSERVICE"
|
|
224
|
+
];
|
|
225
|
+
/**
|
|
226
|
+
* The URL to pass to pg_dump and psql, and the environment to run them with. The password goes
|
|
227
|
+
* through PGPASSWORD, so it's never a process argument that `ps` shows
|
|
228
|
+
*/
|
|
229
|
+
function connection(url) {
|
|
230
|
+
const withoutPassword = new URL(url.href);
|
|
231
|
+
withoutPassword.password = "";
|
|
232
|
+
withoutPassword.searchParams.delete("password");
|
|
233
|
+
const password = url.password ? decodeURIComponent(url.password) : url.searchParams.get("password") ?? void 0;
|
|
234
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !libpqVariables.includes(key)));
|
|
235
|
+
return {
|
|
236
|
+
dbname: withoutPassword.href,
|
|
237
|
+
env: password === void 0 ? env : {
|
|
238
|
+
...env,
|
|
239
|
+
PGPASSWORD: password
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Runs SQL with psql and returns the rows, tab-separated
|
|
245
|
+
*/
|
|
246
|
+
function query(url, sql) {
|
|
247
|
+
const { dbname, env } = connection(url);
|
|
248
|
+
return runTool("psql", [
|
|
249
|
+
"--no-psqlrc",
|
|
250
|
+
"--quiet",
|
|
251
|
+
"--no-align",
|
|
252
|
+
"--tuples-only",
|
|
253
|
+
"--field-separator= ",
|
|
254
|
+
"--set=ON_ERROR_STOP=1",
|
|
255
|
+
`--command=${sql}`,
|
|
256
|
+
`--dbname=${dbname}`
|
|
257
|
+
], {
|
|
258
|
+
env,
|
|
259
|
+
capture: true
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Refuses when pg_dump is an older major version than the source server: it can't dump it
|
|
264
|
+
*/
|
|
265
|
+
async function checkVersion(source) {
|
|
266
|
+
const version = await runTool("pg_dump", ["--version"], {
|
|
267
|
+
env: process.env,
|
|
268
|
+
capture: true
|
|
269
|
+
});
|
|
270
|
+
const dump = Number(/\)\s*(\d+)/.exec(version)?.[1]);
|
|
271
|
+
const server = Math.floor(Number(await query(source.url, "SHOW server_version_num")) / 1e4);
|
|
272
|
+
if (dump < server) throw new SyncError(`pg_dump ${dump} is older than the source server, Postgres ${server}. Install pg_dump ${server} or later. ${postgresTools.hint}`);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* A row estimate for the dry run, e.g. `~1 row`
|
|
276
|
+
*/
|
|
277
|
+
function describeRowEstimate(estimate) {
|
|
278
|
+
const count = estimate === "" ? -1 : Number(estimate);
|
|
279
|
+
return count < 0 ? "row count unknown" : `~${count} ${count === 1 ? "row" : "rows"}`;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Lists the target's tables in the schemas, with row estimates. Changes nothing. Schema names are
|
|
283
|
+
* plain identifiers (see lib/config.ts), so they need no escaping
|
|
284
|
+
*/
|
|
285
|
+
async function listTables(target, schemas, log) {
|
|
286
|
+
const tables = (await query(target.url, `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`)).split("\n").filter((line) => line.trim() !== "").map((line) => {
|
|
287
|
+
const [name = "", estimate = ""] = line.split(" ");
|
|
288
|
+
return ` ${name} ${describeRowEstimate(estimate)}`;
|
|
289
|
+
});
|
|
290
|
+
log(tables.length > 0 ? `Would replace these tables of ${describeDatabase(target)}:\n${tables.join("\n")}` : `No tables in ${schemas.join(", ")} of ${describeDatabase(target)} yet.`);
|
|
291
|
+
log("Dry run: nothing changed.");
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Dumps the schemas of the source and restores them into the target in one transaction
|
|
295
|
+
*/
|
|
296
|
+
async function copyDatabase(source, target, schemas, log) {
|
|
297
|
+
const dir = mkdtempSync(join(tmpdir(), "newsync-"));
|
|
298
|
+
let interrupted = false;
|
|
299
|
+
const interrupt = () => {
|
|
300
|
+
interrupted = true;
|
|
301
|
+
};
|
|
302
|
+
const step = async (command, args, env) => {
|
|
303
|
+
if (interrupted) throw new SyncError("Aborted.");
|
|
304
|
+
await runTool(command, args, { env }).catch((error) => {
|
|
305
|
+
throw interrupted ? new SyncError("Aborted.") : error;
|
|
306
|
+
});
|
|
307
|
+
};
|
|
308
|
+
process.on("SIGINT", interrupt);
|
|
309
|
+
try {
|
|
310
|
+
const dumpFile = join(dir, "source.dump");
|
|
311
|
+
const sqlFile = join(dir, "source.sql");
|
|
312
|
+
log(`Dumping ${describeDatabase(source)}...`);
|
|
313
|
+
const from = connection(source.url);
|
|
314
|
+
await step("pg_dump", [
|
|
315
|
+
...schemas.map((schema) => `--schema="${schema}"`),
|
|
316
|
+
"--format=custom",
|
|
317
|
+
"--no-owner",
|
|
318
|
+
"--no-privileges",
|
|
319
|
+
`--file=${dumpFile}`,
|
|
320
|
+
`--dbname=${from.dbname}`
|
|
321
|
+
], from.env);
|
|
322
|
+
await step("pg_restore", [
|
|
323
|
+
"--no-owner",
|
|
324
|
+
"--no-privileges",
|
|
325
|
+
`--file=${sqlFile}`,
|
|
326
|
+
dumpFile
|
|
327
|
+
], process.env);
|
|
328
|
+
log(`Restoring into ${describeDatabase(target)}...`);
|
|
329
|
+
const to = connection(target.url);
|
|
330
|
+
const drop = schemas.map((schema) => `DROP SCHEMA IF EXISTS "${schema}" CASCADE;`);
|
|
331
|
+
await step("psql", [
|
|
332
|
+
"--no-psqlrc",
|
|
333
|
+
"--quiet",
|
|
334
|
+
"--single-transaction",
|
|
335
|
+
"--set=ON_ERROR_STOP=1",
|
|
336
|
+
`--output=${devNull}`,
|
|
337
|
+
`--command=SET client_min_messages = warning; ${drop.join(" ")}`,
|
|
338
|
+
`--file=${sqlFile}`,
|
|
339
|
+
`--dbname=${to.dbname}`
|
|
340
|
+
], to.env);
|
|
341
|
+
const one = schemas.length === 1;
|
|
342
|
+
log(`Done. ${one ? "Schema" : "Schemas"} ${schemas.join(", ")} of ${describeDatabase(target)} now ${one ? "matches" : "match"} the source.`);
|
|
343
|
+
} finally {
|
|
344
|
+
process.off("SIGINT", interrupt);
|
|
345
|
+
rmSync(dir, {
|
|
346
|
+
recursive: true,
|
|
347
|
+
force: true
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// src/commands/database/sync.ts
|
|
352
|
+
/**
|
|
353
|
+
* Checks the tools, both databases and the pg_dump version, without changing anything
|
|
354
|
+
*/
|
|
355
|
+
async function planDatabaseSync({ source: sourceSide, target: targetSide, dryRun = false, cwd = process.cwd(), log = console.log }) {
|
|
356
|
+
const { database: config } = await loadSyncConfig(cwd);
|
|
357
|
+
if (!config) throw switchedOff("database");
|
|
358
|
+
requireTools(postgresTools);
|
|
359
|
+
const source = await resolveDatabase(sourceSide, config, cwd);
|
|
360
|
+
const target = await resolveDatabase(targetSide, config, cwd);
|
|
361
|
+
if (sameDatabase(source, target)) throw new SyncError(`Source and target are the same database: ${describeDatabase(target)}.`);
|
|
362
|
+
await checkVersion(source);
|
|
363
|
+
const { schemas } = config;
|
|
364
|
+
return {
|
|
365
|
+
source: describeDatabase(source),
|
|
366
|
+
target: describeDatabase(target),
|
|
367
|
+
question: `Replace ${schemas.length === 1 ? "schema" : "schemas"} ${schemas.join(", ")} of ${describeDatabase(target)}`,
|
|
368
|
+
run: () => dryRun ? listTables(target, schemas, log) : copyDatabase(source, target, schemas, log)
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Replaces the configured schemas of the target database with a copy of the source's. Doesn't
|
|
373
|
+
* ask: a script confirms first, e.g. with `confirmEnvironment` from @newcode-team/env
|
|
374
|
+
*/
|
|
375
|
+
async function syncDatabase(options) {
|
|
376
|
+
await (await planDatabaseSync(options)).run();
|
|
377
|
+
}
|
|
378
|
+
// src/commands/s3/helpers.ts
|
|
379
|
+
const rcloneTools = {
|
|
380
|
+
names: ["rclone"],
|
|
381
|
+
hint: "macOS: brew install rclone. Other systems: https://rclone.org/install/"
|
|
382
|
+
};
|
|
383
|
+
/**
|
|
384
|
+
* Parses an S3 endpoint. The message names where it came from, never the value
|
|
385
|
+
*/
|
|
386
|
+
function parseEndpoint(value, from) {
|
|
387
|
+
const url = URL.parse(value);
|
|
388
|
+
if (!url || !["http:", "https:"].includes(url.protocol)) throw new SyncError(`${from} is not an http:// or https:// URL.`);
|
|
389
|
+
return url;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* The bucket of an environment, read from the configured variables, or a custom bucket
|
|
393
|
+
*/
|
|
394
|
+
async function resolveBucket(side, config, cwd) {
|
|
395
|
+
if (typeof side !== "string") {
|
|
396
|
+
const missing = [
|
|
397
|
+
"accessKeyId",
|
|
398
|
+
"secretAccessKey",
|
|
399
|
+
"bucket"
|
|
400
|
+
].filter((key) => !side[key]);
|
|
401
|
+
if (missing.length > 0) throw new SyncError(`The custom bucket misses ${missing.join(", ")}.`);
|
|
402
|
+
return {
|
|
403
|
+
...side,
|
|
404
|
+
label: "custom",
|
|
405
|
+
endpoint: parseEndpoint(side.endpoint, "The custom endpoint"),
|
|
406
|
+
provider: side.provider ?? "auto"
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
const values = (await loadEnvironment(side, { cwd })).require(config.endpoint, config.accessKeyId, config.secretAccessKey, config.bucket);
|
|
410
|
+
const value = (key) => values[key] ?? "";
|
|
411
|
+
return {
|
|
412
|
+
label: side,
|
|
413
|
+
endpoint: parseEndpoint(value(config.endpoint), `${config.endpoint} of environment "${side}"`),
|
|
414
|
+
accessKeyId: value(config.accessKeyId),
|
|
415
|
+
secretAccessKey: value(config.secretAccessKey),
|
|
416
|
+
bucket: value(config.bucket),
|
|
417
|
+
provider: config.provider
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Environment, bucket and host, without the keys
|
|
422
|
+
*/
|
|
423
|
+
const describeBucket = ({ label, bucket, endpoint }) => `${label} (${bucket} on ${endpoint.host})`;
|
|
424
|
+
/**
|
|
425
|
+
* Same bucket on the same endpoint
|
|
426
|
+
*/
|
|
427
|
+
const sameBucket = (a, b) => a.endpoint.host.toLowerCase() === b.endpoint.host.toLowerCase() && a.bucket === b.bucket;
|
|
428
|
+
const endpointKey = ({ endpoint }) => endpoint.href.replace(/\/$/, "").toLowerCase();
|
|
429
|
+
/**
|
|
430
|
+
* Both buckets reachable with one endpoint and one key, e.g. production to staging on R2: then one
|
|
431
|
+
* rclone remote, and the provider copies the files itself. Otherwise they stream through this
|
|
432
|
+
* machine
|
|
433
|
+
*/
|
|
434
|
+
const sameRemote = (a, b) => endpointKey(a) === endpointKey(b) && a.accessKeyId === b.accessKeyId && a.secretAccessKey === b.secretAccessKey;
|
|
435
|
+
/**
|
|
436
|
+
* Cloudflare for R2, otherwise generic S3
|
|
437
|
+
*/
|
|
438
|
+
function rcloneProvider({ provider, endpoint }) {
|
|
439
|
+
if (provider === "auto") return endpoint.hostname.toLowerCase().endsWith(".r2.cloudflarestorage.com") ? "Cloudflare" : "Other";
|
|
440
|
+
return provider === "cloudflare" ? "Cloudflare" : "Other";
|
|
441
|
+
}
|
|
442
|
+
function remoteEnv(name, bucket) {
|
|
443
|
+
const prefix = `RCLONE_CONFIG_${name.toUpperCase()}`;
|
|
444
|
+
return {
|
|
445
|
+
[`${prefix}_TYPE`]: "s3",
|
|
446
|
+
[`${prefix}_PROVIDER`]: rcloneProvider(bucket),
|
|
447
|
+
[`${prefix}_REGION`]: "auto",
|
|
448
|
+
[`${prefix}_ENDPOINT`]: bucket.endpoint.href.replace(/\/$/, ""),
|
|
449
|
+
[`${prefix}_ACCESS_KEY_ID`]: bucket.accessKeyId,
|
|
450
|
+
[`${prefix}_SECRET_ACCESS_KEY`]: bucket.secretAccessKey,
|
|
451
|
+
[`${prefix}_ENV_AUTH`]: "false",
|
|
452
|
+
[`${prefix}_NO_CHECK_BUCKET`]: "true"
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* The rclone source and target paths, and the variables that define their remotes
|
|
457
|
+
*/
|
|
458
|
+
function remotes(source, target) {
|
|
459
|
+
const one = sameRemote(source, target);
|
|
460
|
+
return {
|
|
461
|
+
source: `${one ? "newsync_target" : "newsync_source"}:${source.bucket}`,
|
|
462
|
+
target: `newsync_target:${target.bucket}`,
|
|
463
|
+
env: {
|
|
464
|
+
...remoteEnv("newsync_target", target),
|
|
465
|
+
...one ? {} : remoteEnv("newsync_source", source)
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
// src/commands/s3/sync.ts
|
|
470
|
+
/**
|
|
471
|
+
* Checks the tool and both buckets, without changing anything
|
|
472
|
+
*/
|
|
473
|
+
async function planS3Sync({ source: sourceSide, target: targetSide, dryRun = false, cwd = process.cwd(), log = console.log }) {
|
|
474
|
+
const { s3: config } = await loadSyncConfig(cwd);
|
|
475
|
+
if (!config) throw switchedOff("s3");
|
|
476
|
+
requireTools(rcloneTools);
|
|
477
|
+
const source = await resolveBucket(sourceSide, config, cwd);
|
|
478
|
+
const target = await resolveBucket(targetSide, config, cwd);
|
|
479
|
+
if (sameBucket(source, target)) throw new SyncError(`Source and target are the same bucket: ${describeBucket(target)}.`);
|
|
480
|
+
const paths = remotes(source, target);
|
|
481
|
+
return {
|
|
482
|
+
source: describeBucket(source),
|
|
483
|
+
target: describeBucket(target),
|
|
484
|
+
question: `Overwrite ${describeBucket(target)} and delete its files that aren't in the source`,
|
|
485
|
+
async run() {
|
|
486
|
+
log(dryRun ? "Comparing buckets..." : `Syncing ${describeBucket(target)}...`);
|
|
487
|
+
await runTool("rclone", [
|
|
488
|
+
"sync",
|
|
489
|
+
paths.source,
|
|
490
|
+
paths.target,
|
|
491
|
+
"--fast-list",
|
|
492
|
+
"--delete-after",
|
|
493
|
+
"--stats-one-line",
|
|
494
|
+
...dryRun ? ["--dry-run"] : process.stdout.isTTY ? ["--progress"] : []
|
|
495
|
+
], { env: {
|
|
496
|
+
...process.env,
|
|
497
|
+
...paths.env
|
|
498
|
+
} });
|
|
499
|
+
log(dryRun ? "Dry run: nothing changed." : `Done. ${describeBucket(target)} now has the files of the source.`);
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Makes the target bucket an exact copy of the source bucket. Doesn't ask: a script confirms
|
|
505
|
+
* first, e.g. with `confirmEnvironment` from @newcode-team/env
|
|
506
|
+
*/
|
|
507
|
+
async function syncS3(options) {
|
|
508
|
+
await (await planS3Sync(options)).run();
|
|
509
|
+
}
|
|
510
|
+
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
|
+
|
|
512
|
+
//# sourceMappingURL=sync-C6BM27_L.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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,iDAAi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4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Copy databases and files between environments",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
5
7
|
"license": "MIT",
|
|
6
8
|
"author": "NewCode",
|
|
7
9
|
"repository": {
|
|
@@ -10,7 +12,62 @@
|
|
|
10
12
|
"directory": "packages/sync"
|
|
11
13
|
},
|
|
12
14
|
"homepage": "https://github.com/NewCodeDevelopment/tools/tree/main/packages/sync#readme",
|
|
15
|
+
"bugs": "https://github.com/NewCodeDevelopment/tools/issues",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"sync",
|
|
18
|
+
"postgres",
|
|
19
|
+
"s3",
|
|
20
|
+
"rclone",
|
|
21
|
+
"cli"
|
|
22
|
+
],
|
|
23
|
+
"bin": {
|
|
24
|
+
"newsync": "./dist/cli.mjs"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@inquirer/confirm": "^6.4.0",
|
|
28
|
+
"@inquirer/input": "^5.2.0",
|
|
29
|
+
"@inquirer/password": "^5.3.1",
|
|
30
|
+
"@inquirer/select": "^5.3.1",
|
|
31
|
+
"@newcode-team/env": "^0.2.0",
|
|
32
|
+
"commander": "^15.1.0"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@arethetypeswrong/core": "^0.18.5",
|
|
36
|
+
"@newcode-team/config": "0.2.0",
|
|
37
|
+
"@types/node": "^24.19.2",
|
|
38
|
+
"publint": "^0.3.25",
|
|
39
|
+
"tsdown": "^0.23.7",
|
|
40
|
+
"typescript": "5.9.3",
|
|
41
|
+
"unrun": "^0.3.1",
|
|
42
|
+
"vitest": "^5.1.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"@newcode-team/config": "^0.2.0"
|
|
46
|
+
},
|
|
13
47
|
"publishConfig": {
|
|
14
48
|
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=24"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"dist"
|
|
55
|
+
],
|
|
56
|
+
"exports": {
|
|
57
|
+
".": "./dist/index.mjs",
|
|
58
|
+
"./package.json": "./package.json"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"dev": "tsdown --config tsdown.config.ts --config-loader unrun --watch --no-clean",
|
|
62
|
+
"build": "tsdown --config tsdown.config.ts --config-loader unrun --no-clean",
|
|
63
|
+
"build:release": "tsdown --config tsdown.config.ts --config-loader unrun",
|
|
64
|
+
"lint": "oxlint",
|
|
65
|
+
"lint:fix": "oxlint --fix",
|
|
66
|
+
"format": "oxfmt",
|
|
67
|
+
"format:check": "oxfmt --check",
|
|
68
|
+
"typecheck": "tsc --noEmit",
|
|
69
|
+
"test": "vitest",
|
|
70
|
+
"test:ci": "vitest run",
|
|
71
|
+
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
|
|
15
72
|
}
|
|
16
73
|
}
|