poad 2.75.1 → 2.75.3

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.
@@ -0,0 +1,98 @@
1
+ // Types pour l'éditeur des fonctions du projet (poad/functions) : lus sur
2
+ // l'engine lancé (/functions/v1/types.json, accordés à son runtime) et déposés
3
+ // dans poad/functions/.poad/types, avec le tsconfig.json qui les relie.
4
+ // poad functions types les pose à la demande ; poad start les rafraîchit, pour
5
+ // qu'un projet ne garde pas les types d'une engine plus ancienne (murex :
6
+ // flowStep absent des types alors que le runtime l'exporte).
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+
10
+ // tsconfig.json de poad/functions : API web (celles de workerd) et @poadio/*
11
+ // relié aux types déposés par l'engine. Il inclut le .d.ts de @poadio/functions
12
+ // lui-même : ses déclarations globales (fetch qui accepte tout ArrayBufferView,
13
+ // comme workerd) valent aussi pour une fonction qui ne l'importe pas.
14
+ const TSCONFIG = `{
15
+ "compilerOptions": {
16
+ "target": "ES2022",
17
+ "module": "ESNext",
18
+ "moduleResolution": "bundler",
19
+ "lib": ["ES2022", "WebWorker"],
20
+ "types": [],
21
+ "strict": true,
22
+ "noEmit": true,
23
+ "skipLibCheck": true,
24
+ "allowImportingTsExtensions": true,
25
+ "paths": {
26
+ "@poadio/*": ["./.poad/types/@poadio/*/index.d.ts"]
27
+ }
28
+ },
29
+ "include": ["**/*.ts", "**/*.tsx", ".poad/types/@poadio/functions/index.d.ts"],
30
+ "exclude": ["node_modules"]
31
+ }
32
+ `;
33
+ // Le tsconfig écrit par les CLI précédents : remplacé tel quel, jamais un tsconfig modifié à la main
34
+ const OLD_TSCONFIGS = [TSCONFIG.replace(', ".poad/types/@poadio/functions/index.d.ts"', '')];
35
+
36
+ const TYPE_FILE_RE = /^@poadio\/[a-z][a-z0-9-]*(\/[A-Za-z0-9_-]+)*\/[A-Za-z0-9_.-]+\.d\.ts$/;
37
+
38
+ /** Fichiers de types valides d'une réponse de /types.json */
39
+ const typeFiles = (bundle) =>
40
+ Object.entries((bundle && bundle.files) || {}).filter(([name, text]) => TYPE_FILE_RE.test(name) && !name.includes('..') && typeof text === 'string');
41
+
42
+ /** Lit les types sur l'engine lancé ; réessaie pendant `waitSeconds` le temps que le service functions démarre */
43
+ async function fetchBundle(config, waitSeconds = 0) {
44
+ const deadline = Date.now() + waitSeconds * 1000;
45
+ for (;;) {
46
+ try {
47
+ const res = await fetch(`http://localhost:${config.web.port}/functions/v1/types.json`, { signal: AbortSignal.timeout(5000) });
48
+ if (res.ok) return await res.json();
49
+ } catch {
50
+ /* engine pas encore prêt, ou sans service functions */
51
+ }
52
+ if (Date.now() >= deadline) return null;
53
+ await new Promise((r) => setTimeout(r, 1000));
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Dépose les types dans <dir>/.poad/types (dir = poad/functions) et pose ou met à
59
+ * niveau tsconfig.json. Renvoie { count, changed } ou null si l'engine ne les sert pas.
60
+ */
61
+ function write(dir, bundle) {
62
+ const files = typeFiles(bundle);
63
+ if (!files.length) return null;
64
+ const typesDir = path.join(dir, '.poad', 'types');
65
+ const read = (p) => {
66
+ try {
67
+ return fs.readFileSync(p, 'utf8');
68
+ } catch {
69
+ return null;
70
+ }
71
+ };
72
+ const listed = (d, prefix = '') =>
73
+ !fs.existsSync(d)
74
+ ? []
75
+ : fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? listed(path.join(d, e.name), `${prefix}${e.name}/`) : [`${prefix}${e.name}`]));
76
+ const same = listed(typesDir).sort().join('\n') === files.map(([n]) => n).sort().join('\n') && files.every(([n, text]) => read(path.join(typesDir, n)) === text);
77
+ if (!same) {
78
+ fs.rmSync(typesDir, { recursive: true, force: true });
79
+ for (const [name, text] of files) {
80
+ const target = path.join(typesDir, name);
81
+ fs.mkdirSync(path.dirname(target), { recursive: true });
82
+ fs.writeFileSync(target, text);
83
+ }
84
+ }
85
+ // L'ancien fichier de types (client en « any ») masquerait les nouveaux
86
+ const old = path.join(dir, 'poad-functions.d.ts');
87
+ if (fs.existsSync(old) && fs.readFileSync(old, 'utf8').startsWith('// Généré par poad')) fs.rmSync(old);
88
+ const tsconfig = path.join(dir, 'tsconfig.json');
89
+ const current = read(tsconfig);
90
+ let tsconfigChanged = false;
91
+ if (current === null || OLD_TSCONFIGS.includes(current)) {
92
+ fs.writeFileSync(tsconfig, TSCONFIG);
93
+ tsconfigChanged = true;
94
+ }
95
+ return { count: files.length, changed: !same || tsconfigChanged };
96
+ }
97
+
98
+ module.exports = { TSCONFIG, OLD_TSCONFIGS, typeFiles, fetchBundle, write };
@@ -328,14 +328,16 @@ const sheets = {
328
328
  ],
329
329
  },
330
330
  migrate: {
331
- usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
331
+ usage: ['poad migrate', 'poad migrate --dry-run', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
332
332
  text: [
333
333
  'Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).',
334
+ 'Before applying, reads the pending migrations (never run for this) and counts on the database what they would lose: DROP TABLE, DROP COLUMN (non-null values), ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA, and what breaks API clients (RENAME TABLE / COLUMN, DROP VIEW / FUNCTION served to anon or authenticated). Silent when the target does not exist yet (created by the same batch) or is empty; otherwise a warning with file, statement and number of rows. Locally a warning only (poad deploy asks to confirm on production). Logs: poad logs cli event=migration_data_loss_check.',
334
335
  'Then warns (never blocks) about functions and views granted to anon or authenticated that the API does not serve them (403 not_exposed: SECURITY DEFINER functions, views without security_invoker, materialized views), each with its fix; the ones a migration just created also go to the log sink (poad logs cli event=api_exposure).',
335
336
  ],
336
337
  options: [
338
+ ['--dry-run', 'the pending migrations and the data they would lose (counted on the database), nothing applied'],
337
339
  ['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)'],
338
- ['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
340
+ ['--json', 'one JSON object: applied, failed, pending, data_loss ([{ file, line, statement, target, rows, kind, decision }]), api_exposure (items with reason, roles, fix, created), unprotected tables'],
339
341
  ['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
340
342
  ['pull', 'same as poad migration pull'],
341
343
  ['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
@@ -482,7 +484,7 @@ Object.assign(sheets, {
482
484
  notes: [EXIT_NOTE],
483
485
  },
484
486
  deploy: {
485
- usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
487
+ usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--allow-destructive] [--json]'],
486
488
  text: [
487
489
  'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
488
490
  'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
@@ -490,11 +492,13 @@ Object.assign(sheets, {
490
492
  options: [
491
493
  ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
492
494
  ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
493
- ['--yes', 'no question for production (required outside a terminal)'],
495
+ ['--yes', 'no question for production (required outside a terminal); does not accept a data loss'],
496
+ ['--allow-destructive', 'production: apply migrations that lose data without asking (required outside a terminal when they do); alias --accept-data-loss'],
494
497
  PROJECT_OPT,
495
498
  JSON_OPT,
496
499
  ],
497
500
  notes: [
501
+ 'Before applying, poad.io counts on the database of the environment what the pending migrations would lose (DROP TABLE, DROP COLUMN, ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA; RENAME and DROP VIEW / FUNCTION served by the API break clients): nothing is said when the target is created by the same deploy or is empty; otherwise file, statement and number of rows (data_loss in --json, --dry-run included). Production: a loss of data needs a confirmation in a terminal, or --allow-destructive; refused otherwise (exit code 4), nothing changed. Other environments: a warning.',
498
502
  'Production (main): a summary, then a confirmation (none for --dry-run, which changes nothing). Uncommitted changes in poad/: a warning, and no commit id is sent (the commit id is sent when poad/ is clean).',
499
503
  EXIT_NOTE,
500
504
  ],
@@ -2,7 +2,7 @@
2
2
  const path = require('path');
3
3
 
4
4
  // report : objet rempli pour --json (applied, failed, api_exposure, unprotected, queries)
5
- module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false } = {}) => {
5
+ module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false, dryRun = false, via = 'poad migrate' } = {}) => {
6
6
  const chalk = require('chalk-v2');
7
7
  const migrations = require('./migrations');
8
8
  const rel = (p) => path.relative(process.cwd(), p);
@@ -10,6 +10,12 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
10
10
  let result;
11
11
  try {
12
12
  result = await migrations.migrate(root, config, {
13
+ dryRun,
14
+ via,
15
+ // Avant la première migration appliquée : ce qui sera perdu (silence si la cible est absente ou vide)
16
+ onDataLoss: (list) => {
17
+ for (const l of dataLossLines(list, chalk, { local: true })) console.log(l);
18
+ },
13
19
  onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
14
20
  });
15
21
  } catch (err) {
@@ -19,6 +25,7 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
19
25
  const { applied, failed, state } = result;
20
26
  if (report) {
21
27
  Object.assign(report, {
28
+ data_loss: require('./data-loss').jsonOf(result.dataLoss || []),
22
29
  applied: applied.map((m) => m.file),
23
30
  failed: failed ? { file: failed.migration.file, message: failed.message } : null,
24
31
  pending: state.pending.filter((m) => !applied.includes(m)).map((m) => m.file),
@@ -28,6 +35,11 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
28
35
  });
29
36
  }
30
37
 
38
+ if (dryRun) {
39
+ for (const m of state.pending) console.log(` ${chalk.yellow('○')} ${m.file} ${chalk.grey('(would be applied)')}`);
40
+ console.log(state.pending.length ? chalk.bold(` Dry run: ${state.pending.length} pending migration(s), nothing applied.`) : chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
41
+ return true;
42
+ }
31
43
  for (const m of state.changed) {
32
44
  console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
33
45
  }
@@ -69,3 +81,22 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
69
81
  for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
70
82
  return qr.errors.length === 0;
71
83
  };
84
+
85
+ /**
86
+ * Lignes d'avertissement des pertes de données (utils/data-loss.js), partagées avec poad deploy :
87
+ * « ⚠ fichier:ligne DROP COLUMN public.t.c — 1,240 non-null value(s) will be lost », puis l'instruction.
88
+ * local : la base du poste (avertissement seul) ; sinon le mot de la décision de poad.io.
89
+ */
90
+ function dataLossLines(list, chalk, { local = false, production = false } = {}) {
91
+ const shown = (list || []).filter((d) => d && d.decision !== 'silent' && d.message);
92
+ if (!shown.length) return [];
93
+ const out = [`${chalk.yellowBright('⚠')} ${chalk.bold('Pending migrations lose data or break API clients:')}`];
94
+ for (const d of shown) {
95
+ out.push(` ${chalk.yellow(`${d.file}${d.line ? `:${d.line}` : ''}`)} ${d.loss ? chalk.yellowBright(d.message) : d.message}`);
96
+ if (d.statement) out.push(chalk.grey(` ${d.statement}`));
97
+ }
98
+ if (local) out.push(chalk.grey(' Local database: applied anyway. On the production of poad.io, poad deploy asks to confirm (or --allow-destructive).'));
99
+ else if (production && shown.some((d) => d.decision === 'confirm')) out.push(chalk.grey(' Production: data is lost only after a confirmation (terminal) or with --allow-destructive.'));
100
+ return out;
101
+ }
102
+ module.exports.dataLossLines = dataLossLines;
@@ -137,12 +137,17 @@ function lineOf(sql, position) {
137
137
  * transaction est annulée, les suivantes ne sont pas tentées).
138
138
  * Renvoie { applied: [...], failed: { migration, message } | null, state }.
139
139
  */
140
- async function migrate(root, config, { onApply } = {}) {
140
+ async function migrate(root, config, { onApply, onDataLoss, dryRun = false, via = 'poad migrate' } = {}) {
141
141
  const client = await connect(config);
142
142
  const applied = [];
143
143
  try {
144
144
  await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
145
145
  const state = await status(root, client);
146
+ // Avant d'appliquer : ce que les migrations en attente perdent vraiment sur cette base (utils/data-loss.js).
147
+ // En local, un avertissement seulement (la confirmation est pour la production de poad.io, poad deploy).
148
+ const dataLoss = state.pending.length ? await dataLossCheck(client, state.pending, config, dryRun ? `${via} --dry-run` : via) : [];
149
+ if (onDataLoss) onDataLoss(dataLoss);
150
+ if (dryRun) return { applied, failed: null, state, dataLoss, dryRun: true };
146
151
  // Ce que l'API ne sert pas à anon ni à authenticated alors qu'ils en ont le droit, avant les migrations : ce
147
152
  // qu'elles font apparaître est signalé et va au puits de logs (event=api_exposure)
148
153
  const exposure = require('./api-exposure');
@@ -159,7 +164,7 @@ async function migrate(root, config, { onApply } = {}) {
159
164
  } catch (err) {
160
165
  await client.query('rollback').catch(() => {});
161
166
  const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
162
- return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
167
+ return { applied, failed: { migration: m, message: `${err.message}${where}` }, state, dataLoss };
163
168
  }
164
169
  }
165
170
  // Empreinte de la structure après les migrations (journal des changements)
@@ -170,13 +175,34 @@ async function migrate(root, config, { onApply } = {}) {
170
175
  const unprotected = await unprotectedTables(client, exposedSchemas(config));
171
176
  const apiExposure = exposure.afterMigrate({ engine: config.engine, before, after: await exposure.query(client, exposedSchemas(config)) });
172
177
  if (apiExposure.created.length) await logApiExposure(client, apiExposure, applied);
173
- return { applied, failed: null, state, queries, unprotected, apiExposure };
178
+ return { applied, failed: null, state, queries, unprotected, apiExposure, dataLoss };
174
179
  } finally {
175
180
  await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
176
181
  await client.end().catch(() => {});
177
182
  }
178
183
  }
179
184
 
185
+ /**
186
+ * Pertes de données des migrations en attente, comptées sur la base locale (lecture seule, délai court). Une ligne
187
+ * par constat dans le puits (service cli, event=migration_data_loss_check ; debug quand rien n'est perdu) : fichier,
188
+ * genre, cible, nombre de lignes, décision ; jamais d'instruction ni de valeur. Une erreur ici ne bloque jamais.
189
+ */
190
+ async function dataLossCheck(client, pending, config, via) {
191
+ const dl = require('./data-loss');
192
+ try {
193
+ const findings = dl.analyze(pending.map((m) => ({ file: m.file, sql: m.sql })));
194
+ if (!findings.length) return [];
195
+ const results = await dl.runChecks(client, dl.checks(findings));
196
+ const decided = dl.decide(findings, results, { production: false, exposedSchemas: exposedSchemas(config) });
197
+ const rows = decided.map((d) => [dl.levelOf(d), dl.logMsg(d), JSON.stringify(dl.logAttrs(d, { via, env: 'local' }))]);
198
+ for (const r of rows) await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", r).catch(() => {});
199
+ return decided;
200
+ } catch {
201
+ await client.query('rollback').catch(() => {});
202
+ return [];
203
+ }
204
+ }
205
+
180
206
  /**
181
207
  * Puits de logs (service cli, event=api_exposure) : une migration vient de créer des fonctions ou vues accordées à
182
208
  * anon ou authenticated que l'API ne leur sert pas. Noms et raisons seulement, jamais de SQL ni de secret.