poad 2.49.0 → 2.50.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.49.0",
3
+ "version": "2.50.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/project/cli.js CHANGED
@@ -28,7 +28,9 @@ module.exports = {
28
28
  env: {
29
29
  description: 'Environments (branches) of the linked poad.io project: main is production',
30
30
  ls: 'Environments of the project; the default of poad deploy is the current git branch if it exists there, else main',
31
- create: 'Create an environment: env create <name> [--kind persistent|preview]',
31
+ create: 'Create an environment, a clone of production by default: env create <name> [--kind persistent|preview] [--empty] [--with-data] [--credential <name>=production|custom]',
32
+ clone: 'Reclone an environment from production (everything but the data; --with-data: all of it): env clone <name> [--with-data] [--credential <name>=production|custom]',
33
+ sync: 'Old name of env clone',
32
34
  rm: 'Remove an environment, its database and files (confirmation, --yes); never main',
33
35
  },
34
36
  deploy: 'Send poad/ (migrations, functions, flows, api, auth, storage…, never a secret) to poad.io: deploy [--env <name>] [--dry-run] [--yes]',
package/project/deploy.js CHANGED
@@ -11,8 +11,8 @@
11
11
  // Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
12
12
  // terminal). Codes de sortie : 0 déployé, 5 déploiement en échec (erreurs de
13
13
  // migration), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
14
- const DONE = ['succeeded', 'success', 'done', 'deployed', 'completed', 'ok', 'failed', 'error', 'cancelled', 'canceled'];
15
- const FAILED = ['failed', 'error', 'cancelled', 'canceled'];
14
+ const DONE = ['succeeded', 'success', 'refused', 'done', 'deployed', 'completed', 'ok', 'failed', 'error', 'cancelled', 'canceled'];
15
+ const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
16
16
 
17
17
  const names = (list) => (Array.isArray(list) ? list : []).map((m) => (typeof m === 'string' ? m : m && (m.name || m.version || m.file || m.migration)) || '?');
18
18
  const errorsOf = (list) =>
@@ -20,9 +20,12 @@ const errorsOf = (list) =>
20
20
 
21
21
  /** Résultat d'un déploiement, ramené aux champs connus */
22
22
  function summarize(d = {}) {
23
- const m = d.migrations || {};
23
+ // poad.io rend { outcome, migrations_applied, migrations_pending, errors } (control/server.mjs, deployView) ;
24
+ // l'ancienne forme { status, migrations: { applied, pending, errors } } reste lue
25
+ const m = d.migrations || { applied: d.migrations_applied, pending: d.migrations_pending, errors: d.errors };
24
26
  const errors = errorsOf(m.errors || d.errors);
25
- const status = typeof d.status === 'string' ? d.status.toLowerCase() : null;
27
+ const raw = typeof d.status === 'string' ? d.status : typeof d.outcome === 'string' ? d.outcome : null;
28
+ const status = raw ? raw.toLowerCase() : null;
26
29
  return {
27
30
  deploy_id: typeof d.deploy_id === 'string' || typeof d.deploy_id === 'number' ? String(d.deploy_id) : typeof d.id === 'string' ? d.id : null,
28
31
  status,
@@ -0,0 +1,30 @@
1
+ // poad env clone <nom> [--with-data] [--credential <nom>=production|custom]… [--yes] [--project <id>] [--json]
2
+ // POST v1/projects/:id/branches/:nom/clone { with_data, credentials } : recloner un
3
+ // environnement depuis la production. Ce qu'il a en propre est remplacé (ses
4
+ // données seulement avec --with-data, alias --copy-data). La production n'est que lue.
5
+ module.exports = (args, raw) =>
6
+ require('../../utils/cloud/cli').run(raw, { values: ['project', 'credential'], multi: ['credential'], flags: ['copy-data', 'with-data'] }, async ({ opts, positionals, out }) => {
7
+ const api = require('../../utils/cloud/api');
8
+ const cli = require('../../utils/cloud/cli');
9
+ const clone = require('../../utils/cloud/clone');
10
+ const { chalk } = out;
11
+ if (positionals.length !== 1) throw api.usageError('Usage: poad env clone <name> [--with-data] [--credential <name>=production|custom]');
12
+ const name = cli.checkBranch(positionals[0]);
13
+ if (name === 'main') throw api.usageError('main is production: it is the source, never the target');
14
+ const withData = Boolean(opts['with-data'] || opts['copy-data']);
15
+ const credentials = clone.credentialChoices(opts.credential);
16
+ const { id } = cli.targetProject(opts);
17
+ await cli.confirm(
18
+ `Reclone ${name} from production (${clone.SUMMARY}${withData ? ', and all its data' : ''})? What ${name} has of its own is replaced.`,
19
+ { yes: opts.yes, json: out.json },
20
+ );
21
+ const r = await api.call('POST', `v1/projects/${api.enc(id)}/branches/${api.enc(name)}/clone`, {
22
+ body: { with_data: withData, ...(Object.keys(credentials).length ? { credentials } : {}) },
23
+ what: `clone of production into ${name}`,
24
+ timeout: 60000,
25
+ });
26
+ const kept = (r && Array.isArray(r.credentials_with_values) && r.credentials_with_values) || [];
27
+ out.log(`${chalk.greenBright('✔')} Clone of production into ${chalk.bold(name)} started${withData ? ' (with the data)' : ''}: "poad env ls" to follow.`);
28
+ if (kept.length) out.log(chalk.grey(` Credentials with the production value (same external accounts): ${kept.join(', ')}.`));
29
+ out.result({ id, name, with_data: withData, credentials_with_values: kept });
30
+ });
@@ -1,7 +1,11 @@
1
- // poad env create <nom> [--kind persistent|preview] [--project <id>] [--json]
2
- // POST v1/projects/:id/branches { name, kind }
1
+ // poad env create <nom> [--kind persistent|preview] [--empty] [--with-data] [--credential <nom>=production|custom]… [--project <id>] [--json]
2
+ // POST v1/projects/:id/branches { name, kind, clone, with_data, credentials }
3
+ // Par défaut, un clone de la production (comme la console) : tout sauf les
4
+ // données ; --with-data (alias --copy-data) : avec toutes les données (tables,
5
+ // utilisateurs, fichiers) ; --empty : un environnement vide. --credential :
6
+ // un choix par credential (sans lui : le défaut de poad.io).
3
7
  module.exports = (args, raw) =>
4
- require('../../utils/cloud/cli').run(raw, { values: ['project', 'kind'] }, async ({ opts, positionals, out }) => {
8
+ require('../../utils/cloud/cli').run(raw, { values: ['project', 'kind', 'credential'], multi: ['credential'], flags: ['copy-data', 'with-data', 'empty', 'clone'] }, async ({ opts, positionals, out }) => {
5
9
  const api = require('../../utils/cloud/api');
6
10
  const cli = require('../../utils/cloud/cli');
7
11
  const branches = require('../../utils/cloud/branches');
@@ -11,9 +15,16 @@ module.exports = (args, raw) =>
11
15
  const kind = opts.kind || 'persistent';
12
16
  if (!['persistent', 'preview'].includes(kind)) throw api.usageError('--kind is persistent or preview');
13
17
  const { id } = cli.targetProject(opts);
14
- const data = await api.call('POST', `v1/projects/${api.enc(id)}/branches`, { body: { name, kind }, what: `environment ${name}`, timeout: 60000 });
18
+ if (opts.empty && (opts.clone || opts['with-data'] || opts['copy-data'] || opts.credential)) throw api.usageError('--empty creates an empty environment: no --clone, --with-data nor --credential');
19
+ const clone = !opts.empty;
20
+ const withData = clone && Boolean(opts['with-data'] || opts['copy-data']);
21
+ const credentials = clone ? require('../../utils/cloud/clone').credentialChoices(opts.credential) : {};
22
+ const body = clone ? { name, kind, clone: true, ...(withData ? { with_data: true } : {}), ...(Object.keys(credentials).length ? { credentials } : {}) } : { name, kind, clone: false };
23
+ const data = await api.call('POST', `v1/projects/${api.enc(id)}/branches`, { body, what: `environment ${name}`, timeout: 60000 });
15
24
  const b = branches.normalize(data.branch || data) || { name, kind };
16
25
  out.log(`${chalk.greenBright('✔')} Environment ${chalk.bold(b.name)} created on ${id} ${chalk.grey(`(${b.kind || kind}${b.status ? `, ${b.status}` : ''})`)}.`);
26
+ if (clone) out.log(chalk.grey(` Production clone: ${require('../../utils/cloud/clone').SUMMARY}${withData ? ', and all its data (tables, users, files)' : ', no data'}; "poad env ls" to follow.`));
27
+ else out.log(chalk.grey(' Empty: its first "poad deploy --env" applies the migrations, then poad/seed.sql.'));
17
28
  out.log(chalk.grey(` "poad deploy --env ${b.name}" deploys to it (also by default from the git branch ${b.name}).`));
18
- out.result(b);
29
+ out.result({ ...b, clone, with_data: withData, credentials });
19
30
  });
@@ -0,0 +1,2 @@
1
+ // poad env sync : ancien nom de poad env clone (gardé)
2
+ module.exports = require('./clone');
@@ -95,19 +95,21 @@ function fakeCloud(t, behaviour = {}) {
95
95
  state.branches[id] = state.branches[id].filter((b) => b.name !== branch);
96
96
  return send(res, 200, { removed: branch });
97
97
  }
98
+ if (req.method === 'POST' && (m[2] === '/clone' || m[2] === '/sync')) return send(res, 200, { name: branch, status: 'active', status_detail: 'copie depuis la production : measure', credentials_with_values: ['claude'] });
98
99
  if (req.method === 'POST' && m[2] === '/deploy') {
99
100
  const dry = req.headers['x-poad-dry-run'] === '1';
100
101
  if (behaviour.async) {
101
102
  state.deploys.d1 = 0;
102
- return send(res, 202, { deploy_id: 'd1', status: 'running' });
103
+ // La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
104
+ return send(res, 202, { deploy_id: 'd1', outcome: 'running', migrations_applied: [], migrations_pending: [], errors: [] });
103
105
  }
104
106
  return send(res, 200, { status: 'succeeded', dry_run: dry, migrations: dry ? { applied: [], pending: ['20261101000000_init'], errors: [] } : { applied: ['20261101000000_init'], pending: [], errors: [] } });
105
107
  }
106
108
  const dm = /^\/deploys\/([^/]+)$/.exec(m[2] || '');
107
109
  if (req.method === 'GET' && dm) {
108
110
  state.deploys[dm[1]]++;
109
- if (state.deploys[dm[1]] < 2) return send(res, 200, { deploy_id: dm[1], status: 'running' });
110
- return send(res, 200, { deploy_id: dm[1], status: 'failed', migrations: { applied: [], pending: [], errors: [{ migration: '20261101000000_init', message: 'relation "x" already exists' }] } });
111
+ if (state.deploys[dm[1]] < 2) return send(res, 200, { deploy_id: dm[1], outcome: 'running', migrations_applied: [], migrations_pending: [], errors: [] });
112
+ return send(res, 200, { deploy_id: dm[1], outcome: 'failed', migrations_applied: [], migrations_pending: [], errors: [{ migration: '20261101000000_init', message: 'relation "x" already exists' }] });
111
113
  }
112
114
  }
113
115
  return err(res, 404, 'not_found', `no route ${req.method} ${route}`);
@@ -398,9 +400,36 @@ test('env ls / create / rm : confirmation, --yes, main jamais supprimé', async
398
400
 
399
401
  const c = await poad(box, cloud.api, ['env', 'create', 'feature/x', '--kind', 'preview', '--json']);
400
402
  assert.strictEqual(c.status, 0, c.all);
401
- assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'feature/x', kind: 'preview' });
403
+ // Par défaut, un clone de la production (comme la console), sans les données
404
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'feature/x', kind: 'preview', clone: true });
402
405
  const badKind = await poad(box, cloud.api, ['env', 'create', 'y', '--kind', 'forever']);
403
406
  assert.strictEqual(badKind.status, 2);
407
+ // --with-data (alias --copy-data) et un choix par credential (répétable, ou séparé par des virgules)
408
+ const withData = await poad(box, cloud.api, ['env', 'create', 'recette', '--with-data', '--credential', 'smtp-prod=custom', '--credential', 'claude=production', '--json']);
409
+ assert.strictEqual(withData.status, 0, withData.all);
410
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'recette', kind: 'persistent', clone: true, with_data: true, credentials: { 'smtp-prod': 'custom', claude: 'production' } });
411
+ const legacy = await poad(box, cloud.api, ['env', 'create', 'qa', '--copy-data', '--json']);
412
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'qa', kind: 'persistent', clone: true, with_data: true }, legacy.all);
413
+ // --empty : vide ; incompatible avec les options du clone
414
+ const empty = await poad(box, cloud.api, ['env', 'create', 'vide', '--empty', '--json']);
415
+ assert.strictEqual(empty.status, 0, empty.all);
416
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'vide', kind: 'persistent', clone: false });
417
+ assert.strictEqual((await poad(box, cloud.api, ['env', 'create', 'x', '--empty', '--with-data'])).status, 2);
418
+ assert.strictEqual((await poad(box, cloud.api, ['env', 'create', 'x', '--credential', 'smtp=copie'])).status, 2);
419
+
420
+ // Recloner depuis la production : confirmation, --yes, jamais main ; sync reste un alias
421
+ const syncNoYes = await poad(box, cloud.api, ['env', 'clone', 'dev']);
422
+ assert.strictEqual(syncNoYes.status, 4);
423
+ assert.ok(!cloud.requests.some((q) => q.route.endsWith('/clone')));
424
+ const sync = await poad(box, cloud.api, ['env', 'clone', 'dev', '--with-data', '--credential', 'claude=production', '--yes', '--json']);
425
+ assert.strictEqual(sync.status, 0, sync.all);
426
+ assert.strictEqual(cloud.requests.at(-1).route, `v1/projects/${PID}/branches/dev/clone`);
427
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { with_data: true, credentials: { claude: 'production' } });
428
+ const alias = await poad(box, cloud.api, ['env', 'sync', 'dev', '--yes', '--json']);
429
+ assert.strictEqual(alias.status, 0, alias.all);
430
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { with_data: false });
431
+ const syncMain = await poad(box, cloud.api, ['env', 'sync', 'main', '--yes']);
432
+ assert.strictEqual(syncMain.status, 2);
404
433
 
405
434
  const noYes = await poad(box, cloud.api, ['env', 'rm', 'feature/x']);
406
435
  assert.strictEqual(noYes.status, 4);
@@ -8,9 +8,10 @@ const { CloudError, EXIT, usageError } = require('./api');
8
8
  * Options des mots tapés : « --env x », « --env=x », « env=x » pour les
9
9
  * options à valeur ; « --yes », « -y », « yes » pour les drapeaux ; le reste
10
10
  * est positionnel. Une option à valeur sans valeur : erreur d'usage.
11
- * spec : { values: ['env', 'name'], flags: ['yes', 'json'], alias: { y: 'yes' } }
11
+ * spec : { values: ['env', 'name'], flags: ['yes', 'json'], alias: { y: 'yes' }, multi: ['credential'] }
12
+ * multi : options à valeur répétables (un tableau, dans l'ordre)
12
13
  */
13
- function parse(raw = [], { values = [], flags = [], alias = {} } = {}) {
14
+ function parse(raw = [], { values = [], flags = [], alias = {}, multi = [] } = {}) {
14
15
  const opts = {};
15
16
  const positionals = [];
16
17
  const words = raw.map(String);
@@ -29,7 +30,8 @@ function parse(raw = [], { values = [], flags = [], alias = {} } = {}) {
29
30
  if (i + 1 >= words.length || /^--?[A-Za-z]/.test(words[i + 1])) throw usageError(`--${key} needs a value`);
30
31
  v = words[++i];
31
32
  }
32
- opts[key] = v;
33
+ if (multi.includes(key)) (opts[key] = opts[key] || []).push(v);
34
+ else opts[key] = v;
33
35
  } else if (flags.includes(key)) {
34
36
  opts[key] = true;
35
37
  } else {
@@ -0,0 +1,28 @@
1
+ // Clone de la production vers un environnement (poad env create, poad env clone) :
2
+ // les choix des credentials, « production » (sa valeur reprise : le même compte
3
+ // extérieur réel) ou « custom » (créé vide, à compléter dans l'environnement).
4
+ // Sans choix, poad.io applique son défaut : l'IA reprend la production, le
5
+ // reste (SMTP, paiement, bases et API extérieures) est à saisir.
6
+ const api = require('./api');
7
+
8
+ const NAME = /^[a-z][a-z0-9-]{0,62}$/;
9
+ const MODES = { production: 'production', prod: 'production', custom: 'custom', personnalise: 'custom' };
10
+
11
+ /** --credential nom=production|custom (répétable, ou séparé par des virgules) -> { nom: mode } */
12
+ function credentialChoices(values) {
13
+ const out = {};
14
+ for (const item of [].concat(values || []).flatMap((v) => String(v).split(','))) {
15
+ const s = item.trim();
16
+ if (!s) continue;
17
+ const m = /^([^=]+)=(.+)$/.exec(s);
18
+ const mode = m && MODES[m[2].trim().toLowerCase()];
19
+ if (!m || !NAME.test(m[1].trim()) || !mode) throw api.usageError(`--credential ${s}: expected <name>=production|custom`);
20
+ out[m[1].trim()] = mode;
21
+ }
22
+ return out;
23
+ }
24
+
25
+ /** Ce que le clone reprend, en une phrase (sortie texte) */
26
+ const SUMMARY = 'structure and migration history, code, settings (auth, e-mail templates, AI models, buckets), variables and credentials';
27
+
28
+ module.exports = { credentialChoices, SUMMARY };
@@ -239,13 +239,15 @@ Object.assign(sheets, {
239
239
  },
240
240
  unlink: { usage: ['poad unlink [--json]'], text: ['Remove [cloud] project from poad/config.toml. Nothing changes on poad.io.'], options: [JSON_OPT] },
241
241
  env: {
242
- usage: ['poad env ls', 'poad env create <name> [--kind persistent|preview]', 'poad env rm <name> [--yes]'],
242
+ usage: ['poad env ls', 'poad env create <name> [--kind persistent|preview] [--empty] [--with-data] [--credential <name>=production|custom]…', 'poad env clone <name> [--with-data] [--credential <name>=production|custom]… [--yes]', 'poad env rm <name> [--yes]'],
243
243
  text: [
244
244
  'Environments of the linked poad.io project: one branch each, with its own database and files; main is production. poad deploy, poad db url and poad db pull use the current git branch when an environment of that name exists, else main; --env <name> chooses.',
245
245
  ],
246
246
  options: [
247
247
  ['ls', 'the environments (the default one is marked)'],
248
- ['create <name>', 'a new environment; --kind persistent (default, kept) or preview (short-lived)'],
248
+ ['create <name>', 'a new environment, by default a clone of production: structure and migration history, code, settings, variables and credentials, without the data; --with-data: all the data too (tables, auth users, storage files); --empty: an empty environment; --kind persistent (default) or preview'],
249
+ ['clone <name>', 'reclone an environment from production (asks first, --yes outside a terminal); what it has of its own is replaced; --with-data: its data too. Production is only read. (sync: old name)'],
250
+ ['--credential <name>=production|custom', 'per credential: production reuses its value (the same external account: real e-mails, billed AI calls…), custom creates it empty to fill in the environment. Default: AI credentials production, the others custom'],
249
251
  ['rm <name>', 'remove an environment with its database and files (asks first, --yes outside a terminal); main is never removed here'],
250
252
  PROJECT_OPT,
251
253
  JSON_OPT,