poad 2.54.0 → 2.55.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/global/cli.js CHANGED
@@ -31,6 +31,7 @@ module.exports = {
31
31
  description: 'Projects hosted on poad.io: list, create (and link this folder), info, pause, resume, engine upgrade',
32
32
  projects: 'The poad.io projects of your account',
33
33
  create: 'Create a poad.io project, then link this folder to it: cloud create [--name <name>] [--region paris]',
34
+ clone: 'A local folder from a poad.io project made in the console or by an AI (like git clone): poad init, link, then poad/ rebuilt from the engine (migrations with their SQL, functions, flows, references…): cloud clone <id> [folder] [--env <name>]',
34
35
  info: 'URL, anon key, state and engine of the linked poad.io project (never the service_role key)',
35
36
  pause: 'Pause the linked poad.io project (confirmation, --yes)',
36
37
  resume: 'Resume the linked poad.io project',
@@ -0,0 +1,123 @@
1
+ // poad cloud clone <id> [dossier] [--env <branche>] [--json]
2
+ // Le pendant de git clone pour un projet créé sur poad.io (console, MCP) : un
3
+ // dossier local, poad init, le lien vers le projet, puis poad/ reconstruit à
4
+ // partir de l'engine visé (production par défaut) :
5
+ // - ce que /project contient : migrations, fonctions, flows, auth, storage,
6
+ // api, références, variables, requêtes (jamais config.toml de poad.io, ni
7
+ // credentials/, ni types/) ;
8
+ // - chaque migration de l'historique avec son SQL d'origine (engine 0.55+),
9
+ // à l'octet près (son empreinte est vérifiée) ;
10
+ // - s'il manque le SQL d'une migration (appliquée avant, ou fichier perdu) :
11
+ // une migration de départ, la structure réelle des schémas du projet, qui
12
+ // remplace toutes les migrations jusqu'à la dernière appliquée (même
13
+ // version : poad deploy ne la rejoue pas, poad start la joue sur une base
14
+ // neuve).
15
+ // Les données (lignes des tables) ne sont pas copiées : tables de référence
16
+ // lourdes par poad ref load --local.
17
+ module.exports = (args, raw) =>
18
+ require('../../utils/cloud/cli').run(raw, { values: ['env'] }, async ({ opts, positionals, out }) => {
19
+ const fs = require('fs');
20
+ const os = require('os');
21
+ const path = require('path');
22
+ const crypto = require('crypto');
23
+ const { spawnSync } = require('child_process');
24
+ const api = require('../../utils/cloud/api');
25
+ const cli = require('../../utils/cloud/cli');
26
+ const { chalk } = out;
27
+
28
+ const id = cli.checkId(positionals[0] || '');
29
+ const branch = opts.env ? cli.checkBranch(opts.env) : 'main';
30
+ api.requireToken();
31
+ const project = await api.call('GET', `v1/projects/${api.enc(id)}`, { what: 'project' });
32
+ const slug = String(project.name || id).normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase() || id;
33
+ const target = path.resolve(positionals[1] || slug);
34
+ if (fs.existsSync(target) && fs.readdirSync(target).length) throw api.usageError(`${path.relative(process.cwd(), target) || '.'} is not empty: choose another folder (poad cloud clone ${id} <folder>)`);
35
+ if (cli.projectRoot() && target.startsWith(path.dirname(path.dirname(cli.projectRoot())) + path.sep)) {
36
+ out.log(chalk.yellowBright(' Note: the new folder is inside another poad project.'));
37
+ }
38
+
39
+ out.log(chalk.grey(` Reading ${id} (${branch}) on poad.io…`));
40
+ const ex = await api.call('GET', `v1/projects/${api.enc(id)}/branches/${api.enc(branch)}/export`, { what: 'export', timeout: 150000 });
41
+
42
+ // 1. Dossier, poad init (sans question), lien
43
+ fs.mkdirSync(target, { recursive: true });
44
+ const cwd = process.cwd();
45
+ process.chdir(target);
46
+ let root;
47
+ try {
48
+ const log = console.log;
49
+ if (out.json) console.log = () => {};
50
+ try {
51
+ await require('../init')({}, [], { setup: false });
52
+ } finally {
53
+ console.log = log;
54
+ }
55
+ root = path.join(target, 'poad', 'config.toml');
56
+ cli.writeLink(root, id);
57
+ } finally {
58
+ process.chdir(cwd);
59
+ }
60
+ const poadDir = path.dirname(root);
61
+
62
+ // 2. Fichiers de /project (archive tar.gz)
63
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-clone-'));
64
+ const tgz = path.join(tmp, 'project.tgz');
65
+ fs.writeFileSync(tgz, Buffer.from(ex.files || '', 'base64'));
66
+ const untar = spawnSync('tar', ['xzf', tgz, '-C', poadDir], { encoding: 'utf8' });
67
+ fs.rmSync(tmp, { recursive: true, force: true });
68
+ if (untar.status !== 0) throw new api.CloudError(`files not unpacked: ${String(untar.stderr).trim().slice(0, 200)}`, { code: 'clone_unpack' });
69
+
70
+ // 3. Migrations : chaque entrée de l'historique, avec son SQL quand il y est
71
+ const dir = path.join(poadDir, 'migrations');
72
+ fs.mkdirSync(dir, { recursive: true });
73
+ const sha = (t) => crypto.createHash('sha256').update(t).digest('hex');
74
+ const history = Array.isArray(ex.migrations) ? ex.migrations : [];
75
+ const fileOf = (m) => path.join(dir, `${m.version}_${m.name}.sql`);
76
+ const withoutSql = [];
77
+ let written = 0;
78
+ for (const m of history) {
79
+ if (!/^\d{14}$/.test(m.version) || !/^[A-Za-z0-9_-]+$/.test(m.name)) continue;
80
+ const f = fileOf(m);
81
+ if (fs.existsSync(f) && sha(fs.readFileSync(f)) === m.checksum) continue;
82
+ if (typeof m.sql === 'string' && sha(Buffer.from(m.sql, 'utf8')) === m.checksum) {
83
+ fs.writeFileSync(f, m.sql);
84
+ written++;
85
+ } else withoutSql.push(m);
86
+ }
87
+ let baseline = null;
88
+ if (withoutSql.length) {
89
+ // Une migration de départ remplace toutes les migrations jusqu'à la dernière appliquée
90
+ const last = history[history.length - 1];
91
+ for (const m of history) if (fs.existsSync(fileOf(m))) fs.rmSync(fileOf(m));
92
+ const { cleanDump } = require('../../project/db/pull');
93
+ // CREATE SCHEMA public échoue sur toute base (public existe) ; les extensions d'abord, pg_dump filtré par schéma ne les écrit pas
94
+ const body = cleanDump(ex.schema || '').split('\n').filter((l) => !/^CREATE SCHEMA public;\s*$/.test(l)).join('\n');
95
+ const ident = (x) => `"${String(x).replace(/"/g, '""')}"`;
96
+ const exts = (Array.isArray(ex.extensions) ? ex.extensions : []).filter((e) => e && typeof e.name === 'string' && typeof e.schema === 'string');
97
+ const extSql = exts.length ? `${[...new Set(exts.map((e) => e.schema))].filter((n) => n !== 'public' && n !== 'pg_catalog').map((n) => `create schema if not exists ${ident(n)};`).join('\n')}\n${exts.map((e) => `create extension if not exists ${ident(e.name)} with schema ${ident(e.schema)};`).join('\n')}\n\n` : '';
98
+ const file = path.join(dir, `${last.version}_${last.name}.sql`);
99
+ fs.writeFileSync(
100
+ file,
101
+ `-- poad:baseline\n-- Migration de départ écrite par poad cloud clone (${new Date().toISOString().slice(0, 10)}) : la structure réelle des schémas du projet\n` +
102
+ `-- sur poad.io (${id}, ${branch}), à la place des ${history.length} migration(s) appliquée(s) jusqu'à ${last.version}, dont ${withoutSql.length} sans leur SQL.\n` +
103
+ `-- Même version que la dernière appliquée : poad deploy ne la rejoue pas ; poad start la joue sur une base neuve.\n\n` +
104
+ `set check_function_bodies = off;\n\n${extSql}${body}\n`,
105
+ );
106
+ baseline = { file: path.relative(cwd, file), replaces: history.length, without_sql: withoutSql.length };
107
+ }
108
+
109
+ const count = (d) => {
110
+ try {
111
+ return fs.readdirSync(path.join(poadDir, d)).filter((f) => !f.startsWith('.')).length;
112
+ } catch {
113
+ return 0;
114
+ }
115
+ };
116
+ const summary = { project: id, branch, folder: path.relative(cwd, target) || '.', migrations: count('migrations'), migrations_restored: written, baseline, functions: count('functions'), flows: count('flows'), references: count('reference') };
117
+ out.result(summary);
118
+ out.log(`${chalk.greenBright('✔')} ${project.name || id} cloned into ${chalk.bold(summary.folder)} (${branch}), linked to ${id}`);
119
+ out.log(chalk.grey(` migrations ${summary.migrations}${written ? ` (${written} restored from their SQL on poad.io)` : ''}, functions ${summary.functions}, flows ${summary.flows}, reference tables ${summary.references}`));
120
+ if (baseline) out.log(chalk.yellowBright(` ${baseline.without_sql} migration(s) had lost their SQL: ${baseline.file} is a starting migration with the real structure, in place of the ${baseline.replaces} applied ones.`));
121
+ out.log(chalk.grey(` Credentials are not copied (secrets): set them in the local console. Data: poad ref load --local for heavy reference tables.`));
122
+ out.log(chalk.grey(` Next: cd ${summary.folder} && poad start`));
123
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.54.0",
3
+ "version": "2.55.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
@@ -44,6 +44,7 @@ module.exports = (args, raw) =>
44
44
  const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
45
45
  const r = await S.loadLocal(config.project_uuid, d);
46
46
  out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
47
+ for (const w of r.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
47
48
  results.push({ target, ...r });
48
49
  }
49
50
  out.result({ project: id, local: true, tables: results });
@@ -97,7 +97,10 @@ async function startAndWait(id, branch, targets, opts, out) {
97
97
  for (const s of st.steps) {
98
98
  if (done.has(s.target) || !['done', 'failed'].includes(s.status)) continue;
99
99
  done.add(s.target);
100
- if (s.status === 'done') out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
100
+ if (s.status === 'done') {
101
+ out.log(`${chalk.greenBright('✔')} ${s.target} loaded into ${branch}: ${s.written} rows written, ${s.deleted} removed (${(s.duration_ms / 1000).toFixed(1)} s)`);
102
+ for (const w of s.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
103
+ }
101
104
  else out.log(`${chalk.redBright('✖')} ${s.target}: ${s.error}`);
102
105
  }
103
106
  },
@@ -91,10 +91,17 @@ async function ensureHistory(client) {
91
91
  checksum text not null,
92
92
  applied_at timestamptz not null default now()
93
93
  );
94
+ alter table poad_migrations.history add column if not exists sql text;
94
95
  revoke all on schema poad_migrations from public;
95
96
  `);
96
97
  }
97
98
 
99
+ /**
100
+ * Migration de départ (poad cloud clone) : la structure réelle, à la version de la dernière appliquée ;
101
+ * son empreinte diffère de celle de l'historique sans que ce soit un changement après coup
102
+ */
103
+ const isBaseline = (m) => typeof m.sql === 'string' && m.sql.startsWith('-- poad:baseline');
104
+
98
105
  /** État : appliquées, en attente, modifiées après application, absentes du dossier */
99
106
  async function status(root, client) {
100
107
  const { list, ignored } = files(root);
@@ -105,10 +112,10 @@ async function status(root, client) {
105
112
  return {
106
113
  list: list.map((m) => {
107
114
  const row = applied.get(m.version);
108
- return { ...m, applied: row ? row.applied_at : null, changed: Boolean(row && row.checksum !== m.checksum) };
115
+ return { ...m, applied: row ? row.applied_at : null, changed: Boolean(row && row.checksum !== m.checksum && !isBaseline(m)) };
109
116
  }),
110
117
  pending: list.filter((m) => !applied.has(m.version)),
111
- changed: list.filter((m) => applied.has(m.version) && applied.get(m.version).checksum !== m.checksum),
118
+ changed: list.filter((m) => applied.has(m.version) && applied.get(m.version).checksum !== m.checksum && !isBaseline(m)),
112
119
  missing: rows.filter((r) => !local.has(r.version)),
113
120
  ignored,
114
121
  };
@@ -136,7 +143,8 @@ async function migrate(root, config, { onApply } = {}) {
136
143
  try {
137
144
  await client.query('begin');
138
145
  await client.query(m.sql);
139
- await client.query('insert into poad_migrations.history (version, name, checksum) values ($1, $2, $3)', [m.version, m.name, m.checksum]);
146
+ // Le SQL part avec l'historique : un fichier perdu se reconstruit (poad cloud clone)
147
+ await client.query('insert into poad_migrations.history (version, name, checksum, sql) values ($1, $2, $3, $4)', [m.version, m.name, m.checksum, m.sql]);
140
148
  await client.query('commit');
141
149
  applied.push(m);
142
150
  if (onApply) onApply(m);
@@ -266,7 +274,7 @@ async function saveChanges(root, client, name, sql, upTo) {
266
274
  await client.query("select set_config('poad.migrating', 'on', true)");
267
275
  await client.query('select pg_advisory_xact_lock($1)', [LOCK_ID]);
268
276
  await ensureHistory(client);
269
- await client.query('insert into poad_migrations.history (version, name, checksum) values ($1, $2, $3)', [m[1], m[2], checksum(content)]);
277
+ await client.query('insert into poad_migrations.history (version, name, checksum, sql) values ($1, $2, $3, $4)', [m[1], m[2], checksum(content), content]);
270
278
  await client.query('delete from poad_migrations.journal where id <= $1', [upTo]);
271
279
  await client.query('select poad_migrations.snapshot()');
272
280
  fs.writeFileSync(file, content);
@@ -51,11 +51,23 @@ function head(target, columns) {
51
51
  ].join('\n');
52
52
  }
53
53
 
54
- /** Séquences (serial, identity) : elles repartent après le plus grand identifiant */
55
- const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq
54
+ /**
55
+ * Séquences (serial, identity) des colonnes ENTIÈRES : elles repartent après le plus grand identifiant.
56
+ * Une séquence attachée à une colonne d'un autre type (héritage d'un ancien schéma) est laissée telle
57
+ * quelle, avec un avertissement qui la nomme ; un échec de recalage n'annule pas le chargement.
58
+ */
59
+ const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_sequence(t::text, a.attname) as seq, a.atttypid in ('int2'::regtype, 'int4'::regtype, 'int8'::regtype) as whole
56
60
  from pg_attribute a where a.attrelid = t and a.attnum > 0 and not a.attisdropped loop
57
- if s.seq is not null then
58
- execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
61
+ if s.seq is null then
62
+ continue;
63
+ elsif not s.whole then
64
+ raise warning 'poad-seed séquence % non recalée : colonne %.% non entière', s.seq, t, s.col;
65
+ else
66
+ begin
67
+ execute format('select setval(%L, coalesce((select max(%I) from %s), 0) + 1, false)', s.seq, s.col, t);
68
+ exception when others then
69
+ raise warning 'poad-seed séquence % non recalée : %', s.seq, sqlerrm;
70
+ end;
59
71
  end if;
60
72
  end loop;`;
61
73
 
package/utils/seed/run.js CHANGED
@@ -197,7 +197,8 @@ async function loadLocal(container, d, { database } = {}) {
197
197
  const detail = lines.find((l) => /^DETAIL:/.test(l));
198
198
  throw new api.CloudError(`${d.target}: ${e}${detail ? ` — ${detail.replace(/^DETAIL:\s+/, '')}` : ''}`, { code: 'seed_load_failed' });
199
199
  }
200
- return A.parseNotice(out) || { written: null, deleted: null };
200
+ const warnings = out.split('\n').filter((l) => /WARNING:.*poad-seed/.test(l)).map((l) => l.replace(/^.*WARNING:\s+([0-9A-Z]{5}:\s+)?poad-seed\s+/, ''));
201
+ return { ...(A.parseNotice(out) || { written: null, deleted: null }), warnings };
201
202
  }
202
203
 
203
204
  /** Dépendances entre tables de l'engine local (ordre de chargement) */