create-cwa 2.0.0-alpha.5 → 2.0.0-alpha.51

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/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
 
@@ -31,17 +33,132 @@ const CLI_VERSION: string = JSON.parse(
31
33
  readFileSync(new URL('../package.json', import.meta.url), 'utf8')
32
34
  ).version
33
35
 
34
- function parseArgs(argv: string[]): { projectName?: string; ref: string } {
36
+ interface CliOptions {
37
+ projectName?: string
38
+ ref: string
39
+ refGiven: boolean
40
+ yes: boolean
41
+ ci: boolean
42
+ templateDir?: string
43
+ pipeline?: string
44
+ features?: string[]
45
+ fixtures?: boolean
46
+ start?: boolean
47
+ installDeps?: boolean
48
+ help: boolean
49
+ }
50
+
51
+ const USAGE = `Usage: create-cwa [project-name] [options]
52
+
53
+ Without options every question is asked. A flag answers its question, so it isn't asked.
54
+
55
+ Options:
56
+ --ref <tag|branch> template version to download (default v${CLI_VERSION})
57
+ --template-dir <path> copy the template from a local checkout instead of downloading it
58
+ --pipeline <id> CI/CD pipeline: github, gitlab or none
59
+ --features <list> comma-separated features, "all" or "none"
60
+ --fixtures, --no-fixtures include the sample pages, or not
61
+ --start, --no-start run bin/up once the project is created, or not
62
+ --install-deps, --no-install-deps
63
+ pnpm install in app/ on this machine (only when the stack isn't started)
64
+ -y, --yes take the default for every question no flag answers
65
+ --ci never prompt (implies --yes); a missing project name is an error
66
+ -h, --help show this help`
67
+
68
+ class UsageError extends Error {}
69
+
70
+ const VALUE_FLAGS = ['--ref', '--template-dir', '--pipeline', '--features']
71
+
72
+ // Flags for unattended runs (#215); with none given, every question is asked as before.
73
+ function parseArgs(argv: string[]): CliOptions {
35
74
  const args = argv.slice(2)
36
- let ref = `v${CLI_VERSION}`
75
+ const opts: CliOptions = { ref: `v${CLI_VERSION}`, refGiven: false, yes: false, ci: false, help: false }
37
76
  const positional: string[] = []
38
77
  for (let i = 0; i < args.length; i++) {
39
- const arg = args[i]
40
- if (arg === '--ref' && args[i + 1]) ref = args[++i]
41
- else if (arg.startsWith('--ref=')) ref = arg.slice('--ref='.length)
42
- else positional.push(arg)
78
+ let arg = args[i]
79
+ let value: string | undefined
80
+ const eq = arg.indexOf('=')
81
+ if (arg.startsWith('--') && eq > 0) {
82
+ value = arg.slice(eq + 1)
83
+ arg = arg.slice(0, eq)
84
+ if (!VALUE_FLAGS.includes(arg)) throw new UsageError(`${arg} takes no value`)
85
+ } else if (VALUE_FLAGS.includes(arg)) {
86
+ value = args[i + 1]
87
+ if (value === undefined || value.startsWith('-')) throw new UsageError(`${arg} needs a value`)
88
+ i++
89
+ }
90
+ switch (arg) {
91
+ case '--':
92
+ break
93
+ case '--ref':
94
+ opts.ref = value as string
95
+ opts.refGiven = true
96
+ break
97
+ case '--template-dir':
98
+ opts.templateDir = value
99
+ break
100
+ case '--pipeline':
101
+ opts.pipeline = value
102
+ break
103
+ case '--features':
104
+ opts.features = (value as string).split(',').map((f) => f.trim()).filter(Boolean)
105
+ break
106
+ case '--fixtures':
107
+ case '--no-fixtures':
108
+ opts.fixtures = arg === '--fixtures'
109
+ break
110
+ case '--start':
111
+ case '--no-start':
112
+ opts.start = arg === '--start'
113
+ break
114
+ case '--install-deps':
115
+ case '--no-install-deps':
116
+ opts.installDeps = arg === '--install-deps'
117
+ break
118
+ case '-y':
119
+ case '--yes':
120
+ opts.yes = true
121
+ break
122
+ case '--ci':
123
+ opts.ci = true
124
+ opts.yes = true
125
+ break
126
+ case '-h':
127
+ case '--help':
128
+ opts.help = true
129
+ break
130
+ default:
131
+ if (arg.startsWith('-')) throw new UsageError(`Unknown option ${arg}`)
132
+ positional.push(arg)
133
+ }
134
+ }
135
+ if (positional.length > 1) throw new UsageError(`Unexpected argument "${positional[1]}"`)
136
+ if (opts.templateDir && opts.refGiven) throw new UsageError("--ref and --template-dir can't be used together")
137
+ if (opts.start && opts.installDeps) {
138
+ throw new UsageError('--install-deps is only for a stack that isn\'t started: the app container installs its own')
139
+ }
140
+ opts.projectName = positional[0]
141
+ return opts
142
+ }
143
+
144
+ function fail(message: string): never {
145
+ cancel(message)
146
+ process.exit(1)
147
+ }
148
+
149
+ // A spinner when someone is watching, plain log lines under --ci.
150
+ function progress(plain: boolean): { start(msg: string): void; stop(msg: string): void } {
151
+ return plain ? { start: (msg) => log.step(msg), stop: (msg) => log.info(msg) } : spinner()
152
+ }
153
+
154
+ async function readLocalManifest(templateDir: string): Promise<Manifest> {
155
+ const path = join(resolve(templateDir), 'cwa-manifest.json')
156
+ if (!existsSync(path)) throw new Error(`No CWA template in "${templateDir}": ${path} is missing.`)
157
+ try {
158
+ return JSON.parse(await readFile(path, 'utf-8')) as Manifest
159
+ } catch {
160
+ throw new Error(`${path} is not valid JSON.`)
43
161
  }
44
- return { projectName: positional[0], ref }
45
162
  }
46
163
 
47
164
  async function fetchManifest(ref: string): Promise<Manifest> {
@@ -86,39 +203,100 @@ function run(cmd: string, args: string[], cwd: string): boolean {
86
203
  return result.status === 0
87
204
  }
88
205
 
89
- async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Answers> {
90
- const projectName = checkCancel(
91
- await text({
92
- message: 'Project name?',
93
- placeholder: 'my-cwa-app',
94
- initialValue: targetArg ?? '',
95
- validate: (v) => (v.trim() ? undefined : 'Project name is required'),
96
- })
97
- ) as string
98
-
99
- const ci = checkCancel(
100
- await select({
101
- message: 'CI/CD pipeline?',
102
- options: [
103
- { value: 'github', label: 'GitHub Actions' },
104
- { value: 'gitlab', label: 'GitLab CI' },
105
- { value: 'none', label: 'None' },
106
- ],
107
- })
108
- ) as string
206
+ function withHint(message: string, hint?: string): string {
207
+ return hint ? `${message} ${styleText('dim', `(${hint})`)}` : message
208
+ }
209
+
210
+ // The name becomes the directory and the compose project name.
211
+ const PROJECT_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
212
+
213
+ function validateProjectName(value: string | undefined): string | undefined {
214
+ const name = value?.trim() ?? ''
215
+ if (!name) return 'Project name is required'
216
+ if (!PROJECT_NAME.test(name)) {
217
+ return 'Use lower-case letters, digits and single dashes (for example my-cwa-app)'
218
+ }
219
+ const dir = resolve(process.cwd(), name)
220
+ if (existsSync(dir) && (!statSync(dir).isDirectory() || readdirSync(dir).length > 0)) {
221
+ return `"${name}" already exists here and is not an empty directory`
222
+ }
223
+ return undefined
224
+ }
109
225
 
226
+ // Each answer comes from its flag, else the default under --yes (what Enter picks), else a prompt (#215).
227
+ async function askQuestions(manifest: Manifest, opts: CliOptions): Promise<Answers> {
228
+ const question = (id: string): ManifestQuestion | undefined =>
229
+ manifest.questions.find((q) => q.id === id)
230
+
231
+ const nameQuestion = question('projectName')
232
+ let projectName: string
233
+ if (opts.yes && opts.projectName !== undefined) {
234
+ const error = validateProjectName(opts.projectName)
235
+ if (error) fail(`Project name "${opts.projectName}": ${error}`)
236
+ projectName = opts.projectName
237
+ } else if (opts.ci) {
238
+ fail('--ci needs the project name: create-cwa <project-name> --ci')
239
+ } else {
240
+ projectName = checkCancel(
241
+ await text({
242
+ message: withHint(nameQuestion?.message ?? 'Project name?', nameQuestion?.hint),
243
+ placeholder: nameQuestion?.placeholder ?? 'my-cwa-app',
244
+ initialValue: opts.projectName ?? '',
245
+ validate: validateProjectName,
246
+ })
247
+ ) as string
248
+ }
249
+
250
+ const ciQuestion = question('ci')
251
+ const ciOptions = ciQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? [
252
+ { value: 'github', label: 'GitHub Actions' },
253
+ { value: 'gitlab', label: 'GitLab CI' },
254
+ { value: 'none', label: 'None' },
255
+ ]
256
+ let ci: string
257
+ if (opts.pipeline !== undefined) {
258
+ if (!ciOptions.some((c) => c.value === opts.pipeline)) {
259
+ fail(`--pipeline ${opts.pipeline}: choose one of ${ciOptions.map((c) => c.value).join(', ')}`)
260
+ }
261
+ ci = opts.pipeline
262
+ } else if (opts.yes) {
263
+ ci = ciOptions[0].value
264
+ } else {
265
+ ci = checkCancel(
266
+ await select({
267
+ message: withHint(ciQuestion?.message ?? 'CI/CD pipeline?', ciQuestion?.hint),
268
+ options: ciOptions,
269
+ })
270
+ ) as string
271
+ }
272
+
273
+ const featuresQuestion = question('features')
110
274
  const featureChoices =
111
- manifest.questions
112
- .find((q) => q.id === 'features')
113
- ?.choices?.map((c) => ({ value: c.value, label: c.label })) ?? []
114
-
115
- const features = checkCancel(
116
- await multiselect({
117
- message: 'Which features to include? (space to toggle, enter to confirm)',
118
- options: featureChoices,
119
- required: false,
120
- })
121
- ) as string[]
275
+ featuresQuestion?.choices?.map((c) => ({ value: c.value, label: c.label, hint: c.hint })) ?? []
276
+
277
+ let features: string[]
278
+ if (opts.features !== undefined) {
279
+ const all = featureChoices.map((c) => c.value)
280
+ const flag = opts.features
281
+ features = flag.length === 1 && flag[0] === 'all' ? all : flag.length === 1 && flag[0] === 'none' ? [] : flag
282
+ const unknown = features.filter((f) => !all.includes(f))
283
+ if (unknown.length) {
284
+ fail(`--features: unknown ${unknown.join(', ')}. Choose from ${all.join(', ')}, or "all" or "none"`)
285
+ }
286
+ } else if (opts.yes) {
287
+ features = []
288
+ } else {
289
+ features = checkCancel(
290
+ await multiselect({
291
+ message: withHint(
292
+ `${featuresQuestion?.message ?? 'Which features to include?'} (space to toggle, enter to confirm)`,
293
+ featuresQuestion?.hint
294
+ ),
295
+ options: featureChoices,
296
+ required: false,
297
+ })
298
+ ) as string[]
299
+ }
122
300
 
123
301
  // Auto-include required features
124
302
  const resolved = new Set(features)
@@ -135,18 +313,78 @@ async function askQuestions(manifest: Manifest, targetArg?: string): Promise<Ans
135
313
  note(`Also enabling: ${added.join(', ')} (required by selected features)`, 'Dependencies')
136
314
  }
137
315
 
138
- const fixtures = checkCancel(
139
- await confirm({
140
- message: 'Include database fixtures for selected features?',
141
- initialValue: true,
142
- })
143
- ) as boolean
316
+ const fixturesQuestion = question('fixtures')
317
+ const fixtures =
318
+ opts.fixtures ??
319
+ (opts.yes
320
+ ? (fixturesQuestion?.default ?? true)
321
+ : (checkCancel(
322
+ await confirm({
323
+ message: withHint(
324
+ fixturesQuestion?.message ?? 'Include database fixtures for selected features?',
325
+ fixturesQuestion?.hint
326
+ ),
327
+ initialValue: fixturesQuestion?.default ?? true,
328
+ })
329
+ ) as boolean))
144
330
 
145
331
  return { projectName: projectName.trim(), ci, features: [...resolved], fixtures }
146
332
  }
147
333
 
148
- async function downloadRepo(manifest: Manifest, ref: string, tempDir: string): Promise<void> {
149
- const s = spinner()
334
+ // Files a download would contain: what git tracks or would track, minus export-ignore paths (GitHub's tarball honours them).
335
+ function templateFiles(src: string): string[] | null {
336
+ const ls = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
337
+ cwd: src,
338
+ encoding: 'utf8',
339
+ })
340
+ if (ls.status !== 0) return null
341
+ const files = ls.stdout.split('\0').filter((f) => f && existsSync(join(src, f)))
342
+
343
+ const paths = new Set<string>()
344
+ for (const file of files) {
345
+ const parts = file.split('/')
346
+ for (let i = 1; i <= parts.length; i++) paths.add(parts.slice(0, i).join('/'))
347
+ }
348
+ const attr = spawnSync('git', ['check-attr', '-z', '--stdin', 'export-ignore'], {
349
+ cwd: src,
350
+ input: [...paths].join('\0'),
351
+ encoding: 'utf8',
352
+ })
353
+ if (attr.status !== 0) return null
354
+ const out = attr.stdout.split('\0')
355
+ const ignored = new Set<string>()
356
+ for (let i = 0; i + 2 < out.length; i += 3) {
357
+ if (out[i + 2] === 'set') ignored.add(out[i])
358
+ }
359
+ return files.filter((file) => {
360
+ const parts = file.split('/')
361
+ for (let i = 1; i <= parts.length; i++) if (ignored.has(parts.slice(0, i).join('/'))) return false
362
+ return true
363
+ })
364
+ }
365
+
366
+ // --template-dir (#215): a local checkout instead of the download; excludes and stripping still apply after.
367
+ async function copyTemplateDir(templateDir: string, tempDir: string, plain: boolean): Promise<void> {
368
+ const src = resolve(templateDir)
369
+ const s = progress(plain)
370
+ s.start(`Copying template from ${src}...`)
371
+ const files = templateFiles(src)
372
+ if (files) {
373
+ for (const file of files) {
374
+ await fse.copy(join(src, file), join(tempDir, file), { dereference: false })
375
+ }
376
+ } else {
377
+ // Not a git checkout: everything but dependencies and VCS data.
378
+ const skip = new Set(['.git', 'node_modules', 'vendor'])
379
+ await fse.copy(src, tempDir, {
380
+ filter: (path) => !path.slice(src.length).split(/[\\/]/).some((part) => skip.has(part)),
381
+ })
382
+ }
383
+ s.stop('Template copied.')
384
+ }
385
+
386
+ async function downloadRepo(manifest: Manifest, ref: string, tempDir: string, plain: boolean): Promise<void> {
387
+ const s = progress(plain)
150
388
  s.start(`Downloading template (${ref})...`)
151
389
  try {
152
390
  await downloadTemplate(`github:${manifest.repo}#${ref}`, {
@@ -227,16 +465,18 @@ async function generateReadme(tempDir: string, answers: Answers): Promise<void>
227
465
  ? '## CI/CD\n\nGitLab CI is configured in `.gitlab-ci.yml`. See `bin/devops/` for the reusable pipeline scripts.\n'
228
466
  : ''
229
467
 
230
- const fixturesSection = answers.fixtures
231
- ? `## Fixtures
468
+ const fixturesSection = `## Fixtures and the admin account
232
469
 
233
- Sample content is bundled. Load it after the API container is healthy:
470
+ \`bin/up\` loads the fixtures with \`--append\`, which only creates what's missing: the admin
471
+ (\`ADMIN_USERNAME\` / \`ADMIN_PASSWORD\` / \`ADMIN_EMAIL\` in \`api/.env.local\`, default
472
+ \`admin\` / \`admin\` / \`admin@example.com\`)${answers.fixtures ? ' and the sample pages' : ''}. Each load resets the
473
+ admin's password to \`ADMIN_PASSWORD\`; \`bin/up --skip-fixtures\` keeps one changed in the admin.
474
+ To load them by hand:
234
475
 
235
476
  \`\`\`bash
236
477
  docker compose exec php bin/console doctrine:fixtures:load --append
237
478
  \`\`\`
238
479
  `
239
- : ''
240
480
 
241
481
  const readme = `# ${answers.projectName}
242
482
 
@@ -249,34 +489,40 @@ ${featureList}
249
489
  ## Getting started
250
490
 
251
491
  \`\`\`bash
252
- # Start the stack. The php container runs composer install, waits for the
253
- # database and migrates; the app container installs the Nuxt dependencies and
254
- # runs the dev server. There is nothing to start by hand.
255
- docker compose up -d
492
+ # Start the stack, wait until it's healthy, load the fixtures, pre-compile the
493
+ # first pages and print where to sign in. Safe to run again.
494
+ bin/up
256
495
 
257
496
  # Follow the Nuxt dev server
258
497
  docker compose logs -f app
259
498
  \`\`\`
260
499
 
261
- \`app/\` is mounted into the app container, so its \`node_modules\` is shared. Run
262
- \`pnpm install\` in \`app/\` yourself only if your editor needs the types locally.
500
+ \`bin/up\` runs \`docker compose up -d --wait\`: the php container runs composer install,
501
+ waits for the database and migrates; the app container installs the Nuxt dependencies
502
+ and runs the dev server. Without a POSIX shell (Windows without WSL), run
503
+ \`docker compose up -d --wait\` and the fixtures command below instead.
504
+
505
+ \`app/\` is mounted into the app container, so its \`node_modules\` is shared: your
506
+ editor gets the types from the container's install. Don't run \`pnpm install\` on
507
+ this machine while the stack runs (it rewrites \`node_modules\` under the dev
508
+ server); if you do, run \`docker compose restart app\`.
263
509
 
264
510
  | URL | Description |
265
511
  |---|---|
266
512
  | https://localhost | Nuxt app |
267
513
  | https://localhost/_api | API (JSON-LD / HAL) |
268
514
  | https://localhost/login | Sign in to the CWA admin |
515
+ | http://localhost:8025 | Mailpit: every email the API sends in dev |
269
516
 
270
- > **SSL:** Caddy issues local certificates from its own CA. Accept the browser warning, or trust the CA once:
271
- > \`docker compose cp php:/data/caddy/pki/authorities/local/root.crt caddy-local-root.crt\`,
272
- > then add \`caddy-local-root.crt\` to your system or browser trust store.
517
+ > **Certificate warning:** Caddy signs the local certificate with its own CA, so the browser warns
518
+ > on the first visit. Accepting the warning is expected for local development.
273
519
 
274
520
  ${fixturesSection}
275
521
  ${ciSection}## Learn more
276
522
 
277
523
  - [CWA documentation](https://cwa.rocks)
278
- - [API Components Bundle](https://github.com/silverbackdan/api-components-bundle)
279
- - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-3-module)
524
+ - [API Components Bundle](https://github.com/components-web-app/api-components-bundle)
525
+ - [\`@cwa/nuxt\` module](https://github.com/components-web-app/cwa-nuxt-module)
280
526
  `
281
527
 
282
528
  await writeFile(join(tempDir, 'README.md'), readme, 'utf-8')
@@ -292,28 +538,106 @@ async function moveToTarget(tempDir: string, targetDir: string): Promise<void> {
292
538
  await fse.move(tempDir, targetDir, { overwrite: false })
293
539
  }
294
540
 
541
+ // Decides, before anything is downloaded, whether to start the stack and whether to
542
+ // install app/ dependencies on the host. The host install shares app/node_modules with
543
+ // the app container, so it's only offered when the stack isn't started now (#204).
544
+ // --start fails when the stack can't be started; without it (prompted or --yes) the project is created anyway (#215).
545
+ async function askSetup(opts: CliOptions): Promise<{ startDocker: boolean; installDeps: boolean }> {
546
+ let startDocker = false
547
+ if (commandExists('docker')) {
548
+ startDocker =
549
+ opts.start ??
550
+ (opts.yes ||
551
+ (checkCancel(
552
+ await confirm({
553
+ message: withHint('Start the Docker stack when the project is ready?', 'bin/up: starts it, loads fixtures, prints the login'),
554
+ initialValue: true,
555
+ })
556
+ ) as boolean))
557
+ } else if (opts.start) {
558
+ fail('--start: docker not found. Install Docker Desktop (or Docker Engine with the compose plugin).')
559
+ } else {
560
+ log.warn('docker not found. Install Docker Desktop, then run `bin/up` in the project.')
561
+ }
562
+
563
+ if (startDocker) {
564
+ const s = progress(opts.ci)
565
+ s.start('Checking Docker and ports...')
566
+ const result = await preflight()
567
+ s.stop('Docker checked.')
568
+ const problem = !result.dockerRunning
569
+ ? 'Docker is installed but `docker info` failed: start Docker Desktop (or the Docker daemon).'
570
+ : result.takenPorts.join('\n\n')
571
+ if (result.memoryWarning) log.warn(result.memoryWarning)
572
+ if (problem) {
573
+ if (opts.start) fail(`--start: ${problem}`)
574
+ log.warn(problem)
575
+ log.info('The project will be created without starting Docker. Run `bin/up` in it once that is fixed.')
576
+ startDocker = false
577
+ }
578
+ return { startDocker, installDeps: false }
579
+ }
580
+
581
+ let installDeps = false
582
+ if (commandExists('pnpm')) {
583
+ installDeps =
584
+ opts.installDeps ??
585
+ (!opts.yes &&
586
+ (checkCancel(
587
+ await confirm({
588
+ message: withHint(
589
+ 'Install app/ dependencies on this machine?',
590
+ 'only for editor types; the app container installs its own on first start'
591
+ ),
592
+ initialValue: false,
593
+ })
594
+ ) as boolean))
595
+ } else if (opts.installDeps) {
596
+ fail('--install-deps: pnpm not found.')
597
+ }
598
+ return { startDocker, installDeps }
599
+ }
600
+
295
601
  async function main(): Promise<void> {
296
- intro('create-cwa — Components Web App scaffolder')
602
+ let args: CliOptions
603
+ try {
604
+ args = parseArgs(process.argv)
605
+ } catch (err) {
606
+ if (!(err instanceof UsageError)) throw err
607
+ console.error(`create-cwa: ${err.message}\n\n${USAGE}`)
608
+ process.exit(2)
609
+ }
610
+ if (args.help) {
611
+ console.log(USAGE)
612
+ return
613
+ }
297
614
 
298
- const args = parseArgs(process.argv)
299
- const s = spinner()
300
- s.start('Fetching manifest...')
615
+ intro(`create-cwa ${CLI_VERSION} — Components Web App scaffolder`)
616
+ log.warn(
617
+ 'CWA is a prerelease: expect breaking changes between versions (see CHANGELOG.md on GitHub).\n' +
618
+ 'create-cwa collects no telemetry; it only downloads the template from GitHub.'
619
+ )
620
+
621
+ const s = progress(args.ci)
622
+ s.start(args.templateDir ? `Reading the manifest in ${args.templateDir}...` : 'Fetching manifest...')
301
623
  let manifest: Manifest
302
624
  try {
303
- manifest = await fetchManifest(args.ref)
625
+ manifest = args.templateDir ? await readLocalManifest(args.templateDir) : await fetchManifest(args.ref)
304
626
  s.stop('Manifest loaded.')
305
627
  } catch (err) {
306
628
  s.stop((err as Error).message)
307
629
  process.exit(1)
308
630
  }
309
631
 
310
- const answers = await askQuestions(manifest, args.projectName)
632
+ const answers = await askQuestions(manifest, args)
633
+ const setup = await askSetup(args)
311
634
  const targetDir = resolve(process.cwd(), answers.projectName)
312
635
  const tempDir = join(tmpdir(), `cwa-${randomBytes(6).toString('hex')}`)
313
636
 
314
- await downloadRepo(manifest, args.ref, tempDir)
637
+ if (args.templateDir) await copyTemplateDir(args.templateDir, tempDir, args.ci)
638
+ else await downloadRepo(manifest, args.ref, tempDir, args.ci)
315
639
 
316
- const s2 = spinner()
640
+ const s2 = progress(args.ci)
317
641
  s2.start('Configuring project...')
318
642
 
319
643
  try {
@@ -329,7 +653,8 @@ async function main(): Promise<void> {
329
653
  }
330
654
 
331
655
  if (!answers.fixtures) {
332
- await removeExcluded(tempDir, ['api/src/DataFixtures/Parts/'])
656
+ // Sample content only: UsersFixture stays, so the admin is still created from ADMIN_* (#142).
657
+ await removeExcluded(tempDir, ['api/src/DataFixtures/AppScaffold.php', 'api/src/DataFixtures/Parts/'])
333
658
  }
334
659
 
335
660
  await processNuxtConfig(tempDir, answers.features)
@@ -351,71 +676,64 @@ async function main(): Promise<void> {
351
676
  ' • waits for PostgreSQL to be ready',
352
677
  ' • runs database migrations',
353
678
  '',
354
- 'The app container installs the Nuxt dependencies and runs the dev server,',
355
- 'so there is nothing to start by hand.',
356
- answers.fixtures
357
- ? '\nFixtures are NOT loaded automatically — you will be reminded below.'
358
- : '',
679
+ 'The app container installs the Nuxt dependencies into app/node_modules',
680
+ '(which your editor reads too) and runs the dev server.',
681
+ '',
682
+ 'bin/up waits for all that, loads the fixtures (the admin' +
683
+ (answers.fixtures ? ' and sample pages' : '') +
684
+ '),',
685
+ 'pre-compiles the first pages and prints where to sign in. Run it again any time.',
359
686
  ]
360
687
  .join('\n')
361
688
  .trim(),
362
689
  'What Docker handles for you'
363
690
  )
364
691
 
365
- // Offer to start Docker
366
- const hasDocker = commandExists('docker')
367
- if (hasDocker) {
368
- const startDocker = checkCancel(
369
- await confirm({ message: 'Start the Docker stack now? (docker compose up -d)', initialValue: true })
370
- ) as boolean
371
-
372
- if (startDocker) {
373
- log.step('Running: docker compose up -d')
374
- const ok = run('docker', ['compose', 'up', '-d'], targetDir)
375
- if (!ok) {
376
- log.warn('docker compose up -d failed. Run it manually from the project directory.')
377
- }
692
+ if (setup.installDeps) {
693
+ log.step('Running: pnpm install (in app/)')
694
+ if (!run('pnpm', ['install'], join(targetDir, 'app'))) {
695
+ log.warn('pnpm install failed. Run it manually inside app/.')
696
+ if (args.ci) process.exitCode = 1
378
697
  }
379
- } else {
380
- log.warn('docker not found — install Docker Desktop, then run: docker compose up -d')
381
698
  }
382
699
 
383
- // Offer to install Nuxt deps
384
- const hasPnpm = commandExists('pnpm')
385
- if (hasPnpm) {
386
- const installDeps = checkCancel(
387
- await confirm({
388
- message: 'Also install app/ dependencies on this machine, for editor type support? (the app container installs them either way)',
389
- initialValue: false,
390
- })
391
- ) as boolean
392
-
393
- if (installDeps) {
394
- log.step('Running: pnpm install')
395
- const ok = run('pnpm', ['install'], join(targetDir, 'app'))
396
- if (!ok) {
397
- log.warn('pnpm install failed. Run it manually inside app/.')
700
+ // bin/up is POSIX sh; Windows without sh (no WSL or Git Bash) gets the steps instead (#206).
701
+ const hasShell = process.platform !== 'win32' || commandExists('sh')
702
+ let ready = false
703
+ if (setup.startDocker) {
704
+ if (hasShell) {
705
+ log.step('Running: bin/up')
706
+ ready = run('sh', ['bin/up'], targetDir)
707
+ if (!ready) log.warn('bin/up failed (see above). Fix it, then run bin/up again in the project directory.')
708
+ // Under --ci a failed start fails the run (#215).
709
+ if (!ready && args.ci) process.exitCode = 1
710
+ } else {
711
+ log.step('Running: docker compose up -d --wait')
712
+ if (!run('docker', ['compose', 'up', '-d', '--wait'], targetDir)) {
713
+ log.warn('docker compose up -d --wait failed. Run it again in the project directory.')
714
+ if (args.ci) process.exitCode = 1
398
715
  }
399
716
  }
400
- } else {
401
- log.warn('pnpm not found — run: npm i -g pnpm, then pnpm install inside app/')
402
717
  }
403
718
 
404
- const outroLines = [
405
- `The dev server runs in the app container. Follow it with:`,
406
- ` cd ${answers.projectName} && docker compose logs -f app`,
719
+ const outroLines = ready
720
+ ? [`The site is ready: sign in with the login printed above. Next time: cd ${answers.projectName} && bin/up`]
721
+ : hasShell
722
+ ? ['Start the stack, load the fixtures and get the login with:', ` cd ${answers.projectName} && bin/up`]
723
+ : [
724
+ 'Start the stack and create the admin (and any sample pages) with:',
725
+ ` cd ${answers.projectName}`,
726
+ ' docker compose up -d --wait',
727
+ ' docker compose exec php bin/console doctrine:fixtures:load --append',
728
+ 'Then sign in at https://localhost/login as admin / admin (accept the certificate warning).',
729
+ ]
730
+
731
+ outroLines.push(
407
732
  '',
408
- 'Then visit:',
409
- ' https://localhost — app',
410
- ' https://localhost/_api — API',
411
- ' https://localhost/login — sign in to the admin',
412
- ]
413
-
414
- if (answers.fixtures) {
415
- outroLines.push('')
416
- outroLines.push('Load sample content (once the API container is healthy):')
417
- outroLines.push(' docker compose exec php bin/console doctrine:fixtures:load --append')
418
- }
733
+ 'Follow the dev server with: docker compose logs -f app',
734
+ "Don't run pnpm install on this machine while the stack runs: app/node_modules",
735
+ 'is shared with the dev server. If you do, run: docker compose restart app'
736
+ )
419
737
 
420
738
  outro(outroLines.join('\n'))
421
739
  }