poad 2.37.0 → 2.39.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.
@@ -1,18 +1,15 @@
1
- // poad client init [angular|vue|react] [dir=web] [from=<dossier ou .tgz>] [--yes]
1
+ // poad client init [angular|next|nuxt|vanilla] [dir=web] [from=<dossier ou .tgz>] [--yes]
2
2
  //
3
3
  // Crée le front du projet à partir d'un modèle (@poadio/starter-<framework>
4
4
  // sur npm) : connexion, compte, cadre d'application, branché sur le projet
5
5
  // poad (URL et clé lues dans poad/config.toml au démarrage, rien à écrire).
6
6
  // - à la racine du projet, ou dans dir= (proposé si la racine a déjà un
7
7
  // package.json) ;
8
- // - port de développement libre à partir de 4300 ;
8
+ // - port de développement du modèle (poad.port ; Angular : libre à partir de 4300) ;
9
9
  // - .gitignore complété, dépendances installées (bun, sinon npm).
10
10
  // from= : un modèle local (dossier ou archive), pour le développer.
11
- const FRAMEWORKS = [
12
- { value: 'angular', name: 'Angular (@cadriciel/ui)', package: '@poadio/starter-angular' },
13
- { value: 'vue', name: 'Vue.js (bientôt)', disabled: 'bientôt' },
14
- { value: 'react', name: 'React (bientôt)', disabled: 'bientôt' },
15
- ];
11
+ // Archive npm : intégrité vérifiée et extraction sûre (utils/registry, utils/tar),
12
+ // comme poad create.
16
13
 
17
14
  // Jamais copiés depuis un dossier modèle local
18
15
  const SKIP = new Set(['node_modules', 'dist', '.angular', '.git', '.github', '.env.local', 'env.json', '.DS_Store', 'poad']);
@@ -36,17 +33,28 @@ module.exports = async (args = {}) => {
36
33
  const flag = (f) => Boolean(args[f] || args[`--${f}`]);
37
34
  const tty = process.stdin.isTTY && process.stdout.isTTY && !flag('yes');
38
35
  const prompts = tty ? require('@inquirer/prompts') : null;
36
+ const starter = require('../../utils/starter');
37
+ const registry = require('../../utils/registry');
38
+ const local = typeof args.from === 'string';
39
39
 
40
- // 1. Framework
41
- let fw = FRAMEWORKS.find((f) => args[f.value]);
42
- if (!fw && prompts) {
43
- const v = await prompts.select({ message: 'Front-end framework', choices: FRAMEWORKS }).catch(() => null);
44
- fw = FRAMEWORKS.find((f) => f.value === v);
40
+ // 1. Framework : seuls les modèles publiés sur npm peuvent être choisis
41
+ let fw = starter.TEMPLATES.find((f) => args[f.value]);
42
+ let metadata = null;
43
+ if (!fw && prompts && !local) {
44
+ const states = await Promise.all(starter.TEMPLATES.map(async (t) => ({ ...t, metadata: await registry.packageMetadata(t.package) })));
45
+ const choices = states.map((t) => ({ value: t.value, name: t.label, disabled: t.metadata.status === 'missing' ? 'coming soon' : t.metadata.status === 'offline' && !registry.cachedVersion(t.package) ? 'offline' : false }));
46
+ const v = await prompts.select({ message: 'Front-end framework', choices }).catch(() => null);
47
+ if (!v) return;
48
+ fw = starter.templateByValue(v);
49
+ metadata = states.find((t) => t.value === v).metadata;
45
50
  }
46
- if (!fw) fw = FRAMEWORKS[0];
47
- if (fw.disabled) {
48
- process.exitCode = 1;
49
- return console.log(chalk.yellowBright(`${fw.value}: coming soon. Angular is available now.`));
51
+ if (!fw) fw = starter.TEMPLATES[0];
52
+ if (!local) {
53
+ metadata = metadata || (await registry.packageMetadata(fw.package, { timeout: 5000 }));
54
+ if (metadata.status === 'missing') {
55
+ process.exitCode = 1;
56
+ return console.log(chalk.yellowBright(`${fw.value}: coming soon (${fw.package} is not published yet).`));
57
+ }
50
58
  }
51
59
 
52
60
  // 2. Dossier : la racine si elle est libre, sinon un sous-dossier
@@ -74,15 +82,12 @@ module.exports = async (args = {}) => {
74
82
  let tgz = null;
75
83
  if (from && fs.statSync(from).isDirectory()) source = from;
76
84
  else if (from) tgz = from;
77
- else {
78
- const r = spawnSync('npm', ['pack', `${fw.package}@latest`, '--pack-destination', work, '--json', '--silent'], { encoding: 'utf8', shell: process.platform === 'win32' });
79
- if (r.status !== 0) throw new Error((r.stderr || r.stdout || 'npm pack failed').trim().split('\n').slice(-3).join(' '));
80
- tgz = path.join(work, JSON.parse(r.stdout)[0].filename);
81
- }
82
- if (tgz) {
83
- const x = spawnSync('tar', ['-xzf', tgz, '-C', work], { encoding: 'utf8' });
84
- if (x.status !== 0) throw new Error(`tar: ${x.stderr.trim()}`);
85
+ let buf = null;
86
+ if (!from) buf = (await registry.fetchLatestTarball(fw.package, { metadata, timeout: 5000 })).buf;
87
+ else if (tgz) buf = fs.readFileSync(tgz);
88
+ if (buf) {
85
89
  source = path.join(work, 'package');
90
+ require('../../utils/tar').extractTgz(buf, source);
86
91
  }
87
92
  progress.succeed(`Template: ${chalk.bold(require(path.join(source, 'package.json')).name)} ${chalk.grey(require(path.join(source, 'package.json')).version)}`);
88
93
  } catch (err) {
@@ -110,44 +115,23 @@ module.exports = async (args = {}) => {
110
115
  const pkgFile = path.join(target, 'package.json');
111
116
  const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
112
117
  const tpl = (pkg.poad && pkg.poad.template) || {};
113
- const name = String(config.project_id || path.basename(projectDir))
114
- .toLowerCase()
115
- .replace(/[^a-z0-9._-]+/g, '-')
116
- .replace(/^[-._]+|[-._]+$/g, '') || 'app';
117
- pkg.name = dir === '.' ? name : `${name}-${path.basename(target)}`;
118
- pkg.title = config.project_id || pkg.title;
119
- // La description du paquet npm parle du modèle : l'application reprend la sienne
120
- if (tpl.description) pkg.description = tpl.description;
121
- pkg.version = '0.1.0';
122
- pkg.private = true;
123
- for (const k of ['files', 'repository', 'publishConfig', 'license']) delete pkg[k];
118
+ const name = starter.packageName(config.project_id || path.basename(projectDir));
124
119
  const origin = require(path.join(source, 'package.json'));
125
- pkg.poad = { ...(pkg.poad || {}), from: `${origin.name}@${origin.version}` };
126
- delete pkg.poad.template;
127
- fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
120
+ const app = starter.rewritePackageJson(pkg, {
121
+ name: dir === '.' ? name : `${name}-${path.basename(target)}`,
122
+ title: config.project_id || pkg.title,
123
+ from: `${origin.name}@${origin.version}`,
124
+ });
125
+ fs.writeFileSync(pkgFile, JSON.stringify(app, null, 2) + '\n');
128
126
 
129
- // 6. Port de développement libre (4200 est souvent pris)
130
- const net = require('net');
131
- const free = (port) =>
132
- new Promise((ok) => {
133
- const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
134
- s.listen(port, '127.0.0.1');
135
- });
136
- let port = Number(tpl.port) || 4300;
137
- while (!(await free(port)) && port < 4400) port++;
138
- const ngFile = path.join(target, 'angular.json');
139
- if (fw.value === 'angular' && fs.existsSync(ngFile)) {
140
- const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
141
- for (const p of Object.values(ng.projects || {})) {
142
- const serve = p.architect && p.architect.serve;
143
- if (serve) serve.options = { ...(serve.options || {}), port };
144
- }
145
- fs.writeFileSync(ngFile, JSON.stringify(ng, null, 2) + '\n');
146
- }
127
+ // 6. Port de développement selon le framework (poad.port / poad.template.port
128
+ // du modèle ; Angular : premier libre, écrit dans angular.json)
129
+ const dev = await starter.devServer(target, pkg);
130
+ const label = dev.label || (local ? 'Front-end' : fw.label.split(' (')[0]);
147
131
 
148
132
  // Titre de la page : le nom du projet
149
133
  const html = path.join(target, 'src', 'index.html');
150
- if (fs.existsSync(html)) fs.writeFileSync(html, fs.readFileSync(html, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${String(pkg.title).replace(/[<&]/g, '')}</title>`));
134
+ if (fs.existsSync(html)) fs.writeFileSync(html, fs.readFileSync(html, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${String(app.title).replace(/[<&]/g, '')}</title>`));
151
135
 
152
136
  // 7. .gitignore : celui de poad init (racine), complété des fichiers du front
153
137
  const git = require('../../utils/git');
@@ -170,10 +154,10 @@ module.exports = async (args = {}) => {
170
154
  const rel = path.relative(process.cwd(), target) || '.';
171
155
  const run = hasBun ? 'bun start' : 'npm start';
172
156
  console.log(' ');
173
- console.log(`${chalk.greenBright('✔')} ${chalk.bold(`${fw.value} front-end created`)} in ${chalk.cyanBright(rel)}`);
157
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(label === 'Front-end' ? 'Front-end created' : `${label} front-end created`)} in ${chalk.cyanBright(rel)}`);
174
158
  console.log(chalk.grey(' Sign-in (e-mail, magic link, providers), account and app layout, wired to this poad project.'));
175
159
  console.log(' ');
176
160
  console.log(` ${chalk.bold('poad start')}${chalk.grey(' the backend (if not running)')}`);
177
- console.log(` ${chalk.bold(`${rel === '.' ? '' : `cd ${rel} && `}${run}`)}${chalk.grey(` http://localhost:${port}`)}`);
161
+ console.log(` ${chalk.bold(`${rel === '.' ? '' : `cd ${rel} && `}${run}`)}${dev.url ? chalk.grey(` ${dev.url}`) : ''}`);
178
162
  console.log(' ');
179
163
  };
package/project/info.js CHANGED
@@ -1,7 +1,24 @@
1
1
  // poad info : le projet (URL, base, clés, migrations), puis un panneau à part
2
2
  // pour les services qui tournent à côté de l'engine (Mailpit, Keycloak, Valkey).
3
3
  // poad start affiche la même chose à la fin du démarrage.
4
- module.exports = async () => {
4
+ // Les secrets (secret JWT, clé service_role, mot de passe admin de Keycloak…)
5
+ // sont masqués ; poad info --secrets les montre.
6
+
7
+ /** --secrets, secrets : montrer les secrets */
8
+ const wantsSecrets = (args = {}) => Boolean(args.secrets || args['--secrets']);
9
+
10
+ function help() {
11
+ const chalk = require('chalk-v2');
12
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad info')} ${chalk.cyan('[--secrets]')}`);
13
+ console.log(' ');
14
+ console.log(' State of the running project: URLs, database, keys, migrations, then the services next to the engine.');
15
+ console.log(' The JWT secret, the service_role key, the S3 secret key and the Keycloak admin password are hidden.');
16
+ console.log(' ');
17
+ console.log(` ${chalk.cyanBright('--secrets')} show them too (not in a shared screen, a recording or a ticket)`);
18
+ console.log(' ');
19
+ }
20
+
21
+ module.exports = async (args = {}) => {
5
22
  const chalk = require('chalk-v2');
6
23
  const { findPoadDir } = require('../utils/findpoad');
7
24
  const { isDockerExist } = require('../utils/docker');
@@ -12,5 +29,8 @@ module.exports = async () => {
12
29
  if (!(await isDockerExist(config.project_uuid))) {
13
30
  return console.log(chalk.redBright('The project is not started: "poad start".'));
14
31
  }
15
- await require('../utils/report').printReport(root, config);
32
+ await require('../utils/report').printReport(root, config, { secrets: wantsSecrets(args) });
16
33
  };
34
+
35
+ module.exports.help = help;
36
+ module.exports.wantsSecrets = wantsSecrets;
@@ -103,16 +103,19 @@ module.exports = async (args = {}) => {
103
103
  }
104
104
 
105
105
  // Mise à jour
106
- // Sans to= : le dernier engine publié (Docker Hub), sinon celui inscrit dans le CLI
106
+ // Sans to= : la version recommandée du canal du projet (poadio/permalink),
107
+ // sinon le dernier engine publié (Docker Hub), sinon celui inscrit dans le CLI
107
108
  const current = config.engine;
108
109
  let target = String(args.to || '');
109
110
  if (!target) {
110
- const { latestEngine } = require('../utils/latest');
111
- const latest = await latestEngine();
112
- target = String(latest || global.package.engine || '');
113
- if (!latest) {
114
- console.log(chalk.grey(` Docker Hub unreachable: latest engine unknown, this CLI knows ${target || 'none'}.`));
115
- // La version du CLI peut être en retard : jamais de retour en arrière sans to=
111
+ const latest = require('../utils/latest');
112
+ const channel = latest.engineChannel(config, args);
113
+ const info = await latest.engineReleaseInfo({ fresh: true, channel, timeout: 4000 });
114
+ target = String(info.version || '');
115
+ if (channel === 'beta') console.log(chalk.grey(` Channel: beta (${target || 'none'}).`));
116
+ if (info.source === 'cache' || info.source === 'cli') {
117
+ console.log(chalk.grey(` Offline: latest engine unknown, last known ${target || 'none'}.`));
118
+ // Hors ligne, la version connue peut être en retard : jamais de retour en arrière sans to=
116
119
  if (target && target !== current && !isNewerVersion(target, current)) {
117
120
  return console.log(chalk.yellow(` This project uses engine ${current}. Retry online, or "poad upgrade to=<version>".`));
118
121
  }
@@ -0,0 +1,73 @@
1
+ // Bout en bout, contre le vrai registre npm (sans Docker, sans poad start) :
2
+ // POAD_E2E=1 node --test test/create.e2e.test.js
3
+ const test = require('node:test');
4
+ const assert = require('node:assert');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+ const { tmpdir } = require('./helpers');
9
+
10
+ const CLI = path.join(__dirname, '..', 'poad.js');
11
+ const e2e = process.env.POAD_E2E === '1';
12
+
13
+ test('poad create my-app --template angular --no-install --yes', { skip: !e2e && 'POAD_E2E=1 to run it (network)', timeout: 120000 }, async (t) => {
14
+ const cwd = tmpdir(t, 'poad-create-');
15
+ const r = spawnSync(process.execPath, [CLI, 'create', 'my-app', '--template', 'angular', '--no-install', '--yes'], {
16
+ cwd,
17
+ encoding: 'utf8',
18
+ input: '',
19
+ env: { ...process.env, GIT_AUTHOR_NAME: 'poad test', GIT_AUTHOR_EMAIL: 'test@example.invalid', GIT_COMMITTER_NAME: 'poad test', GIT_COMMITTER_EMAIL: 'test@example.invalid' },
20
+ });
21
+ const out = r.stdout + r.stderr;
22
+ assert.strictEqual(r.status, 0, out);
23
+ assert.match(out, /integrity verified/);
24
+ const app = path.join(cwd, 'my-app');
25
+
26
+ // package.json renommé, sans champs de publication
27
+ const pkg = JSON.parse(fs.readFileSync(path.join(app, 'package.json'), 'utf8'));
28
+ assert.strictEqual(pkg.name, 'my-app');
29
+ assert.strictEqual(pkg.version, '0.1.0');
30
+ assert.strictEqual(pkg.private, true);
31
+ for (const k of ['files', 'repository', 'publishConfig']) assert.ok(!(k in pkg), `${k} dropped`);
32
+ assert.match(pkg.poad.from, /^@poadio\/starter-angular@\d+\.\d+\.\d+/);
33
+ assert.strictEqual(pkg.scripts.start, 'node scripts/dev.mjs');
34
+
35
+ // poad init : config.toml avec l'engine recommandé par permalink
36
+ const config = fs.readFileSync(path.join(app, 'poad', 'config.toml'), 'utf8');
37
+ assert.match(config, /^project_id = "my-app"$/m);
38
+ const engine = /^engine = "([^"]+)"$/m.exec(config);
39
+ assert.ok(engine, config);
40
+ const permalink = await fetch('https://raw.githubusercontent.com/poadio/permalink/main/poad.json', { signal: AbortSignal.timeout(5000) })
41
+ .then((res) => res.json())
42
+ .catch(() => null);
43
+ if (permalink && permalink.engine && permalink.engine.stable) assert.strictEqual(engine[1], permalink.engine.stable);
44
+ assert.ok(fs.existsSync(path.join(app, 'poad', 'secrets.toml')));
45
+ assert.ok(fs.existsSync(path.join(app, 'poad', 'migrations')));
46
+
47
+ // .gitignore : lignes du modèle et de poad init
48
+ const gitignore = fs.readFileSync(path.join(app, '.gitignore'), 'utf8');
49
+ for (const line of ['poad/secrets.toml', 'poad/data/', 'node_modules/', '/public/env.json']) assert.ok(gitignore.split('\n').includes(line), line);
50
+
51
+ // Premier commit, sans secret
52
+ const log = spawnSync('git', ['log', '--format=%s'], { cwd: app, encoding: 'utf8' });
53
+ assert.match(log.stdout.trim(), /^Initial commit from @poadio\/starter-angular@/);
54
+ const files = spawnSync('git', ['ls-files'], { cwd: app, encoding: 'utf8' }).stdout.split('\n');
55
+ assert.ok(files.includes('package.json') && files.includes('poad/config.toml'));
56
+ assert.ok(!files.some((f) => f.startsWith('poad/secrets') || f.startsWith('poad/data/') || f === '.npmignore'));
57
+
58
+ // Aucune clé dans la sortie
59
+ const secrets = fs.readFileSync(path.join(app, 'poad', 'secrets.toml'), 'utf8');
60
+ for (const [, value] of secrets.matchAll(/=\s*"([^"]{16,})"/g)) assert.ok(!out.includes(value), 'a secret was printed');
61
+
62
+ // Dossier non vide : refusé, rien n'est touché
63
+ const again = spawnSync(process.execPath, [CLI, 'create', 'my-app', '--template', 'angular', '--yes'], { cwd, encoding: 'utf8', input: '' });
64
+ assert.match(again.stdout, /is not empty/);
65
+ assert.notStrictEqual(again.status, 0);
66
+
67
+ // Modèle pas encore publié : « coming soon »
68
+ const soon = spawnSync(process.execPath, [CLI, 'create', 'other', '--template', 'vanilla', '--yes'], { cwd, encoding: 'utf8', input: '' });
69
+ if (/coming soon/.test(soon.stdout)) {
70
+ assert.notStrictEqual(soon.status, 0);
71
+ assert.ok(!fs.existsSync(path.join(cwd, 'other')));
72
+ }
73
+ });
@@ -0,0 +1,95 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { parseCreateArgs, checkTarget } = require('../global/create');
6
+ const { tmpdir } = require('./helpers');
7
+
8
+ test('create arguments: flags, --key value, --key=value and key=value', () => {
9
+ assert.deepStrictEqual(parseCreateArgs(['app', '--template', 'Nuxt', '--yes', '--no-install', '--no-git', '--pm=pnpm']), {
10
+ dir: 'app', template: 'nuxt', pm: 'pnpm', from: null, yes: true, noInstall: true, noGit: true, help: false,
11
+ });
12
+ assert.strictEqual(parseCreateArgs(['template=vanilla', 'x']).template, 'vanilla');
13
+ assert.throws(() => parseCreateArgs(['a', 'b']), /unexpected argument/);
14
+ assert.throws(() => parseCreateArgs(['a', '--pm', 'yarn']), /--pm must be/);
15
+ assert.throws(() => parseCreateArgs(['a', '--template']), /needs a value/);
16
+ assert.throws(() => parseCreateArgs(['a', '--force']), /unknown option/);
17
+ });
18
+
19
+ test('target folder: new or empty only', (t) => {
20
+ const dir = tmpdir(t);
21
+ assert.strictEqual(checkTarget(path.join(dir, 'new')), 'new');
22
+ fs.writeFileSync(path.join(dir, '.DS_Store'), '');
23
+ assert.strictEqual(checkTarget(dir), 'empty');
24
+ fs.writeFileSync(path.join(dir, 'x'), '');
25
+ assert.throws(() => checkTarget(dir), /not empty/);
26
+ assert.throws(() => checkTarget(path.join(dir, 'x')), /not a folder/);
27
+ });
28
+
29
+ test('poad create --from <malicious.tgz>: refused, nothing left behind', (t) => {
30
+ const { spawnSync } = require('child_process');
31
+ const { tgz } = require('./helpers');
32
+ const cwd = tmpdir(t);
33
+ fs.writeFileSync(
34
+ path.join(cwd, 'evil.tgz'),
35
+ tgz([
36
+ { name: 'package/package.json', data: '{"name":"evil","version":"1.0.0"}' },
37
+ { name: 'package/../../escaped.txt', data: 'evil' },
38
+ ])
39
+ );
40
+ const r = spawnSync(process.execPath, [path.join(__dirname, '..', 'poad.js'), 'create', 'app', '--from', 'evil.tgz', '--yes', '--no-install', '--no-git'], { cwd, encoding: 'utf8', input: '' });
41
+ assert.match(r.stdout + r.stderr, /Template unavailable: refused entry .*"\.\."/);
42
+ assert.notStrictEqual(r.status, 0);
43
+ assert.deepStrictEqual(fs.readdirSync(cwd), ['evil.tgz']);
44
+ assert.ok(!fs.existsSync(path.join(cwd, '..', 'escaped.txt')));
45
+ });
46
+
47
+ test('created title: framework label, never "Application application"', () => {
48
+ const { createdTitle } = require('../global/create');
49
+ const { templateByValue } = require('../utils/starter');
50
+ assert.strictEqual(createdTitle(null, {}), 'Application created');
51
+ assert.strictEqual(createdTitle(null, { label: 'Next.js' }), 'Next.js application created');
52
+ assert.strictEqual(createdTitle(templateByValue('angular'), { label: 'Angular' }), 'Angular application created');
53
+ assert.strictEqual(createdTitle(templateByValue('vanilla'), { label: null }), 'Vanilla application created');
54
+ });
55
+
56
+ // poad create --from <archive locale> jusqu'au bout (sans réseau, sans
57
+ // installation ni git) : titre et URL du front selon le framework du modèle
58
+ function createFrom(t, pkg, extra = []) {
59
+ const { spawnSync } = require('child_process');
60
+ const { tgz } = require('./helpers');
61
+ const cwd = tmpdir(t);
62
+ const home = path.join(cwd, 'home');
63
+ fs.mkdirSync(home);
64
+ // version déjà vérifiée : pas de npm view
65
+ fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
66
+ fs.writeFileSync(path.join(cwd, 'tpl.tgz'), tgz([{ name: 'package/package.json', data: JSON.stringify(pkg) }, ...extra]));
67
+ const r = spawnSync(process.execPath, ['--require', path.join(__dirname, 'offline-stub.js'), path.join(__dirname, '..', 'poad.js'), 'create', 'app', '--from', 'tpl.tgz', '--yes', '--no-install', '--no-git'], {
68
+ cwd,
69
+ encoding: 'utf8',
70
+ input: '',
71
+ timeout: 30000,
72
+ env: { ...process.env, HOME: home, NODE_OPTIONS: '' },
73
+ });
74
+ return { r, out: r.stdout + r.stderr, app: path.join(cwd, 'app') };
75
+ }
76
+
77
+ test('poad create --from a Next.js template: "Next.js application created", URL from poad.port, poad.port kept', (t) => {
78
+ const pkg = { name: '@poadio/starter-next', version: '0.1.0', dependencies: { next: '16.4.6' }, poad: { port: 3300, template: { framework: 'next', label: 'Next.js + @poadio/ui-react', port: 3300 } } };
79
+ const { r, out, app } = createFrom(t, pkg);
80
+ assert.strictEqual(r.status, 0, out);
81
+ assert.match(out, /Next\.js application created/);
82
+ assert.doesNotMatch(out, /Application application/);
83
+ assert.match(out, /front-end on http:\/\/localhost:3300/);
84
+ const written = JSON.parse(fs.readFileSync(path.join(app, 'package.json'), 'utf8'));
85
+ assert.strictEqual(written.poad.port, 3300);
86
+ assert.ok(!('template' in written.poad));
87
+ });
88
+
89
+ test('poad create --from an unknown template: "Application created", no URL', (t) => {
90
+ const { r, out } = createFrom(t, { name: 'custom', version: '1.0.0' });
91
+ assert.strictEqual(r.status, 0, out);
92
+ assert.match(out, /✔ Application created in app/);
93
+ assert.doesNotMatch(out, /Application application|localhost:\d+ *$/m);
94
+ assert.doesNotMatch(out, /front-end on/);
95
+ });
@@ -0,0 +1,29 @@
1
+ // Chargé avec node --require par test/help.test.js : tout appel à Docker, à un
2
+ // processus ou au réseau est noté dans POAD_TEST_CALLS, puis refusé. Une aide
3
+ // (--help, -h) ne doit rien noter.
4
+ const fs = require('fs');
5
+ const Module = require('module');
6
+ const childProcess = require('child_process');
7
+
8
+ const file = process.env.POAD_TEST_CALLS;
9
+ const note = (what) => {
10
+ fs.appendFileSync(file, what + '\n');
11
+ throw new Error(`blocked by the test: ${what}`);
12
+ };
13
+
14
+ class FakeDocker {
15
+ constructor() {
16
+ note('new Docker()');
17
+ }
18
+ }
19
+
20
+ const load = Module._load;
21
+ Module._load = function (request, ...rest) {
22
+ if (request === 'dockerode') return FakeDocker;
23
+ return load.call(this, request, ...rest);
24
+ };
25
+
26
+ for (const fn of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {
27
+ childProcess[fn] = (cmd, args) => note(`child_process.${fn}(${cmd} ${Array.isArray(args) ? args.join(' ') : ''})`);
28
+ }
29
+ globalThis.fetch = async (url) => note(`fetch(${url})`);
@@ -0,0 +1,124 @@
1
+ // --help et -h sur toutes les commandes : l'aide s'affiche, rien ne s'exécute.
2
+ // Le CLI tourne dans un projet poad factice avec test/help-stub.js chargé :
3
+ // Docker, processus et réseau y sont refusés et notés. Aucune note attendue.
4
+ const test = require('node:test');
5
+ const assert = require('node:assert');
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { spawnSync } = require('child_process');
9
+ const { tmpdir } = require('./helpers');
10
+ const { helpRequested, resolveCommand } = require('../utils/help');
11
+
12
+ const POAD = path.join(__dirname, '..', 'poad.js');
13
+ const STUB = path.join(__dirname, 'help-stub.js');
14
+
15
+ /** Projet poad factice (conteneur inexistant) et HOME à part */
16
+ function sandbox(t) {
17
+ const dir = tmpdir(t);
18
+ fs.mkdirSync(path.join(dir, 'poad'));
19
+ const config = 'project_id = "helptest"\nproject_uuid = "poad-help-test-not-a-container"\nengine = "0.28.0"\n[web]\nport = 1\n[db]\nport = 1\n[auth]\nsecret = "s"\nanon = "a"\nservice = "x"\n';
20
+ fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), config);
21
+ fs.mkdirSync(path.join(dir, 'home'));
22
+ return { dir, config, calls: path.join(dir, 'calls.log') };
23
+ }
24
+
25
+ function poad(box, args) {
26
+ return spawnSync(process.execPath, ['--require', STUB, POAD, ...args], {
27
+ cwd: box.dir,
28
+ encoding: 'utf8',
29
+ input: '',
30
+ timeout: 15000,
31
+ env: { ...process.env, HOME: path.join(box.dir, 'home'), POAD_TEST_CALLS: box.calls, NODE_OPTIONS: '' },
32
+ });
33
+ }
34
+
35
+ /** Toutes les commandes des deux tables, sous-commandes comprises */
36
+ function allCommands() {
37
+ const out = [];
38
+ const walk = (node, prefix) => {
39
+ for (const [k, v] of Object.entries(node)) {
40
+ if (k === 'description') continue;
41
+ out.push([...prefix, k]);
42
+ if (v && typeof v === 'object') walk(v, [...prefix, k]);
43
+ }
44
+ };
45
+ walk(require('../global/cli'), []);
46
+ walk(require('../project/cli'), []);
47
+ return out;
48
+ }
49
+
50
+ test('help flag detection', () => {
51
+ assert.strictEqual(helpRequested(['stop', '--help']), true);
52
+ assert.strictEqual(helpRequested(['db', 'reset', '-h']), true);
53
+ assert.strictEqual(helpRequested(['flows', 'run', 'x', 'msg=--help']), false);
54
+ assert.strictEqual(helpRequested(['stop']), false);
55
+ });
56
+
57
+ test('command resolution: deepest known command, global first', () => {
58
+ assert.deepStrictEqual(resolveCommand(['db', 'reset', '--yes', '--help']).dir, ['db', 'reset']);
59
+ assert.strictEqual(resolveCommand(['db', 'reset', '--help']).scope, 'project');
60
+ assert.deepStrictEqual(resolveCommand(['upgrade', '--rollback', '-h']).dir, ['upgrade']);
61
+ assert.strictEqual(resolveCommand(['stop', 'kc', '--help']).scope, 'global');
62
+ assert.strictEqual(resolveCommand(['nope', '--help']), null);
63
+ // une clé héritée d'Object n'est pas une commande
64
+ assert.strictEqual(resolveCommand(['constructor', '--help']), null);
65
+ });
66
+
67
+ test('destructive commands with --help or -h: usage shown, nothing run (no Docker, no process, no network)', (t) => {
68
+ const box = sandbox(t);
69
+ const cases = [
70
+ ['stop', '--help'],
71
+ ['stop', '-h'],
72
+ ['stop', 'kc', '--help'],
73
+ ['db', 'reset', '--help'],
74
+ ['db', 'reset', '--yes', '-h'],
75
+ ['clean', '--yes', '--help'],
76
+ ['upgrade', '--rollback', '--help'],
77
+ ['upgrade', '--yes', '-h'],
78
+ ['start', '--help'],
79
+ ['run', '--all', '--help'],
80
+ ['init', '--help'],
81
+ ['install', '--help'],
82
+ ['setup', '--none', '--help'],
83
+ ['migrate', '--help'],
84
+ ['flows', 'run', 'x', '--help'],
85
+ ['help', 'stop'],
86
+ ];
87
+ for (const args of cases) {
88
+ const r = poad(box, args);
89
+ assert.strictEqual(r.status, 0, `${args.join(' ')}: exit ${r.status}\n${r.stdout}${r.stderr}`);
90
+ assert.match(r.stdout, /Usage :/, args.join(' '));
91
+ assert.ok(!fs.existsSync(box.calls), `${args.join(' ')} called: ${fs.existsSync(box.calls) && fs.readFileSync(box.calls, 'utf8')}`);
92
+ }
93
+ // rien n'a bougé dans le projet
94
+ assert.deepStrictEqual(fs.readdirSync(box.dir).sort(), ['home', 'poad']);
95
+ assert.deepStrictEqual(fs.readdirSync(path.join(box.dir, 'poad')), ['config.toml']);
96
+ assert.strictEqual(fs.readFileSync(path.join(box.dir, 'poad', 'config.toml'), 'utf8'), box.config);
97
+ assert.deepStrictEqual(fs.readdirSync(path.join(box.dir, 'home')), []);
98
+ });
99
+
100
+ test('every command answers --help with its usage and runs nothing', (t) => {
101
+ const box = sandbox(t);
102
+ for (const cmd of allCommands()) {
103
+ const r = poad(box, [...cmd, '--help']);
104
+ assert.strictEqual(r.status, 0, `${cmd.join(' ')}: exit ${r.status}\n${r.stdout}${r.stderr}`);
105
+ assert.match(r.stdout, /Usage :/, cmd.join(' '));
106
+ assert.ok(!fs.existsSync(box.calls), `${cmd.join(' ')} called: ${fs.existsSync(box.calls) && fs.readFileSync(box.calls, 'utf8')}`);
107
+ }
108
+ });
109
+
110
+ test('the stub does catch a real call (poad stop without --help reaches Docker)', (t) => {
111
+ const box = sandbox(t);
112
+ // version déjà vérifiée : pas de npm view avant la commande
113
+ fs.writeFileSync(path.join(box.dir, 'home', '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
114
+ poad(box, ['stop']);
115
+ assert.match(fs.readFileSync(box.calls, 'utf8'), /new Docker\(\)/);
116
+ });
117
+
118
+ test('unknown command with --help: error and command list, exit 1', (t) => {
119
+ const box = sandbox(t);
120
+ const r = poad(box, ['nope', '--help']);
121
+ assert.strictEqual(r.status, 1);
122
+ assert.match(r.stdout + r.stderr, /Unknown command : nope/);
123
+ assert.ok(!fs.existsSync(box.calls));
124
+ });
@@ -0,0 +1,53 @@
1
+ // Fabrication d'archives tar/tgz pour les tests (en-têtes ustar écrits à la main,
2
+ // pour pouvoir y mettre ce qu'un outil tar refuserait : « .. », chemins absolus, liens)
3
+ const zlib = require('zlib');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+
8
+ const octal = (n, len) => n.toString(8).padStart(len - 1, '0') + '\0';
9
+
10
+ /** entries : [{ name, type: '0'|'2'|'1'|'5'|'x'..., data, linkname, mode }] */
11
+ function tar(entries) {
12
+ const blocks = [];
13
+ for (const e of entries) {
14
+ const data = Buffer.isBuffer(e.data) ? e.data : Buffer.from(e.data || '');
15
+ const h = Buffer.alloc(512);
16
+ h.write(e.name, 0, 100, 'utf8');
17
+ h.write(octal(e.mode || 0o644, 8), 100);
18
+ h.write(octal(0, 8), 108);
19
+ h.write(octal(0, 8), 116);
20
+ h.write(octal(data.length, 12), 124);
21
+ h.write(octal(0, 12), 136);
22
+ h.write(' '.repeat(8), 148);
23
+ h.write(e.type || '0', 156);
24
+ if (e.linkname) h.write(e.linkname, 157, 100);
25
+ h.write('ustar\0', 257);
26
+ h.write('00', 263);
27
+ let sum = 0;
28
+ for (const b of h) sum += b;
29
+ h.write(octal(sum, 7) + ' ', 148);
30
+ blocks.push(h, data, Buffer.alloc((512 - (data.length % 512)) % 512));
31
+ }
32
+ blocks.push(Buffer.alloc(1024));
33
+ return Buffer.concat(blocks);
34
+ }
35
+
36
+ const tgz = (entries) => zlib.gzipSync(tar(entries));
37
+
38
+ /** Enregistrement pax « longueur clé=valeur\n » */
39
+ function paxRecord(key, value) {
40
+ const body = ` ${key}=${value}\n`;
41
+ let len = body.length + 1;
42
+ while (String(len).length + body.length !== len) len = String(len).length + body.length;
43
+ return `${len}${body}`;
44
+ }
45
+
46
+ /** Dossier temporaire (sous TMPDIR) supprimé à la fin du test */
47
+ function tmpdir(t, prefix = 'poad-test-') {
48
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
49
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
50
+ return dir;
51
+ }
52
+
53
+ module.exports = { tar, tgz, paxRecord, tmpdir };
@@ -0,0 +1,5 @@
1
+ // Chargé avec node --require par les tests qui lancent poad create : pas de
2
+ // réseau (l'engine retenu par poad init est alors celui que le CLI connaît).
3
+ globalThis.fetch = async () => {
4
+ throw new Error('offline (test)');
5
+ };