poad 2.38.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.
package/global/cli.js CHANGED
@@ -9,7 +9,8 @@
9
9
  module.exports = {
10
10
  install: `Install poad environment`,
11
11
  init: `Init poad project`,
12
- start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one',
12
+ create: 'Create an application wired to poad in a new folder: create <dir> --template angular|next|nuxt|vanilla (asked if omitted), --yes, --no-install, --no-git, --pm bun|npm|pnpm. Template from npm (integrity checked), then poad init, dependencies, first git commit (create --help)',
13
+ start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state, secrets hidden: poad info --secrets (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one',
13
14
  stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
14
15
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
15
16
  clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey/flows runner, networks, unused engine images (--dry-run to list, --yes without question)',
@@ -0,0 +1,286 @@
1
+ // poad create [dir] [--template angular|next|nuxt|vanilla] [--yes] [--no-install] [--no-git] [--pm bun|npm|pnpm]
2
+ //
3
+ // Crée une application branchée sur poad dans un dossier neuf (ou vide) :
4
+ // 1. modèle @poadio/starter-<template>, dernière version du registre npm :
5
+ // archive téléchargée en HTTPS, intégrité sha512 vérifiée, extraite sans
6
+ // dépendance (utils/tar : ni chemin absolu, ni « .. », ni lien) ;
7
+ // 2. .gitignore rétabli, fichiers de publication retirés, package.json
8
+ // réécrit (nom du dossier, 0.1.0, private) ;
9
+ // 3. poad init dans le dossier (poad/config.toml, secrets, migrations) ;
10
+ // 4. dépendances installées (bun s'il est là, sinon npm), sauf --no-install ;
11
+ // 5. git init et premier commit, sauf --no-git.
12
+ // Ensuite : cd <dir> && bun start (démarre poad puis le front).
13
+ //
14
+ // Options aussi au format du CLI : template=next pm=npm. --from=<archive.tgz> :
15
+ // un modèle local (npm pack), pour mettre au point un nouveau modèle.
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const { spawn, spawnSync } = require('child_process');
19
+
20
+ const PMS = ['bun', 'npm', 'pnpm'];
21
+ const VALUED = ['template', 'pm', 'from'];
22
+ const FLAGS = { yes: 'yes', y: 'yes', 'no-install': 'noInstall', 'no-git': 'noGit', help: 'help', h: 'help' };
23
+
24
+ class UsageError extends Error {}
25
+
26
+ /** Arguments tels que tapés -> { dir, template, pm, from, yes, noInstall, noGit, help } */
27
+ function parseCreateArgs(raw = []) {
28
+ const opts = { dir: null, template: null, pm: null, from: null, yes: false, noInstall: false, noGit: false, help: false };
29
+ for (let i = 0; i < raw.length; i++) {
30
+ const arg = String(raw[i]);
31
+ const m = /^--?([a-z][a-z-]*)(?:=(.*))?$/.exec(arg) || /^([a-z]+)=(.*)$/.exec(arg);
32
+ if (!m) {
33
+ if (opts.dir) throw new UsageError(`unexpected argument "${arg}" (the folder is already "${opts.dir}")`);
34
+ opts.dir = arg;
35
+ continue;
36
+ }
37
+ const [, key, inline] = m;
38
+ if (VALUED.includes(key)) {
39
+ const value = inline !== undefined ? inline : raw[++i];
40
+ if (value === undefined || value === '' || /^--?[a-z]/.test(value)) throw new UsageError(`--${key} needs a value`);
41
+ opts[key] = value;
42
+ } else if (FLAGS[key] && inline === undefined) {
43
+ opts[FLAGS[key]] = true;
44
+ } else {
45
+ throw new UsageError(`unknown option "${arg}"`);
46
+ }
47
+ }
48
+ if (opts.template) opts.template = opts.template.toLowerCase();
49
+ if (opts.pm && !PMS.includes(opts.pm)) throw new UsageError(`--pm must be one of ${PMS.join(', ')}`);
50
+ return opts;
51
+ }
52
+
53
+ const has = (cmd) => {
54
+ const r = spawnSync(cmd, ['--version'], { encoding: 'utf8', shell: process.platform === 'win32' });
55
+ return !r.error && r.status === 0;
56
+ };
57
+
58
+ /** Dossier cible : neuf, ou vide (un .DS_Store ne compte pas) */
59
+ function checkTarget(target) {
60
+ if (!fs.existsSync(target)) return 'new';
61
+ if (!fs.statSync(target).isDirectory()) throw new UsageError(`${target} exists and is not a folder`);
62
+ const content = fs.readdirSync(target).filter((n) => n !== '.DS_Store');
63
+ if (content.length) throw new UsageError(`${target} is not empty: choose a new folder`);
64
+ return 'empty';
65
+ }
66
+
67
+ /** Disponibilité de chaque modèle sur npm (en parallèle, délai court) */
68
+ async function availability(templates, registry) {
69
+ const { packageMetadata, cachedVersion } = registry;
70
+ return Promise.all(
71
+ templates.map(async (t) => {
72
+ const metadata = await packageMetadata(t.package, { timeout: 3000 });
73
+ const cached = cachedVersion(t.package);
74
+ const state = metadata.status === 'ok' ? 'available' : metadata.status === 'missing' ? 'soon' : cached ? 'cached' : 'offline';
75
+ return { ...t, metadata, cached, state };
76
+ })
77
+ );
78
+ }
79
+
80
+ /** Commande lancée de façon asynchrone (le spinner tourne) ; { ok, output } */
81
+ const run = (cmd, args, cwd) =>
82
+ new Promise((resolve) => {
83
+ let output = '';
84
+ const child = spawn(cmd, args, { cwd, shell: process.platform === 'win32' });
85
+ child.stdout.on('data', (d) => (output += d));
86
+ child.stderr.on('data', (d) => (output += d));
87
+ child.on('error', (err) => resolve({ ok: false, output: err.message }));
88
+ child.on('close', (code) => resolve({ ok: code === 0, output }));
89
+ });
90
+
91
+ const tail = (text, n = 8) => text.trim().split(/\r?\n/).slice(-n).map((l) => ` ${l}`).join('\n');
92
+
93
+ /** « Next.js application created » ; framework inconnu (--from) : « Application created » */
94
+ function createdTitle(template, dev = {}) {
95
+ const label = dev.label || (template && template.label.split(' (')[0]);
96
+ return label ? `${label} application created` : 'Application created';
97
+ }
98
+
99
+ function usage(chalk) {
100
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad create <dir>')} ${chalk.cyan('[--template angular|next|nuxt|vanilla] [--yes] [--no-install] [--no-git] [--pm bun|npm|pnpm]')}`);
101
+ console.log(' ');
102
+ console.log(' Creates an application wired to poad in a new folder, from the template @poadio/starter-<template> on npm,');
103
+ console.log(' initialises its poad project (poad/config.toml), installs the dependencies and makes the first git commit.');
104
+ console.log(' ');
105
+ console.log(` ${chalk.cyanBright('--template')} angular, next, nuxt or vanilla (asked when omitted in a terminal; angular otherwise)`);
106
+ console.log(` ${chalk.cyanBright('--yes')} no question`);
107
+ console.log(` ${chalk.cyanBright('--no-install')} do not install the dependencies (bun start does it later)`);
108
+ console.log(` ${chalk.cyanBright('--no-git')} no git repository, no commit`);
109
+ console.log(` ${chalk.cyanBright('--pm')} bun, npm or pnpm (default: bun if installed, else npm)`);
110
+ console.log(` ${chalk.cyanBright('--from')} a local template archive (npm pack), to develop a template`);
111
+ console.log(' ');
112
+ console.log(' The front-end URL shown at the end comes from the template: poad.port in its package.json (or poad.template.port),');
113
+ console.log(' else the default port of its framework; Angular gets the first free port from there, written to angular.json.');
114
+ console.log(' ');
115
+ }
116
+
117
+ module.exports = async (_parsed, raw = []) => {
118
+ const chalk = require('chalk-v2');
119
+ const ora = require('ora');
120
+ const registry = require('../utils/registry');
121
+ const starter = require('../utils/starter');
122
+ const { extractTgz } = require('../utils/tar');
123
+ const fail = (msg) => {
124
+ process.exitCode = 1;
125
+ console.log(chalk.redBright(` ${msg}`));
126
+ };
127
+
128
+ let opts;
129
+ try {
130
+ opts = parseCreateArgs(raw);
131
+ } catch (err) {
132
+ fail(err.message);
133
+ return usage(chalk);
134
+ }
135
+ if (opts.help) return usage(chalk);
136
+ const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY && !opts.yes);
137
+ const prompts = tty ? require('@inquirer/prompts') : null;
138
+
139
+ // 1. Dossier
140
+ if (!opts.dir && prompts) opts.dir = await prompts.input({ message: 'Folder of the new application', default: 'my-app' }).catch(() => null);
141
+ if (!opts.dir) {
142
+ fail('Missing folder: poad create <dir>');
143
+ return usage(chalk);
144
+ }
145
+ const target = path.resolve(process.cwd(), opts.dir);
146
+ const rel = path.relative(process.cwd(), target) || '.';
147
+ let existed;
148
+ try {
149
+ existed = checkTarget(target) === 'empty';
150
+ } catch (err) {
151
+ return fail(err.message);
152
+ }
153
+
154
+ // Gestionnaire de paquets : vérifié avant de télécharger quoi que ce soit
155
+ const bun = has('bun');
156
+ const pm = opts.pm || (bun ? 'bun' : 'npm');
157
+ if (opts.pm && !opts.noInstall && !has(opts.pm)) return fail(`${opts.pm} is not installed: choose another --pm, or --no-install.`);
158
+
159
+ // 2. Modèle
160
+ let template = opts.template ? starter.templateByValue(opts.template) : null;
161
+ if (opts.template && !template) return fail(`Unknown template "${opts.template}": ${starter.TEMPLATES.map((t) => t.value).join(', ')}.`);
162
+ let metadata;
163
+ if (!opts.from) {
164
+ if (!template && prompts) {
165
+ const spin = ora('Checking the templates on npm').start();
166
+ const states = await availability(starter.TEMPLATES, registry);
167
+ spin.stop();
168
+ const note = { soon: 'coming soon', offline: 'offline', cached: 'offline, cached' };
169
+ const choices = states.map((t) => ({
170
+ value: t.value,
171
+ short: t.label,
172
+ name: `${t.label.padEnd(26)}${chalk.grey(t.package)}${t.state === 'cached' ? chalk.grey(` (${note.cached} ${t.cached})`) : ''}`,
173
+ disabled: t.state === 'soon' || t.state === 'offline' ? note[t.state] : false,
174
+ }));
175
+ if (choices.every((c) => c.disabled)) return fail('No template can be fetched: the npm registry cannot be reached and nothing is cached.');
176
+ const value = await prompts.select({ message: 'Template', choices }).catch(() => null);
177
+ if (!value) return;
178
+ template = starter.templateByValue(value);
179
+ metadata = states.find((s) => s.value === value).metadata;
180
+ }
181
+ if (!template) {
182
+ template = starter.templateByValue('angular');
183
+ console.log(chalk.grey(` Template: angular (--template to choose another one).`));
184
+ }
185
+ if (!metadata) metadata = await registry.packageMetadata(template.package, { timeout: 5000 });
186
+ if (metadata.status === 'missing') return fail(`${template.value}: coming soon (${template.package} is not published yet).`);
187
+ }
188
+
189
+ // 3. Téléchargement, intégrité, extraction
190
+ let source;
191
+ let progress = ora(opts.from ? `Reading ${opts.from}` : `Fetching ${template.package}`).start();
192
+ try {
193
+ if (opts.from) {
194
+ const file = path.resolve(process.cwd(), opts.from);
195
+ source = { name: null, version: null, buf: fs.readFileSync(file), source: 'local' };
196
+ } else {
197
+ const got = await registry.fetchLatestTarball(template.package, { metadata, timeout: 5000 });
198
+ source = { name: template.package, ...got };
199
+ }
200
+ extractTgz(source.buf, target);
201
+ } catch (err) {
202
+ progress.fail(chalk.redBright(`Template unavailable: ${err.message}`));
203
+ process.exitCode = 1;
204
+ // Rien ne reste d'une extraction ratée
205
+ if (!existed) fs.rmSync(target, { recursive: true, force: true });
206
+ else if (fs.existsSync(target)) for (const n of fs.readdirSync(target)) if (n !== '.DS_Store') fs.rmSync(path.join(target, n), { recursive: true, force: true });
207
+ return;
208
+ }
209
+ const tplPkg = starter.readPackage(target);
210
+ if (!tplPkg) {
211
+ progress.fail(chalk.redBright('Template unusable: no package.json in it.'));
212
+ process.exitCode = 1;
213
+ if (!existed) fs.rmSync(target, { recursive: true, force: true });
214
+ return;
215
+ }
216
+ const from = `${source.name || tplPkg.name}@${source.version || tplPkg.version}`;
217
+ progress.succeed(`Template ${chalk.bold(from)}${source.source === 'registry' ? chalk.grey(' (integrity verified)') : source.source === 'cache' ? chalk.grey(' (cache, integrity verified)') : chalk.grey(' (local archive)')}`);
218
+
219
+ // 4. Fichiers de publication, .gitignore, package.json
220
+ starter.prepareStarter(target);
221
+ const name = starter.packageName(path.basename(target));
222
+ const pkg = starter.rewritePackageJson(tplPkg, { name, title: path.basename(target), from });
223
+ fs.writeFileSync(path.join(target, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
224
+ for (const html of ['src/index.html', 'index.html']) {
225
+ const file = path.join(target, html);
226
+ if (fs.existsSync(file)) fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/<title>[^<]*<\/title>/, `<title>${path.basename(target).replace(/[<&]/g, '')}</title>`));
227
+ }
228
+ starter.adaptToPackageManager(target, pm);
229
+ // Port et URL du front selon le framework (poad.port / poad.template.port du modèle)
230
+ const dev = await starter.devServer(target, tplPkg);
231
+
232
+ // 5. poad init dans le dossier (le dépôt git est fait plus bas)
233
+ const cwd = process.cwd();
234
+ try {
235
+ process.chdir(target);
236
+ await require('./init')({}, [], { git: false, setup: false });
237
+ } catch (err) {
238
+ return fail(`poad init failed in ${rel}: ${err.message}`);
239
+ } finally {
240
+ process.chdir(cwd);
241
+ }
242
+
243
+ // 6. Dépendances
244
+ let installed = false;
245
+ if (!opts.noInstall) {
246
+ console.log(' ');
247
+ progress = ora(`Installing the dependencies (${pm} install)`).start();
248
+ const r = await run(pm, ['install'], target);
249
+ if (r.ok) {
250
+ installed = true;
251
+ progress.succeed('Dependencies installed');
252
+ } else {
253
+ progress.fail(chalk.yellowBright(`${pm} install failed (bun start installs them too):`));
254
+ console.log(chalk.grey(tail(r.output)));
255
+ }
256
+ }
257
+
258
+ // 7. Dépôt git et premier commit
259
+ if (!opts.noGit) {
260
+ const git = require('../utils/git');
261
+ const repo = git.setupRepo(target);
262
+ if (repo.repo === 'created') {
263
+ const add = spawnSync('git', ['add', '-A'], { cwd: target, encoding: 'utf8' });
264
+ const commit = add.status === 0 ? spawnSync('git', ['commit', '-q', '-m', `Initial commit from ${from} (poad create)`], { cwd: target, encoding: 'utf8' }) : add;
265
+ if (commit.status === 0) console.log(chalk.grey(' git repository created, first commit done (branch main).'));
266
+ else console.log(chalk.yellowBright(` git repository created, but the first commit failed: ${(commit.stderr || commit.stdout).trim().split('\n').pop()}`));
267
+ } else if (repo.repo === 'existing') console.log(chalk.grey(` Inside the git repository ${repo.root}: no new repository, nothing committed.`));
268
+ else if (repo.repo === 'no-git') console.log(chalk.yellowBright(' git is not installed: no repository created.'));
269
+ else if (repo.repo === 'failed') console.log(chalk.yellowBright(` git init failed: ${repo.error}`));
270
+ }
271
+
272
+ // 8. La suite
273
+ const start = pm === 'npm' ? 'npm start' : `${pm} start`;
274
+ console.log(' ');
275
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(createdTitle(template, dev))} in ${chalk.cyanBright(rel)}`);
276
+ console.log(' ');
277
+ console.log(` ${chalk.bold(`cd ${rel} && ${start}`)}${chalk.grey(` starts the poad project, then the front-end${dev.url ? ` on ${dev.url}` : ''}${installed ? '' : ' (installs the dependencies first)'}`)}`);
278
+ console.log(chalk.grey(' poad setup: choose the services started with the project (Keycloak, Valkey, e-mails).'));
279
+ console.log(' ');
280
+ };
281
+
282
+ module.exports.help = () => usage(require('chalk-v2'));
283
+ module.exports.parseCreateArgs = parseCreateArgs;
284
+ module.exports.createdTitle = createdTitle;
285
+ module.exports.checkTarget = checkTarget;
286
+ module.exports.UsageError = UsageError;
package/global/init.js CHANGED
@@ -7,7 +7,11 @@
7
7
  // .gitignore à la racine (fichiers des systèmes, éditeurs, dépendances,
8
8
  // secrets), puis git init si git est installé et que le
9
9
  // dossier n'est pas déjà dans un dépôt (aucun commit)
10
- module.exports = async () => {
10
+ //
11
+ // Appelé par poad create avec options : { git: false } (le .gitignore seulement,
12
+ // poad create s'occupe du dépôt), { setup: false } (pas de question sur les
13
+ // services). Renvoie { initialized, repo } (repo : résultat de setupRepo).
14
+ module.exports = async (args = {}, raw, options = {}) => {
11
15
  const path = require('path');
12
16
  const fs = require('fs');
13
17
  const { findFreePorts } = require('../utils/ports');
@@ -19,7 +23,10 @@ module.exports = async () => {
19
23
 
20
24
  const dir = path.join(process.cwd(), 'poad');
21
25
  const root = path.join(dir, 'config.toml');
22
- if (fs.existsSync(root)) return console.log(chalk.bold('\n ✅ Your project has already been initialized'));
26
+ if (fs.existsSync(root)) {
27
+ console.log(chalk.bold('\n ✅ Your project has already been initialized'));
28
+ return { initialized: false };
29
+ }
23
30
 
24
31
  fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
25
32
  const ports = await findFreePorts(3);
@@ -48,7 +55,8 @@ module.exports = async () => {
48
55
  console.log(chalk.grey(' poad/config.toml and poad/migrations/ are versioned; poad/secrets.toml and poad/data/ stay on this machine.'));
49
56
 
50
57
  // Dépôt git : les migrations suivent les branches
51
- const repo = require('../utils/git').setupRepo(process.cwd());
58
+ const git = require('../utils/git');
59
+ const repo = options.git === false ? { gitignore: git.ensureRootGitignore(process.cwd()), repo: 'skipped' } : git.setupRepo(process.cwd());
52
60
  if (repo.gitignore) console.log(chalk.grey(` .gitignore: ${repo.gitignore} entries (macOS, Windows, Linux, editors, dependencies, poad secrets).`));
53
61
  if (repo.repo === 'created') console.log(chalk.grey(' git repository created (branch main, nothing committed yet).'));
54
62
  else if (repo.repo === 'existing') console.log(chalk.grey(` Already in the git repository ${path.relative(process.cwd(), repo.root) || '.'}: left as is.`));
@@ -56,11 +64,15 @@ module.exports = async () => {
56
64
  else if (repo.repo === 'failed') console.log(chalk.yellowBright(` git init failed: ${repo.error}`));
57
65
 
58
66
  // Dans un terminal : on enchaîne sur le choix des services (poad setup)
59
- if (process.stdin.isTTY && process.stdout.isTTY) {
67
+ if (options.setup !== false && process.stdin.isTTY && process.stdout.isTTY) {
60
68
  const { confirm } = require('@inquirer/prompts');
61
69
  console.log(' ');
62
70
  const go = await confirm({ message: 'Choose the services started with the project now (Keycloak, Valkey, e-mails)?', default: true }).catch(() => false);
63
- if (go) return require('../project/setup')({});
71
+ if (go) {
72
+ await require('../project/setup')({});
73
+ return { initialized: true, repo };
74
+ }
64
75
  console.log(chalk.grey(' Later: "poad setup".'));
65
76
  }
77
+ return { initialized: true, repo };
66
78
  };
package/global/run.js CHANGED
@@ -33,14 +33,7 @@ module.exports = async (args = {}) => {
33
33
  if (!quiet) console.log(' ');
34
34
  if (listed && !wanted.length) return;
35
35
  if (!all && !wanted.length) {
36
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
37
- console.log(' ');
38
- console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
39
- console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
40
- console.log(` ${chalk.cyanBright('runner')} Flows runner (engine 0.18.0+, needs Valkey): starts the container steps of the flows, gets the Docker socket`);
41
- console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
42
- console.log(' ');
43
- return;
36
+ return help();
44
37
  }
45
38
 
46
39
  const root = findPoadDir(process.cwd());
@@ -190,7 +183,7 @@ module.exports = async (args = {}) => {
190
183
  const info = {
191
184
  'Keycloak URL': base,
192
185
  Issuer: `${base}/realms/${project.realm}`,
193
- 'Admin console': `${base}/admin (admin ${secrets.admin_password})`,
186
+ 'Admin console': `${base}/admin (admin ${require('../utils/report').secretValue(secrets.admin_password)})`,
194
187
  Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
195
188
  'Test users': project.users.map(
196
189
  (u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
@@ -229,7 +222,7 @@ module.exports = async (args = {}) => {
229
222
  prettyoutput({
230
223
  'Keycloak URL': `${base} (shared by the local projects)`,
231
224
  Issuer: `${base}/realms/${realm}`,
232
- 'Admin console': `${base}/admin (admin ${state.admin_password})`,
225
+ 'Admin console': `${base}/admin (admin ${require('../utils/report').secretValue(state.admin_password)})`,
233
226
  Provider: `"${kc.PROVIDER}" (signInWithOAuth({ provider: '${kc.PROVIDER}' }))`,
234
227
  'Test users': project.users.map(
235
228
  (u) => `${u.username.padEnd(6)} ${u.password} ${u.email}${u.roles.length ? ` [${u.roles.join(', ')}]` : ''}${u.emailVerified ? '' : ' (email not verified)'}`
@@ -398,3 +391,17 @@ module.exports = async (args = {}) => {
398
391
  }
399
392
  }
400
393
  };
394
+
395
+ /** poad run sans service, ou poad run --help */
396
+ function help() {
397
+ const chalk = require('chalk-v2');
398
+ console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad run <service>')}`);
399
+ console.log(' ');
400
+ console.log(` ${chalk.cyanBright('keycloak')} ${chalk.grey('(or kc)')} Local Keycloak, registered as the "keycloak" OIDC provider`);
401
+ console.log(` ${chalk.cyanBright('valkey')} ${chalk.grey('(or redis)')} Local Valkey (Redis compatible), REDIS_URL of the engine`);
402
+ console.log(` ${chalk.cyanBright('runner')} Flows runner (engine 0.18.0+, needs Valkey): starts the container steps of the flows, gets the Docker socket`);
403
+ console.log(` ${chalk.cyanBright('--all')} ${chalk.grey('(or all)')} The project if stopped, then every service configured in config.toml`);
404
+ console.log(' ');
405
+ }
406
+
407
+ module.exports.help = help;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.38.0",
3
+ "version": "2.39.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
@@ -9,7 +9,9 @@
9
9
  "poad": "poad.js"
10
10
  },
11
11
  "scripts": {
12
- "build": "bun install"
12
+ "build": "bun install",
13
+ "test": "node --test test/*.test.js",
14
+ "test:e2e": "POAD_E2E=1 node --test test/create.e2e.test.js"
13
15
  },
14
16
  "dependencies": {
15
17
  "@inquirer/prompts": "^7.10.1",
package/poad.js CHANGED
@@ -365,7 +365,8 @@ const processCommands = (args) => {
365
365
  if (POAD_GLOBAL_COMMANDS[command]) {
366
366
  const px = parseCommandArgs(require(__dirname + '/global/cli'), args);
367
367
  const unit = require(path.join(__dirname, 'global', px.dir));
368
- unit(parseArgs(px.args));
368
+ // Second argument : les mots tels que tapés (poad create --template next)
369
+ unit(parseArgs(px.args), px.args);
369
370
  } else {
370
371
  if (POAD_COMMANDS[command]) {
371
372
  console.log(' ');
@@ -476,8 +477,32 @@ const isNewerVersion = (a, b) => {
476
477
  return false;
477
478
  };
478
479
 
480
+ // Aide : `poad <commande…> --help` (ou -h, ou `poad help <commande…>`)
481
+ // affiche l'aide et s'arrête, avant la vérification de version et avant
482
+ // d'exécuter quoi que ce soit (poad stop --help n'arrête plus le projet).
483
+ const helpGuard = () => {
484
+ const help = require('./utils/help');
485
+ let argv = process.argv.slice(2);
486
+ const asked = argv[0] === 'help' || help.helpRequested(argv);
487
+ if (!asked) return false;
488
+ if (argv[0] === 'help') argv = argv.slice(1);
489
+ POAD_GLOBAL_COMMANDS = loadPoadCommands(__dirname + '/global/cli.js');
490
+ const words = argv.filter((a) => !help.HELP_FLAGS.includes(a));
491
+ if (!words.length) {
492
+ displayBanner();
493
+ return true;
494
+ }
495
+ if (!help.printHelp(argv)) {
496
+ process.exitCode = 1;
497
+ log.error('Unknown command : ' + words[0]);
498
+ displayBanner();
499
+ }
500
+ return true;
501
+ };
502
+
479
503
  // Main function.
480
504
  const main = async () => {
505
+ if (helpGuard()) return;
481
506
  let version = await checkVersion();
482
507
  const current_version = require(__dirname + '/package.json').version;
483
508
 
package/project/cli.js CHANGED
@@ -7,10 +7,10 @@
7
7
  *
8
8
  */
9
9
  module.exports = {
10
- info: `Information about your project`,
10
+ info: 'Information about your project: URLs, keys, migrations, services (secrets hidden; info --secrets shows the JWT secret, the service_role key and the admin passwords)',
11
11
  client: {
12
- description: 'Front-end of the project: client init creates it from a template (Angular; Vue and React soon), wired to poad with sign-in',
13
- init: 'Create the front-end (angular | vue | react, dir=<folder>, from=<local template>, --yes)',
12
+ description: 'Front-end of the project: client init creates it from a template (Angular; Next.js, Nuxt and vanilla soon), wired to poad with sign-in. For a new folder: poad create',
13
+ init: 'Create the front-end (angular | next | nuxt | vanilla, dir=<folder>, from=<local template>, --yes)',
14
14
  },
15
15
  console: 'Open the administration console of the running project in the browser (engine 0.11.0+, no password, this machine only)',
16
16
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
@@ -3,7 +3,7 @@ module.exports = async () => {
3
3
  const chalk = require('chalk-v2');
4
4
  console.log(`${chalk.bold(' Usage :')}`);
5
5
  console.log(' ');
6
- console.log(` ${chalk.cyanBright('poad client init')} Create the front-end of the project (Angular; Vue and React soon), wired to poad with sign-in`);
7
- console.log(` ${chalk.grey(' options: angular | vue | react, dir=<folder>, from=<local template>, --yes')}`);
6
+ console.log(` ${chalk.cyanBright('poad client init')} Create the front-end of the project (Angular; Next.js, Nuxt and vanilla soon), wired to poad with sign-in`);
7
+ console.log(` ${chalk.grey(' options: angular | next | nuxt | vanilla, dir=<folder>, from=<local template>, --yes')}`);
8
8
  console.log(' ');
9
9
  };
@@ -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
  };