poad 2.39.0 → 2.41.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.
@@ -7,15 +7,30 @@ const { tmpdir } = require('./helpers');
7
7
 
8
8
  test('create arguments: flags, --key value, --key=value and key=value', () => {
9
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,
10
+ name: 'app', template: 'nuxt', pm: 'pnpm', from: null, app: null, dir: null, yes: true, noInstall: true, noGit: true, flat: false, help: false,
11
11
  });
12
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');
13
16
  assert.throws(() => parseCreateArgs(['a', 'b']), /unexpected argument/);
14
17
  assert.throws(() => parseCreateArgs(['a', '--pm', 'yarn']), /--pm must be/);
15
18
  assert.throws(() => parseCreateArgs(['a', '--template']), /needs a value/);
16
19
  assert.throws(() => parseCreateArgs(['a', '--force']), /unknown option/);
17
20
  });
18
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
+
19
34
  test('target folder: new or empty only', (t) => {
20
35
  const dir = tmpdir(t);
21
36
  assert.strictEqual(checkTarget(path.join(dir, 'new')), 'new');
@@ -55,41 +70,271 @@ test('created title: framework label, never "Application application"', () => {
55
70
 
56
71
  // poad create --from <archive locale> jusqu'au bout (sans réseau, sans
57
72
  // 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');
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) {
61
77
  const cwd = tmpdir(t);
62
78
  const home = path.join(cwd, 'home');
63
79
  fs.mkdirSync(home);
64
- // version déjà vérifiée : pas de npm view
65
80
  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'], {
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], {
68
95
  cwd,
69
96
  encoding: 'utf8',
70
97
  input: '',
71
98
  timeout: 30000,
72
- env: { ...process.env, HOME: home, NODE_OPTIONS: '' },
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' },
73
100
  });
74
- return { r, out: r.stdout + r.stderr, app: path.join(cwd, 'app') };
101
+ return { r, out: r.stdout + r.stderr };
75
102
  }
76
103
 
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);
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);
80
120
  assert.strictEqual(r.status, 0, out);
81
121
  assert.match(out, /Next\.js application created/);
82
122
  assert.doesNotMatch(out, /Application application/);
83
123
  assert.match(out, /front-end on http:\/\/localhost:3300/);
84
- const written = JSON.parse(fs.readFileSync(path.join(app, 'package.json'), 'utf8'));
124
+ const written = json(app, 'package.json');
85
125
  assert.strictEqual(written.poad.port, 3300);
126
+ assert.strictEqual(written.poad.app, 'app');
86
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')));
87
131
  });
88
132
 
89
- test('poad create --from an unknown template: "Application created", no URL', (t) => {
133
+ test('poad create --flat --from an unknown template: "Application created", no URL', (t) => {
90
134
  const { r, out } = createFrom(t, { name: 'custom', version: '1.0.0' });
91
135
  assert.strictEqual(r.status, 0, out);
92
136
  assert.match(out, /✔ Application created in app/);
93
137
  assert.doesNotMatch(out, /Application application|localhost:\d+ *$/m);
94
- assert.doesNotMatch(out, /front-end on/);
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`);
95
340
  });
@@ -0,0 +1,24 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const { maxBody, engineEnv } = require('../utils/gateway');
4
+
5
+ test('gateway : max_body par défaut 10m', () => {
6
+ assert.deepStrictEqual(maxBody({}), { value: '10m' });
7
+ assert.deepStrictEqual(maxBody({ gateway: {} }), { value: '10m' });
8
+ assert.deepStrictEqual(engineEnv({}), ['POAD_GATEWAY_MAX_BODY=10m']);
9
+ });
10
+
11
+ test('gateway : max_body de config.toml, normalisé', () => {
12
+ assert.deepStrictEqual(engineEnv({ gateway: { max_body: '50m' } }), ['POAD_GATEWAY_MAX_BODY=50m']);
13
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: ' 512K ' } }), { value: '512k' });
14
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: 1048576 } }), { value: '1048576' });
15
+ assert.deepStrictEqual(maxBody({ gateway: { max_body: '0' } }), { value: '0' });
16
+ });
17
+
18
+ test('gateway : une valeur qui n’est pas une taille donne 10m et un avertissement', () => {
19
+ for (const bad of ['10 MB', '10mb', '-1', '1.5m', 'big', '10m; return 200']) {
20
+ const r = maxBody({ gateway: { max_body: bad } });
21
+ assert.strictEqual(r.value, '10m', bad);
22
+ assert.match(r.warning, /is not a size/);
23
+ }
24
+ });
@@ -0,0 +1,71 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const ws = require('../utils/workspace');
6
+ const starter = require('../utils/starter');
7
+ const { tmpdir } = require('./helpers');
8
+
9
+ test('application name: poad.app, else the package name without scope; same rule as the engine', () => {
10
+ assert.strictEqual(ws.appNameOf({ name: 'web', poad: { app: 'admin' } }), 'admin');
11
+ assert.strictEqual(ws.appNameOf({ name: '@acme/Site_Web' }), 'site-web');
12
+ assert.strictEqual(ws.appNameOf({ name: '123' }), '');
13
+ assert.strictEqual(ws.appNameOf({ name: 'web', poad: { app: 'Bad Name' } }), 'web');
14
+ assert.strictEqual(ws.checkAppName('admin-2'), 'admin-2');
15
+ for (const bad of ['Admin', '2web', '', 'a_b', 'x'.repeat(64)]) assert.throws(() => ws.checkAppName(bad), /not a valid application name/);
16
+ });
17
+
18
+ test('apps of a project: workspaces, apps/*, the root when it is itself a front-end; ports from poad.port or angular.json', (t) => {
19
+ const root = tmpdir(t);
20
+ const write = (rel, value) => {
21
+ fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
22
+ fs.writeFileSync(path.join(root, rel), typeof value === 'string' ? value : JSON.stringify(value));
23
+ };
24
+ write('poad/config.toml', '[db]\nport = 41000\n[web]\nport = 41001\n');
25
+ write('package.json', { name: 'proj', workspaces: ['apps/*', 'front/docs'] });
26
+ write('apps/web/package.json', { name: 'web', poad: { app: 'web', port: 3300 } });
27
+ write('apps/admin/package.json', { name: 'admin' });
28
+ write('apps/admin/angular.json', { projects: { a: { architect: { serve: { options: { port: 4301 } } } } } });
29
+ write('front/docs/package.json', { name: 'docs', poad: { port: 3301 } });
30
+ write('apps/notes.txt', 'not a folder');
31
+ const apps = ws.listApps(root);
32
+ assert.deepStrictEqual(apps.map((a) => [a.rel, a.name, a.port]), [['apps/admin', 'admin', 4301], ['apps/web', 'web', 3300], ['front/docs', 'docs', 3301]]);
33
+ assert.deepStrictEqual([...ws.usedPorts(root)].sort((a, b) => a - b), [3300, 3301, 4301, 41000, 41001]);
34
+
35
+ // Ancienne disposition : la racine est un front (pas de workspaces)
36
+ write('package.json', { name: 'flat', scripts: { start: 'node scripts/dev.mjs' } });
37
+ assert.strictEqual(ws.listApps(root)[0].rel, '.');
38
+ });
39
+
40
+ test('registerApp: folder added to workspaces when not covered, start scripts; nothing without workspaces', (t) => {
41
+ const root = tmpdir(t);
42
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(ws.rootPackageJson('proj', ['web'])));
43
+ assert.deepStrictEqual(ws.registerApp(root, path.join(root, 'apps', 'admin'), 'admin'), { workspace: true, added: ['start:admin'] });
44
+ assert.deepStrictEqual(ws.registerApp(root, path.join(root, 'front', 'docs'), 'docs'), { workspace: true, added: ['workspaces', 'start:docs'] });
45
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
46
+ assert.deepStrictEqual(pkg.workspaces, ['apps/*', 'front/docs']);
47
+ assert.strictEqual(pkg.scripts['start:docs'], 'node scripts/start.mjs docs');
48
+ // Encore une fois : rien de plus
49
+ assert.deepStrictEqual(ws.registerApp(root, path.join(root, 'apps', 'admin'), 'admin').added, []);
50
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: 'flat' }));
51
+ assert.deepStrictEqual(ws.registerApp(root, path.join(root, 'apps', 'x'), 'x'), { workspace: false, added: [] });
52
+ });
53
+
54
+ test('prepareStarter: a folder that already has a .gitignore gets the template lines merged', (t) => {
55
+ const dir = tmpdir(t);
56
+ fs.writeFileSync(path.join(dir, '.gitignore'), 'poad/secrets.toml\n');
57
+ fs.writeFileSync(path.join(dir, 'gitignore'), '# modèle\n/.next/\npoad/secrets.toml\n');
58
+ assert.strictEqual(starter.prepareStarter(dir).gitignore, 'merged');
59
+ assert.ok(!fs.existsSync(path.join(dir, 'gitignore')));
60
+ assert.deepStrictEqual(fs.readFileSync(path.join(dir, '.gitignore'), 'utf8').split('\n').filter((l) => l && !l.startsWith('#')), ['poad/secrets.toml', '/.next/']);
61
+ });
62
+
63
+ test('devServer: a port used by another front-end of the project is skipped', async (t) => {
64
+ const dir = tmpdir(t);
65
+ const next = { poad: { port: 3300, template: { framework: 'next' } } };
66
+ assert.strictEqual((await starter.devServer(dir, next, { exclude: new Set([3300, 3301]) })).port, 3302);
67
+ fs.writeFileSync(path.join(dir, 'angular.json'), JSON.stringify({ projects: { a: { architect: { serve: { options: {} } } } } }));
68
+ const ng = await starter.devServer(dir, { poad: { template: { framework: 'angular', port: 4300 } } }, { exclude: new Set([4300]) });
69
+ assert.ok(ng.port > 4300);
70
+ assert.strictEqual(JSON.parse(fs.readFileSync(path.join(dir, 'angular.json'), 'utf8')).projects.a.architect.serve.options.port, ng.port);
71
+ });
@@ -0,0 +1,31 @@
1
+ // Passerelle de l'engine : réglages de poad/config.toml qu'elle lit au
2
+ // démarrage, passés en variables d'environnement par `poad start`.
3
+ //
4
+ // [gateway]
5
+ // max_body = "10m" taille maximale d'un corps de requête (k, m ou g ;
6
+ // "0" = aucune limite). Au-delà : 413. Les envois du
7
+ // storage y échappent (le service a sa propre limite).
8
+ //
9
+ // Engine 0.28.2 et plus (POAD_GATEWAY_MAX_BODY) ; un engine plus ancien ignore
10
+ // la variable et n'a pas de limite. L'engine vérifie aussi la valeur et revient
11
+ // à 10m si elle n'est pas une taille.
12
+
13
+ const DEFAULT_MAX_BODY = '10m';
14
+ const SIZE = /^[0-9]+[kmg]?$/;
15
+
16
+ /** Taille maximale d'un corps, normalisée ; { value, warning } si la valeur de config.toml est refusée */
17
+ const maxBody = (config) => {
18
+ const raw = config && config.gateway ? config.gateway.max_body : undefined;
19
+ if (raw === undefined || raw === null || raw === '') return { value: DEFAULT_MAX_BODY };
20
+ const value = String(raw).trim().toLowerCase();
21
+ if (SIZE.test(value)) return { value };
22
+ return {
23
+ value: DEFAULT_MAX_BODY,
24
+ warning: `[gateway] max_body = "${String(raw).slice(0, 32)}" in poad/config.toml is not a size (examples: "10m", "512k", "1g"): ${DEFAULT_MAX_BODY} is used.`,
25
+ };
26
+ };
27
+
28
+ /** Variables de l'engine */
29
+ const engineEnv = (config) => [`POAD_GATEWAY_MAX_BODY=${maxBody(config).value}`];
30
+
31
+ module.exports = { DEFAULT_MAX_BODY, maxBody, engineEnv };
package/utils/starter.js CHANGED
@@ -82,12 +82,17 @@ function packageName(dir) {
82
82
  function prepareStarter(dir) {
83
83
  const result = { gitignore: null, stripped: [] };
84
84
  const gi = path.join(dir, '.gitignore');
85
- if (!fs.existsSync(gi)) {
86
- const src = GITIGNORE_SOURCES.map((n) => path.join(dir, n)).find((f) => fs.existsSync(f) && fs.statSync(f).isFile());
87
- if (src) {
88
- fs.renameSync(src, gi);
89
- result.gitignore = 'restored';
90
- }
85
+ const src = GITIGNORE_SOURCES.map((n) => path.join(dir, n)).find((f) => fs.existsSync(f) && fs.statSync(f).isFile());
86
+ if (src && !fs.existsSync(gi)) {
87
+ fs.renameSync(src, gi);
88
+ result.gitignore = 'restored';
89
+ } else if (src && path.basename(src) !== '.npmignore') {
90
+ // Dossier qui a déjà son .gitignore (front posé à la racine du projet) :
91
+ // les lignes du modèle y sont ajoutées, le fichier « gitignore » disparaît
92
+ const lines = fs.readFileSync(src, 'utf8').split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
93
+ require('./git').ensureLines(dir, 'Front-end', lines);
94
+ fs.rmSync(src);
95
+ result.gitignore = 'merged';
91
96
  }
92
97
  for (const rel of STRIP) {
93
98
  const abs = path.join(dir, ...rel.split('/'));
@@ -145,16 +150,36 @@ function adaptToPackageManager(dir, pm) {
145
150
  /** Premier port libre sur 127.0.0.1 à partir de start (4200 est souvent pris) */
146
151
  async function freePort(start, max = start + 100) {
147
152
  const net = require('net');
148
- const free = (port) =>
153
+ // Rien n'y répond (IPv4 ni IPv6 : un serveur sur [::1] seul n'empêche pas
154
+ // d'écouter sur 127.0.0.1) et on peut y écouter
155
+ const answers = (port, host) =>
156
+ new Promise((ok) => {
157
+ const c = net.connect({ port, host });
158
+ c.setTimeout(500, () => c.destroy() && ok(false));
159
+ c.once('connect', () => c.destroy() && ok(true));
160
+ c.once('error', () => ok(false));
161
+ });
162
+ const bindable = (port) =>
149
163
  new Promise((ok) => {
150
164
  const s = net.createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
151
165
  s.listen(port, '127.0.0.1');
152
166
  });
167
+ const free = async (port) => !(await answers(port, '127.0.0.1')) && !(await answers(port, '::1')) && (await bindable(port));
153
168
  let port = start;
154
169
  while (!(await free(port)) && port < max) port++;
155
170
  return port;
156
171
  }
157
172
 
173
+ /** Premier port libre à partir de start qui n'est pas dans exclude */
174
+ async function nextPort(start, exclude = new Set()) {
175
+ let port = start;
176
+ for (;;) {
177
+ port = await freePort(port);
178
+ if (!exclude.has(port)) return port;
179
+ port++;
180
+ }
181
+ }
182
+
158
183
  // Frameworks reconnus : étiquette affichée, dépendance qui les trahit, port de
159
184
  // développement par défaut quand le modèle n'en déclare pas (celui de l'outil).
160
185
  const FRAMEWORKS = {
@@ -188,13 +213,15 @@ function declaredPort(pkg = {}) {
188
213
  * l'application) et prennent le premier libre au démarrage : rien à écrire.
189
214
  * Renvoie { framework, label, port, url } (port et url null si inconnus).
190
215
  */
191
- async function devServer(dir, pkg = {}) {
216
+ async function devServer(dir, pkg = {}, { exclude = new Set() } = {}) {
192
217
  const framework = frameworkOf(pkg);
193
218
  const fw = framework ? FRAMEWORKS[framework] : null;
194
219
  let port = declaredPort(pkg) || (fw && fw.port) || null;
220
+ // Port d'un autre front du projet (ou d'un de ses services) : le suivant libre
221
+ if (port && exclude.has(port)) port = await nextPort(port, exclude);
195
222
  const ngFile = path.join(dir, 'angular.json');
196
223
  if (fs.existsSync(ngFile)) {
197
- port = await freePort(port || FRAMEWORKS.angular.port);
224
+ port = await nextPort(port || FRAMEWORKS.angular.port, exclude);
198
225
  const ng = JSON.parse(fs.readFileSync(ngFile, 'utf8'));
199
226
  for (const p of Object.values(ng.projects || {})) {
200
227
  const serve = p.architect && p.architect.serve;
@@ -211,4 +238,4 @@ async function applyDevPort(dir, template = {}) {
211
238
  return (await devServer(dir, { poad: { template } })).port;
212
239
  }
213
240
 
214
- module.exports = { freePort, applyDevPort, devServer, frameworkOf, declaredPort, FRAMEWORKS, TEMPLATES, templateByValue, STRIP, PACKAGE_RULES, rewritePackageJson, packageName, prepareStarter, readPackage, adaptToPackageManager };
241
+ module.exports = { LOCKFILES, freePort, nextPort, applyDevPort, devServer, frameworkOf, declaredPort, FRAMEWORKS, TEMPLATES, templateByValue, STRIP, PACKAGE_RULES, rewritePackageJson, packageName, prepareStarter, readPackage, adaptToPackageManager };