@open-mercato/starter 0.10.1-develop.7983.1.fd91207efe → 0.10.1-develop.7994.1.c9f31972aa

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ // Compact setup output, using the same keyboard and compact log hints as dev.
2
+ // Keep this build-free: setup runs before the workspace dependencies exist.
3
+ import { StringDecoder } from 'node:string_decoder'
4
+ import { format } from 'node:util'
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ const MAX_LINES = 200
9
+ const MAX_LINE_LENGTH = 4096
10
+
11
+ export function createSetupLogs({
12
+ input = process.stdin,
13
+ output = process.stdout,
14
+ env = process.env,
15
+ verbose = false,
16
+ nonInteractive = false,
17
+ repoRoot = null,
18
+ name = 'setup',
19
+ onInterrupt = () => process.kill(process.pid, 'SIGINT'),
20
+ } = {}) {
21
+ const interactive = Boolean(input.isTTY && output.isTTY
22
+ && env.CI !== 'true' && env.TERM !== 'dumb' && env.MERCATO_DEV_OUTPUT !== 'verbose'
23
+ && !verbose && !nonInteractive)
24
+ const colored = interactive && !env.NO_COLOR
25
+ let active = false
26
+ let started = false
27
+ let fileInitialized = false
28
+ let logFile = null
29
+ let fileFailed = false
30
+ let activity = null
31
+ let visible = !interactive
32
+ let previousRaw = false
33
+ let previousFlowing = false
34
+ let lines = []
35
+ let partial = ''
36
+ let visiblePartial = false
37
+ let rawLineStart = true
38
+ const decoder = new StringDecoder('utf8')
39
+
40
+ const write = (value) => output.write(value)
41
+ const tint = (code, value) => colored ? `\u001b[${code}m${value}\u001b[0m` : value
42
+
43
+
44
+ function writeRaw(text) {
45
+ let formatted = ''
46
+ for (const part of text.split(/(\r\n|\r|\n)/)) {
47
+ if (part === '\n' || part === '\r' || part === '\r\n') { formatted += part; rawLineStart = true }
48
+ else if (part) { formatted += (rawLineStart ? ' ' : '') + part; rawLineStart = false }
49
+ }
50
+ write(formatted)
51
+ }
52
+
53
+ function reportFileFailure() {
54
+ if (fileFailed) return
55
+ fileFailed = true
56
+ activity?.pause()
57
+ write(' ⚠️ Could not save setup logs; terminal output is still available.\n')
58
+ if (active && !visible) activity?.resume()
59
+ }
60
+
61
+ function initializeFile() {
62
+ if (fileInitialized) return
63
+ fileInitialized = true
64
+ if (!repoRoot || ['0', 'false'].includes(env.OM_DEV_LOG_TEE)) return
65
+ try {
66
+ const directory = env.OM_DEV_LOG_DIR?.trim()
67
+ ? path.resolve(repoRoot, env.OM_DEV_LOG_DIR.trim())
68
+ : path.join(repoRoot, '.mercato', 'logs')
69
+ const defaultId = `${new Date().toISOString().toLowerCase().replace(/[:.]/g, '-')}-pid${process.pid}`
70
+ // Run IDs are filenames, never paths, including when supplied by a shell.
71
+ const safe = (value) => String(value).replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 160)
72
+ const runId = safe(env.OM_DEV_RUN_ID?.trim() || defaultId)
73
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
74
+ const target = path.join(directory, `${runId}-${safe(name)}-raw.log`)
75
+ fs.appendFileSync(target, '', { mode: 0o600 })
76
+ logFile = target
77
+ } catch {
78
+ reportFileFailure()
79
+ }
80
+ }
81
+
82
+ function show(reason = 'Raw logs shown') {
83
+ if (!interactive || visible) return
84
+ activity?.pause()
85
+ visible = true
86
+ write(` 📖 ${reason} · press [d] to hide\n`)
87
+ rawLineStart = true
88
+ if (lines.length === 0 && !partial) {
89
+ write(' 📭 No buffered logs yet\n')
90
+ return
91
+ }
92
+ if (lines.length > 0) writeRaw(`${lines.join('\n')}\n`)
93
+ if (partial) writeRaw(partial)
94
+ visiblePartial = partial.length > 0
95
+ // Displayed output remains in terminal scrollback and in the full log
96
+ // file. Replay only new output collected while the panel was hidden.
97
+ lines = []
98
+ partial = ''
99
+ }
100
+
101
+ function onData(chunk) {
102
+ for (const key of String(chunk)) {
103
+ if (key === '\u0003') {
104
+ suspend()
105
+ onInterrupt()
106
+ return
107
+ }
108
+ if (key.toLowerCase() !== 'd') continue
109
+ if (visible) {
110
+ visible = false
111
+ if (visiblePartial) write('\n')
112
+ visiblePartial = false
113
+ rawLineStart = true
114
+ activity?.resume()
115
+ } else show()
116
+ }
117
+ }
118
+
119
+ function resume() {
120
+ if (!interactive || active) return
121
+ previousRaw = Boolean(input.isRaw)
122
+ previousFlowing = input.readableFlowing === true
123
+ input.setRawMode?.(true)
124
+ input.on('data', onData)
125
+ input.resume()
126
+ active = true
127
+ }
128
+
129
+ function suspend() {
130
+ activity?.pause()
131
+ if (!active) return
132
+ input.removeListener('data', onData)
133
+ input.setRawMode?.(previousRaw)
134
+ if (!previousFlowing) input.pause()
135
+ active = false
136
+ }
137
+
138
+ function persist(chunk) {
139
+ initializeFile()
140
+ if (logFile && !fileFailed) {
141
+ try {
142
+ // Synchronous appends avoid losing the last output when setup hands
143
+ // over to dev or a failing command exits immediately.
144
+ fs.appendFileSync(logFile, chunk)
145
+ } catch {
146
+ reportFileFailure()
147
+ }
148
+ }
149
+ }
150
+
151
+ function raw(chunk, displayChunk = chunk) {
152
+ persist(chunk)
153
+ if (!interactive) {
154
+ write(chunk)
155
+ return
156
+ }
157
+ const text = typeof displayChunk === 'string' ? displayChunk : decoder.write(displayChunk)
158
+ if (visible) {
159
+ if (text) { writeRaw(text); visiblePartial = !text.endsWith('\n') }
160
+ return
161
+ }
162
+ // Bound both completed lines and partial progress output. A process can
163
+ // emit megabytes without a newline; it must not grow the buffer forever.
164
+ const entries = `${partial}${text}`.split('\n')
165
+ partial = entries.pop().slice(-MAX_LINE_LENGTH)
166
+ if (entries.length > 0) {
167
+ lines = lines.concat(entries.slice(-MAX_LINES).map((line) => line.slice(-MAX_LINE_LENGTH))).slice(-MAX_LINES)
168
+ }
169
+ }
170
+
171
+ return {
172
+ interactive,
173
+ setActivity(next) {
174
+ activity?.stop()
175
+ activity = next
176
+ if (visible) activity?.pause()
177
+ else activity?.resume()
178
+ },
179
+ resumeActivity() { if (!visible && active) activity?.resume() },
180
+ get logFile() { return logFile },
181
+ start() {
182
+ if (started) return
183
+ started = true
184
+ initializeFile()
185
+ if (logFile && !fileFailed) write(` 📝 Verbose logs ${logFile}\n`)
186
+ if (interactive) write(`${tint('2', ' 📋 Press [d] to show or hide raw logs')}\n`)
187
+ process.once('exit', suspend)
188
+ resume()
189
+ },
190
+ stop() { activity?.stop(); activity = null; suspend(); process.removeListener('exit', suspend); started = false },
191
+ suspend,
192
+ resume,
193
+ raw,
194
+ show,
195
+ log(...args) {
196
+ const text = format(...args)
197
+ raw(`${text}\n`, `${text.replace(/^ {1,3}/gm, '')}\n`)
198
+ },
199
+ record(...args) { persist(`${format(...args)}\n`) },
200
+ }
201
+ }
package/src/steps.mjs CHANGED
@@ -3,7 +3,7 @@ import crypto from 'node:crypto'
3
3
  import fs from 'node:fs'
4
4
  import path from 'node:path'
5
5
 
6
- import { detectDocker, parseComposePsOutput, runCaptureSync, runCompose, runStreamingSync } from './compose.mjs'
6
+ import { detectDocker, parseComposePsOutput, runCaptureSync, runCompose, runStreaming } from './compose.mjs'
7
7
  import { captureInterceptionCas, findVendorCaBundles, harvestWindowsStoreCas, hostTrustEnv, probeTlsInterception, provisionDockerCerts, provisionRancherDesktopCa, summarizeProbeResults, writeCaBundle } from './certs.mjs'
8
8
  import { loadCompanyConfig, resolveCompanyCertBundles } from './company.mjs'
9
9
  import { CAPTURED_CA_BUNDLE, DEFAULT_OPENCODE_BASE_IMAGE, OPENCODE_SERVICE_IMAGE, STARTER_STATE_DIR, resolveStackPorts } from './constants.mjs'
@@ -11,9 +11,11 @@ import { checkBuildToolchain, checkContainerRuntime, checkGit, checkNodeVersion,
11
11
  import { ensureEnvFiles } from './env-setup.mjs'
12
12
  import { addEnvValue, readEnvValue } from './env-file.mjs'
13
13
  import { describeInfraProblem, startInfra } from './infra.mjs'
14
- import { findUnhealthyServices } from './infra-preflight.mjs'
14
+ import { WITHOUT_DOCKER_GUIDE_URL, findUnhealthyServices, requestExistingServicesConsent } from './infra-preflight.mjs'
15
15
  import { ensureLlmProvider } from './providers.mjs'
16
- import { color, formatDuration, guideBox, statusLine, stepHeader } from './ui.mjs'
16
+ import { verifyServiceConnections } from './service-connections.mjs'
17
+ import { createSetupLogs } from './setup-logs.mjs'
18
+ import { color, createSpinner, formatDuration, guideBox, statusLine, stepHeader } from './ui.mjs'
17
19
 
18
20
  // The idempotent convergence pipeline behind `up`. Every step follows the same
19
21
  // contract so re-running is always safe and always cheap when nothing changed:
@@ -251,9 +253,9 @@ export function yarnInvocation(ctx, args) {
251
253
  : { command: 'yarn', args }
252
254
  }
253
255
 
254
- function runYarn(ctx, args) {
256
+ async function runYarn(ctx, args) {
255
257
  const invocation = yarnInvocation(ctx, args)
256
- const status = (ctx.runStreamingImpl ?? runStreamingSync)(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env })
258
+ const status = await (ctx.runStreamingImpl ?? runStreaming)(invocation.command, invocation.args, { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
257
259
  if (status !== 0) {
258
260
  throw new Error(`yarn ${args.join(' ')} failed (exit ${status}) — fix the error above and re-run; completed steps are skipped.`)
259
261
  }
@@ -281,9 +283,9 @@ export const prerequisitesStep = {
281
283
  // Node exists (we are running on it), so yarn is ours to install: enable
282
284
  // corepack and activate the exact version pinned in package.json.
283
285
  const spec = JSON.parse(fs.readFileSync(path.join(ctx.repoRoot, 'package.json'), 'utf8')).packageManager.split('+')[0]
284
- const enable = runStreamingSync('corepack', ['enable'], { cwd: ctx.repoRoot, env: ctx.env })
286
+ const enable = await runStreaming('corepack', ['enable'], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
285
287
  if (enable !== 0) ctx.log('⚠️ corepack enable failed (PATH not writable?) — falling back to running yarn through corepack.')
286
- const prepare = runStreamingSync('corepack', ['prepare', spec, '--activate'], { cwd: ctx.repoRoot, env: ctx.env })
288
+ const prepare = await runStreaming('corepack', ['prepare', spec, '--activate'], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
287
289
  if (prepare !== 0) {
288
290
  throw new Error(`corepack prepare ${spec} failed. Behind a corporate proxy? Set HTTPS_PROXY and re-run — the starter provisions the corporate CA automatically in the next step; if this step itself is blocked, set COREPACK_NPM_REGISTRY to your internal mirror (see starters/company/).`)
289
291
  }
@@ -316,7 +318,12 @@ export const containerRuntimeStep = {
316
318
  if (wsl && wsl.level !== 'pass') guide.push(`WSL2 first: ${wsl.detail}`, ...wsl.guide, '')
317
319
  guide.push(...runtime.guide)
318
320
  guide.push('', 'Re-run this starter once the runtime is up — every completed step is skipped.')
319
- if (ctx.mode === 'hybrid') guide.push('No container runtime at all? `yarn setup --no-infra` (or `yarn om up --no-infra`) starts just the app against services you point .env at, without any Docker call.')
321
+ if (ctx.mode === 'hybrid') {
322
+ guide.push(
323
+ `No container runtime at all? Run PostgreSQL yourself (Redis and Meilisearch are optional): ${WITHOUT_DOCKER_GUIDE_URL}`,
324
+ 'Point apps/mercato/.env at it, then run `node packages/starter/bin/om-start.mjs up --no-infra` (or `yarn om up --no-infra` once dependencies are installed); it makes no Docker call.',
325
+ )
326
+ }
320
327
  throw new StepBlocked(this.id, guide)
321
328
  },
322
329
  }
@@ -419,7 +426,7 @@ export const envFilesStep = {
419
426
  return { ok: false, detail: 'converging (never overwrites existing values)' }
420
427
  },
421
428
  async apply(ctx) {
422
- ensureEnvFiles(ctx.repoRoot, { log: (line) => ctx.log(` ${line}`), warn: (line) => ctx.log(` ⚠️ ${line}`), extraDefaults: ctx.company.env })
429
+ ensureEnvFiles(ctx.repoRoot, { log: (line) => ctx.log(` ${String(line).trimStart()}`), warn: (line) => ctx.log(` ⚠️ ${line}`), extraDefaults: ctx.company.env })
423
430
  },
424
431
  }
425
432
 
@@ -438,7 +445,7 @@ export const workspaceInstallStep = {
438
445
  if (ctx.company.mirrors.npmRegistry) {
439
446
  ctx.env = { ...ctx.env, COREPACK_NPM_REGISTRY: ctx.company.mirrors.npmRegistry, YARN_NPM_REGISTRY_SERVER: ctx.company.mirrors.npmRegistry }
440
447
  }
441
- runYarn(ctx, ['install'])
448
+ await runYarn(ctx, ['install'])
442
449
  writeState(ctx.repoRoot, 'install.hash', ctx.installHash)
443
450
  ctx.installChanged = true
444
451
  },
@@ -466,29 +473,27 @@ export const workspaceBuildStep = {
466
473
  // Mirrors the root `yarn build`: core only compiles `generated/**` into
467
474
  // dist/generated when it exists, which on a fresh clone is after `generate`.
468
475
  const run = ctx.runYarnImpl ?? runYarn
469
- run(ctx, ['build:packages'])
470
- run(ctx, ['generate'])
471
- run(ctx, ['build:packages'])
476
+ await run(ctx, ['build:packages'])
477
+ await run(ctx, ['generate'])
478
+ await run(ctx, ['build:packages'])
472
479
  },
473
480
  }
474
481
 
475
482
  export const llmProviderStep = {
476
483
  id: 'llm-provider',
477
- expectation: 'waits for your input on first run; have an API key ready',
478
- title: 'AI provider (LLM API key)',
484
+ interactive: true,
485
+ expectation: 'optional; press Enter to configure AI later',
486
+ title: 'AI provider (optional)',
479
487
  async apply(ctx) {
480
- const outcome = await ensureLlmProvider({
488
+ await ensureLlmProvider({
481
489
  rootEnv: path.join(ctx.repoRoot, '.env'),
482
490
  appEnv: path.join(ctx.repoRoot, 'apps', 'mercato', '.env'),
483
491
  }, {
484
492
  skipPrompt: ctx.flags.skipLlmPrompt,
485
493
  nonInteractive: ctx.flags.nonInteractive,
486
- log: (line) => ctx.log(` ${line}`),
487
- warn: (line) => ctx.log(` ⚠️ ${line}`),
494
+ log: (line) => ctx.log(` ${String(line).trimStart()}`),
495
+ warn: (line) => ctx.log(` ⚠️ ${line}`),
488
496
  })
489
- if (outcome === 'failed') {
490
- throw new Error('No LLM provider configured. Pass --skip-llm-prompt to continue without AI, or set a provider key in .env.')
491
- }
492
497
  },
493
498
  async check() {
494
499
  return { ok: false, detail: 'checking configured provider' }
@@ -508,15 +513,15 @@ export function resolveOpencodeBaseImage(repoRoot, env = process.env) {
508
513
  // Desktop) and therefore survives corporate TLS interception that breaks
509
514
  // build-stage egress; the thin build itself only COPYs project files.
510
515
  // --rebuild forces the thin rebuild (e.g. after yarn generate in prod mode).
511
- export function ensureOpencodeImage(ctx) {
516
+ export async function ensureOpencodeImage(ctx) {
512
517
  const baseImage = resolveOpencodeBaseImage(ctx.repoRoot, ctx.env)
513
518
  const baseExists = spawnSync('docker', ['image', 'inspect', baseImage], { stdio: 'ignore' }).status === 0
514
519
  if (baseExists) {
515
520
  ctx.log(` opencode base image: ${baseImage} (already present)`)
516
521
  } else {
517
522
  ctx.log(` pulling OpenCode base image ${baseImage} ...`)
518
- const pull = spawnSync('docker', ['pull', baseImage], { stdio: 'inherit' })
519
- if (pull.status !== 0) {
523
+ const pull = await (ctx.runStreamingImpl ?? runStreaming)('docker', ['pull', baseImage], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
524
+ if (pull !== 0) {
520
525
  throw new Error(`Could not pull the OpenCode base image ${baseImage}. Behind a proxy that blocks registry-1.docker.io? Set OPENCODE_BASE_IMAGE in .env to your internal mirror (build/push runbook: docker/opencode/BASE_IMAGE.md), then re-run.`)
521
526
  }
522
527
  }
@@ -526,13 +531,13 @@ export function ensureOpencodeImage(ctx) {
526
531
  return
527
532
  }
528
533
  ctx.log(` building ${OPENCODE_SERVICE_IMAGE} from ${baseImage} (project files only — no network) ...`)
529
- const build = spawnSync('docker', [
534
+ const build = await (ctx.runStreamingImpl ?? runStreaming)('docker', [
530
535
  'build',
531
536
  '-t', OPENCODE_SERVICE_IMAGE,
532
537
  '--build-arg', `OPENCODE_BASE_IMAGE=${baseImage}`,
533
538
  path.join(ctx.repoRoot, 'docker', 'opencode'),
534
- ], { stdio: 'inherit', cwd: ctx.repoRoot })
535
- if (build.status !== 0) {
539
+ ], { cwd: ctx.repoRoot, env: ctx.env, logs: ctx.logs })
540
+ if (build !== 0) {
536
541
  throw new Error('Local build of the OpenCode service image failed — see the output above, then re-run.')
537
542
  }
538
543
  }
@@ -561,10 +566,28 @@ export const infraUpStep = {
561
566
  const prepareOpencodeImage = ctx.ensureOpencodeImageImpl ?? ensureOpencodeImage
562
567
  const outcome = await (ctx.startInfraImpl ?? startInfra)(ctx.repoRoot, {
563
568
  profiles: ctx.flags.profiles,
569
+ env: ctx.env,
570
+ logs: ctx.logs,
564
571
  log: ctx.log,
565
572
  beforeUp: () => prepareOpencodeImage(ctx),
573
+ protectExistingServices: true,
566
574
  })
567
575
  if (!outcome.ok) {
576
+ if (outcome.problem.code === 'port-conflict' || (outcome.problem.code === 'unhealthy' && outcome.problem.existingServices)) {
577
+ let accepted
578
+ ctx.logs?.suspend()
579
+ try {
580
+ accepted = await (ctx.confirmExistingServicesImpl ?? requestExistingServicesConsent)(outcome.problem, { nonInteractive: ctx.flags.nonInteractive, log: ctx.promptLog ?? ctx.log })
581
+ } finally {
582
+ ctx.logs?.resume()
583
+ ctx.logs?.resumeActivity?.()
584
+ }
585
+ if (accepted) {
586
+ ctx.flags.noInfra = true
587
+ ctx.existingInfraAccepted = true
588
+ return
589
+ }
590
+ }
568
591
  const lines = describeInfraProblem(outcome.problem)
569
592
  if (ctx.tlsProbes?.some((entry) => entry.status === 'intercepted')) {
570
593
  lines.push(' TLS/certificate errors from the engine usually mean it does not trust the corporate CA yet: restart Docker Desktop (it re-imports the Windows certificate store) or Rancher Desktop (the starter wrote a provisioning script for it), then re-run.')
@@ -575,6 +598,20 @@ export const infraUpStep = {
575
598
  },
576
599
  }
577
600
 
601
+ export const serviceConnectionsStep = {
602
+ id: 'service-connections',
603
+ title: 'Service credentials and connections',
604
+ appliesTo: (ctx) => ctx.mode === 'hybrid',
605
+ async apply(ctx) {
606
+ await (ctx.verifyServiceConnectionsImpl ?? verifyServiceConnections)({
607
+ projectDir: path.join(ctx.repoRoot, 'apps', 'mercato'),
608
+ envFiles: [path.join(ctx.repoRoot, '.env')],
609
+ env: ctx.env,
610
+ log: ctx.log,
611
+ })
612
+ },
613
+ }
614
+
578
615
  export const databaseStep = {
579
616
  id: 'database',
580
617
  expectation: 'migrations + seed take a minute or two on first run',
@@ -633,7 +670,7 @@ export const databaseStep = {
633
670
  'or start over with a fresh database (DELETES all local data): yarn om reset',
634
671
  ].join('\n'))
635
672
  }
636
- runYarn(ctx, ['db:migrate'])
673
+ await runYarn(ctx, ['db:migrate'])
637
674
  writeState(ctx.repoRoot, ctx.dbMigrationsMarker, ctx.migrationsFingerprint)
638
675
  const applied = readAppliedMigrationModules(ctx)
639
676
  if (applied && applied.size > 0) {
@@ -652,7 +689,15 @@ export const databaseStep = {
652
689
  // to run the destructive --reinstall. An emptied volume (dbReinitialize)
653
690
  // has no users, so it seeds either way; the flag is left off there.
654
691
  const initArgs = ctx.dbReinitialize ? ['initialize'] : ['initialize', '--', '--skip-if-initialized']
655
- runYarn({ ...ctx, env: { ...ctx.env, OM_INIT_DEV_AUTOSTART: '1' } }, initArgs)
692
+ await runYarn({
693
+ ...ctx,
694
+ env: {
695
+ ...ctx.env,
696
+ OM_INIT_DEV_AUTOSTART: '1',
697
+ OM_INIT_SUMMARY_COLUMNS: String(Math.max(8, (process.stdout.columns || 80) - (ctx.logs ? 3 : 0))),
698
+ OM_INIT_SUMMARY_COLOR: process.stdout.isTTY && ctx.env.NO_COLOR === undefined ? '1' : '0',
699
+ },
700
+ }, initArgs)
656
701
  }
657
702
  writeState(ctx.repoRoot, ctx.dbMarker, new Date().toISOString())
658
703
  }
@@ -735,6 +780,7 @@ export function buildUpSteps(ctx) {
735
780
  llmProviderStep,
736
781
  hostGatewayStep,
737
782
  infraUpStep,
783
+ serviceConnectionsStep,
738
784
  databaseStep,
739
785
  ]
740
786
  const disabled = new Set(ctx.company.steps.disable)
@@ -767,31 +813,68 @@ export async function createStepContext(repoRoot, { mode = 'hybrid', flags = {},
767
813
  }
768
814
 
769
815
  export async function runSteps(steps, ctx) {
770
- const active = steps.filter((step) => !step.appliesTo || step.appliesTo(ctx))
771
- let index = 0
772
- for (const step of active) {
773
- index += 1
774
- stepHeader(index, active.length, step.title, step.expectation, { log: ctx.log })
775
- const startedAt = Date.now()
776
- try {
777
- const checked = step.check ? await step.check(ctx) : { ok: false, detail: '' }
778
- if (checked.ok) {
779
- statusLine('ok', `${checked.detail || 'already satisfied'} ${color.dim('(skipped — already done)')}`, { log: ctx.log })
780
- continue
816
+ const originalLog = ctx.log
817
+ const originalPromptLog = ctx.promptLog
818
+ const logs = ctx.logs ?? createSetupLogs({ repoRoot: ctx.repoRoot, ...ctx.flags })
819
+ // Step summaries stay visible; routine details and child output share the
820
+ // foldable buffer. Keep mutations to ctx (env, markers) on the real context.
821
+ let spinner = null
822
+ const log = (...args) => { spinner?.pause(); originalLog(...args); logs.record(...args) }
823
+ ctx.promptLog = log
824
+ const stopSpinner = () => {
825
+ spinner?.stop()
826
+ spinner = null
827
+ logs.setActivity?.(null)
828
+ }
829
+ ctx.logs = logs
830
+ logs.start()
831
+ try {
832
+ const active = steps.filter((step) => !step.appliesTo || step.appliesTo(ctx))
833
+ let index = 0
834
+ for (const step of active) {
835
+ index += 1
836
+ stepHeader(index, active.length, step.title, step.expectation, { log })
837
+ const startedAt = Date.now()
838
+ if (step.interactive) logs.suspend()
839
+ else if (logs.interactive) {
840
+ spinner = (ctx.createSpinnerImpl ?? createSpinner)('⚙️ working…', { startPaused: true, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] })
841
+ logs.setActivity?.(spinner)
781
842
  }
782
- if (checked.detail) statusLine('info', checked.detail, { log: ctx.log })
783
- if (!step.apply) continue
784
- await step.apply(ctx)
785
- statusLine('ok', `done ${color.dim(`in ${formatDuration(Date.now() - startedAt)}`)}`, { log: ctx.log })
786
- } catch (error) {
787
- if (error instanceof StepBlocked) {
788
- statusLine('fail', 'blocked — this starter proposes, it does not install system components', { log: ctx.log })
789
- guideBox('What to do next', error.guide, { log: ctx.log })
790
- return { ok: false, blockedStep: step.id }
843
+ ctx.log = step.interactive ? log : (...args) => logs.log(...args)
844
+ try {
845
+ const checked = step.check ? await step.check(ctx) : { ok: false, detail: '' }
846
+ if (checked.ok) {
847
+ statusLine('ok', `${checked.detail || 'already satisfied'} ${color.dim('(skipped — already done)')}`, { log })
848
+ continue
849
+ }
850
+ if (step.id === 'infra-up' && checked.detail?.startsWith('starting:')) log('')
851
+ if (checked.detail) statusLine('info', checked.detail, { log })
852
+ if (!step.apply) continue
853
+ logs.resumeActivity?.()
854
+ await step.apply(ctx)
855
+ statusLine('ok', `done ${color.dim(`in ${formatDuration(Date.now() - startedAt)}`)}`, { log })
856
+ } catch (error) {
857
+ stopSpinner()
858
+ logs.show(`Setup stopped at ${step.title}`)
859
+ if (error instanceof StepBlocked) {
860
+ statusLine('fail', 'blocked — this starter proposes, it does not install system components', { log })
861
+ guideBox('What to do next', error.guide, { log })
862
+ return { ok: false, blockedStep: step.id }
863
+ }
864
+ statusLine('fail', error instanceof Error ? error.message : String(error), { log })
865
+ return { ok: false, failedStep: step.id }
866
+ } finally {
867
+ stopSpinner()
868
+ ctx.log = originalLog
869
+ if (step.interactive) logs.resume()
791
870
  }
792
- statusLine('fail', error instanceof Error ? error.message : String(error), { log: ctx.log })
793
- return { ok: false, failedStep: step.id }
794
871
  }
872
+ return { ok: true }
873
+ } finally {
874
+ stopSpinner()
875
+ ctx.log = originalLog
876
+ if (originalPromptLog === undefined) delete ctx.promptLog
877
+ else ctx.promptLog = originalPromptLog
878
+ logs.stop()
795
879
  }
796
- return { ok: true }
797
880
  }
package/src/ui.mjs CHANGED
@@ -51,15 +51,15 @@ export function printBanner(subtitle, { log = console.log } = {}) {
51
51
 
52
52
  export function stepHeader(index, total, title, expectation, { log = console.log } = {}) {
53
53
  log('')
54
- log(`${color.bold(color.blue(`── Step ${index}/${total}`))} ${color.bold(title)}`)
55
- if (expectation) log(color.dim(` Expected: ${expectation}`))
54
+ log(` ${color.bold(color.blue(`── Step ${index}/${total}`))} ${color.bold(title)}`)
55
+ if (expectation) log(` ${color.bold(color.yellow('Expected:'))} ${expectation}`)
56
56
  }
57
57
 
58
58
  export const icons = {
59
- ok: color.green('OK'),
60
- warn: color.yellow('!!'),
61
- fail: color.red('XX'),
62
- info: color.cyan('--'),
59
+ ok: color.green('✅'),
60
+ warn: color.yellow('⚠️'),
61
+ fail: color.red('❌'),
62
+ info: color.cyan('ℹ️'),
63
63
  }
64
64
 
65
65
  export function statusLine(kind, message, { log = console.log } = {}) {
@@ -80,37 +80,58 @@ const SPINNER_FRAMES = ['|', '/', '-', '\\']
80
80
 
81
81
  // Spinner for long waits that produce no streamed output. In non-TTY contexts
82
82
  // it prints the label once and then only meaningful updates via update().
83
- export function createSpinner(label) {
83
+ export function createSpinner(label, {
84
+ output = process.stdout,
85
+ env = process.env,
86
+ log = console.log,
87
+ frames = SPINNER_FRAMES,
88
+ startPaused = false,
89
+ now = Date.now,
90
+ setIntervalImpl = setInterval,
91
+ clearIntervalImpl = clearInterval,
92
+ } = {}) {
84
93
  let frame = 0
85
94
  let currentLabel = label
86
95
  let timer = null
87
- const startedAt = Date.now()
96
+ let stopped = false
97
+ let rendered = false
98
+ const startedAt = now()
99
+ const animated = Boolean(output.isTTY && env.CI !== 'true' && env.TERM !== 'dumb')
88
100
 
89
101
  const render = () => {
90
- const elapsed = Math.round((Date.now() - startedAt) / 1000)
91
- process.stdout.write(`\r ${color.cyan(SPINNER_FRAMES[frame % SPINNER_FRAMES.length])} ${currentLabel} ${color.dim(`(${elapsed}s)`)} `)
102
+ const elapsed = Math.round((now() - startedAt) / 1000)
103
+ output.write(`\r ${color.cyan(frames[frame % frames.length])} ${currentLabel} ${color.dim(`(${elapsed}s)`)} `)
92
104
  frame += 1
105
+ rendered = true
93
106
  }
94
107
 
95
- if (isTty) {
96
- timer = setInterval(render, 120)
108
+ const pause = () => {
109
+ if (timer !== null) clearIntervalImpl(timer)
110
+ timer = null
111
+ if (rendered) output.write('\r' + ' '.repeat(Math.max(1, Math.min(output.columns ?? 100, 100) - 1)) + '\r')
112
+ rendered = false
113
+ }
114
+ const resume = () => {
115
+ if (!animated || stopped || timer !== null) return
116
+ timer = setIntervalImpl(render, 120)
97
117
  render()
98
- } else {
99
- console.log(` ... ${label}`)
100
118
  }
101
119
 
120
+ if (animated) { if (!startPaused) resume() }
121
+ else log(` ... ${label}`)
122
+
102
123
  return {
124
+ pause,
125
+ resume,
103
126
  update(nextLabel) {
104
127
  if (nextLabel === currentLabel) return
105
128
  currentLabel = nextLabel
106
- if (!isTty) console.log(` ... ${nextLabel}`)
129
+ if (!animated) log(` ... ${nextLabel}`)
107
130
  },
108
131
  stop(kind = null, message = null) {
109
- if (timer) {
110
- clearInterval(timer)
111
- process.stdout.write('\r' + ' '.repeat(100) + '\r')
112
- }
113
- if (kind && message) statusLine(kind, message)
132
+ pause()
133
+ stopped = true
134
+ if (kind && message) statusLine(kind, message, { log })
114
135
  },
115
136
  }
116
137
  }