poad 2.12.0 → 2.14.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/start.js CHANGED
@@ -1,5 +1,8 @@
1
- // poad start démarre le projet (engine + Mailpit)
2
- // poad start --all puis tous les services optionnels configurés (Keycloak, Valkey…)
1
+ // poad start démarre le projet (engine + Mailpit), applique les
2
+ // migrations, lance les services en autostart (poad setup),
3
+ // puis affiche l'état complet (comme poad info)
4
+ // poad start --all tous les services configurés, autostart ou non
5
+ // poad start --bare l'engine et Mailpit seulement, cette fois-ci
3
6
  module.exports = async (args = {}) => {
4
7
  const chalk = require('chalk-v2');
5
8
  const Docker = require('dockerode');
@@ -20,12 +23,21 @@ module.exports = async (args = {}) => {
20
23
  const config = require('../utils/config').readConfig(root);
21
24
  const containerName = config.project_uuid;
22
25
  console.log(' ');
23
- const { wantsAll } = require('../utils/services');
26
+ const { wantsAll, SERVICES, autostartServices } = require('../utils/services');
24
27
  const all = wantsAll(args);
28
+ const bare = Boolean(args.bare || args['--bare']);
29
+
30
+ // Services optionnels à lancer, puis l'état complet du projet
31
+ const finish = async () => {
32
+ const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config);
33
+ if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
34
+ console.log(' ');
35
+ await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root));
36
+ };
37
+
25
38
  if (await isDockerExist(containerName)) {
26
39
  console.log(chalk.bold('Container already started'));
27
- if (all) await require('./run')({ all: true });
28
- return;
40
+ return finish();
29
41
  }
30
42
  config.engine = await offerEngineUpgrade(root, config, args);
31
43
  const image = 'poadio/engine:' + config.engine;
@@ -38,6 +50,11 @@ module.exports = async (args = {}) => {
38
50
  }
39
51
  if (mailpit && !(await pullIfMissing(docker, mail.MAILPIT_IMAGE))) return;
40
52
 
53
+ // Base neuve (premier démarrage, poad db reset) : seed.sql après les migrations
54
+ const fsSync = require('fs');
55
+ const pgDir = path.join(path.dirname(root), 'data', 'postgres');
56
+ const fresh = !fsSync.existsSync(pgDir) || !fsSync.readdirSync(pgDir).length;
57
+
41
58
  const progress = ora('Starting containers').start();
42
59
  try {
43
60
  // Réseau du projet : l'engine y joint Mailpit (« mail ») et Keycloak
@@ -83,41 +100,31 @@ module.exports = async (args = {}) => {
83
100
  return;
84
101
  }
85
102
  progress.succeed(chalk.bold('containers started.'));
86
- if (!all && valkey.enabled(config) && !(await isDockerExist(valkey.containerName(config)))) {
87
- console.log(chalk.grey(' Valkey is configured: start it with "poad run valkey".'));
88
- }
89
- console.log(' ');
90
- console.log(chalk.bold(' 🚀 Container started successfully'));
91
- console.log(' ');
92
- const info = {
93
- 'API URL': `http://localhost:${config.web.port}`,
94
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
95
- ...storageInfo(config),
96
- ...(mailpit ? { 'Mail URL': `http://localhost:${mail.mailPort(config)}` } : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
97
- 'JWT secret': `${config.auth.secret}`,
98
- 'anon key': config.auth.anon,
99
- 'service_role key': config.auth.service,
100
- };
101
- console.log(prettyoutput(info));
102
-
103
103
  // Migrations en attente de poad/migrations ([db] auto_migrate = false pour
104
- // les appliquer à la main avec poad migrate)
104
+ // les appliquer à la main avec poad migrate ; poad db reset les applique
105
+ // toujours), puis seed.sql sur une base neuve
105
106
  const migrations = require('../utils/migrations');
106
- if (migrations.files(root).list.length) {
107
- if (!migrations.autoMigrate(config)) {
108
- console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
107
+ const { seedFile, runSeed } = require('../utils/seed');
108
+ const hasMigrations = migrations.files(root).list.length > 0;
109
+ const migrate = hasMigrations && (migrations.autoMigrate(config) || args.forceMigrate);
110
+ const seed = fresh && fsSync.existsSync(seedFile(root));
111
+ if (hasMigrations && !migrate) console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
112
+ if (migrate || seed) {
113
+ const waiting = ora(fresh ? 'Waiting for the new database' : 'Waiting for the database to apply migrations').start();
114
+ const ready = (await migrations.waitForDb(config)) && (await migrations.waitForServices(config));
115
+ if (!ready) {
116
+ waiting.fail(chalk.redBright('The engine does not answer: migrations and seed not applied (poad migrate, poad db seed later).'));
117
+ process.exitCode = 1;
109
118
  } else {
110
- const waiting = ora('Waiting for the database to apply migrations').start();
111
- const ready = (await migrations.waitForDb(config)) && (await migrations.waitForServices(config));
112
- if (!ready) {
113
- waiting.fail(chalk.redBright('Migrations not applied: the engine does not answer (poad migrate later).'));
114
- } else {
115
- waiting.stop();
116
- await require('../utils/migrate-run')(root, config, { quietWhenNone: false });
117
- }
119
+ waiting.stop();
120
+ const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false }) : true;
121
+ // Code de sortie 1 si une migration ou le seed échoue (scripts, CI)
122
+ if (!migrated) process.exitCode = 1;
123
+ if (seed && !migrated) console.log(chalk.yellowBright(' Seed skipped: a migration failed. Fix it, "poad migrate", then "poad db seed".'));
124
+ else if (seed && !migrations.autoMigrate(config) && !args.forceMigrate && hasMigrations) console.log(chalk.grey(' Seed skipped: migrations are manual here ("poad migrate" then "poad db seed").'));
125
+ else if (seed && !(await runSeed(root, config))) process.exitCode = 1;
118
126
  }
119
- console.log(' ');
120
127
  }
121
128
 
122
- if (all) await require('./run')({ all: true });
129
+ await finish();
123
130
  };
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.12.0",
4
- "engine": "0.7.1",
3
+ "version": "2.14.0",
4
+ "engine": "0.7.2",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
8
8
  "poad": "./poad.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "yarn clean && yarn"
11
+ "build": "bun install"
12
12
  },
13
13
  "dependencies": {
14
+ "@inquirer/prompts": "^8.8.0",
14
15
  "axios": "^1.7.7",
15
16
  "boxen": "^5.1.2",
16
17
  "chalk-v2": "^1.0.2",
@@ -26,5 +27,6 @@
26
27
  "pg": "8.16.3",
27
28
  "prettyoutput": "^1.2.0",
28
29
  "toml": "^3.0.0"
29
- }
30
+ },
31
+ "packageManager": "bun@1.4.4"
30
32
  }
package/project/cli.js CHANGED
@@ -9,6 +9,13 @@
9
9
  module.exports = {
10
10
  info: `Information about your project`,
11
11
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
12
+ setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, --all, --none, --list)',
13
+ db: {
14
+ description: 'Local database: db reset (erase, migrate, seed), db seed (apply poad/seed.sql)',
15
+ reset: 'Erase the database and storage files, restart, apply migrations then poad/seed.sql (--yes outside a terminal)',
16
+ seed: 'Apply poad/seed.sql (development data)',
17
+ },
18
+ upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade --rollback, upgrade --list (--yes outside a terminal)',
12
19
  migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
13
20
  migration: 'Database migrations: migration new <name>, migration list',
14
21
  /* status: `[AI] Vérification du statut de l'environnement`,
@@ -0,0 +1,10 @@
1
+ // poad db : aide des commandes de la base
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ console.log(`${chalk.bold(' Usage :')}`);
5
+ console.log(' ');
6
+ console.log(` ${chalk.cyanBright('poad db reset')} Erase the database and storage files, restart, apply migrations then poad/seed.sql`);
7
+ console.log(` ${chalk.cyanBright('poad db seed')} Apply poad/seed.sql (development data)`);
8
+ console.log(` ${chalk.cyanBright('poad migrate')} Apply pending migrations`);
9
+ console.log(' ');
10
+ };
@@ -0,0 +1,92 @@
1
+ // poad db reset : repart d'une base neuve
2
+ // 1. arrête le projet (engine, Mailpit, services) ;
3
+ // 2. efface les données de l'engine dans poad/data : base PostgreSQL et
4
+ // fichiers du storage. Keycloak (jeu de test, identifiants) et Valkey
5
+ // sont gardés ;
6
+ // 3. redémarre, applique toutes les migrations puis poad/seed.sql, et
7
+ // relance les services qui tournaient.
8
+ // Sans retour possible : confirmation demandée, ou --yes hors terminal.
9
+ module.exports = async (args = {}) => {
10
+ const chalk = require('chalk-v2');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const Docker = require('dockerode');
14
+ const docker = new Docker();
15
+ const { findPoadDir } = require('../../utils/findpoad');
16
+ const { isDockerExist } = require('../../utils/docker');
17
+ const { readConfig } = require('../../utils/config');
18
+ const { SERVICES, containerState } = require('../../utils/services');
19
+ const { pullIfMissing } = require('../../utils/pull');
20
+
21
+ // Ce que poad db reset garde dans poad/data (services gérés par le CLI)
22
+ const KEEP = new Set(['keycloak', 'valkey']);
23
+
24
+ const root = findPoadDir(process.cwd());
25
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
26
+ const config = readConfig(root);
27
+ const dataDir = path.join(path.dirname(root), 'data');
28
+ const erase = fs.existsSync(dataDir) ? fs.readdirSync(dataDir).filter((d) => !KEEP.has(d) && !d.startsWith('.')) : [];
29
+ const rel = path.relative(process.cwd(), dataDir) || dataDir;
30
+
31
+ console.log(' ');
32
+ console.log(chalk.bold('Reset the local database'));
33
+ console.log(chalk.grey(` Erased: ${erase.length ? erase.map((d) => `${rel}/${d}`).join(', ') : '(nothing yet)'} — users, tables, files, providers set in the database`));
34
+ console.log(chalk.grey(` Kept: poad/migrations, poad/seed.sql, poad/keycloak.json, ${[...KEEP].map((d) => `${rel}/${d}`).join(', ')}`));
35
+ console.log(' ');
36
+
37
+ const yes = Boolean(args.yes || args['--yes'] || args['-y']);
38
+ if (!yes) {
39
+ if (!process.stdin.isTTY) {
40
+ process.exitCode = 1;
41
+ return console.log(chalk.redBright('Not a terminal: confirm with "poad db reset --yes".'));
42
+ }
43
+ const { confirm } = require('@inquirer/prompts');
44
+ const ok = await confirm({ message: 'Erase the local database and start again? This cannot be undone.', default: false }).catch(() => false);
45
+ if (!ok) return console.log(chalk.grey(' Nothing changed.'));
46
+ }
47
+
48
+ // Services optionnels qui tournent : relancés après le redémarrage
49
+ const running = [];
50
+ for (const s of SERVICES.filter((x) => x.optional && x.configured(config))) {
51
+ if ((await containerState(docker, s.container(config))) === 'running') running.push(s.id);
52
+ }
53
+ if (await isDockerExist(config.project_uuid)) await require('../../global/stop')({});
54
+
55
+ // Effacement depuis un conteneur : sous Linux, les fichiers de la base
56
+ // appartiennent à l'utilisateur postgres du conteneur
57
+ if (erase.length) {
58
+ const ora = require('ora');
59
+ const progress = ora('Erasing the database').start();
60
+ const image = `poadio/engine:${config.engine}`;
61
+ try {
62
+ if (!(await pullIfMissing(docker, image))) throw new Error(`image ${image} unavailable`);
63
+ const container = await docker.createContainer({
64
+ Image: image,
65
+ Entrypoint: ['sh', '-c'],
66
+ Cmd: [erase.map((d) => `rm -rf "/data/${d.replace(/"/g, '')}"`).join(' && ')],
67
+ HostConfig: { Binds: [`${dataDir}:/data`], AutoRemove: false },
68
+ });
69
+ await container.start();
70
+ const { StatusCode } = await container.wait();
71
+ await container.remove().catch(() => {});
72
+ if (StatusCode !== 0) throw new Error(`exit ${StatusCode}`);
73
+ progress.succeed(chalk.bold('Database erased.'));
74
+ } catch (err) {
75
+ progress.fail(chalk.redBright(`Erase failed: ${err.message}. Nothing restarted.`));
76
+ process.exitCode = 1;
77
+ return;
78
+ }
79
+ }
80
+
81
+ console.log(' ');
82
+ // poad start : base neuve, donc migrations (forcées) puis seed.sql
83
+ const { autostartServices } = require('../../utils/services');
84
+ const auto = new Set(autostartServices(config).map((s) => s.id));
85
+ await require('../../global/start')({ forceMigrate: true });
86
+ const again = running.filter((id) => !auto.has(id));
87
+ if (again.length) {
88
+ await require('../../global/run')({ services: again, quiet: true });
89
+ console.log(' ');
90
+ await require('../../utils/report').printServices(root, readConfig(root));
91
+ }
92
+ };
@@ -0,0 +1,19 @@
1
+ // poad db seed : applique poad/seed.sql (données de développement)
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { findPoadDir } = require('../../utils/findpoad');
7
+ const { isDockerExist } = require('../../utils/docker');
8
+ const { readConfig } = require('../../utils/config');
9
+ const { seedFile, runSeed } = require('../../utils/seed');
10
+
11
+ const root = findPoadDir(process.cwd());
12
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
13
+ const config = readConfig(root);
14
+ if (!fs.existsSync(seedFile(root))) {
15
+ return console.log(chalk.grey(` No ${path.relative(process.cwd(), seedFile(root))}: write your development data there (applied after migrations on a new database).`));
16
+ }
17
+ if (!(await isDockerExist(config.project_uuid))) return console.log(chalk.redBright('The project is not started: "poad start".'));
18
+ if (!(await runSeed(root, config))) process.exitCode = 1;
19
+ };
package/project/info.js CHANGED
@@ -1,84 +1,16 @@
1
- // poad info : le projet (URL, base, clés), puis un panneau à part pour les
2
- // services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
1
+ // poad info : le projet (URL, base, clés, migrations), puis un panneau à part
2
+ // pour les services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
3
+ // poad start affiche la même chose à la fin du démarrage.
3
4
  module.exports = async () => {
4
5
  const chalk = require('chalk-v2');
5
- const toml = require('toml');
6
- const fs = require('fs').promises;
7
- const Docker = require('dockerode');
8
- const docker = new Docker();
9
- const prettyoutput = require('prettyoutput');
10
6
  const { findPoadDir } = require('../utils/findpoad');
11
7
  const { isDockerExist } = require('../utils/docker');
12
- const { storageInfo } = require('../utils/engine');
13
- const { SERVICES, containerState } = require('../utils/services');
14
8
  const root = findPoadDir(process.cwd());
15
9
  if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
16
10
  const config = require('../utils/config').readConfig(root);
17
11
  console.log(' ');
18
12
  if (!(await isDockerExist(config.project_uuid))) {
19
- return console.log(chalk.redBright('Container not found'));
13
+ return console.log(chalk.redBright('The project is not started: "poad start".'));
20
14
  }
21
- console.log(chalk.bold('POAD project info'));
22
- console.log(' ');
23
- const info = {
24
- Engine: config.engine,
25
- 'API URL': `http://localhost:${config.web.port}`,
26
- 'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
27
- ...storageInfo(config),
28
- ...(config.smtp && config.smtp.host ? { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` } : {}),
29
- 'JWT secret': `${config.auth.secret}`,
30
- 'anon key': config.auth.anon,
31
- 'service_role key': config.auth.service,
32
- };
33
- // Migrations : appliquées / en attente (poad/migrations)
34
- const migrations = require('../utils/migrations');
35
- if (migrations.files(root).list.length) {
36
- let client;
37
- try {
38
- client = await migrations.connect(config);
39
- const st = await migrations.status(root, client);
40
- const done = st.list.length - st.pending.length;
41
- info.Migrations = `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
42
- } catch {
43
- info.Migrations = `${migrations.files(root).list.length} file(s), state unknown`;
44
- } finally {
45
- if (client) await client.end().catch(() => {});
46
- }
47
- }
48
- console.log(prettyoutput(info));
49
-
50
- // Panneau des services : en cours, arrêtés (configurés), ou disponibles
51
- const rows = [];
52
- for (const s of SERVICES) {
53
- const configured = s.configured(config);
54
- if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
55
- const state = configured ? await containerState(docker, s.container(config)) : null;
56
- rows.push({ s, configured, running: state === 'running' });
57
- }
58
- if (!rows.length) return;
59
-
60
- const width = Math.max(...rows.map((r) => r.s.label.length));
61
- const line = chalk.grey('─'.repeat(48));
62
- console.log(chalk.bold('Services'));
63
- console.log(line);
64
- for (const { s, configured, running } of rows) {
65
- const label = chalk.bold(s.label.padEnd(width));
66
- if (running) {
67
- console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}`);
68
- for (const [k, v] of Object.entries(s.info(config, root))) {
69
- // Une liste (comptes de test) : une ligne par entrée, alignées
70
- const lines = Array.isArray(v) ? v : [v];
71
- lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
72
- }
73
- } else if (configured) {
74
- const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
75
- console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')} ${chalk.grey(`(${how})`)}`);
76
- } else {
77
- console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}`)}`);
78
- }
79
- }
80
- console.log(line);
81
- const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
82
- if (stopped) console.log(chalk.grey(` "poad run --all" starts every configured service.`));
83
- console.log(' ');
15
+ await require('../utils/report').printReport(root, config);
84
16
  };
@@ -0,0 +1,241 @@
1
+ // poad setup : ce que "poad start" lance avec le projet
2
+ //
3
+ // poad setup interactif (terminal) : e-mails, services, migrations
4
+ // poad setup kc=on valkey=off non interactif : ne change que ce qui est cité
5
+ // poad setup --all | --none tous les services optionnels en autostart, ou aucun
6
+ // poad setup mail=smtp smtp.host=smtp.example.com smtp.port=587 smtp.user=apikey smtp.pass=…
7
+ // poad setup mail=mailpit revient à Mailpit (e-mails capturés en local)
8
+ // poad setup migrate=off migrations appliquées à la main (poad migrate)
9
+ // poad setup --list affiche les réglages sans rien changer
10
+ //
11
+ // Tout va dans poad/config.toml, sauf le mot de passe SMTP (poad/secrets.toml).
12
+ // Désactiver un service ne retire que son autostart : port, données et jeu de
13
+ // test restent, le réactiver ne coûte rien.
14
+ module.exports = async (args = {}) => {
15
+ const chalk = require('chalk-v2');
16
+ const Docker = require('dockerode');
17
+ const docker = new Docker();
18
+ const { findPoadDir } = require('../utils/findpoad');
19
+ const { isDockerExist } = require('../utils/docker');
20
+ const { findFreePorts } = require('../utils/ports');
21
+ const { setKeys, removeSection } = require('../utils/tomlfile');
22
+ const { loadConfig, readConfig, writeSmtpPass } = require('../utils/config');
23
+ const { SERVICES, containerState } = require('../utils/services');
24
+ const mail = require('../utils/mail');
25
+ const migrations = require('../utils/migrations');
26
+
27
+ const root = findPoadDir(process.cwd());
28
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
29
+ let config = readConfig(root);
30
+ const optional = SERVICES.filter((s) => s.optional);
31
+ console.log(' ');
32
+
33
+ // ------------------------------------------------------------ lecture
34
+ const ALIASES = { kc: 'keycloak', keycloak: 'keycloak', valkey: 'valkey', redis: 'valkey' };
35
+ const ON = new Set(['on', 'true', 'yes', 'oui', '1', 'auto']);
36
+ const OFF = new Set(['off', 'false', 'no', 'non', '0', 'manual']);
37
+ const flag = (v) => {
38
+ const t = String(v).toLowerCase();
39
+ if (ON.has(t)) return true;
40
+ if (OFF.has(t)) return false;
41
+ return null;
42
+ };
43
+ const has = (k) => args[k] || args[`--${k}`];
44
+
45
+ const current = () => ({
46
+ mail: mail.usesMailpit(config) ? 'mailpit' : 'smtp',
47
+ smtp: { ...(config.smtp || {}) },
48
+ services: Object.fromEntries(optional.map((s) => [s.id, s.configured(config) && s.autostart(config)])),
49
+ migrate: migrations.autoMigrate(config),
50
+ });
51
+
52
+ const summary = () => {
53
+ const c = current();
54
+ const pad = (s) => chalk.bold(s.padEnd(11));
55
+ console.log(chalk.bold('Started with "poad start"'));
56
+ console.log(chalk.grey('─'.repeat(48)));
57
+ console.log(` ${pad('E-mails')} ${c.mail === 'mailpit' ? `Mailpit ${chalk.grey(`(local, http://localhost:${mail.mailPort(config)})`)}` : `SMTP ${c.smtp.host}:${c.smtp.port || 587}${c.smtp.user ? chalk.grey(` (${c.smtp.user})`) : ''}`}`);
58
+ for (const s of optional) {
59
+ const state = c.services[s.id]
60
+ ? chalk.greenBright('auto')
61
+ : s.configured(config)
62
+ ? `${chalk.yellowBright('manual')} ${chalk.grey(`(poad run ${s.cmd})`)}`
63
+ : chalk.grey('off');
64
+ console.log(` ${pad(s.label)} ${state}`);
65
+ }
66
+ console.log(` ${pad('Migrations')} ${c.migrate ? chalk.greenBright('applied at start') : `${chalk.yellowBright('manual')} ${chalk.grey('(poad migrate)')}`}`);
67
+ console.log(chalk.grey('─'.repeat(48)));
68
+ };
69
+
70
+ if (has('list')) {
71
+ summary();
72
+ return console.log(' ');
73
+ }
74
+
75
+ // ------------------------------------------------------------ souhaits
76
+ const before = current();
77
+ const wasConfigured = Object.fromEntries(optional.map((s) => [s.id, s.configured(config)]));
78
+ const wish = { services: {} };
79
+ const keys = Object.keys(args).filter((k) => !/^-/.test(k));
80
+
81
+ if (has('all')) for (const s of optional) wish.services[s.id] = true;
82
+ if (has('none')) for (const s of optional) wish.services[s.id] = false;
83
+ for (const k of keys) {
84
+ const v = args[k];
85
+ if (ALIASES[k]) {
86
+ const f = flag(v);
87
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
88
+ wish.services[ALIASES[k]] = f;
89
+ } else if (k === 'mail') {
90
+ if (!['mailpit', 'smtp'].includes(String(v))) return console.log(chalk.redBright('mail=mailpit or mail=smtp.'));
91
+ wish.mail = String(v);
92
+ } else if (k.startsWith('smtp.')) {
93
+ (wish.smtp ??= {})[k.slice(5)] = v;
94
+ } else if (k === 'migrate' || k === 'migrations') {
95
+ const f = flag(v);
96
+ if (f === null) return console.log(chalk.redBright(`${k}=${v}: expected on or off.`));
97
+ wish.migrate = f;
98
+ } else if (!['all', 'none', 'list'].includes(k)) {
99
+ return console.log(chalk.redBright(`Unknown setting "${k}". See: poad setup --help`));
100
+ }
101
+ }
102
+ if (wish.smtp && !wish.mail) wish.mail = 'smtp';
103
+
104
+ const interactive = !keys.length && !has('all') && !has('none');
105
+ if (interactive) {
106
+ if (!process.stdin.isTTY) {
107
+ summary();
108
+ console.log(chalk.grey(' Not a terminal: pass settings, e.g. "poad setup kc=on valkey=off", "--all", "--none", "mail=smtp smtp.host=…".'));
109
+ return console.log(' ');
110
+ }
111
+ const { select, checkbox, input, password, confirm } = require('@inquirer/prompts');
112
+ try {
113
+ console.log(chalk.bold('Services started with "poad start"'));
114
+ console.log(' ');
115
+ wish.mail = await select({
116
+ message: 'E-mails (sign up, magic links, password reset)',
117
+ default: before.mail,
118
+ choices: [
119
+ { name: 'Mailpit: captured locally, read them in the browser', value: 'mailpit' },
120
+ { name: 'SMTP server: real delivery', value: 'smtp' },
121
+ ],
122
+ });
123
+ if (wish.mail === 'smtp') {
124
+ const s = before.smtp;
125
+ wish.smtp = {};
126
+ wish.smtp.host = await input({ message: 'SMTP host', default: s.host, required: true });
127
+ wish.smtp.port = Number(await input({ message: 'SMTP port', default: String(s.port || 587), validate: (v) => /^\d+$/.test(v) || 'a port number' }));
128
+ wish.smtp.user = await input({ message: 'SMTP user (empty: none)', default: s.user || '' });
129
+ const pass = await password({ message: s.pass ? 'SMTP password (empty: keep the current one)' : 'SMTP password (empty: none)', mask: '*' });
130
+ if (pass) wish.smtp.pass = pass;
131
+ wish.smtp.sender = await input({ message: 'Sender address', default: s.sender || 'no-reply@poad.local' });
132
+ wish.smtp.secure = await confirm({ message: 'TLS from the start (port 465)?', default: Boolean(s.secure) || wish.smtp.port === 465 });
133
+ }
134
+ const picked = await checkbox({
135
+ message: 'Started with the project (space to toggle, enter to confirm)',
136
+ choices: [
137
+ ...optional.map((s) => ({
138
+ name: s.id === 'keycloak' ? 'Keycloak: OIDC provider with test users (poad/keycloak.json)' : 'Valkey: Redis compatible cache (REDIS_URL of the engine)',
139
+ value: s.id,
140
+ checked: before.services[s.id],
141
+ })),
142
+ { name: 'Migrations: apply poad/migrations at start', value: '_migrate', checked: before.migrate },
143
+ ],
144
+ });
145
+ for (const s of optional) wish.services[s.id] = picked.includes(s.id);
146
+ wish.migrate = picked.includes('_migrate');
147
+ console.log(' ');
148
+ } catch (err) {
149
+ // Ctrl+C dans un prompt
150
+ if (err && err.name === 'ExitPromptError') return console.log(chalk.grey(' Nothing changed.'));
151
+ throw err;
152
+ }
153
+ }
154
+
155
+ // ------------------------------------------------------------ écriture
156
+ const changes = [];
157
+ for (const [id, on] of Object.entries(wish.services)) {
158
+ const s = optional.find((x) => x.id === id);
159
+ if (on === before.services[id]) continue;
160
+ if (on && !s.configured(config)) {
161
+ const [port] = await findFreePorts(1);
162
+ s.savePort(root, port);
163
+ }
164
+ if (on || s.configured(config)) setKeys(root, s.section, { autostart: on });
165
+ changes.push(`${s.label}: ${on ? 'started with the project' : 'manual (poad run ' + s.cmd + ')'}`);
166
+ config = loadConfig(root);
167
+ }
168
+
169
+ let mailChanged = false;
170
+ if (wish.mail === 'smtp') {
171
+ const next = { ...before.smtp, ...(wish.smtp || {}) };
172
+ if (!next.host) return console.log(chalk.redBright('mail=smtp needs smtp.host=…'));
173
+ const { pass, ...visible } = next;
174
+ const fields = {
175
+ host: String(visible.host),
176
+ port: Number(visible.port || 587),
177
+ user: visible.user ? String(visible.user) : null,
178
+ sender: visible.sender ? String(visible.sender) : null,
179
+ secure: visible.secure === true || visible.secure === 'true' ? true : null,
180
+ };
181
+ setKeys(root, 'smtp', fields);
182
+ if (wish.smtp && wish.smtp.pass !== undefined) writeSmtpPass(root, String(wish.smtp.pass));
183
+ const was = before.mail === 'smtp' ? JSON.stringify({ ...before.smtp, pass: undefined }) : '';
184
+ mailChanged = before.mail !== 'smtp' || was !== JSON.stringify({ ...next, pass: undefined }) || (wish.smtp && wish.smtp.pass !== undefined);
185
+ if (mailChanged) changes.push(`E-mails: SMTP ${fields.host}:${fields.port}`);
186
+ } else if (wish.mail === 'mailpit' && before.mail === 'smtp') {
187
+ removeSection(root, 'smtp');
188
+ writeSmtpPass(root, null);
189
+ if (!mail.mailPort(loadConfig(root))) {
190
+ const [port] = await findFreePorts(1);
191
+ setKeys(root, 'mail', { port });
192
+ }
193
+ mailChanged = true;
194
+ changes.push('E-mails: Mailpit');
195
+ }
196
+
197
+ if (wish.migrate !== undefined && wish.migrate !== before.migrate) {
198
+ setKeys(root, 'db', { auto_migrate: wish.migrate ? null : false });
199
+ changes.push(`Migrations: ${wish.migrate ? 'applied at start' : 'manual (poad migrate)'}`);
200
+ }
201
+
202
+ config = loadConfig(root);
203
+ if (!changes.length) {
204
+ summary();
205
+ console.log(chalk.grey(' Nothing changed.'));
206
+ return console.log(' ');
207
+ }
208
+ for (const c of changes) console.log(`${chalk.greenBright('✔')} ${c}`);
209
+ console.log(' ');
210
+ summary();
211
+
212
+ // ------------------------------------------------------------ projet lancé
213
+ if (await isDockerExist(config.project_uuid)) {
214
+ // REDIS_URL n'est donné à l'engine que si Valkey était configuré à son démarrage
215
+ const valkeyNew = wish.services.valkey === true && !wasConfigured.valkey;
216
+ if (mailChanged || valkeyNew) {
217
+ console.log(chalk.yellowBright(' The engine reads its mail and Valkey settings at start: "poad stop" then "poad start" to apply them.'));
218
+ }
219
+ const missing = [];
220
+ for (const s of optional) {
221
+ if (wish.services[s.id] && (await containerState(docker, s.container(config))) !== 'running') missing.push(s);
222
+ }
223
+ if (missing.length) {
224
+ let go = !interactive;
225
+ if (interactive) {
226
+ const { confirm } = require('@inquirer/prompts');
227
+ go = await confirm({ message: `Start ${missing.map((s) => s.label).join(' and ')} now?`, default: true }).catch(() => false);
228
+ }
229
+ if (go) {
230
+ await require('../global/run')({ services: missing.map((s) => s.id), quiet: true });
231
+ console.log(' ');
232
+ await require('../utils/report').printServices(root, loadConfig(root));
233
+ return;
234
+ }
235
+ console.log(chalk.grey(' Applied at the next "poad start" (or "poad run --all").'));
236
+ }
237
+ } else {
238
+ console.log(chalk.grey(' Applied at the next "poad start".'));
239
+ }
240
+ console.log(' ');
241
+ };