create-cwa 2.0.0-alpha.43 → 2.0.0-alpha.44

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/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # create-cwa
2
+
3
+ Create a new [CWA (Components Web App)](https://cwa.rocks) project: a Nuxt front end with the [`@cwa/nuxt`](https://github.com/components-web-app/cwa-nuxt-module) module, and a Symfony and API Platform API with the [API Components Bundle](https://github.com/components-web-app/api-components-bundle), run locally with Docker.
4
+
5
+ > **Prerelease.** CWA 2 is in alpha: expect breaking changes between versions. Each release's changes and upgrade notes are in the template's [CHANGELOG](https://github.com/components-web-app/components-web-app/blob/main/CHANGELOG.md).
6
+
7
+ ## Usage
8
+
9
+ ```sh
10
+ pnpm create cwa my-app
11
+ # or
12
+ npx create-cwa my-app
13
+ ```
14
+
15
+ Requires Node.js 22.13 or later, and Docker to run the project.
16
+
17
+ The CLI asks for:
18
+
19
+ - **Project name**: lower-case letters, digits and dashes. It becomes the directory (which must not exist yet, or be empty) and the Docker Compose project name.
20
+ - **CI/CD pipeline**: GitHub Actions, GitLab CI (both deploy to Kubernetes) or None to decide later.
21
+ - **Features**: navigation links, an HTML content editor, image uploads, a blog, nested pages and an example form. Features another one needs are added for you.
22
+ - **Fixtures**: sample pages for the chosen features.
23
+ - **Start the Docker stack?** Before anything is downloaded, it checks that Docker is running and that ports 80, 443, 3001, 5432 and 8025 are free, and names whatever holds a port. If you don't start the stack now, it offers to install `app/` dependencies on your machine for editor types (default No): the app container installs its own either way.
24
+
25
+ If you start the stack, the CLI runs the project's `bin/up`: it waits until the stack is healthy, loads the fixtures (which create the admin, and the sample pages if you chose them), pre-compiles the first pages and prints the login. Run `bin/up` again any time; it's safe to repeat. The site is at `https://localhost`, the admin signs in at `https://localhost/login` (`admin` / `admin` in dev), and Mailpit shows the emails the API sends at `http://localhost:8025`. Without a POSIX shell (Windows without WSL), the CLI prints the steps instead.
26
+
27
+ ## Options
28
+
29
+ - `--ref <tag or branch>`: the template version to download. By default `create-cwa` X downloads the template tagged `vX`, so an install is reproducible. `--ref main` gets the latest unreleased template.
30
+
31
+ ## Privacy
32
+
33
+ `create-cwa` collects no telemetry. It only downloads the template and its manifest from GitHub.
34
+
35
+ ## Licence
36
+
37
+ MIT
package/dist/index.js CHANGED
@@ -3,11 +3,13 @@ import { downloadTemplate } from 'giget';
3
3
  import fse from 'fs-extra';
4
4
  import fg from 'fast-glob';
5
5
  import { readFile, writeFile } from 'node:fs/promises';
6
- import { existsSync, readFileSync } from 'node:fs';
6
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
7
7
  import { join, resolve } from 'node:path';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { randomBytes } from 'node:crypto';
10
10
  import { spawnSync } from 'node:child_process';
11
+ import { styleText } from 'node:util';
12
+ import { preflight } from './preflight.js';
11
13
  const REPO = 'components-web-app/components-web-app';
12
14
  // The CLI and the template share a version: create-cwa X downloads the template at
13
15
  // tag vX, so an install is reproducible. `--ref <branch|tag>` overrides it, for
@@ -66,26 +68,46 @@ function run(cmd, args, cwd) {
66
68
  const result = spawnSync(cmd, args, { stdio: 'inherit', cwd });
67
69
  return result.status === 0;
68
70
  }
71
+ function withHint(message, hint) {
72
+ return hint ? `${message} ${styleText('dim', `(${hint})`)}` : message;
73
+ }
74
+ // The name becomes the directory and the compose project name.
75
+ const PROJECT_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
76
+ function validateProjectName(value) {
77
+ const name = value?.trim() ?? '';
78
+ if (!name)
79
+ return 'Project name is required';
80
+ if (!PROJECT_NAME.test(name)) {
81
+ return 'Use lower-case letters, digits and single dashes (for example my-cwa-app)';
82
+ }
83
+ const dir = resolve(process.cwd(), name);
84
+ if (existsSync(dir) && (!statSync(dir).isDirectory() || readdirSync(dir).length > 0)) {
85
+ return `"${name}" already exists here and is not an empty directory`;
86
+ }
87
+ return undefined;
88
+ }
69
89
  async function askQuestions(manifest, targetArg) {
90
+ const question = (id) => manifest.questions.find((q) => q.id === id);
91
+ const nameQuestion = question('projectName');
70
92
  const projectName = checkCancel(await text({
71
- message: 'Project name?',
72
- placeholder: 'my-cwa-app',
93
+ message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
94
+ placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
73
95
  initialValue: targetArg ?? '',
74
- validate: (v) => (v?.trim() ? undefined : 'Project name is required'),
96
+ validate: validateProjectName,
75
97
  }));
98
+ const ciQuestion = question('ci');
76
99
  const ci = checkCancel(await select({
77
- message: 'CI/CD pipeline?',
78
- options: [
100
+ message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
101
+ options: ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
79
102
  { value: 'github', label: 'GitHub Actions' },
80
103
  { value: 'gitlab', label: 'GitLab CI' },
81
104
  { value: 'none', label: 'None' },
82
105
  ],
83
106
  }));
84
- const featureChoices = manifest.questions
85
- .find((q) => q.id === 'features')
86
- ?.choices?.map((c) => ({ value: c.value, label: c.label })) ?? [];
107
+ const featuresQuestion = question('features');
108
+ const featureChoices = featuresQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [];
87
109
  const features = checkCancel(await multiselect({
88
- message: 'Which features to include? (space to toggle, enter to confirm)',
110
+ message: withHint(`${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`, featuresQuestion?.hint),
89
111
  options: featureChoices,
90
112
  required: false,
91
113
  }));
@@ -101,9 +123,10 @@ async function askQuestions(manifest, targetArg) {
101
123
  const added = [...resolved].filter((f) => !features.includes(f));
102
124
  note(`Also enabling: ${added.join(', ')} (required by selected features)`, 'Dependencies');
103
125
  }
126
+ const fixturesQuestion = question('fixtures');
104
127
  const fixtures = checkCancel(await confirm({
105
- message: 'Include database fixtures for selected features?',
106
- initialValue: true,
128
+ message: withHint(fixturesQuestion?.message ?? 'Include database fixtures for selected features?', fixturesQuestion?.hint),
129
+ initialValue: fixturesQuestion?.default ?? true,
107
130
  }));
108
131
  return { projectName: projectName.trim(), ci, features: [...resolved], fixtures };
109
132
  }
@@ -173,24 +196,17 @@ async function generateReadme(tempDir, answers) {
173
196
  : answers.ci === 'gitlab'
174
197
  ? '## CI/CD\n\nGitLab CI is configured in `.gitlab-ci.yml`. See `bin/devops/` for the reusable pipeline scripts.\n'
175
198
  : '';
176
- const fixturesSection = answers.fixtures
177
- ? `## Fixtures
178
-
179
- Sample content is bundled. Load it after the API container is healthy:
199
+ const fixturesSection = `## Fixtures and the admin account
180
200
 
181
- \`\`\`bash
182
- docker compose exec php bin/console doctrine:fixtures:load --append
183
- \`\`\`
184
- `
185
- : `## Admin account
186
-
187
- No sample content is bundled. Create the admin (\`ADMIN_USERNAME\` / \`ADMIN_PASSWORD\` / \`ADMIN_EMAIL\`, default \`admin\` / \`admin\`) once the API container is healthy:
201
+ \`bin/up\` loads the fixtures with \`--append\`, which only creates what's missing: the admin
202
+ (\`ADMIN_USERNAME\` / \`ADMIN_PASSWORD\` / \`ADMIN_EMAIL\` in \`api/.env.local\`, default
203
+ \`admin\` / \`admin\` / \`admin@example.com\`)${answers.fixtures ? ' and the sample pages' : ''}. Each load resets the
204
+ admin's password to \`ADMIN_PASSWORD\`; \`bin/up --skip-fixtures\` keeps one changed in the admin.
205
+ To load them by hand:
188
206
 
189
207
  \`\`\`bash
190
208
  docker compose exec php bin/console doctrine:fixtures:load --append
191
209
  \`\`\`
192
-
193
- Or create one by hand: \`docker compose exec php bin/console silverback:api-components:user:create --admin\`.
194
210
  `;
195
211
  const readme = `# ${answers.projectName}
196
212
 
@@ -203,34 +219,40 @@ ${featureList}
203
219
  ## Getting started
204
220
 
205
221
  \`\`\`bash
206
- # Start the stack. The php container runs composer install, waits for the
207
- # database and migrates; the app container installs the Nuxt dependencies and
208
- # runs the dev server. There is nothing to start by hand.
209
- docker compose up -d
222
+ # Start the stack, wait until it's healthy, load the fixtures, pre-compile the
223
+ # first pages and print where to sign in. Safe to run again.
224
+ bin/up
210
225
 
211
226
  # Follow the Nuxt dev server
212
227
  docker compose logs -f app
213
228
  \`\`\`
214
229
 
215
- \`app/\` is mounted into the app container, so its \`node_modules\` is shared. Run
216
- \`pnpm install\` in \`app/\` yourself only if your editor needs the types locally.
230
+ \`bin/up\` runs \`docker compose up -d --wait\`: the php container runs composer install,
231
+ waits for the database and migrates; the app container installs the Nuxt dependencies
232
+ and runs the dev server. Without a POSIX shell (Windows without WSL), run
233
+ \`docker compose up -d --wait\` and the fixtures command below instead.
234
+
235
+ \`app/\` is mounted into the app container, so its \`node_modules\` is shared: your
236
+ editor gets the types from the container's install. Don't run \`pnpm install\` on
237
+ this machine while the stack runs (it rewrites \`node_modules\` under the dev
238
+ server); if you do, run \`docker compose restart app\`.
217
239
 
218
240
  | URL | Description |
219
241
  |---|---|
220
242
  | https://localhost | Nuxt app |
221
243
  | https://localhost/_api | API (JSON-LD / HAL) |
222
244
  | https://localhost/login | Sign in to the CWA admin |
245
+ | http://localhost:8025 | Mailpit: every email the API sends in dev |
223
246
 
224
- > **SSL:** Caddy issues local certificates from its own CA. Accept the browser warning, or trust the CA once:
225
- > \`docker compose cp php:/data/caddy/pki/authorities/local/root.crt caddy-local-root.crt\`,
226
- > then add \`caddy-local-root.crt\` to your system or browser trust store.
247
+ > **Certificate warning:** Caddy signs the local certificate with its own CA, so the browser warns
248
+ > on the first visit. Accepting the warning is expected for local development.
227
249
 
228
250
  ${fixturesSection}
229
251
  ${ciSection}## Learn more
230
252
 
231
253
  - [CWA documentation](https://cwa.rocks)
232
- - [API Components Bundle](https://github.com/silverbackdan/api-components-bundle)
233
- - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-3-module)
254
+ - [API Components Bundle](https://github.com/components-web-app/api-components-bundle)
255
+ - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-module)
234
256
  `;
235
257
  await writeFile(join(tempDir, 'README.md'), readme, 'utf-8');
236
258
  }
@@ -243,8 +265,53 @@ async function moveToTarget(tempDir, targetDir) {
243
265
  }
244
266
  await fse.move(tempDir, targetDir, { overwrite: false });
245
267
  }
268
+ // Decides, before anything is downloaded, whether to start the stack and whether to
269
+ // install app/ dependencies on the host. The host install shares app/node_modules with
270
+ // the app container, so it's only offered when the stack isn't started now (#204).
271
+ async function askSetup() {
272
+ let startDocker = false;
273
+ if (commandExists('docker')) {
274
+ startDocker = checkCancel(await confirm({
275
+ message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
276
+ initialValue: true,
277
+ }));
278
+ }
279
+ else {
280
+ log.warn('docker not found. Install Docker Desktop, then run `bin/up` in the project.');
281
+ }
282
+ if (startDocker) {
283
+ const s = spinner();
284
+ s.start('Checking Docker and ports...');
285
+ const result = await preflight();
286
+ s.stop('Docker checked.');
287
+ if (!result.dockerRunning) {
288
+ log.warn('Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).');
289
+ startDocker = false;
290
+ }
291
+ else if (result.takenPorts.length) {
292
+ log.warn(result.takenPorts.join('\n\n'));
293
+ startDocker = false;
294
+ }
295
+ if (result.memoryWarning)
296
+ log.warn(result.memoryWarning);
297
+ if (!startDocker) {
298
+ log.info('The project will be created without starting Docker. Run `bin/up` in it once that is fixed.');
299
+ }
300
+ return { startDocker, installDeps: false };
301
+ }
302
+ let installDeps = false;
303
+ if (commandExists('pnpm')) {
304
+ installDeps = checkCancel(await confirm({
305
+ message: withHint('Install app/ dependencies on this machine?', 'only for editor types; the app container installs its own on first start'),
306
+ initialValue: false,
307
+ }));
308
+ }
309
+ return { startDocker, installDeps };
310
+ }
246
311
  async function main() {
247
- intro('create-cwa — Components Web App scaffolder');
312
+ intro(`create-cwa ${CLI_VERSION} — Components Web App scaffolder`);
313
+ log.warn('CWA is a prerelease: expect breaking changes between versions (see CHANGELOG.md on GitHub).\n' +
314
+ 'create-cwa collects no telemetry; it only downloads the template from GitHub.');
248
315
  const args = parseArgs(process.argv);
249
316
  const s = spinner();
250
317
  s.start('Fetching manifest...');
@@ -258,6 +325,7 @@ async function main() {
258
325
  process.exit(1);
259
326
  }
260
327
  const answers = await askQuestions(manifest, args.projectName);
328
+ const setup = await askSetup();
261
329
  const targetDir = resolve(process.cwd(), answers.projectName);
262
330
  const tempDir = join(tmpdir(), `cwa-${randomBytes(6).toString('hex')}`);
263
331
  await downloadRepo(manifest, args.ref, tempDir);
@@ -293,66 +361,51 @@ async function main() {
293
361
  ' • waits for PostgreSQL to be ready',
294
362
  ' • runs database migrations',
295
363
  '',
296
- 'The app container installs the Nuxt dependencies and runs the dev server,',
297
- 'so there is nothing to start by hand.',
298
- answers.fixtures
299
- ? '\nFixtures are NOT loaded automatically — you will be reminded below.'
300
- : '',
364
+ 'The app container installs the Nuxt dependencies into app/node_modules',
365
+ '(which your editor reads too) and runs the dev server.',
366
+ '',
367
+ 'bin/up waits for all that, loads the fixtures (the admin' +
368
+ (answers.fixtures ? ' and sample pages' : '') +
369
+ '),',
370
+ 'pre-compiles the first pages and prints where to sign in. Run it again any time.',
301
371
  ]
302
372
  .join('\n')
303
373
  .trim(), 'What Docker handles for you');
304
- // Offer to start Docker
305
- const hasDocker = commandExists('docker');
306
- if (hasDocker) {
307
- const startDocker = checkCancel(await confirm({ message: 'Start the Docker stack now? (docker compose up -d)', initialValue: true }));
308
- if (startDocker) {
309
- log.step('Running: docker compose up -d');
310
- const ok = run('docker', ['compose', 'up', '-d'], targetDir);
311
- if (!ok) {
312
- log.warn('docker compose up -d failed. Run it manually from the project directory.');
313
- }
374
+ if (setup.installDeps) {
375
+ log.step('Running: pnpm install (in app/)');
376
+ if (!run('pnpm', ['install'], join(targetDir, 'app'))) {
377
+ log.warn('pnpm install failed. Run it manually inside app/.');
314
378
  }
315
379
  }
316
- else {
317
- log.warn('docker not found — install Docker Desktop, then run: docker compose up -d');
318
- }
319
- // Offer to install Nuxt deps
320
- const hasPnpm = commandExists('pnpm');
321
- if (hasPnpm) {
322
- const installDeps = checkCancel(await confirm({
323
- message: 'Also install app/ dependencies on this machine, for editor type support? (the app container installs them either way)',
324
- initialValue: false,
325
- }));
326
- if (installDeps) {
327
- log.step('Running: pnpm install');
328
- const ok = run('pnpm', ['install'], join(targetDir, 'app'));
329
- if (!ok) {
330
- log.warn('pnpm install failed. Run it manually inside app/.');
380
+ // bin/up is POSIX sh; Windows without sh (no WSL or Git Bash) gets the steps instead (#206).
381
+ const hasShell = process.platform !== 'win32' || commandExists('sh');
382
+ let ready = false;
383
+ if (setup.startDocker) {
384
+ if (hasShell) {
385
+ log.step('Running: bin/up');
386
+ ready = run('sh', ['bin/up'], targetDir);
387
+ if (!ready)
388
+ log.warn('bin/up failed (see above). Fix it, then run bin/up again in the project directory.');
389
+ }
390
+ else {
391
+ log.step('Running: docker compose up -d --wait');
392
+ if (!run('docker', ['compose', 'up', '-d', '--wait'], targetDir)) {
393
+ log.warn('docker compose up -d --wait failed. Run it again in the project directory.');
331
394
  }
332
395
  }
333
396
  }
334
- else {
335
- log.warn('pnpm not found — run: npm i -g pnpm, then pnpm install inside app/');
336
- }
337
- const outroLines = [
338
- `The dev server runs in the app container. Follow it with:`,
339
- ` cd ${answers.projectName} && docker compose logs -f app`,
340
- '',
341
- 'Then visit:',
342
- ' https://localhost — app',
343
- ' https://localhost/_api — API',
344
- ' https://localhost/login — sign in to the admin',
345
- ];
346
- if (answers.fixtures) {
347
- outroLines.push('');
348
- outroLines.push('Load sample content (once the API container is healthy):');
349
- outroLines.push(' docker compose exec php bin/console doctrine:fixtures:load --append');
350
- }
351
- else {
352
- outroLines.push('');
353
- outroLines.push('Create the admin from ADMIN_* (once the API container is healthy):');
354
- outroLines.push(' docker compose exec php bin/console doctrine:fixtures:load --append');
355
- }
397
+ const outroLines = ready
398
+ ? [`The site is ready: sign in with the login printed above. Next time: cd ${answers.projectName} && bin/up`]
399
+ : hasShell
400
+ ? ['Start the stack, load the fixtures and get the login with:', ` cd ${answers.projectName} && bin/up`]
401
+ : [
402
+ 'Start the stack and create the admin (and any sample pages) with:',
403
+ ` cd ${answers.projectName}`,
404
+ ' docker compose up -d --wait',
405
+ ' docker compose exec php bin/console doctrine:fixtures:load --append',
406
+ 'Then sign in at https://localhost/login as admin / admin (accept the certificate warning).',
407
+ ];
408
+ outroLines.push('', 'Follow the dev server with: docker compose logs -f app', "Don't run pnpm install on this machine while the stack runs: app/node_modules", 'is shared with the dev server. If you do, run: docker compose restart app');
356
409
  outro(outroLines.join('\n'));
357
410
  }
358
411
  main().catch((err) => {
@@ -0,0 +1,12 @@
1
+ export declare const STACK_PORTS: {
2
+ port: number;
3
+ service: string;
4
+ culprits: string;
5
+ alternative?: string;
6
+ }[];
7
+ export interface PreflightResult {
8
+ dockerRunning: boolean;
9
+ takenPorts: string[];
10
+ memoryWarning: string | null;
11
+ }
12
+ export declare function preflight(): Promise<PreflightResult>;
@@ -0,0 +1,107 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createConnection, createServer } from 'node:net';
3
+ // Ports the dev stack publishes: compose.yaml (80, 443) and compose.override.yaml (3001, 5432, 8025).
4
+ export const STACK_PORTS = [
5
+ {
6
+ port: 80,
7
+ service: 'Caddy (php container), HTTP',
8
+ culprits: 'another CWA project (`docker compose stop` in its directory), Laravel Valet (`valet stop`), Herd (quit it), nginx or Apache',
9
+ },
10
+ {
11
+ port: 443,
12
+ service: 'Caddy (php container), HTTPS',
13
+ culprits: 'another CWA project (`docker compose stop` in its directory), Laravel Valet (`valet stop`), Herd (quit it), nginx or Apache',
14
+ },
15
+ {
16
+ port: 3001,
17
+ service: 'Nuxt dev server (app container)',
18
+ culprits: 'another CWA project (`docker compose stop` in its directory) or a Node dev server',
19
+ alternative: 'Or change `published: 3001` under `app:` in compose.override.yaml to a free port.',
20
+ },
21
+ {
22
+ port: 5432,
23
+ service: 'PostgreSQL (database container)',
24
+ culprits: 'another CWA project (`docker compose stop` in its directory) or a local PostgreSQL (Postgres.app, `brew services stop postgresql`)',
25
+ alternative: 'Or change `published: 5432` under `database:` in compose.override.yaml to a free port.',
26
+ },
27
+ {
28
+ port: 8025,
29
+ service: 'Mailpit web UI (mailpit container)',
30
+ culprits: 'another CWA project (`docker compose stop` in its directory) or a local Mailpit or MailHog',
31
+ alternative: 'Or change `published: 8025` under `mailpit:` in compose.override.yaml to a free port.',
32
+ },
33
+ ];
34
+ // Docker Desktop reports a little less than the VM's allocation, so 4 GiB shows as ~3.8 GiB.
35
+ const MIN_DOCKER_MEMORY = 3.5 * 1024 ** 3;
36
+ function canConnect(port) {
37
+ return new Promise((resolve) => {
38
+ const socket = createConnection({ host: '127.0.0.1', port });
39
+ const done = (result) => {
40
+ socket.destroy();
41
+ resolve(result);
42
+ };
43
+ socket.setTimeout(1000, () => done(false));
44
+ socket.once('connect', () => done(true));
45
+ socket.once('error', () => done(false));
46
+ });
47
+ }
48
+ function addressInUse(port) {
49
+ return new Promise((resolve) => {
50
+ const server = createServer();
51
+ server.once('error', (err) => resolve(err.code === 'EADDRINUSE'));
52
+ server.once('listening', () => server.close(() => resolve(false)));
53
+ server.listen(port, '0.0.0.0');
54
+ });
55
+ }
56
+ function output(cmd, args) {
57
+ const result = spawnSync(cmd, args, { stdio: 'pipe', encoding: 'utf8' });
58
+ return result.status === 0 ? result.stdout.trim() : null;
59
+ }
60
+ // What holds the port: the containers Docker publishes it for, else the process lsof sees.
61
+ function portHolder(port) {
62
+ const containers = output('docker', [
63
+ 'ps',
64
+ '--filter',
65
+ `publish=${port}`,
66
+ '--format',
67
+ '{{.Names}}\t{{.Label "com.docker.compose.project"}}',
68
+ ]);
69
+ if (containers) {
70
+ const rows = containers.split('\n').map((row) => row.split('\t'));
71
+ const names = rows.map(([name]) => name).join(', ');
72
+ const projects = [...new Set(rows.map(([, project]) => project).filter(Boolean))];
73
+ return projects.length
74
+ ? {
75
+ holder: `container ${names} (compose project ${projects.join(', ')})`,
76
+ stop: projects.map((p) => `docker compose -p ${p} stop`).join(' and '),
77
+ }
78
+ : { holder: `container ${names}`, stop: `docker stop ${rows.map(([name]) => name).join(' ')}` };
79
+ }
80
+ if (process.platform === 'win32')
81
+ return null;
82
+ const lsof = output('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fc']);
83
+ const command = lsof?.split('\n').find((l) => l.startsWith('c'))?.slice(1);
84
+ return command ? { holder: `process ${command}` } : null;
85
+ }
86
+ export async function preflight() {
87
+ const memTotal = output('docker', ['info', '--format', '{{.MemTotal}}']);
88
+ if (memTotal === null) {
89
+ return { dockerRunning: false, takenPorts: [], memoryWarning: null };
90
+ }
91
+ const takenPorts = [];
92
+ for (const { port, service, culprits, alternative } of STACK_PORTS) {
93
+ if ((await canConnect(port)) || (await addressInUse(port))) {
94
+ const found = portHolder(port);
95
+ const lines = [`Port ${port} (${service}) is in use${found ? ` by ${found.holder}` : ''}.`];
96
+ lines.push(found?.stop ? ` Stop it with: ${found.stop}` : ` Free it. Likely: ${culprits}.`);
97
+ if (alternative)
98
+ lines.push(` ${alternative}`);
99
+ takenPorts.push(lines.join('\n'));
100
+ }
101
+ }
102
+ const bytes = Number(memTotal);
103
+ const memoryWarning = bytes > 0 && bytes < MIN_DOCKER_MEMORY
104
+ ? `Docker has ${(bytes / 1024 ** 3).toFixed(1)} GiB of memory; the stack needs about 4 GiB. Raise it in Docker Desktop → Settings → Resources.`
105
+ : null;
106
+ return { dockerRunning: true, takenPorts, memoryWarning };
107
+ }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export interface ManifestChoice {
2
2
  value: string;
3
3
  label: string;
4
+ hint?: string;
4
5
  requires?: string[];
5
6
  }
6
7
  export interface ManifestQuestion {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-cwa",
3
- "version": "2.0.0-alpha.43",
3
+ "version": "2.0.0-alpha.44",
4
4
  "description": "Create a new CWA (Components Web App) project",
5
5
  "type": "module",
6
6
  "bin": {
package/src/index.ts CHANGED
@@ -15,12 +15,14 @@ import { downloadTemplate } from 'giget'
15
15
  import fse from 'fs-extra'
16
16
  import fg from 'fast-glob'
17
17
  import { readFile, writeFile } from 'node:fs/promises'
18
- import { existsSync, readFileSync } from 'node:fs'
18
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
19
19
  import { join, resolve } from 'node:path'
20
20
  import { tmpdir } from 'node:os'
21
21
  import { randomBytes } from 'node:crypto'
22
22
  import { spawnSync } from 'node:child_process'
23
- import type { Manifest, Answers } from './types.js'
23
+ import { styleText } from 'node:util'
24
+ import { preflight } from './preflight.js'
25
+ import type { Manifest, ManifestQuestion, Answers } from './types.js'
24
26
 
25
27
  const REPO = 'components-web-app/components-web-app'
26
28
 
@@ -86,20 +88,45 @@ function run(cmd: string, args: string[], cwd: string): boolean {
86
88
  return result.status === 0
87
89
  }
88
90
 
91
+ function withHint(message: string, hint?: string): string {
92
+ return hint ? `${message} ${styleText('dim', `(${hint})`)}` : message
93
+ }
94
+
95
+ // The name becomes the directory and the compose project name.
96
+ const PROJECT_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
97
+
98
+ function validateProjectName(value: string | undefined): string | undefined {
99
+ const name = value?.trim() ?? ''
100
+ if (!name) return 'Project name is required'
101
+ if (!PROJECT_NAME.test(name)) {
102
+ return 'Use lower-case letters, digits and single dashes (for example my-cwa-app)'
103
+ }
104
+ const dir = resolve(process.cwd(), name)
105
+ if (existsSync(dir) && (!statSync(dir).isDirectory() || readdirSync(dir).length > 0)) {
106
+ return `"${name}" already exists here and is not an empty directory`
107
+ }
108
+ return undefined
109
+ }
110
+
89
111
  async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Answers> {
112
+ const question = (id: string): ManifestQuestion | undefined =>
113
+ manifest.questions.find((q) => q.id === id)
114
+
115
+ const nameQuestion = question('projectName')
90
116
  const projectName = checkCancel(
91
117
  await text({
92
- message: 'Project name?',
93
- placeholder: 'my-cwa-app',
118
+ message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
119
+ placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
94
120
  initialValue: targetArg ?? '',
95
- validate: (v) => (v?.trim() ? undefined : 'Project name is required'),
121
+ validate: validateProjectName,
96
122
  })
97
123
  ) as string
98
124
 
125
+ const ciQuestion = question('ci')
99
126
  const ci = checkCancel(
100
127
  await select({
101
- message: 'CI/CD pipeline?',
102
- options: [
128
+ message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
129
+ options: ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
103
130
  { value: 'github', label: 'GitHub Actions' },
104
131
  { value: 'gitlab', label: 'GitLab CI' },
105
132
  { value: 'none', label: 'None' },
@@ -107,14 +134,16 @@ async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Ans
107
134
  })
108
135
  ) as string
109
136
 
137
+ const featuresQuestion = question('features')
110
138
  const featureChoices =
111
- manifest.questions
112
- .find((q) => q.id === 'features')
113
- ?.choices?.map((c) => ({ value: c.value, label: c.label })) ?? []
139
+ featuresQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? []
114
140
 
115
141
  const features = checkCancel(
116
142
  await multiselect({
117
- message: 'Which features to include? (space to toggle, enter to confirm)',
143
+ message: withHint(
144
+ `${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`,
145
+ featuresQuestion?.hint
146
+ ),
118
147
  options: featureChoices,
119
148
  required: false,
120
149
  })
@@ -135,10 +164,14 @@ async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Ans
135
164
  note(`Also enabling: ${added.join(', ')} (required by selected features)`, 'Dependencies')
136
165
  }
137
166
 
167
+ const fixturesQuestion = question('fixtures')
138
168
  const fixtures = checkCancel(
139
169
  await confirm({
140
- message: 'Include database fixtures for selected features?',
141
- initialValue: true,
170
+ message: withHint(
171
+ fixturesQuestion?.message ?? 'Include database fixtures for selected features?',
172
+ fixturesQuestion?.hint
173
+ ),
174
+ initialValue: fixturesQuestion?.default ?? true,
142
175
  })
143
176
  ) as boolean
144
177
 
@@ -227,24 +260,17 @@ async function generateReadme(tempDir: string, answers: Answers): Promise<void>
227
260
  ? '## CI/CD\n\nGitLab CI is configured in `.gitlab-ci.yml`. See `bin/devops/` for the reusable pipeline scripts.\n'
228
261
  : ''
229
262
 
230
- const fixturesSection = answers.fixtures
231
- ? `## Fixtures
263
+ const fixturesSection = `## Fixtures and the admin account
232
264
 
233
- Sample content is bundled. Load it after the API container is healthy:
265
+ \`bin/up\` loads the fixtures with \`--append\`, which only creates what's missing: the admin
266
+ (\`ADMIN_USERNAME\` / \`ADMIN_PASSWORD\` / \`ADMIN_EMAIL\` in \`api/.env.local\`, default
267
+ \`admin\` / \`admin\` / \`admin@example.com\`)${answers.fixtures ? ' and the sample pages' : ''}. Each load resets the
268
+ admin's password to \`ADMIN_PASSWORD\`; \`bin/up --skip-fixtures\` keeps one changed in the admin.
269
+ To load them by hand:
234
270
 
235
271
  \`\`\`bash
236
272
  docker compose exec php bin/console doctrine:fixtures:load --append
237
273
  \`\`\`
238
- `
239
- : `## Admin account
240
-
241
- No sample content is bundled. Create the admin (\`ADMIN_USERNAME\` / \`ADMIN_PASSWORD\` / \`ADMIN_EMAIL\`, default \`admin\` / \`admin\`) once the API container is healthy:
242
-
243
- \`\`\`bash
244
- docker compose exec php bin/console doctrine:fixtures:load --append
245
- \`\`\`
246
-
247
- Or create one by hand: \`docker compose exec php bin/console silverback:api-components:user:create --admin\`.
248
274
  `
249
275
 
250
276
  const readme = `# ${answers.projectName}
@@ -258,34 +284,40 @@ ${featureList}
258
284
  ## Getting started
259
285
 
260
286
  \`\`\`bash
261
- # Start the stack. The php container runs composer install, waits for the
262
- # database and migrates; the app container installs the Nuxt dependencies and
263
- # runs the dev server. There is nothing to start by hand.
264
- docker compose up -d
287
+ # Start the stack, wait until it's healthy, load the fixtures, pre-compile the
288
+ # first pages and print where to sign in. Safe to run again.
289
+ bin/up
265
290
 
266
291
  # Follow the Nuxt dev server
267
292
  docker compose logs -f app
268
293
  \`\`\`
269
294
 
270
- \`app/\` is mounted into the app container, so its \`node_modules\` is shared. Run
271
- \`pnpm install\` in \`app/\` yourself only if your editor needs the types locally.
295
+ \`bin/up\` runs \`docker compose up -d --wait\`: the php container runs composer install,
296
+ waits for the database and migrates; the app container installs the Nuxt dependencies
297
+ and runs the dev server. Without a POSIX shell (Windows without WSL), run
298
+ \`docker compose up -d --wait\` and the fixtures command below instead.
299
+
300
+ \`app/\` is mounted into the app container, so its \`node_modules\` is shared: your
301
+ editor gets the types from the container's install. Don't run \`pnpm install\` on
302
+ this machine while the stack runs (it rewrites \`node_modules\` under the dev
303
+ server); if you do, run \`docker compose restart app\`.
272
304
 
273
305
  | URL | Description |
274
306
  |---|---|
275
307
  | https://localhost | Nuxt app |
276
308
  | https://localhost/_api | API (JSON-LD / HAL) |
277
309
  | https://localhost/login | Sign in to the CWA admin |
310
+ | http://localhost:8025 | Mailpit: every email the API sends in dev |
278
311
 
279
- > **SSL:** Caddy issues local certificates from its own CA. Accept the browser warning, or trust the CA once:
280
- > \`docker compose cp php:/data/caddy/pki/authorities/local/root.crt caddy-local-root.crt\`,
281
- > then add \`caddy-local-root.crt\` to your system or browser trust store.
312
+ > **Certificate warning:** Caddy signs the local certificate with its own CA, so the browser warns
313
+ > on the first visit. Accepting the warning is expected for local development.
282
314
 
283
315
  ${fixturesSection}
284
316
  ${ciSection}## Learn more
285
317
 
286
318
  - [CWA documentation](https://cwa.rocks)
287
- - [API Components Bundle](https://github.com/silverbackdan/api-components-bundle)
288
- - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-3-module)
319
+ - [API Components Bundle](https://github.com/components-web-app/api-components-bundle)
320
+ - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-module)
289
321
  `
290
322
 
291
323
  await writeFile(join(tempDir, 'README.md'), readme, 'utf-8')
@@ -301,8 +333,62 @@ async function moveToTarget(tempDir: string, targetDir: string): Promise<void> {
301
333
  await fse.move(tempDir, targetDir, { overwrite: false })
302
334
  }
303
335
 
336
+ // Decides, before anything is downloaded, whether to start the stack and whether to
337
+ // install app/ dependencies on the host. The host install shares app/node_modules with
338
+ // the app container, so it's only offered when the stack isn't started now (#204).
339
+ async function askSetup(): Promise<{ startDocker: boolean; installDeps: boolean }> {
340
+ let startDocker = false
341
+ if (commandExists('docker')) {
342
+ startDocker = checkCancel(
343
+ await confirm({
344
+ message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
345
+ initialValue: true,
346
+ })
347
+ ) as boolean
348
+ } else {
349
+ log.warn('docker not found. Install Docker Desktop, then run `bin/up` in the project.')
350
+ }
351
+
352
+ if (startDocker) {
353
+ const s = spinner()
354
+ s.start('Checking Docker and ports...')
355
+ const result = await preflight()
356
+ s.stop('Docker checked.')
357
+ if (!result.dockerRunning) {
358
+ log.warn('Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).')
359
+ startDocker = false
360
+ } else if (result.takenPorts.length) {
361
+ log.warn(result.takenPorts.join('\n\n'))
362
+ startDocker = false
363
+ }
364
+ if (result.memoryWarning) log.warn(result.memoryWarning)
365
+ if (!startDocker) {
366
+ log.info('The project will be created without starting Docker. Run `bin/up` in it once that is fixed.')
367
+ }
368
+ return { startDocker, installDeps: false }
369
+ }
370
+
371
+ let installDeps = false
372
+ if (commandExists('pnpm')) {
373
+ installDeps = checkCancel(
374
+ await confirm({
375
+ message: withHint(
376
+ 'Install app/ dependencies on this machine?',
377
+ 'only for editor types; the app container installs its own on first start'
378
+ ),
379
+ initialValue: false,
380
+ })
381
+ ) as boolean
382
+ }
383
+ return { startDocker, installDeps }
384
+ }
385
+
304
386
  async function main(): Promise<void> {
305
- intro('create-cwa — Components Web App scaffolder')
387
+ intro(`create-cwa ${CLI_VERSION} — Components Web App scaffolder`)
388
+ log.warn(
389
+ 'CWA is a prerelease: expect breaking changes between versions (see CHANGELOG.md on GitHub).\n' +
390
+ 'create-cwa collects no telemetry; it only downloads the template from GitHub.'
391
+ )
306
392
 
307
393
  const args = parseArgs(process.argv)
308
394
  const s = spinner()
@@ -317,6 +403,7 @@ async function main(): Promise<void> {
317
403
  }
318
404
 
319
405
  const answers = await askQuestions(manifest, args.projectName)
406
+ const setup = await askSetup()
320
407
  const targetDir = resolve(process.cwd(), answers.projectName)
321
408
  const tempDir = join(tmpdir(), `cwa-${randomBytes(6).toString('hex')}`)
322
409
 
@@ -361,75 +448,60 @@ async function main(): Promise<void> {
361
448
  ' • waits for PostgreSQL to be ready',
362
449
  ' • runs database migrations',
363
450
  '',
364
- 'The app container installs the Nuxt dependencies and runs the dev server,',
365
- 'so there is nothing to start by hand.',
366
- answers.fixtures
367
- ? '\nFixtures are NOT loaded automatically — you will be reminded below.'
368
- : '',
451
+ 'The app container installs the Nuxt dependencies into app/node_modules',
452
+ '(which your editor reads too) and runs the dev server.',
453
+ '',
454
+ 'bin/up waits for all that, loads the fixtures (the admin' +
455
+ (answers.fixtures ? ' and sample pages' : '') +
456
+ '),',
457
+ 'pre-compiles the first pages and prints where to sign in. Run it again any time.',
369
458
  ]
370
459
  .join('\n')
371
460
  .trim(),
372
461
  'What Docker handles for you'
373
462
  )
374
463
 
375
- // Offer to start Docker
376
- const hasDocker = commandExists('docker')
377
- if (hasDocker) {
378
- const startDocker = checkCancel(
379
- await confirm({ message: 'Start the Docker stack now? (docker compose up -d)', initialValue: true })
380
- ) as boolean
381
-
382
- if (startDocker) {
383
- log.step('Running: docker compose up -d')
384
- const ok = run('docker', ['compose', 'up', '-d'], targetDir)
385
- if (!ok) {
386
- log.warn('docker compose up -d failed. Run it manually from the project directory.')
387
- }
464
+ if (setup.installDeps) {
465
+ log.step('Running: pnpm install (in app/)')
466
+ if (!run('pnpm', ['install'], join(targetDir, 'app'))) {
467
+ log.warn('pnpm install failed. Run it manually inside app/.')
388
468
  }
389
- } else {
390
- log.warn('docker not found — install Docker Desktop, then run: docker compose up -d')
391
469
  }
392
470
 
393
- // Offer to install Nuxt deps
394
- const hasPnpm = commandExists('pnpm')
395
- if (hasPnpm) {
396
- const installDeps = checkCancel(
397
- await confirm({
398
- message: 'Also install app/ dependencies on this machine, for editor type support? (the app container installs them either way)',
399
- initialValue: false,
400
- })
401
- ) as boolean
402
-
403
- if (installDeps) {
404
- log.step('Running: pnpm install')
405
- const ok = run('pnpm', ['install'], join(targetDir, 'app'))
406
- if (!ok) {
407
- log.warn('pnpm install failed. Run it manually inside app/.')
471
+ // bin/up is POSIX sh; Windows without sh (no WSL or Git Bash) gets the steps instead (#206).
472
+ const hasShell = process.platform !== 'win32' || commandExists('sh')
473
+ let ready = false
474
+ if (setup.startDocker) {
475
+ if (hasShell) {
476
+ log.step('Running: bin/up')
477
+ ready = run('sh', ['bin/up'], targetDir)
478
+ if (!ready) log.warn('bin/up failed (see above). Fix it, then run bin/up again in the project directory.')
479
+ } else {
480
+ log.step('Running: docker compose up -d --wait')
481
+ if (!run('docker', ['compose', 'up', '-d', '--wait'], targetDir)) {
482
+ log.warn('docker compose up -d --wait failed. Run it again in the project directory.')
408
483
  }
409
484
  }
410
- } else {
411
- log.warn('pnpm not found — run: npm i -g pnpm, then pnpm install inside app/')
412
485
  }
413
486
 
414
- const outroLines = [
415
- `The dev server runs in the app container. Follow it with:`,
416
- ` cd ${answers.projectName} && docker compose logs -f app`,
487
+ const outroLines = ready
488
+ ? [`The site is ready: sign in with the login printed above. Next time: cd ${answers.projectName} && bin/up`]
489
+ : hasShell
490
+ ? ['Start the stack, load the fixtures and get the login with:', ` cd ${answers.projectName} && bin/up`]
491
+ : [
492
+ 'Start the stack and create the admin (and any sample pages) with:',
493
+ ` cd ${answers.projectName}`,
494
+ ' docker compose up -d --wait',
495
+ ' docker compose exec php bin/console doctrine:fixtures:load --append',
496
+ 'Then sign in at https://localhost/login as admin / admin (accept the certificate warning).',
497
+ ]
498
+
499
+ outroLines.push(
417
500
  '',
418
- 'Then visit:',
419
- ' https://localhost — app',
420
- ' https://localhost/_api — API',
421
- ' https://localhost/login — sign in to the admin',
422
- ]
423
-
424
- if (answers.fixtures) {
425
- outroLines.push('')
426
- outroLines.push('Load sample content (once the API container is healthy):')
427
- outroLines.push(' docker compose exec php bin/console doctrine:fixtures:load --append')
428
- } else {
429
- outroLines.push('')
430
- outroLines.push('Create the admin from ADMIN_* (once the API container is healthy):')
431
- outroLines.push(' docker compose exec php bin/console doctrine:fixtures:load --append')
432
- }
501
+ 'Follow the dev server with: docker compose logs -f app',
502
+ "Don't run pnpm install on this machine while the stack runs: app/node_modules",
503
+ 'is shared with the dev server. If you do, run: docker compose restart app'
504
+ )
433
505
 
434
506
  outro(outroLines.join('\n'))
435
507
  }
@@ -0,0 +1,125 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { createConnection, createServer } from 'node:net'
3
+
4
+ // Ports the dev stack publishes: compose.yaml (80, 443) and compose.override.yaml (3001, 5432, 8025).
5
+ export const STACK_PORTS: { port: number; service: string; culprits: string; alternative?: string }[] = [
6
+ {
7
+ port: 80,
8
+ service: 'Caddy (php container), HTTP',
9
+ culprits:
10
+ 'another CWA project (`docker compose stop` in its directory), Laravel Valet (`valet stop`), Herd (quit it), nginx or Apache',
11
+ },
12
+ {
13
+ port: 443,
14
+ service: 'Caddy (php container), HTTPS',
15
+ culprits:
16
+ 'another CWA project (`docker compose stop` in its directory), Laravel Valet (`valet stop`), Herd (quit it), nginx or Apache',
17
+ },
18
+ {
19
+ port: 3001,
20
+ service: 'Nuxt dev server (app container)',
21
+ culprits: 'another CWA project (`docker compose stop` in its directory) or a Node dev server',
22
+ alternative: 'Or change `published: 3001` under `app:` in compose.override.yaml to a free port.',
23
+ },
24
+ {
25
+ port: 5432,
26
+ service: 'PostgreSQL (database container)',
27
+ culprits:
28
+ 'another CWA project (`docker compose stop` in its directory) or a local PostgreSQL (Postgres.app, `brew services stop postgresql`)',
29
+ alternative: 'Or change `published: 5432` under `database:` in compose.override.yaml to a free port.',
30
+ },
31
+ {
32
+ port: 8025,
33
+ service: 'Mailpit web UI (mailpit container)',
34
+ culprits: 'another CWA project (`docker compose stop` in its directory) or a local Mailpit or MailHog',
35
+ alternative: 'Or change `published: 8025` under `mailpit:` in compose.override.yaml to a free port.',
36
+ },
37
+ ]
38
+
39
+ // Docker Desktop reports a little less than the VM's allocation, so 4 GiB shows as ~3.8 GiB.
40
+ const MIN_DOCKER_MEMORY = 3.5 * 1024 ** 3
41
+
42
+ function canConnect(port: number): Promise<boolean> {
43
+ return new Promise((resolve) => {
44
+ const socket = createConnection({ host: '127.0.0.1', port })
45
+ const done = (result: boolean) => {
46
+ socket.destroy()
47
+ resolve(result)
48
+ }
49
+ socket.setTimeout(1000, () => done(false))
50
+ socket.once('connect', () => done(true))
51
+ socket.once('error', () => done(false))
52
+ })
53
+ }
54
+
55
+ function addressInUse(port: number): Promise<boolean> {
56
+ return new Promise((resolve) => {
57
+ const server = createServer()
58
+ server.once('error', (err: NodeJS.ErrnoException) => resolve(err.code === 'EADDRINUSE'))
59
+ server.once('listening', () => server.close(() => resolve(false)))
60
+ server.listen(port, '0.0.0.0')
61
+ })
62
+ }
63
+
64
+ function output(cmd: string, args: string[]): string | null {
65
+ const result = spawnSync(cmd, args, { stdio: 'pipe', encoding: 'utf8' })
66
+ return result.status === 0 ? result.stdout.trim() : null
67
+ }
68
+
69
+ // What holds the port: the containers Docker publishes it for, else the process lsof sees.
70
+ function portHolder(port: number): { holder: string; stop?: string } | null {
71
+ const containers = output('docker', [
72
+ 'ps',
73
+ '--filter',
74
+ `publish=${port}`,
75
+ '--format',
76
+ '{{.Names}}\t{{.Label "com.docker.compose.project"}}',
77
+ ])
78
+ if (containers) {
79
+ const rows = containers.split('\n').map((row) => row.split('\t'))
80
+ const names = rows.map(([name]) => name).join(', ')
81
+ const projects = [...new Set(rows.map(([, project]) => project).filter(Boolean))]
82
+ return projects.length
83
+ ? {
84
+ holder: `container ${names} (compose project ${projects.join(', ')})`,
85
+ stop: projects.map((p) => `docker compose -p ${p} stop`).join(' and '),
86
+ }
87
+ : { holder: `container ${names}`, stop: `docker stop ${rows.map(([name]) => name).join(' ')}` }
88
+ }
89
+ if (process.platform === 'win32') return null
90
+ const lsof = output('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fc'])
91
+ const command = lsof?.split('\n').find((l) => l.startsWith('c'))?.slice(1)
92
+ return command ? { holder: `process ${command}` } : null
93
+ }
94
+
95
+ export interface PreflightResult {
96
+ dockerRunning: boolean
97
+ takenPorts: string[]
98
+ memoryWarning: string | null
99
+ }
100
+
101
+ export async function preflight(): Promise<PreflightResult> {
102
+ const memTotal = output('docker', ['info', '--format', '{{.MemTotal}}'])
103
+ if (memTotal === null) {
104
+ return { dockerRunning: false, takenPorts: [], memoryWarning: null }
105
+ }
106
+
107
+ const takenPorts: string[] = []
108
+ for (const { port, service, culprits, alternative } of STACK_PORTS) {
109
+ if ((await canConnect(port)) || (await addressInUse(port))) {
110
+ const found = portHolder(port)
111
+ const lines = [`Port ${port} (${service}) is in use${found ? ` by ${found.holder}` : ''}.`]
112
+ lines.push(found?.stop ? ` Stop it with: ${found.stop}` : ` Free it. Likely: ${culprits}.`)
113
+ if (alternative) lines.push(` ${alternative}`)
114
+ takenPorts.push(lines.join('\n'))
115
+ }
116
+ }
117
+
118
+ const bytes = Number(memTotal)
119
+ const memoryWarning =
120
+ bytes > 0 && bytes < MIN_DOCKER_MEMORY
121
+ ? `Docker has ${(bytes / 1024 ** 3).toFixed(1)} GiB of memory; the stack needs about 4 GiB. Raise it in Docker Desktop → Settings → Resources.`
122
+ : null
123
+
124
+ return { dockerRunning: true, takenPorts, memoryWarning }
125
+ }
package/src/types.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export interface ManifestChoice {
2
2
  value: string
3
3
  label: string
4
+ hint?: string
4
5
  requires?: string[]
5
6
  }
6
7