poad 2.75.3 → 2.76.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.75.3",
3
+ "version": "2.76.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -63,6 +63,8 @@ module.exports = {
63
63
  sync: 'Old name of env clone',
64
64
  rm: 'Remove an environment, its database and files (confirmation, --yes); never main',
65
65
  },
66
+ push: 'The whole local project to a poad.io environment, the target becoming its mirror: code (poad deploy), base (rows of the project tables), auth (accounts, password hashes), s3 (storage files), refs; preview first, backup and typed confirmation for production: push [--env <name>] [--dry-run] [--only|--skip code,base,auth,s3,refs] [--tables a,b] [--with-secrets]',
67
+ pull: 'A whole poad.io environment into the local project (the other way of poad push): code (migrations and files), base, auth, s3, refs; preview first, local backup: pull [--env <name>] [--dry-run] [--only|--skip …] [--tables a,b] [--with-secrets]',
66
68
  deploy: 'Send poad/ (migrations, functions, flows, api, auth, storage…, never a secret) to poad.io: deploy [--env <name>] [--dry-run] [--yes]',
67
69
  upgrade: 'Upgrade the engine of the project (backup first), or roll back to a backup',
68
70
  logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
@@ -0,0 +1,4 @@
1
+ // poad pull [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
2
+ // [--yes] [--project <id>] [--json]
3
+ // Tout un environnement de poad.io vers le projet local : utils/project-sync/run.js
4
+ module.exports = (args, raw) => require('../utils/project-sync/run').run('pull', raw);
@@ -0,0 +1,4 @@
1
+ // poad push [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
2
+ // [--allow-destructive] [--yes] [--confirm <id>] [--project <id>] [--json]
3
+ // Tout le projet local vers un environnement de poad.io : utils/project-sync/run.js
4
+ module.exports = (args, raw) => require('../utils/project-sync/run').run('push', raw);
@@ -81,6 +81,7 @@ function fakeCloud(t, behaviour = {}) {
81
81
  if (req.method === 'GET' && rest === '/engine') return send(res, 200, { current: '0.38.0', offered: '0.39.0', available: true, reason: null });
82
82
  if (req.method === 'POST' && rest === '/upgrade') return send(res, 202, { state: 'running', to: json().to });
83
83
  if (req.method === 'GET' && rest === '/db-password') return send(res, 200, { user: `postgres.${id}`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
84
+ if (req.method === 'GET' && rest === '/branches/dev/db-password') return send(res, 200, { user: `postgres.${id}--dev`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
84
85
  if (req.method === 'GET' && rest === '/branches') return send(res, 200, { branches: state.branches[id] });
85
86
  if (req.method === 'POST' && rest === '/branches') {
86
87
  const b = { name: json().name, kind: json().kind, status: 'creating' };
@@ -567,9 +568,11 @@ test('db url : mot de passe masqué par défaut, --show-password l’affiche, mo
567
568
  assert.strictEqual(cloud.requests.at(-1).query.purpose, 'reveal');
568
569
  const bad = await poad(box, cloud.api, ['db', 'url', '--mode', 'pool']);
569
570
  assert.strictEqual(bad.status, 2);
571
+ // Un environnement : sa propre base (postgres.<id>--<branche>, route par branche de poad.io)
570
572
  const dev = await poad(box, cloud.api, ['db', 'url', '--env', 'dev']);
571
- assert.strictEqual(dev.status, 1);
572
- assert.match(dev.stderr, /production database only/);
573
+ assert.strictEqual(dev.status, 0, dev.all);
574
+ assert.match(dev.stdout, new RegExp(`postgresql://postgres\\.${PID}--dev:•+@db\\.poad\\.io:5432/postgres`));
575
+ assert.ok(!dev.all.includes(DB_PASSWORD));
573
576
  });
574
577
 
575
578
  test('db pull : pg_dump --schema-only avec PGPASSWORD (jamais en argument), nouvelle migration à chaque fois', async (t) => {
@@ -0,0 +1,297 @@
1
+ // poad push / poad pull : décisions sans base ni réseau (utils/project-sync/plan.js, code.js),
2
+ // puis la commande entière contre un faux poad.io et une fausse base (deps.pg).
3
+ const { test } = require('node:test');
4
+ const assert = require('node:assert');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const http = require('http');
9
+ const P = require('../utils/project-sync/plan');
10
+ const C = require('../utils/project-sync/code');
11
+
12
+ const col = (name, type = 'text', extra = {}) => ({ name, type, generated: false, notnull: false, default: false, ...extra });
13
+ const tbl = (schema, name, columns, extra = {}) => ({ schema, name, columns, pk: ['id'], estimate: 10, bytes: 8192, refs: [], ...extra });
14
+
15
+ test('parseParts: all by default, --only, --skip, aliases, --tables needs base, secrets only with --with-secrets', () => {
16
+ assert.deepStrictEqual(P.parseParts({}), { parts: ['code', 'base', 'auth', 'refs', 's3'], tables: null });
17
+ assert.deepStrictEqual(P.parseParts({ only: 'db,storage' }).parts, ['base', 's3']);
18
+ assert.deepStrictEqual(P.parseParts({ skip: 'code,refs' }).parts, ['base', 'auth', 's3']);
19
+ assert.deepStrictEqual(P.parseParts({ only: 'base', withSecrets: true }).parts, ['base', 'secrets']);
20
+ assert.deepStrictEqual(P.parseParts({ tables: 'livres,compta.ecritures' }).tables, ['public.livres', 'compta.ecritures']);
21
+ assert.throws(() => P.parseParts({ only: 'base', skip: 'auth' }), /choose one/);
22
+ assert.throws(() => P.parseParts({ only: 'secrets' }), /--with-secrets/);
23
+ assert.throws(() => P.parseParts({ only: 'tout' }), /unknown part/);
24
+ assert.throws(() => P.parseParts({ only: 'auth', tables: 'a' }), /base part/);
25
+ assert.throws(() => P.parseParts({ tables: 'a;drop' }), /expected table/);
26
+ });
27
+
28
+ test('compareTables: copiable, missing, different type, new not-null column, references left out, --tables', () => {
29
+ const src = [
30
+ tbl('public', 'livres', [col('id', 'integer'), col('titre'), col('titre_maj', 'text', { generated: true })]),
31
+ tbl('public', 'absente', [col('id', 'integer')]),
32
+ tbl('public', 'typee', [col('id', 'integer'), col('prix', 'numeric')]),
33
+ tbl('public', 'stricte', [col('id', 'integer')]),
34
+ tbl('ref', 'communes', [col('id', 'integer')]),
35
+ ];
36
+ const dst = [
37
+ tbl('public', 'livres', [col('id', 'integer'), col('titre'), col('titre_maj', 'text', { generated: true }), col('note', 'text')]),
38
+ tbl('public', 'typee', [col('id', 'integer'), col('prix', 'text')]),
39
+ tbl('public', 'stricte', [col('id', 'integer'), col('obligatoire', 'text', { notnull: true })]),
40
+ tbl('ref', 'communes', [col('id', 'integer')]),
41
+ tbl('public', 'seulement_cible', [col('id', 'integer')]),
42
+ ];
43
+ const r = P.compareTables(src, dst, { exclude: ['ref.communes'] });
44
+ assert.deepStrictEqual(r.tables.map((t) => [t.key, t.columns]), [['public.livres', ['id', 'titre']]]);
45
+ assert.deepStrictEqual(r.blocked.map((b) => [b.key, b.reason]), [['public.absente', 'missing'], ['public.typee', 'differs'], ['public.stricte', 'differs']]);
46
+ assert.match(r.blocked[1].detail, /numeric here, text on the target/);
47
+ assert.match(r.blocked[2].detail, /obligatoire \(not null, no default\) only on the target/);
48
+ assert.deepStrictEqual(r.excluded, [{ key: 'ref.communes', reason: 'reference' }]);
49
+ assert.deepStrictEqual(r.extra, ['public.seulement_cible']);
50
+ const only = P.compareTables(src, dst, { only: ['public.livres', 'public.inconnue'] });
51
+ assert.deepStrictEqual(only.tables.map((t) => t.key), ['public.livres']);
52
+ assert.deepStrictEqual(only.unknown, ['public.inconnue']);
53
+ });
54
+
55
+ test('diffHashes: by primary key (added, replaced, deleted, unchanged), and as multisets without one', () => {
56
+ const src = ['k1 a', 'k2 b', 'k3 c'].join('\n');
57
+ const dst = ['k1 a', 'k2 X', 'k9 z'].join('\n');
58
+ assert.deepStrictEqual(P.diffHashes(src, dst, true), { added: 1, replaced: 1, deleted: 1, unchanged: 1, rows: 3, target_rows: 3, exact: true });
59
+ assert.deepStrictEqual(P.diffHashes('a\na\nb', 'a\nc', false), { added: 2, replaced: 0, deleted: 1, unchanged: 1, rows: 3, target_rows: 2, exact: true });
60
+ assert.ok(!P.changed(P.diffHashes('k1 a', 'k1 a', true)));
61
+ assert.ok(P.changed({ exact: false, rows: 3, target_rows: 3 }));
62
+ assert.ok(!P.changed({ exact: false, rows: 0, target_rows: 0 }));
63
+ });
64
+
65
+ test('hashSql: fingerprints of key and row over the copied columns, tokens blanked; never a value out', () => {
66
+ const t = { schema: 'auth', name: 'users', columns: ['id', 'email', 'confirmation_token'], pk: ['id'] };
67
+ assert.strictEqual(P.hashSql(t, { blank: ['confirmation_token'] }), `select md5(row("id")::text) || ' ' || md5(row("id", "email", null::text)::text) from "auth"."users"`);
68
+ assert.strictEqual(P.hashSql({ ...t, pk: null }), `select md5(row("id", "email", "confirmation_token")::text) from "auth"."users"`);
69
+ });
70
+
71
+ test('fits: rows to write + 10 % + journal reserve against the room left', () => {
72
+ const GiB = 1024 ** 3;
73
+ assert.deepStrictEqual(P.fits(100, null), { known: false, ok: true });
74
+ const ok = P.fits(100 * 1024 ** 2, { limit: GiB, used: 0.2 * GiB });
75
+ assert.ok(ok.known && ok.ok);
76
+ assert.strictEqual(ok.reserve, 256 * 1024 ** 2);
77
+ assert.ok(!P.fits(700 * 1024 ** 2, { limit: GiB, used: 0.2 * GiB }).ok);
78
+ assert.strictEqual(P.walReserve(100), 64 * 1024 ** 2);
79
+ });
80
+
81
+ test('sequencesFor: those of the copied tables, unowned ones only for the whole base, already equal ones skipped', () => {
82
+ const src = [{ schema: 'public', name: 'a_id_seq', owner: 'public.a', last: 10 }, { schema: 'public', name: 'libre', owner: null, last: 3 }, { schema: 'public', name: 'b_id_seq', owner: 'public.b', last: 5 }, { schema: 'public', name: 'egal', owner: 'public.a', last: 7 }];
83
+ const dst = [{ schema: 'public', name: 'a_id_seq', last: 1 }, { schema: 'public', name: 'libre', last: 1 }, { schema: 'public', name: 'egal', last: 7 }];
84
+ assert.deepStrictEqual(P.sequencesFor(src, dst, ['public.a']).map((s) => s.name), ['a_id_seq']);
85
+ assert.deepStrictEqual(P.sequencesFor(src, dst, ['public.a'], { all: true }).map((s) => s.name), ['a_id_seq', 'libre']);
86
+ assert.match(P.sequencesSql([{ schema: 'public', name: 'a_id_seq' }]), /setval/);
87
+ assert.strictEqual(P.sequencesSql([]), null);
88
+ });
89
+
90
+ test('authPlan: common columns, columns lost, sessions closed before accounts, tokens emptied', () => {
91
+ const users = (extra = []) => ({ rows: 2, bytes: 100, pk: ['id'], columns: [col('id', 'uuid'), col('email'), col('confirmation_token'), ...extra] });
92
+ const src = { users: users([col('nouvelle')]), identities: { rows: 2, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email', 'text', { generated: true })] }, sessions: { rows: 0, columns: [] } };
93
+ const dst = { users: users(), identities: { rows: 0, bytes: 0, pk: ['id'], columns: [col('id', 'uuid'), col('email', 'text', { generated: true })] }, sessions: { rows: 4, columns: [] }, refresh_tokens: { rows: 4, columns: [] } };
94
+ const a = P.authPlan(src, dst);
95
+ assert.deepStrictEqual(a.tables.map((t) => [t.name, t.columns]), [['users', ['id', 'email', 'confirmation_token']], ['identities', ['id']]]);
96
+ assert.deepStrictEqual(a.dropped, ['auth.users.nouvelle']);
97
+ assert.deepStrictEqual(a.clear, ['delete from auth."refresh_tokens";', 'delete from auth."sessions";', 'delete from auth."identities";', 'delete from auth."users";']);
98
+ assert.deepStrictEqual(a.after, [`update auth."users" set "confirmation_token" = '' where "confirmation_token" <> '';`]);
99
+ });
100
+
101
+ test('transferScript: one target transaction, replica role, one consistent source snapshot, quoted names, stop on error', () => {
102
+ const s = P.transferScript({ srcFn: 'SRC', dstFn: 'DST', tables: [{ schema: 'public', name: "l'o", columns: ['a', 'b'] }], clear: ['delete from "public"."l\'o";'], sequences: 'select 1' });
103
+ assert.match(s, /set -o pipefail/);
104
+ assert.match(s, /printf '%s\\n' 'begin;'/);
105
+ assert.match(s, /session_replication_role = replica/);
106
+ assert.match(s, /begin isolation level repeatable read read only;/);
107
+ assert.match(s, /\\echo 'COPY "public"\."l''o" \("a", "b"\) FROM stdin;'/);
108
+ assert.match(s, /COPY \(select "a", "b" from "public"\."l'o"\) TO STDOUT;/);
109
+ assert.match(s, /\\echo '\\\\\.'/);
110
+ assert.match(s, /\| dst -v ON_ERROR_STOP=1/);
111
+ assert.ok(s.indexOf("'commit;'") > s.indexOf('POAD_SRC_EOF\n printf'), 'commit after the source');
112
+ assert.ok(!/PGPASSWORD=/.test(s), 'no password in the script');
113
+ });
114
+
115
+ test('secretsSql: storage credentials kept on both sides, nothing read from the target; source stops on the first error', () => {
116
+ const q = P.secretsSql({ variables: true, credentials: true, vault: true }, { targetStorage: ['s3-prod'] }).join('\n');
117
+ assert.match(q, /update _poad\.variables set value = null/);
118
+ assert.match(q, /slot like 'storage\.%'\)::text\[\]/);
119
+ assert.match(q, /array\['s3-prod'\]::text\[\]/);
120
+ assert.match(q, /vault\.decrypted_secrets/);
121
+ const sh = P.secretsScript({ srcFn: 'S', dstFn: 'D', queries: ['select 1'] });
122
+ assert.match(sh, /src -v ON_ERROR_STOP=1 -tA -c 'select 1' 2> \/dev\/null \| dst -v ON_ERROR_STOP=1 > \/dev\/null 2>&1/);
123
+ });
124
+
125
+ test('parseMarkers and errorLine: timings, exit code, the ERROR line only (never CONTEXT, which quotes rows)', () => {
126
+ const m = P.parseMarkers('@@poad start 0 1000\n@@poad start 1 1500\npsql:<stdin>:9: ERROR: duplicate key value\nCONTEXT: COPY t, line 1: "secret row"\n@@poad done 2000 3\n');
127
+ assert.deepStrictEqual(m.tables, { 0: { start: 1000 }, 1: { start: 1500 } });
128
+ assert.strictEqual(m.rc, 3);
129
+ assert.strictEqual(P.errorLine(m.errors), 'ERROR: duplicate key value');
130
+ });
131
+
132
+ test('code: mirrored paths, plan keeps uncommitted or untracked local files', () => {
133
+ assert.ok(C.mirrored('functions/hello/index.ts'));
134
+ assert.ok(C.mirrored('seed.sql'));
135
+ assert.ok(!C.mirrored('migrations/20260101000000_a.sql'));
136
+ assert.ok(!C.mirrored('functions/node_modules/x/index.js'));
137
+ assert.ok(!C.mirrored('config.toml'));
138
+ assert.ok(!C.mirrored('reference/.gitignore'));
139
+ const B = (t) => Buffer.from(t);
140
+ const remote = new Map([['functions/a/index.ts', B('new')], ['flows/f.json', B('same')], ['functions/b/index.ts', B('remote')], ['queries/new.sql', B('q')]]);
141
+ const local = new Map([['functions/a/index.ts', B('old')], ['flows/f.json', B('same')], ['functions/b/index.ts', B('local edit')], ['sources/gone.yaml', B('x')], ['sources/mine.yaml', B('y')]]);
142
+ const git = { repo: true, tracked: new Set(['functions/a/index.ts', 'flows/f.json', 'functions/b/index.ts', 'sources/gone.yaml']), dirty: new Set(['functions/b/index.ts']) };
143
+ const p = C.planFiles(remote, local, git);
144
+ assert.deepStrictEqual(p.add, ['queries/new.sql']);
145
+ assert.deepStrictEqual(p.update, ['functions/a/index.ts']);
146
+ assert.deepStrictEqual(p.remove, ['sources/gone.yaml']);
147
+ assert.strictEqual(p.unchanged, 1);
148
+ assert.deepStrictEqual(p.kept.map((k) => [k.rel, k.reason]), [['functions/b/index.ts', 'uncommitted changes'], ['sources/mine.yaml', 'not tracked by git']]);
149
+ // Hors dépôt git : rien n'est remplacé ni retiré
150
+ const nogit = C.planFiles(remote, local, { repo: false, tracked: new Set(), dirty: new Set() });
151
+ assert.deepStrictEqual([nogit.update, nogit.remove], [[], []]);
152
+ assert.strictEqual(nogit.kept[0].reason, 'not in a git repository');
153
+ });
154
+
155
+ // --- La commande entière : faux poad.io (HTTP) et fausse base (deps.pg) ------------------------------------
156
+
157
+ function fakeCloud(t, seen) {
158
+ return new Promise((resolve) => {
159
+ const server = http.createServer((req, res) => {
160
+ let body = '';
161
+ req.on('data', (d) => (body += d)).on('end', () => {
162
+ seen.push({ method: req.method, url: req.url, body });
163
+ const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
164
+ if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
165
+ if (/\/seeds$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
+ if (/\/sync-plan$/.test(req.url)) return send(200, { space: { limit: 1024 ** 3, used: 1024 ** 2 } });
167
+ if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
+ if (/\/sync-events$/.test(req.url)) return send(200, { written: JSON.parse(body).lines.length });
169
+ send(404, { error: { code: 'not_found', message: 'route inconnue' } });
170
+ });
171
+ });
172
+ server.listen(0, '127.0.0.1', () => {
173
+ t.after(() => server.close());
174
+ resolve(`http://127.0.0.1:${server.address().port}`);
175
+ });
176
+ });
177
+ }
178
+
179
+ /** Fausse base : inventaires de la source et de la cible, empreintes, transfert enregistré */
180
+ function fakePg(scripts) {
181
+ const real = require('../utils/project-sync/pg');
182
+ const inv = (rows) => ({
183
+ tables: [tbl('public', 'livres', [col('id', 'integer'), col('titre')], { pk: ['id'] }), tbl('ref', 'communes', [col('id', 'integer')])],
184
+ sequences: [{ schema: 'public', name: 'livres_id_seq', owner: 'public.livres', last: rows }],
185
+ migrations: ['20261205100000'],
186
+ auth: { users: { rows: 1, bytes: 10, pk: ['id'], columns: [col('id', 'uuid'), col('email')] } },
187
+ variables: ['MAIL_FROM'],
188
+ credentials: ['api-meteo'],
189
+ storage_credentials: [],
190
+ });
191
+ return {
192
+ localSide: real.localSide,
193
+ cloudSide: real.cloudSide,
194
+ json: async (container, side, sql) => (sql === P.PROBE_SQL ? { history: true, variables: true, credentials: true, vault: true, auth: ['users'] } : inv(side.kind === 'local' ? 3 : 2)),
195
+ query: async (container, side, sql) => {
196
+ // Empreintes : la source a trois livres, la cible deux (un remplacé) ; un compte identique
197
+ const local = side.kind === 'local';
198
+ const parts = sql.split(/\\echo @@T (\d+)\n/).filter(Boolean);
199
+ let out = '';
200
+ for (let i = 0; i < parts.length; i += 2) {
201
+ out += `@@T ${parts[i]}\n`;
202
+ if (/"auth"\."users"/.test(parts[i + 1])) out += 'u1 h\n';
203
+ else out += local ? 'k1 a\nk2 b\nk3 c\n' : 'k1 a\nk2 X\n';
204
+ }
205
+ return out;
206
+ },
207
+ transfer: async (container, src, dst, script) => {
208
+ scripts.push(script);
209
+ return { code: 0, stdout: Buffer.alloc(0), stderr: '@@poad start 0 1000\n@@poad done 1200 0\n' };
210
+ },
211
+ dumpLocal: async () => 10,
212
+ };
213
+ }
214
+
215
+ async function runCmd(t, args, { tty = false } = {}) {
216
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-pp-'));
217
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
218
+ fs.mkdirSync(path.join(dir, 'poad'));
219
+ fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), 'project_id = "t"\nproject_uuid = "ppuuid1"\nengine = "0.73.1"\n[db]\nport = 1\n[web]\nport = 2\n[cloud]\nproject = "pptest123456"\n');
220
+ const seen = [];
221
+ const scripts = [];
222
+ const base = await fakeCloud(t, seen);
223
+ const saved = { cwd: process.cwd(), api: process.env.POAD_CLOUD_API, tok: process.env.POAD_ACCESS_TOKEN, log: console.log, err: console.error, code: process.exitCode };
224
+ const printed = [];
225
+ process.chdir(dir);
226
+ process.env.POAD_CLOUD_API = base;
227
+ process.env.POAD_ACCESS_TOKEN = 'poad_pat_test';
228
+ console.log = (...a) => printed.push(a.join(' '));
229
+ console.error = (...a) => printed.push(a.join(' '));
230
+ const isTTY = process.stdin.isTTY;
231
+ process.stdin.isTTY = tty;
232
+ try {
233
+ process.exitCode = 0;
234
+ await require('../utils/project-sync/run').run(args[0], args.slice(1), {
235
+ pg: fakePg(scripts),
236
+ started: async () => true,
237
+ credentials: async () => ({ user: 'postgres.pptest123456--dev', password: 'pw-never-shown', host: 'db.poad.io', port: () => 5432 }),
238
+ });
239
+ return { code: process.exitCode, out: printed.join('\n'), seen, scripts };
240
+ } finally {
241
+ process.stdin.isTTY = isTTY;
242
+ process.chdir(saved.cwd);
243
+ process.env.POAD_CLOUD_API = saved.api;
244
+ process.env.POAD_ACCESS_TOKEN = saved.tok;
245
+ if (saved.api === undefined) delete process.env.POAD_CLOUD_API;
246
+ if (saved.tok === undefined) delete process.env.POAD_ACCESS_TOKEN;
247
+ console.log = saved.log;
248
+ console.error = saved.err;
249
+ process.exitCode = saved.code;
250
+ }
251
+ }
252
+
253
+ test('poad push --dry-run: preview per table, reference tables left to refs, nothing written, nothing logged', async (t) => {
254
+ const r = await runCmd(t, ['push', '--env', 'dev', '--only', 'base,auth', '--dry-run', '--json']);
255
+ assert.strictEqual(r.code, 0);
256
+ const j = JSON.parse(r.out.slice(r.out.indexOf('{')));
257
+ assert.strictEqual(j.dry_run, true);
258
+ assert.deepStrictEqual(j.preview.base.tables.map((x) => [x.table, x.added, x.replaced, x.deleted, x.unchanged]), [['public.livres', 1, 1, 0, 1]]);
259
+ assert.deepStrictEqual(j.preview.base.excluded, [{ key: 'ref.communes', reason: 'reference' }]);
260
+ assert.strictEqual(j.preview.auth.changed, false);
261
+ assert.strictEqual(r.scripts.length, 0);
262
+ assert.ok(!r.seen.some((s) => /sync-events|backup/.test(s.url)));
263
+ assert.ok(!r.out.includes('pw-never-shown'));
264
+ });
265
+
266
+ test('poad push to production outside a terminal: refused without --yes --confirm <id>, nothing written', async (t) => {
267
+ const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base', '--yes']);
268
+ assert.strictEqual(r.code, 4);
269
+ assert.match(r.out, /--yes --confirm pptest123456/);
270
+ assert.strictEqual(r.scripts.length, 0);
271
+ assert.ok(!r.seen.some((s) => /backup/.test(s.url)));
272
+ const bad = await runCmd(t, ['push', '--env', 'main', '--only', 'base', '--yes', '--confirm', 'autre']);
273
+ assert.strictEqual(bad.code, 4);
274
+ });
275
+
276
+ test('poad push to production with --yes --confirm: backup first, one transfer, logs per table on poad.io (no value)', async (t) => {
277
+ const r = await runCmd(t, ['push', '--env', 'main', '--only', 'base,auth', '--yes', '--confirm', 'pptest123456']);
278
+ assert.strictEqual(r.code, 0, r.out);
279
+ const order = r.seen.map((s) => s.url.replace(/^.*\/branches\/[^/]+\//, '')).filter((u) => ['backup', 'sync-events'].includes(u));
280
+ assert.deepStrictEqual(order, ['backup', 'sync-events']);
281
+ assert.strictEqual(r.scripts.length, 1);
282
+ assert.match(r.scripts[0], /delete from "public"\."livres";/);
283
+ assert.ok(!/auth\."users"/.test(r.scripts[0]), 'identical accounts are not rewritten');
284
+ assert.match(r.scripts[0], /setval/);
285
+ const ev = JSON.parse(r.seen.find((s) => /sync-events/.test(s.url)).body);
286
+ assert.strictEqual(ev.event, 'project_push');
287
+ assert.deepStrictEqual(ev.lines.map((l) => [l.part, l.table || null, l.outcome]), [['backup', null, 'done'], ['base', 'public.livres', 'done'], ['data', null, 'done'], ['all', null, 'done']]);
288
+ assert.strictEqual(ev.lines[1].rows, 3);
289
+ assert.ok(!JSON.stringify(ev).includes('pw-never-shown'));
290
+ });
291
+
292
+ test('poad pull --tables of an unknown table: stopped before anything is written', async (t) => {
293
+ const r = await runCmd(t, ['pull', '--env', 'dev', '--only', 'base', '--tables', 'inconnue', '--yes']);
294
+ assert.strictEqual(r.code, 5);
295
+ assert.match(r.out, /public\.inconnue not in the source/);
296
+ assert.strictEqual(r.scripts.length, 0);
297
+ });
package/utils/banner.js CHANGED
@@ -31,6 +31,8 @@ const SHORT = {
31
31
  db: 'Local database: reset, seed, diff',
32
32
  upgrade: 'Upgrade the engine of the project',
33
33
  deploy: 'Send poad/ to its poad.io project (poad link)',
34
+ push: 'The whole project to poad.io: code, data, accounts, files',
35
+ pull: 'A whole poad.io environment into the local project',
34
36
  },
35
37
  };
36
38
 
package/utils/cloud/db.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Connexion directe à la base d'un projet poad.io (passerelle db.poad.io).
2
- // GET v1/projects/:id/db-password?purpose=copy|reveal|pull
2
+ // GET v1/projects/:id/db-password?purpose=copy|reveal|pull production
3
+ // GET v1/projects/:id/branches/:branche/db-password?purpose=copy|reveal environnement (postgres.<id>--<branche>)
3
4
  // -> { user, password, host, session_port, transaction_port }
4
5
  // Le mot de passe n'est gardé qu'en mémoire ; il ne s'affiche qu'avec
5
6
  // --show-password (poad db url) et ne passe jamais en argument d'un processus.
@@ -10,15 +11,13 @@ const PORTS = { session: 5432, transaction: 6543 };
10
11
  const MASK = '••••••••';
11
12
 
12
13
  async function credentials(id, { env, purpose = 'copy' } = {}) {
13
- if (env && !env.production) {
14
- // Pas encore de route par environnement côté serveur : on ne devine pas
15
- throw new api.CloudError(`The database of the environment "${env.branch}" is not reachable from the CLI yet (poad.io gives the password of the production database only). Use --env main.`, { code: 'unsupported' });
16
- }
17
- const d = await api.call('GET', `v1/projects/${api.enc(id)}/db-password?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
14
+ // Un environnement : sa propre base (route par branche de poad.io, utilisateur postgres.<id>--<branche>)
15
+ const route = env && !env.production ? `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}/db-password` : `v1/projects/${api.enc(id)}/db-password`;
16
+ const d = await api.call('GET', `${route}?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
18
17
  if (typeof d.password !== 'string' || !d.password) throw new api.CloudError('poad.io sent no database password.', { code: 'bad_response' });
19
18
  const port = (mode) => Number(mode === 'transaction' ? d.transaction_port : d.session_port) || PORTS[mode];
20
19
  return {
21
- user: typeof d.user === 'string' && d.user ? d.user : `postgres.${id}`,
20
+ user: typeof d.user === 'string' && /^[A-Za-z0-9._-]{1,120}$/.test(d.user) ? d.user : env && !env.production ? `postgres.${id}--${env.branch}` : `postgres.${id}`,
22
21
  password: d.password,
23
22
  host: typeof d.host === 'string' && /^[A-Za-z0-9.-]+$/.test(d.host) ? d.host : HOST,
24
23
  port,
@@ -23,8 +23,8 @@ const CAP = 100000; // lignes comptées au plus par cible ; au-delà, estimation
23
23
  const MAX_FINDINGS = 60;
24
24
 
25
25
  // ------------------------------------------------------------------ lexer
26
- const WORD_START = /[A-Za-z_\u0080-￿]/;
27
- const WORD = /[A-Za-z0-9_$\u0080-￿]/;
26
+ const WORD_START = /[A-Za-z_\u0080-\uffff]/;
27
+ const WORD = /[A-Za-z0-9_$\u0080-\uffff]/;
28
28
 
29
29
  /** Jetons d'un script SQL : { k: 'w' (mot, v en minuscules) | 'id' (identifiant entre guillemets) | 's' (chaîne) | 'n' | 'p' (ponctuation), v, s, e } */
30
30
  function tokenize(sql) {
@@ -73,8 +73,8 @@ function tokenize(sql) {
73
73
  }
74
74
  i = Math.min(n, i + 1);
75
75
  out.push({ k: 'id', v, s, e: i });
76
- } else if (c === '$' && /[A-Za-z_\u0080-￿$]/.test(d || '')) {
77
- const m = /^\$([A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$/.exec(sql.slice(i, i + 80));
76
+ } else if (c === '$' && /[A-Za-z_\u0080-\uffff$]/.test(d || '')) {
77
+ const m = /^\$([A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(sql.slice(i, i + 80));
78
78
  if (!m) {
79
79
  out.push({ k: 'p', v: c, s: i, e: ++i });
80
80
  continue;
@@ -503,17 +503,67 @@ Object.assign(sheets, {
503
503
  EXIT_NOTE,
504
504
  ],
505
505
  },
506
+ push: {
507
+ usage: [
508
+ 'poad push [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]',
509
+ 'poad push --env main --yes --confirm <project id> (production, outside a terminal)',
510
+ ],
511
+ text: [
512
+ 'Make an environment of the linked poad.io project the mirror of the local project, part by part, in this order: code (what poad deploy sends: migrations, functions, flows, API…), base (rows of the tables of the project schemas), auth (accounts with their password hashes, identities and metadata, as they are), refs (reference tables of the store), s3 (files of the storage). The target becomes the mirror of the source for the chosen parts: what it has of its own there is replaced; nothing is merged both ways. Tables that exist only on the target are left alone.',
513
+ 'A preview always comes first, part by part and table by table: rows added (+), replaced (~), deleted (-) and identical, compared row by row with fingerprints of the primary key and of each row (never a value; above 200,000 rows a table is compared by counts only), sizes, room left on the target. An identical table is not rewritten.',
514
+ 'Base and auth go in ONE transaction, through the direct database access of poad.io (db.poad.io), run by the PostgreSQL tools of the local engine: the source is read in one consistent snapshot, the target is written with triggers and foreign keys paused during the load (nothing cascades), sequences are set as on the source; any error and nothing changes. Sessions and refresh tokens of the target are closed (accounts sign in again there), confirmation and recovery tokens are emptied. The structure must match first: a table missing or different on the target stops the base part before anything is written, and the code part (when chosen) runs first and is checked again after it.',
515
+ 'Secrets only with --with-secrets, after a confirmation of their own: the values of the variables of the engine and the credentials (fields, uses, vault values), except those of the storage, which each environment keeps. Values are never shown, written to a file or logged; keys of the engine, auth provider secrets and MCP tokens are never copied.',
516
+ ],
517
+ options: [
518
+ ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
519
+ ['--dry-run, -n', 'the preview only, nothing changes (also: poad push status)'],
520
+ ['--only <parts>', 'only these parts: code, base, auth, s3, refs (comma separated)'],
521
+ ['--skip <parts>', 'all parts but these'],
522
+ ['--tables <a,b>', 'only these tables of the base part (table or schema.table)'],
523
+ ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
524
+ ['--allow-destructive', 'passed to poad deploy (alias --accept-data-loss): migrations that lose data are applied on production without asking'],
525
+ ['--yes', 'no question (required outside a terminal)'],
526
+ ['--confirm <id>', 'production: the project id, typed in the command (outside a terminal: with --yes)'],
527
+ PROJECT_OPT,
528
+ JSON_OPT,
529
+ ],
530
+ notes: [
531
+ 'Production (main): a backup of its database first (kept in its volume, 3 kept), a check of the room left (rows to write + 10 % + the journal of the database), and a strong confirmation: type the project id; outside a terminal, --yes --confirm <id>, else nothing changes.',
532
+ 'The local project must be started (poad start). Logs, one line per part and per table (part, table, rows, bytes, duration_ms, outcome; never a value): poad logs cli event=project_push here, and in the logs of the environment on poad.io (poad logs --project … event=project_push).',
533
+ EXIT_NOTE.replace('5 deploy failed', '5 a part failed (the base part is all or nothing)'),
534
+ ],
535
+ },
536
+ pull: {
537
+ usage: ['poad pull [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]'],
538
+ text: [
539
+ 'The other way of poad push: make the local project the mirror of an environment of poad.io, part by part: code (the migrations written there, by poad migration pull, then the deployed files of queries, auth, storage, functions, flows, api, reference, sources, transforms, connections, variables and seed.sql, then poad migrate), base, auth, refs (the reference tables of the store, loaded into the local engine), s3 (files of the storage).',
540
+ 'A local file is replaced or removed only when git tracks it without uncommitted change; otherwise it is kept and named (commit or stash it, then pull again). Migrations are never overwritten (a version used here under another name is a conflict, said and left alone).',
541
+ 'Same preview, same single transaction for base and auth, same structure check and same --with-secrets as poad push. Before writing a local database that holds rows, a backup: poad/backups/<timestamp>-pre-pull.dump (pg_dump custom format, outside git; pg_restore brings it back).',
542
+ ],
543
+ options: [
544
+ ['--env <name>', 'the environment to read (default: the current git branch if it exists on poad.io, else main); never written'],
545
+ ['--dry-run, -n', 'the preview only, nothing changes (also: poad pull status)'],
546
+ ['--only <parts>', 'only these parts: code, base, auth, s3, refs'],
547
+ ['--skip <parts>', 'all parts but these'],
548
+ ['--tables <a,b>', 'only these tables of the base part'],
549
+ ['--with-secrets', 'also the values of variables and credentials (asks separately)'],
550
+ ['--yes', 'no question (required outside a terminal)'],
551
+ PROJECT_OPT,
552
+ JSON_OPT,
553
+ ],
554
+ notes: ['Logs: poad logs cli event=project_pull (and in the logs of the environment on poad.io). ' + EXIT_NOTE.replace('5 deploy failed', '5 a part failed')],
555
+ },
506
556
  'db url': {
507
557
  usage: ['poad db url [--env <name>] [--mode session|transaction] [--show-password] [--copy | --no-copy] [--json]'],
508
558
  text: [
509
- 'Connection string of the database of the linked poad.io project: postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
559
+ 'Connection string of the database of the linked poad.io project (or of one of its environments: user postgres.<id>--<env>): postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
510
560
  ],
511
561
  options: [
512
562
  ['--mode session', 'port 5432, long connections (psql, pg_dump, migrations); the default'],
513
563
  ['--mode transaction', 'port 6543, pooled short connections (serverless functions)'],
514
564
  ['--show-password', 'print the full string (it stays in your terminal history)'],
515
565
  ['--copy, --no-copy', 'copy to the clipboard even outside a terminal, or never'],
516
- ['--env <name>', 'the environment (production only for now)'],
566
+ ['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'],
517
567
  PROJECT_OPT,
518
568
  JSON_OPT,
519
569
  ],
@@ -525,7 +575,7 @@ Object.assign(sheets, {
525
575
  'Write the schema of the poad.io database into a new local migration (poad/migrations/<timestamp>_cloud_main_schema.sql), with pg_dump --schema-only through db.poad.io. Engine schemas (auth, storage, _poad…) are left out. An existing migration is never overwritten.',
526
576
  'pg_dump: the one of this machine, else the one of the local engine (project started), else the command tells what to install.',
527
577
  ],
528
- options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (production only for now)'], PROJECT_OPT, JSON_OPT],
578
+ options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'], PROJECT_OPT, JSON_OPT],
529
579
  notes: [EXIT_NOTE],
530
580
  },
531
581
  });
@@ -0,0 +1,122 @@
1
+ // poad pull, partie code : les fichiers déployés d'un environnement de poad.io (export de /project) face au
2
+ // dossier poad/ local, pour les dossiers que poad deploy envoie. Les migrations ont leur commande (poad
3
+ // migration pull) ; types/ est régénéré ; config.toml et credentials/ restent ceux de chaque côté.
4
+ //
5
+ // Rien n'est perdu : un fichier local n'est remplacé ou retiré que s'il est suivi par git et sans
6
+ // modification en cours ; sinon il est gardé et nommé (« commit ou stash, puis relancez »).
7
+ 'use strict';
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ const MIRRORED = ['queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'transforms', 'connections', 'variables'];
12
+ const FILES = ['seed.sql'];
13
+
14
+ /** Le chemin (relatif à poad/) fait-il partie du miroir ? Pure. */
15
+ function mirrored(rel) {
16
+ if (FILES.includes(rel)) return true;
17
+ const parts = rel.split('/');
18
+ if (parts.length < 2 || !MIRRORED.includes(parts[0])) return false;
19
+ if (parts.includes('node_modules') || parts.some((p) => p.startsWith('.'))) return false;
20
+ return true;
21
+ }
22
+
23
+ /** Fichiers locaux du miroir : { rel: Buffer } (au-delà de la limite des références lourdes : laissés de côté) */
24
+ function localFiles(poadDir, { maxFile = 20 * 1024 * 1024 } = {}) {
25
+ const out = new Map();
26
+ const walk = (dir, rel) => {
27
+ let names = [];
28
+ try {
29
+ names = fs.readdirSync(dir, { withFileTypes: true });
30
+ } catch {
31
+ return;
32
+ }
33
+ for (const d of names) {
34
+ const r = rel ? `${rel}/${d.name}` : d.name;
35
+ if (d.isDirectory()) {
36
+ if (d.name === 'node_modules' || d.name.startsWith('.')) continue;
37
+ walk(path.join(dir, d.name), r);
38
+ } else if (d.isFile() && mirrored(r)) {
39
+ const abs = path.join(dir, d.name);
40
+ if (fs.statSync(abs).size <= maxFile) out.set(r, fs.readFileSync(abs));
41
+ }
42
+ }
43
+ };
44
+ for (const d of MIRRORED) walk(path.join(poadDir, d), d);
45
+ for (const f of FILES) {
46
+ try {
47
+ out.set(f, fs.readFileSync(path.join(poadDir, f)));
48
+ } catch {}
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** État git des fichiers de poad/ : { repo, tracked: Set, dirty: Set } (chemins relatifs à poad/) */
54
+ function gitFiles(poadDir) {
55
+ const { spawnSync } = require('child_process');
56
+ const git = (a) => spawnSync('git', a, { cwd: poadDir, encoding: 'utf8', timeout: 15000, maxBuffer: 64 * 1024 * 1024 });
57
+ const prefix = git(['rev-parse', '--show-prefix']);
58
+ if (prefix.status !== 0) return { repo: false, tracked: new Set(), dirty: new Set() };
59
+ const pre = prefix.stdout.trim();
60
+ const ls = git(['ls-files', '-z', '--', '.']);
61
+ const tracked = new Set(ls.status === 0 ? ls.stdout.split('\0').filter(Boolean) : []);
62
+ const st = git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.']);
63
+ const dirty = new Set();
64
+ if (st.status === 0) {
65
+ const items = st.stdout.split('\0');
66
+ for (let i = 0; i < items.length; i++) {
67
+ const it = items[i];
68
+ if (!it) continue;
69
+ const p = it.slice(3);
70
+ if (it[0] === 'R' || it[0] === 'C') i++; // renommage : le chemin d'origine suit
71
+ dirty.add(pre && p.startsWith(pre) ? p.slice(pre.length) : p);
72
+ }
73
+ }
74
+ return { repo: true, tracked, dirty };
75
+ }
76
+
77
+ /**
78
+ * Plan : remote (Map rel → Buffer, de l'export) face à local (Map), avec l'état git. Pure.
79
+ * Rend { add: [rel], update: [rel], remove: [rel], unchanged: n, kept: [{ rel, reason }] }
80
+ */
81
+ function planFiles(remote, local, git) {
82
+ const plan = { add: [], update: [], remove: [], unchanged: 0, kept: [] };
83
+ const safe = (rel) => git.repo && git.tracked.has(rel) && !git.dirty.has(rel);
84
+ const why = (rel) => (!git.repo ? 'not in a git repository' : !git.tracked.has(rel) ? 'not tracked by git' : 'uncommitted changes');
85
+ for (const [rel, data] of remote) {
86
+ if (!mirrored(rel)) continue;
87
+ const here = local.get(rel);
88
+ if (!here) plan.add.push(rel);
89
+ else if (Buffer.compare(here, data) === 0) plan.unchanged++;
90
+ else if (safe(rel)) plan.update.push(rel);
91
+ else plan.kept.push({ rel, reason: why(rel), change: 'update' });
92
+ }
93
+ for (const rel of local.keys()) {
94
+ if (remote.has(rel)) continue;
95
+ if (safe(rel)) plan.remove.push(rel);
96
+ else plan.kept.push({ rel, reason: why(rel), change: 'remove' });
97
+ }
98
+ for (const k of ['add', 'update', 'remove']) plan[k].sort();
99
+ plan.kept.sort((a, b) => a.rel.localeCompare(b.rel));
100
+ return plan;
101
+ }
102
+
103
+ /** Fichiers de l'export (tar.gz en base64) → Map rel → Buffer */
104
+ function exportFiles(b64) {
105
+ const tar = require('../tar');
106
+ const entries = tar.readTar(tar.gunzip(Buffer.from(String(b64 || ''), 'base64')), { strip: 0 });
107
+ const out = new Map();
108
+ for (const e of entries) if (e.type === 'file' && mirrored(e.path)) out.set(e.path, Buffer.from(e.data));
109
+ return out;
110
+ }
111
+
112
+ /** Applique le plan dans poad/ */
113
+ function applyFiles(poadDir, plan, remote) {
114
+ for (const rel of [...plan.add, ...plan.update]) {
115
+ const abs = path.join(poadDir, rel);
116
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
117
+ fs.writeFileSync(abs, remote.get(rel));
118
+ }
119
+ for (const rel of plan.remove) fs.rmSync(path.join(poadDir, rel), { force: true });
120
+ }
121
+
122
+ module.exports = { MIRRORED, mirrored, localFiles, gitFiles, planFiles, exportFiles, applyFiles };