poad 2.38.0 → 2.40.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.
@@ -0,0 +1,340 @@
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
+ name: 'app', template: 'nuxt', pm: 'pnpm', from: null, app: null, dir: null, yes: true, noInstall: true, noGit: true, flat: false, help: false,
11
+ });
12
+ assert.strictEqual(parseCreateArgs(['template=vanilla', 'x']).template, 'vanilla');
13
+ const o = parseCreateArgs(['proj', '--app', 'web', '--dir=front/admin', '--flat']);
14
+ assert.deepStrictEqual([o.name, o.app, o.dir, o.flat], ['proj', 'web', 'front/admin', true]);
15
+ assert.strictEqual(parseCreateArgs(['app=admin']).app, 'admin');
16
+ assert.throws(() => parseCreateArgs(['a', 'b']), /unexpected argument/);
17
+ assert.throws(() => parseCreateArgs(['a', '--pm', 'yarn']), /--pm must be/);
18
+ assert.throws(() => parseCreateArgs(['a', '--template']), /needs a value/);
19
+ assert.throws(() => parseCreateArgs(['a', '--force']), /unknown option/);
20
+ });
21
+
22
+ test('mode: new project outside a poad project, front-end added inside, --flat refused inside', () => {
23
+ const { modeOf } = require('../global/create');
24
+ const project = { root: '/p', config: '/p/poad/config.toml' };
25
+ assert.strictEqual(modeOf({ name: 'proj' }, null), 'new');
26
+ assert.strictEqual(modeOf({ name: 'proj', flat: true }, null), 'flat');
27
+ assert.strictEqual(modeOf({ name: 'admin' }, project), 'add');
28
+ assert.strictEqual(modeOf({ name: 'admin', app: 'admin' }, project), 'add');
29
+ assert.throws(() => modeOf({ name: 'admin', app: 'other' }, project), /Two names/);
30
+ assert.throws(() => modeOf({ name: 'x', flat: true }, project), /Already inside the poad project/);
31
+ assert.throws(() => modeOf({ name: 'x', dir: 'apps/x' }, null), /--dir is for a front-end added inside/);
32
+ });
33
+
34
+ test('target folder: new or empty only', (t) => {
35
+ const dir = tmpdir(t);
36
+ assert.strictEqual(checkTarget(path.join(dir, 'new')), 'new');
37
+ fs.writeFileSync(path.join(dir, '.DS_Store'), '');
38
+ assert.strictEqual(checkTarget(dir), 'empty');
39
+ fs.writeFileSync(path.join(dir, 'x'), '');
40
+ assert.throws(() => checkTarget(dir), /not empty/);
41
+ assert.throws(() => checkTarget(path.join(dir, 'x')), /not a folder/);
42
+ });
43
+
44
+ test('poad create --from <malicious.tgz>: refused, nothing left behind', (t) => {
45
+ const { spawnSync } = require('child_process');
46
+ const { tgz } = require('./helpers');
47
+ const cwd = tmpdir(t);
48
+ fs.writeFileSync(
49
+ path.join(cwd, 'evil.tgz'),
50
+ tgz([
51
+ { name: 'package/package.json', data: '{"name":"evil","version":"1.0.0"}' },
52
+ { name: 'package/../../escaped.txt', data: 'evil' },
53
+ ])
54
+ );
55
+ const r = spawnSync(process.execPath, [path.join(__dirname, '..', 'poad.js'), 'create', 'app', '--from', 'evil.tgz', '--yes', '--no-install', '--no-git'], { cwd, encoding: 'utf8', input: '' });
56
+ assert.match(r.stdout + r.stderr, /Template unavailable: refused entry .*"\.\."/);
57
+ assert.notStrictEqual(r.status, 0);
58
+ assert.deepStrictEqual(fs.readdirSync(cwd), ['evil.tgz']);
59
+ assert.ok(!fs.existsSync(path.join(cwd, '..', 'escaped.txt')));
60
+ });
61
+
62
+ test('created title: framework label, never "Application application"', () => {
63
+ const { createdTitle } = require('../global/create');
64
+ const { templateByValue } = require('../utils/starter');
65
+ assert.strictEqual(createdTitle(null, {}), 'Application created');
66
+ assert.strictEqual(createdTitle(null, { label: 'Next.js' }), 'Next.js application created');
67
+ assert.strictEqual(createdTitle(templateByValue('angular'), { label: 'Angular' }), 'Angular application created');
68
+ assert.strictEqual(createdTitle(templateByValue('vanilla'), { label: null }), 'Vanilla application created');
69
+ });
70
+
71
+ // poad create --from <archive locale> jusqu'au bout (sans réseau, sans
72
+ // installation ni git) : titre et URL du front selon le framework du modèle
73
+ const CLI = path.join(__dirname, '..', 'poad.js');
74
+
75
+ /** Dossier de test : HOME à part (version déjà vérifiée : pas de npm view) */
76
+ function sandbox(t) {
77
+ const cwd = tmpdir(t);
78
+ const home = path.join(cwd, 'home');
79
+ fs.mkdirSync(home);
80
+ fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
81
+ return { cwd, home };
82
+ }
83
+
84
+ /** Archive de modèle (npm pack) écrite dans dir */
85
+ function template(dir, file, pkg, extra = []) {
86
+ const { tgz } = require('./helpers');
87
+ fs.writeFileSync(path.join(dir, file), tgz([{ name: 'package/package.json', data: JSON.stringify(pkg) }, ...extra]));
88
+ return path.join(dir, file);
89
+ }
90
+
91
+ /** poad create … sans réseau (offline-stub), sans question */
92
+ function poad(sb, cwd, args) {
93
+ const { spawnSync } = require('child_process');
94
+ const r = spawnSync(process.execPath, ['--require', path.join(__dirname, 'offline-stub.js'), CLI, ...args], {
95
+ cwd,
96
+ encoding: 'utf8',
97
+ input: '',
98
+ timeout: 30000,
99
+ env: { ...process.env, HOME: sb.home, NODE_OPTIONS: '', GIT_AUTHOR_NAME: 'poad test', GIT_AUTHOR_EMAIL: 'test@example.invalid', GIT_COMMITTER_NAME: 'poad test', GIT_COMMITTER_EMAIL: 'test@example.invalid' },
100
+ });
101
+ return { r, out: r.stdout + r.stderr };
102
+ }
103
+
104
+ function createFrom(t, pkg, extra = [], args = ['--flat']) {
105
+ const sb = sandbox(t);
106
+ template(sb.cwd, 'tpl.tgz', pkg, extra);
107
+ const { r, out } = poad(sb, sb.cwd, ['create', 'app', '--from', 'tpl.tgz', '--yes', '--no-install', '--no-git', ...args]);
108
+ return { r, out, app: path.join(sb.cwd, 'app') };
109
+ }
110
+
111
+ const json = (...p) => JSON.parse(fs.readFileSync(path.join(...p), 'utf8'));
112
+
113
+ const NEXT = { name: '@poadio/starter-next', version: '0.2.0', scripts: { start: 'node scripts/dev.mjs' }, dependencies: { next: '16.4.6' }, packageManager: 'bun@1.4.4', poad: { port: 3300, template: { framework: 'next', label: 'Next.js + @poadio/ui-react', port: 3300, gitignore: ['/.next/', '/public/env.json'] } } };
114
+ const ANGULAR = { name: '@poadio/starter-angular', version: '0.5.0', scripts: { start: 'node scripts/dev.mjs' }, dependencies: { '@angular/core': '^21.1.0' }, packageManager: 'bun@1.4.4', poad: { routing: 'classic', template: { framework: 'angular', appEnv: true, label: 'Angular + @poadio/ui-angular', port: 4300, gitignore: ['/dist'] } } };
115
+ const ANGULAR_JSON = { name: 'package/angular.json', data: JSON.stringify({ projects: { starter: { architect: { serve: { options: {} } } } } }) };
116
+ const files = (name, data) => ({ name: `package/${name}`, data });
117
+
118
+ test('poad create --flat --from a Next.js template: "Next.js application created", URL from poad.port, poad.port kept', (t) => {
119
+ const { r, out, app } = createFrom(t, NEXT);
120
+ assert.strictEqual(r.status, 0, out);
121
+ assert.match(out, /Next\.js application created/);
122
+ assert.doesNotMatch(out, /Application application/);
123
+ assert.match(out, /front-end on http:\/\/localhost:3300/);
124
+ const written = json(app, 'package.json');
125
+ assert.strictEqual(written.poad.port, 3300);
126
+ assert.strictEqual(written.poad.app, 'app');
127
+ assert.ok(!('template' in written.poad));
128
+ // Ancienne disposition : poad/ dans le front
129
+ assert.ok(fs.existsSync(path.join(app, 'poad', 'config.toml')));
130
+ assert.ok(!fs.existsSync(path.join(app, 'apps')));
131
+ });
132
+
133
+ test('poad create --flat --from an unknown template: "Application created", no URL', (t) => {
134
+ const { r, out } = createFrom(t, { name: 'custom', version: '1.0.0' });
135
+ assert.strictEqual(r.status, 0, out);
136
+ assert.match(out, /✔ Application created in app/);
137
+ assert.doesNotMatch(out, /Application application|localhost:\d+ *$/m);
138
+ assert.doesNotMatch(out, /front-end on http/);
139
+ });
140
+
141
+ test('poad create <project>: poad/ at the root, the front-end in apps/web, workspace package.json, one git repository', (t) => {
142
+ const sb = sandbox(t);
143
+ template(sb.cwd, 'next.tgz', NEXT, [files('gitignore', '/.next/\nnode_modules\n'), files('bun.lock', '{}'), files('poad/config.toml', 'project_id = "template"\n'), files('src/app/page.tsx', 'export default 1;\n')]);
144
+ const { r, out } = poad(sb, sb.cwd, ['create', 'proj', '--from', 'next.tgz', '--yes', '--no-install']);
145
+ assert.strictEqual(r.status, 0, out);
146
+ const proj = path.join(sb.cwd, 'proj');
147
+ const web = path.join(proj, 'apps', 'web');
148
+ assert.match(out, /Next\.js application created in proj\/apps\/web \(application "web"\)/);
149
+ assert.match(out, /cd proj && bun start/);
150
+ // Modèle publié avant les variables par application : prévenu, poad.app écrit quand même
151
+ assert.match(out, /@poadio\/starter-next@0\.2\.0 does not read the public variables of its application yet/);
152
+ assert.doesNotMatch(out, /Public variables of this front-end only/);
153
+
154
+ // Backend à la racine, jamais celui du modèle
155
+ assert.match(fs.readFileSync(path.join(proj, 'poad', 'config.toml'), 'utf8'), /^project_id = "proj"$/m);
156
+ assert.ok(fs.existsSync(path.join(proj, 'poad', 'secrets.toml')));
157
+ assert.ok(!fs.existsSync(path.join(web, 'poad')));
158
+
159
+ // Le front : nom d'application, port, pas de verrouillage ni de packageManager à lui
160
+ const pkg = json(web, 'package.json');
161
+ assert.strictEqual(pkg.name, 'web');
162
+ assert.strictEqual(pkg.poad.app, 'web');
163
+ assert.strictEqual(pkg.poad.port, 3300);
164
+ assert.match(pkg.poad.from, /^@poadio\/starter-next@0\.2\.0$/);
165
+ assert.ok(!('packageManager' in pkg));
166
+ assert.ok(!fs.existsSync(path.join(web, 'bun.lock')));
167
+ assert.ok(fs.existsSync(path.join(web, '.gitignore')));
168
+ assert.ok(!fs.existsSync(path.join(web, 'gitignore')));
169
+
170
+ // Racine : espace de travail, scripts, packageManager du modèle, scripts/start.mjs
171
+ const root = json(proj, 'package.json');
172
+ assert.deepStrictEqual(root.workspaces, ['apps/*']);
173
+ assert.strictEqual(root.private, true);
174
+ assert.deepStrictEqual(root.scripts, { start: 'node scripts/start.mjs', 'start:web': 'node scripts/start.mjs web' });
175
+ assert.strictEqual(root.packageManager, 'bun@1.4.4');
176
+ assert.ok(fs.existsSync(path.join(proj, 'scripts', 'start.mjs')));
177
+ const gitignore = fs.readFileSync(path.join(proj, '.gitignore'), 'utf8').split('\n');
178
+ for (const line of ['poad/secrets.toml', 'poad/data/', 'node_modules/']) assert.ok(gitignore.includes(line), line);
179
+
180
+ // Un seul dépôt, à la racine, un commit sans secret
181
+ const { spawnSync } = require('child_process');
182
+ assert.strictEqual(spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: web, encoding: 'utf8' }).stdout.trim(), fs.realpathSync(proj));
183
+ assert.ok(!fs.existsSync(path.join(web, '.git')));
184
+ const log = spawnSync('git', ['log', '--format=%s'], { cwd: proj, encoding: 'utf8' }).stdout.trim();
185
+ assert.match(log, /^Initial commit from @poadio\/starter-next@0\.2\.0 \(poad create\)$/);
186
+ const tracked = spawnSync('git', ['ls-files'], { cwd: proj, encoding: 'utf8' }).stdout.split('\n');
187
+ for (const f of ['package.json', 'scripts/start.mjs', 'poad/config.toml', 'apps/web/package.json', 'apps/web/src/app/page.tsx']) assert.ok(tracked.includes(f), f);
188
+ assert.ok(!tracked.some((f) => f.startsWith('poad/secrets') || f.startsWith('poad/data/')));
189
+ });
190
+
191
+ test('poad create <app> inside a project: apps/<app>, distinct port, registered, poad/ untouched, no commit', (t) => {
192
+ const sb = sandbox(t);
193
+ template(sb.cwd, 'next.tgz', NEXT);
194
+ template(sb.cwd, 'angular.tgz', ANGULAR, [ANGULAR_JSON, files('src/index.html', '<title>Starter</title>')]);
195
+ const next2 = template(sb.cwd, 'next2.tgz', NEXT);
196
+ assert.strictEqual(poad(sb, sb.cwd, ['create', 'proj', '--from', 'next.tgz', '--yes', '--no-install', '--app', 'site']).r.status, 0);
197
+ const proj = path.join(sb.cwd, 'proj');
198
+ const poadBefore = fs.readFileSync(path.join(proj, 'poad', 'config.toml'), 'utf8');
199
+ const secretsBefore = fs.readFileSync(path.join(proj, 'poad', 'secrets.toml'), 'utf8');
200
+ const { spawnSync } = require('child_process');
201
+ const head = () => spawnSync('git', ['rev-parse', 'HEAD'], { cwd: proj, encoding: 'utf8' }).stdout.trim();
202
+ const commit = head();
203
+
204
+ // Angular, lancé depuis un sous-dossier du projet
205
+ fs.mkdirSync(path.join(proj, 'apps', 'site', 'src'), { recursive: true });
206
+ let res = poad(sb, path.join(proj, 'apps', 'site', 'src'), ['create', 'admin', '--from', path.join(sb.cwd, 'angular.tgz'), '--yes', '--no-install']);
207
+ assert.strictEqual(res.r.status, 0, res.out);
208
+ assert.match(res.out, /Angular application created in \.\.\/\.\.\/admin \(application "admin"\)/);
209
+ assert.match(res.out, /Nothing committed: git add apps\/admin package\.json/);
210
+ assert.doesNotMatch(res.out, /does not read the public variables/);
211
+ assert.match(res.out, /Public variables of this front-end only: PUBLIC_\* with application "admin"/);
212
+ const admin = json(proj, 'apps', 'admin', 'package.json');
213
+ assert.strictEqual(admin.poad.app, 'admin');
214
+ assert.ok(admin.poad.port >= 4300);
215
+ const ng = json(proj, 'apps', 'admin', 'angular.json');
216
+ assert.strictEqual(ng.projects.starter.architect.serve.options.port, admin.poad.port);
217
+ assert.match(fs.readFileSync(path.join(proj, 'apps', 'admin', 'src', 'index.html'), 'utf8'), /<title>proj · admin<\/title>/);
218
+
219
+ // Un second Next.js : pas le port 3300 du premier
220
+ res = poad(sb, proj, ['create', 'blog', '--from', next2, '--yes', '--no-install']);
221
+ assert.strictEqual(res.r.status, 0, res.out);
222
+ const blog = json(proj, 'apps', 'blog', 'package.json');
223
+ assert.notStrictEqual(blog.poad.port, 3300);
224
+ assert.ok(blog.poad.port > 3300);
225
+ assert.match(res.out, new RegExp(`localhost:${blog.poad.port}`));
226
+
227
+ // Ailleurs que dans apps/ : --dir, ajouté aux workspaces
228
+ res = poad(sb, proj, ['create', 'docs', '--from', next2, '--dir', 'front/docs', '--yes', '--no-install']);
229
+ assert.strictEqual(res.r.status, 0, res.out);
230
+ const root = json(proj, 'package.json');
231
+ assert.deepStrictEqual(root.workspaces, ['apps/*', 'front/docs']);
232
+ assert.deepStrictEqual(Object.keys(root.scripts), ['start', 'start:site', 'start:admin', 'start:blog', 'start:docs']);
233
+ const ports = ['site', 'admin', 'blog'].map((a) => json(proj, 'apps', a, 'package.json').poad.port).concat(json(proj, 'front', 'docs', 'package.json').poad.port);
234
+ assert.strictEqual(new Set(ports).size, 4, `distinct ports: ${ports}`);
235
+
236
+ // poad/ jamais touché, aucun commit, aucun nouveau dépôt
237
+ assert.strictEqual(fs.readFileSync(path.join(proj, 'poad', 'config.toml'), 'utf8'), poadBefore);
238
+ assert.strictEqual(fs.readFileSync(path.join(proj, 'poad', 'secrets.toml'), 'utf8'), secretsBefore);
239
+ assert.strictEqual(head(), commit);
240
+ assert.ok(!fs.existsSync(path.join(proj, 'apps', 'admin', '.git')));
241
+
242
+ // Refusés : nom pris, nom invalide, dossier hors du projet, poad/
243
+ for (const [args, re] of [
244
+ [['create', 'admin', '--from', next2], /already has a front-end "admin"/],
245
+ [['create', 'Admin', '--from', next2], /not a valid application name/],
246
+ [['create', 'x', '--from', next2, '--dir', '../x'], /outside the poad project/],
247
+ [['create', 'x', '--from', next2, '--dir', 'poad/x'], /poad\/ is the backend/],
248
+ [['create', 'x', '--from', next2, '--flat'], /Already inside the poad project/],
249
+ ]) {
250
+ res = poad(sb, proj, [...args, '--yes', '--no-install']);
251
+ assert.notStrictEqual(res.r.status, 0, res.out);
252
+ assert.match(res.out, re);
253
+ }
254
+ assert.ok(!fs.existsSync(path.join(proj, 'apps', 'x')) && !fs.existsSync(path.join(sb.cwd, 'x')));
255
+ });
256
+
257
+ test('poad client init: same path as poad create <app> (alias), apps/web by default, dir= kept', (t) => {
258
+ const sb = sandbox(t);
259
+ template(sb.cwd, 'next.tgz', NEXT);
260
+ const proj = path.join(sb.cwd, 'proj');
261
+ fs.mkdirSync(proj);
262
+ // Projet fait par poad init seul (pas de package.json racine)
263
+ assert.strictEqual(poad(sb, proj, ['init']).r.status, 0);
264
+ let res = poad(sb, proj, ['client', 'init', 'next', `from=${path.join(sb.cwd, 'next.tgz')}`, '--yes', '--no-install']);
265
+ assert.match(res.out, /poad client init is now "poad create web --template next"/);
266
+ assert.match(res.out, /Next\.js application created in apps\/web/);
267
+ assert.strictEqual(json(proj, 'apps', 'web', 'package.json').poad.app, 'web');
268
+ res = poad(sb, proj, ['client', 'init', 'next', 'dir=shop', `from=${path.join(sb.cwd, 'next.tgz')}`, '--yes', '--no-install']);
269
+ assert.match(res.out, /created in shop \(application "shop"\)/);
270
+ assert.notStrictEqual(json(proj, 'shop', 'package.json').poad.port, 3300);
271
+ });
272
+
273
+ // scripts/start.mjs du projet (bun start à la racine) : fronts factices dont
274
+ // le « serveur » affiche ce qu'il reçoit, sans poad (POAD_URL donné)
275
+ function fakeWorkspace(t, apps) {
276
+ const dir = tmpdir(t);
277
+ fs.mkdirSync(path.join(dir, 'scripts'));
278
+ fs.copyFileSync(path.join(__dirname, '..', 'templates', 'workspace', 'start.mjs'), path.join(dir, 'scripts', 'start.mjs'));
279
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'proj', private: true, workspaces: ['apps/*'], packageManager: 'npm@10.0.0' }));
280
+ for (const [name, port, body] of apps) {
281
+ const app = path.join(dir, 'apps', name);
282
+ fs.mkdirSync(app, { recursive: true });
283
+ fs.writeFileSync(path.join(app, 'server.js'), body);
284
+ fs.writeFileSync(path.join(app, 'package.json'), JSON.stringify({ name, scripts: { start: 'node server.js' }, poad: { app: name, port } }));
285
+ }
286
+ return dir;
287
+ }
288
+
289
+ test('start.mjs: every front-end, distinct ports, prefixed output, POAD_APP and POAD_SKIP_START', (t) => {
290
+ const { spawnSync } = require('child_process');
291
+ const echo = 'console.log(JSON.stringify({ app: process.env.POAD_APP, skip: process.env.POAD_SKIP_START, args: process.argv.slice(2) }));';
292
+ const dir = fakeWorkspace(t, [['web', 47311, echo], ['admin', 47311, echo]]);
293
+ const r = spawnSync(process.execPath, ['scripts/start.mjs'], { cwd: dir, encoding: 'utf8', timeout: 30000, env: { ...process.env, POAD_URL: 'http://localhost:1' } });
294
+ assert.strictEqual(r.status, 0, r.stdout + r.stderr);
295
+ const seen = {};
296
+ for (const m of r.stdout.matchAll(/^\[(\w+)\]\s+(\{.*\})$/gm)) seen[m[1]] = JSON.parse(m[2]);
297
+ assert.deepStrictEqual(Object.keys(seen).sort(), ['admin', 'web']);
298
+ for (const [name, v] of Object.entries(seen)) {
299
+ assert.strictEqual(v.app, name);
300
+ assert.strictEqual(v.skip, '1');
301
+ assert.strictEqual(v.args[0], '--port');
302
+ }
303
+ assert.notStrictEqual(seen.web.args[1], seen.admin.args[1]);
304
+
305
+ // Un seul front, par son nom ; un nom inconnu est refusé
306
+ const one = spawnSync(process.execPath, ['scripts/start.mjs', 'admin'], { cwd: dir, encoding: 'utf8', timeout: 30000, env: { ...process.env, POAD_URL: 'http://localhost:1' } });
307
+ assert.match(one.stdout, /^\[admin\]/m);
308
+ assert.doesNotMatch(one.stdout, /^\[web\]/m);
309
+ const bad = spawnSync(process.execPath, ['scripts/start.mjs', 'nope'], { cwd: dir, encoding: 'utf8', env: { ...process.env, POAD_URL: 'http://localhost:1' } });
310
+ assert.notStrictEqual(bad.status, 0);
311
+ assert.match(bad.stderr, /Unknown front-end: nope\. Known: admin, web/);
312
+ });
313
+
314
+ test('start.mjs: SIGINT stops every front-end and what they started', { skip: process.platform === 'win32' && 'process groups' }, async (t) => {
315
+ const { spawn } = require('child_process');
316
+ // Chaque front lance un petit-enfant qui écoute : il doit disparaître aussi
317
+ const body = "const { spawn } = require('child_process'); const c = spawn(process.execPath, ['-e', 'require(\"http\").createServer().listen(0); setInterval(() => {}, 1000)'], { stdio: 'ignore' }); console.log('child ' + c.pid); setInterval(() => {}, 1000);";
318
+ const dir = fakeWorkspace(t, [['web', 47411, body], ['admin', 47421, body]]);
319
+ const child = spawn(process.execPath, ['scripts/start.mjs'], { cwd: dir, env: { ...process.env, POAD_URL: 'http://localhost:1' } });
320
+ let out = '';
321
+ child.stdout.on('data', (d) => (out += d));
322
+ const pids = await new Promise((ok, ko) => {
323
+ const timer = setTimeout(() => ko(new Error(`no children: ${out}`)), 20000);
324
+ const iv = setInterval(() => {
325
+ const found = [...out.matchAll(/child (\d+)/g)].map((m) => Number(m[1]));
326
+ if (found.length === 2) {
327
+ clearInterval(iv);
328
+ clearTimeout(timer);
329
+ ok(found);
330
+ }
331
+ }, 100);
332
+ });
333
+ child.kill('SIGINT');
334
+ const code = await new Promise((ok) => child.on('exit', (c) => ok(c)));
335
+ assert.strictEqual(code, 0, out);
336
+ assert.match(out, /\[web\]\s+stopped/);
337
+ assert.match(out, /\[admin\]\s+stopped/);
338
+ await new Promise((ok) => setTimeout(ok, 300));
339
+ for (const pid of pids) assert.throws(() => process.kill(pid, 0), /ESRCH/, `grandchild ${pid} still alive`);
340
+ });
@@ -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
+ };
@@ -0,0 +1,95 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const crypto = require('crypto');
4
+ const { verifyIntegrity, parseIntegrity, latestDist, metadataUrl, RegistryError } = require('../utils/registry');
5
+
6
+ const sri = (buf) => `sha512-${crypto.createHash('sha512').update(buf).digest('base64')}`;
7
+
8
+ test('accepts content matching its sha512 integrity', () => {
9
+ const buf = Buffer.from('template archive');
10
+ assert.doesNotThrow(() => verifyIntegrity(buf, sri(buf)));
11
+ // plusieurs empreintes SRI : une seule doit correspondre
12
+ assert.doesNotThrow(() => verifyIntegrity(buf, `${sri(Buffer.from('other'))} ${sri(buf)}`));
13
+ });
14
+
15
+ test('refuses content whose sha512 does not match (integrity mismatch)', () => {
16
+ const buf = Buffer.from('template archive');
17
+ const tampered = Buffer.from('template archivE');
18
+ assert.throws(() => verifyIntegrity(tampered, sri(buf), 'x@1.0.0'), (err) => err instanceof RegistryError && /integrity check failed/.test(err.message));
19
+ });
20
+
21
+ test('refuses a missing or non-sha512 integrity', () => {
22
+ const buf = Buffer.from('a');
23
+ assert.throws(() => verifyIntegrity(buf, undefined), /no sha512 integrity/);
24
+ assert.throws(() => verifyIntegrity(buf, `sha1-${crypto.createHash('sha1').update(buf).digest('base64')}`), /no sha512 integrity/);
25
+ assert.strictEqual(parseIntegrity('sha512-short'), null);
26
+ });
27
+
28
+ test('latest version: HTTPS tarball and sha512 integrity are required', () => {
29
+ const data = (dist) => ({ 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': { dist } } });
30
+ const integrity = sri(Buffer.from('x'));
31
+ assert.deepStrictEqual(latestDist('p', data({ tarball: 'https://r/p.tgz', integrity })), { version: '1.0.0', tarball: 'https://r/p.tgz', integrity });
32
+ assert.throws(() => latestDist('p', data({ tarball: 'http://r/p.tgz', integrity })), /not HTTPS/);
33
+ assert.throws(() => latestDist('p', data({ tarball: 'https://r/p.tgz', shasum: 'abc' })), /no sha512 integrity/);
34
+ assert.throws(() => latestDist('p', { 'dist-tags': {} }), /no "latest"/);
35
+ });
36
+
37
+ test('scoped package metadata URL', () => {
38
+ assert.strictEqual(metadataUrl('@poadio/starter-next'), 'https://registry.npmjs.org/@poadio%2fstarter-next');
39
+ });
40
+
41
+ // Téléchargement complet, fetch remplacé : ni réseau ni ~/.poad touchés
42
+ const fs = require('fs');
43
+ const os = require('os');
44
+ const path = require('path');
45
+ const { fetchLatestTarball } = require('../utils/registry');
46
+ const { tmpdir } = require('./helpers');
47
+
48
+ const withHome = (t) => {
49
+ const home = tmpdir(t, 'poad-home-');
50
+ const old = process.env.HOME;
51
+ process.env.HOME = home;
52
+ t.after(() => (process.env.HOME = old));
53
+ return home;
54
+ };
55
+
56
+ const stubFetch = (t, body) => {
57
+ const old = globalThis.fetch;
58
+ globalThis.fetch = async (url) => {
59
+ const res = new Response(body, { status: 200 });
60
+ Object.defineProperty(res, 'url', { value: url });
61
+ return res;
62
+ };
63
+ t.after(() => (globalThis.fetch = old));
64
+ };
65
+
66
+ const metadataFor = (integrity) => ({
67
+ status: 'ok',
68
+ data: { 'dist-tags': { latest: '1.2.3' }, versions: { '1.2.3': { dist: { tarball: 'https://registry.example/p-1.2.3.tgz', integrity } } } },
69
+ });
70
+
71
+ test('download: a tarball that does not match the registry integrity is refused and not cached', async (t) => {
72
+ const home = withHome(t);
73
+ assert.strictEqual(os.homedir(), home);
74
+ stubFetch(t, Buffer.from('tampered tarball'));
75
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: metadataFor(sri(Buffer.from('genuine tarball'))) }), /integrity check failed/);
76
+ assert.strictEqual(fs.existsSync(path.join(home, '.poad', 'starters')), false);
77
+ });
78
+
79
+ test('download: verified tarball is cached, then used offline; a tampered cache is ignored', async (t) => {
80
+ const home = withHome(t);
81
+ const buf = Buffer.from('genuine tarball');
82
+ stubFetch(t, buf);
83
+ const got = await fetchLatestTarball('@poadio/starter-x', { metadata: metadataFor(sri(buf)) });
84
+ assert.strictEqual(got.source, 'registry');
85
+ assert.strictEqual(got.version, '1.2.3');
86
+ const offline = await fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'offline', error: 'timeout' } });
87
+ assert.strictEqual(offline.source, 'cache');
88
+ assert.ok(offline.buf.equals(buf));
89
+ fs.writeFileSync(path.join(home, '.poad', 'starters', 'poadio__starter-x.tgz'), 'tampered');
90
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'offline', error: 'timeout' } }), /not in the cache/);
91
+ });
92
+
93
+ test('unpublished package: not published on npm', async () => {
94
+ await assert.rejects(fetchLatestTarball('@poadio/starter-x', { metadata: { status: 'missing' } }), /not published/);
95
+ });