From f8efe721cea65e826f837facc1457a43d762295b Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 21:32:37 +0000 Subject: [PATCH 1/2] feat(build): render project logs in the clack gutter --- packages/nuxt-cli/src/commands/build.ts | 5 + packages/nuxt-cli/src/utils/console.ts | 66 +++++- packages/nuxt-cli/src/utils/logger.ts | 10 +- .../nuxt-cli/test/unit/commands/build.spec.ts | 33 +++ .../nuxt-cli/test/unit/utils/console.spec.ts | 213 +++++++++++++++++- 5 files changed, 317 insertions(+), 10 deletions(-) diff --git a/packages/nuxt-cli/src/commands/build.ts b/packages/nuxt-cli/src/commands/build.ts index 34e426f07..9647b4c06 100644 --- a/packages/nuxt-cli/src/commands/build.ts +++ b/packages/nuxt-cli/src/commands/build.ts @@ -8,6 +8,7 @@ import { resolveDotenvFileNames } from '../utils/args' import { showBanner } from '../utils/banner' import { BuildProgress } from '../utils/build-progress' import { createBuildReport } from '../utils/build-report' +import { configureProjectConsola, reportThroughClack } from '../utils/console' import { overrideEnv } from '../utils/env' import { ActionableError } from '../utils/errors' @@ -63,8 +64,10 @@ export default defineCommand({ const releaseLocks: Array<() => void> = [] const progress = new BuildProgress() let stopReporting = () => {} + let stopClackReporting = () => {} try { intro(styleText('cyan', 'Building Nuxt for production...')) + stopClackReporting = reportThroughClack() // The phase line owns a row of the terminal, which a silent build has no // business drawing on. Subscribed after the intro so the first phase is @@ -83,6 +86,7 @@ export default defineCommand({ } const kit = await loadKit(cwd) + await configureProjectConsola(cwd) const nuxt = await kit.loadNuxt({ cwd, ready: false, @@ -190,6 +194,7 @@ export default defineCommand({ } finally { stopReporting() + stopClackReporting() for (const release of releaseLocks.reverse()) { release() } diff --git a/packages/nuxt-cli/src/utils/console.ts b/packages/nuxt-cli/src/utils/console.ts index 8c9f65a10..668cfb58f 100644 --- a/packages/nuxt-cli/src/utils/console.ts +++ b/packages/nuxt-cli/src/utils/console.ts @@ -1,19 +1,43 @@ -import type { ConsolaInstance, ConsolaOptions, ConsolaReporter } from 'consola' +import type { ConsolaInstance, ConsolaOptions, ConsolaReporter, FormatOptions, LogObject } from 'consola' import process from 'node:process' import { pathToFileURL } from 'node:url' +import { format, styleText } from 'node:util' import { consola } from 'consola' import { resolveModulePath } from 'exsolve' +import { isCI } from 'std-env' import { isRemotePeerError } from './errors' -import { debug } from './logger' +import { debug, isEmittingCliLog, logger } from './logger' import { tryResolveNuxt } from './resolve-nuxt' import { holdScreen, isScreenHeld, takeUnseenOutput } from './screen' import { withUserAttention } from './startup-clock' import { isInteractiveSession, trackOutputSpacing, writeDirect } from './stdout' +import { MUTED } from './terminal-theme' -function wrapReporter(reporter: ConsolaReporter) { +type FormattingReporter = ConsolaReporter & { + formatArgs?: (args: unknown[], opts: FormatOptions) => string +} + +let clackReporting = false + +/** + * Render consola logs as clack log lines, so the project's logs share the + * gutter the CLI draws down the side of a command's output. Only takes effect + * where that gutter is drawn. Returns a function that switches it off again. + */ +export function reportThroughClack(): () => void { + if (!process.stdout.isTTY || isCI) { + return () => {} + } + clackReporting = true + return () => { + clackReporting = false + } +} + +export function wrapReporter(reporter: FormattingReporter): ConsolaReporter { return ({ log(logObj, ctx) { if (!logObj.args || !logObj.args.length) { @@ -26,11 +50,45 @@ function wrapReporter(reporter: ConsolaReporter) { return } } + if (clackReporting && !isEmittingCliLog() && logObj.type !== 'box') { + const opts = { columns: process.stdout.columns || 0, ...ctx.options.formatOptions } + const message = reporter.formatArgs + ? reporter.formatArgs(logObj.args, opts) + : format(...logObj.args) + return logThroughClack(logObj, message) + } return reporter.log(logObj, ctx) }, }) satisfies ConsolaReporter } +/** Bypasses `consola.wrapStd()`, which would hand each line back to consola. */ +const directOutput = { write: writeDirect } as unknown as NodeJS.WriteStream + +function logThroughClack(logObj: LogObject, message: string): void { + message = message.replace(/`([^`\n]+)`/g, (_, code) => styleText('cyan', code)) + if (logObj.tag) { + message = `${styleText(MUTED, `[${logObj.tag}]`)} ${message}` + } + const options = { output: directOutput } + switch (logObj.type) { + case 'fatal': + case 'error': + case 'fail': + return logger.error(message, options) + case 'warn': + return logger.warn(message, options) + case 'success': + case 'ready': + return logger.success(message, options) + case 'info': + case 'start': + return logger.info(message, options) + default: + return logger.message(message, options) + } +} + /** How Node opens a process warning, such as `(node:1234) DeprecationWarning: …`. */ const PROCESS_WARNING_RE = /^\(node:\d+\) / @@ -62,7 +120,7 @@ export async function configureProjectConsola(rootDir: string): Promise { projectConsola.options.formatOptions.date = false routeProcessWarnings(projectConsola) interceptPrompts(projectConsola) - // Logs from a separate instance would otherwise bypass the dev UI's reporters. + // Logs from a separate instance would otherwise bypass the CLI's reporters. if (projectConsola !== consola) { projectConsola.setReporters([ { diff --git a/packages/nuxt-cli/src/utils/logger.ts b/packages/nuxt-cli/src/utils/logger.ts index cf579f5bb..6e47f62b7 100644 --- a/packages/nuxt-cli/src/utils/logger.ts +++ b/packages/nuxt-cli/src/utils/logger.ts @@ -69,11 +69,11 @@ export function setLoggerImpl(next?: LoggerImpl): void { } export const logger: LoggerImpl = { - info: message => emit(() => (impl ?? defaultImpl()).info(message)), - warn: message => emit(() => (impl ?? defaultImpl()).warn(message)), - error: message => emit(() => (impl ?? defaultImpl()).error(message)), - success: message => emit(() => (impl ?? defaultImpl()).success(message)), - step: message => emit(() => (impl ?? defaultImpl()).step(message)), + info: (message, options) => emit(() => (impl ?? defaultImpl()).info(message, options)), + warn: (message, options) => emit(() => (impl ?? defaultImpl()).warn(message, options)), + error: (message, options) => emit(() => (impl ?? defaultImpl()).error(message, options)), + success: (message, options) => emit(() => (impl ?? defaultImpl()).success(message, options)), + step: (message, options) => emit(() => (impl ?? defaultImpl()).step(message, options)), message: (message, options) => emit(() => (impl ?? defaultImpl()).message(message, options)), } diff --git a/packages/nuxt-cli/test/unit/commands/build.spec.ts b/packages/nuxt-cli/test/unit/commands/build.spec.ts index 45db78f92..13e42e27a 100644 --- a/packages/nuxt-cli/test/unit/commands/build.spec.ts +++ b/packages/nuxt-cli/test/unit/commands/build.spec.ts @@ -10,10 +10,13 @@ const mocks = vi.hoisted(() => ({ acquireOutputLock: vi.fn(), buildNuxt: vi.fn(), clearBuildDir: vi.fn(), + configureProjectConsola: vi.fn(), loadNuxt: vi.fn(), releaseBuildDir: vi.fn(), releaseOutputDir: vi.fn(), + reportThroughClack: vi.fn(), startCpuProfile: vi.fn(), + stopClackReporting: vi.fn(), stopCpuProfile: vi.fn(), useNitro: vi.fn(), writeTypes: vi.fn(), @@ -26,6 +29,10 @@ vi.mock('@clack/prompts', () => ({ vi.mock('../../../src/utils/banner', () => ({ showBanner: vi.fn(), })) +vi.mock('../../../src/utils/console', () => ({ + configureProjectConsola: mocks.configureProjectConsola, + reportThroughClack: mocks.reportThroughClack, +})) vi.mock('../../../src/utils/env', () => ({ overrideEnv: vi.fn(), })) @@ -86,6 +93,32 @@ describe('build', () => { }) mocks.acquireLock.mockReturnValue({ release: mocks.releaseBuildDir }) mocks.acquireOutputLock.mockReturnValue({ release: mocks.releaseOutputDir }) + mocks.reportThroughClack.mockReturnValue(mocks.stopClackReporting) + }) + + it.each([ + ['succeeds', undefined], + [ + 'fails', + new Error('build failed'), + ], + ])('renders project logs through clack while the build runs, and stops when it %s', async (_, error) => { + mocks.buildNuxt.mockImplementationOnce(async () => { + expect(mocks.reportThroughClack).toHaveBeenCalledOnce() + expect(mocks.configureProjectConsola).toHaveBeenCalledWith(cwd) + expect(mocks.reportThroughClack.mock.invocationCallOrder[0]).toBeLessThan(mocks.loadNuxt.mock.invocationCallOrder[0]!) + expect(mocks.configureProjectConsola.mock.invocationCallOrder[0]).toBeLessThan(mocks.loadNuxt.mock.invocationCallOrder[0]!) + expect(mocks.stopClackReporting).not.toHaveBeenCalled() + if (error) { + throw error + } + }) + + await (error + ? expect(run()).rejects.toBe(error) + : run()) + + expect(mocks.stopClackReporting).toHaveBeenCalledOnce() }) it('loads Nuxt with build arguments and runs the build in order', async () => { diff --git a/packages/nuxt-cli/test/unit/utils/console.spec.ts b/packages/nuxt-cli/test/unit/utils/console.spec.ts index 5bde40805..974f2bc05 100644 --- a/packages/nuxt-cli/test/unit/utils/console.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/console.spec.ts @@ -10,7 +10,9 @@ import { consola, createConsola } from 'consola' import { resolveModulePath } from 'exsolve' import { afterEach, describe, expect, it, vi } from 'vitest' -import { askQuestion, configureProjectConsola, interceptPrompts, restoreRawMode, routeProcessWarnings, withDirectStdout } from '../../../src/utils/console' +import { askQuestion, configureProjectConsola, interceptPrompts, reportThroughClack, restoreRawMode, routeProcessWarnings, withDirectStdout, wrapReporter } from '../../../src/utils/console' +import { stripAnsi } from '../../../src/utils/formatting' +import { logger } from '../../../src/utils/logger' import { holdScreen, onScreenHeld, registerUnseenOutput } from '../../../src/utils/screen' import { registerTerminalHost } from '../../../src/utils/terminal-host' @@ -19,6 +21,17 @@ type PromptFn = NonNullable /** Whether the session has a terminal a question could be answered on. */ let interactive = true +const stdEnv = vi.hoisted(() => ({ + isCI: false, +})) + +vi.mock('std-env', async importOriginal => ({ + ...await importOriginal(), + get isCI() { + return stdEnv.isCI + }, +})) + vi.mock('../../../src/utils/resolve-nuxt', () => ({ tryResolveNuxt: () => null, })) @@ -434,6 +447,204 @@ describe('routeProcessWarnings', () => { }) }) +describe('reportThroughClack', () => { + const stdout = process.stdout as Omit & { isTTY?: boolean } + const isTTY = Object.getOwnPropertyDescriptor(stdout, 'isTTY') + let stop = () => {} + + afterEach(() => { + stop() + stdEnv.isCI = false + if (isTTY) { + Object.defineProperty(stdout, 'isTTY', isTTY) + } + else { + delete stdout.isTTY + } + }) + + function setup(options: { tty?: boolean } = {}) { + Object.defineProperty(stdout, 'isTTY', { value: options.tty ?? true, configurable: true, writable: true }) + const original = { + log: vi.fn(), + } + const instance = createConsola({ + reporters: [ + wrapReporter(original), + ], + level: 5, + }) + const calls: Array<[method: string, message: string]> = [] + for (const method of [ + 'error', + 'warn', + 'success', + 'info', + 'message', + ] as const) { + vi.spyOn(logger, method).mockImplementation((message?: string) => void calls.push([ + method, + stripAnsi(String(message)), + ])) + } + return { original, instance, calls } + } + + it('renders each consola type with the matching clack log method', () => { + const { original, instance, calls } = setup() + stop = reportThroughClack() + + instance.error('boom') + instance.fail('broken') + instance.warn('slow') + instance.success('done') + instance.ready('ready') + instance.info('Building', 'app') + instance.start('starting') + instance.log('plain') + instance.debug('detail') + + expect(original.log).not.toHaveBeenCalled() + expect(calls).toEqual([ + ['error', 'boom'], + ['error', 'broken'], + ['warn', 'slow'], + ['success', 'done'], + ['success', 'ready'], + ['info', 'Building app'], + ['info', 'starting'], + ['message', 'plain'], + ['message', 'detail'], + ]) + }) + + it('prefixes the tag and formats the message with the wrapped reporter', () => { + const { instance, calls } = setup() + const fancy = { + log: vi.fn(), + formatArgs: (args: unknown[]) => `formatted ${args.join(' ')}`, + } + instance.setReporters([ + wrapReporter(fancy), + ]) + stop = reportThroughClack() + + instance.withTag('site-data').info('Using `cached` data') + + expect(calls).toEqual([ + ['info', '[site-data] formatted Using cached data'], + ]) + }) + + it('writes past consola\'s stdout wrapper', () => { + Object.defineProperty(stdout, 'isTTY', { value: true, configurable: true, writable: true }) + const written: string[] = [] + const write = vi.spyOn(process.stdout, 'write').mockImplementation((chunk: string | Uint8Array) => { + written.push(stripAnsi(String(chunk))) + return true + }) + const original = { + log: vi.fn(), + } + const instance = createConsola({ + reporters: [ + wrapReporter(original), + ], + level: 5, + }) + instance.wrapStd() + stop = reportThroughClack() + try { + instance.error('boom') + instance.warn('slow') + instance.success('done') + instance.info('Building app') + instance.log('plain') + } + finally { + instance.restoreStd() + write.mockRestore() + } + + expect(original.log).not.toHaveBeenCalled() + const output = written.join('') + expect(output).toContain('■ boom') + expect(output).toContain('▲ slow') + expect(output).toContain('◆ done') + expect(output).toContain('● Building app') + expect(output).toContain('│ plain') + }) + + it('leaves the CLI\'s own logs, handed back by consola\'s stdout wrapper, to the wrapped reporter', () => { + Object.defineProperty(stdout, 'isTTY', { value: true, configurable: true, writable: true }) + const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) + const original = { + log: vi.fn(), + } + const instance = createConsola({ + reporters: [ + wrapReporter(original), + ], + level: 5, + }) + instance.wrapStd() + stop = reportThroughClack() + try { + logger.info('Deploy target: static') + } + finally { + instance.restoreStd() + write.mockRestore() + } + + expect(original.log).toHaveBeenCalledWith(expect.objectContaining({ + args: [ + expect.stringContaining('Deploy target: static'), + ], + }), expect.anything()) + }) + + it('leaves boxes to the wrapped reporter', () => { + const { original, instance, calls } = setup() + stop = reportThroughClack() + + instance.box('Hello') + + expect(calls).toEqual([]) + expect(original.log).toHaveBeenCalledWith(expect.objectContaining({ type: 'box' }), expect.anything()) + }) + + it('stops once switched off', () => { + const { original, instance, calls } = setup() + reportThroughClack()() + + instance.info('after') + + expect(calls).toEqual([]) + expect(original.log).toHaveBeenCalledOnce() + }) + + it.each([ + [ + 'stdout is not a terminal', + { tty: false, ci: false }, + ], + [ + 'running in CI', + { tty: true, ci: true }, + ], + ])('does nothing when %s', (_, { tty, ci }) => { + const { original, instance, calls } = setup({ tty }) + stdEnv.isCI = ci + stop = reportThroughClack() + + instance.warn('slow') + + expect(calls).toEqual([]) + expect(original.log).toHaveBeenCalledOnce() + }) +}) + describe('configureProjectConsola', () => { it('should send logs from a separate project consola through the CLI\'s reporters', async () => { const root = realpathSync(mkdtempSync(join(tmpdir(), 'nuxt-cli-consola-'))) From db18110f08180c915dc57f0a768044430474d351 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 22 Nov 2026 22:02:05 +0000 Subject: [PATCH 2/2] fix(build): leave consola traces to its own reporter --- packages/nuxt-cli/src/utils/console.ts | 2 +- .../nuxt-cli/test/unit/utils/console.spec.ts | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/nuxt-cli/src/utils/console.ts b/packages/nuxt-cli/src/utils/console.ts index 668cfb58f..e512b8a17 100644 --- a/packages/nuxt-cli/src/utils/console.ts +++ b/packages/nuxt-cli/src/utils/console.ts @@ -50,7 +50,7 @@ export function wrapReporter(reporter: FormattingReporter): ConsolaReporter { return } } - if (clackReporting && !isEmittingCliLog() && logObj.type !== 'box') { + if (clackReporting && !isEmittingCliLog() && logObj.type !== 'box' && logObj.type !== 'trace') { const opts = { columns: process.stdout.columns || 0, ...ctx.options.formatOptions } const message = reporter.formatArgs ? reporter.formatArgs(logObj.args, opts) diff --git a/packages/nuxt-cli/test/unit/utils/console.spec.ts b/packages/nuxt-cli/test/unit/utils/console.spec.ts index 974f2bc05..1d7b62533 100644 --- a/packages/nuxt-cli/test/unit/utils/console.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/console.spec.ts @@ -614,6 +614,30 @@ describe('reportThroughClack', () => { expect(original.log).toHaveBeenCalledWith(expect.objectContaining({ type: 'box' }), expect.anything()) }) + it('leaves traces to the wrapped reporter, which prints their stack', () => { + const { calls } = setup() + const fancyOptions = { fancy: true, level: 5 } + const fancy = createConsola(fancyOptions).options.reporters[0]! + const written: string[] = [] + const stdout = { + write: (chunk: string) => void written.push(stripAnsi(chunk)), + } + const instance = createConsola({ + reporters: [ + wrapReporter(fancy), + ], + level: 5, + stdout: stdout as unknown as NodeJS.WriteStream, + }) + stop = reportThroughClack() + + instance.trace('checkpoint') + + expect(calls).toEqual([]) + expect(written.join('')).toContain('checkpoint') + expect(written.join('')).toMatch(/^ +at /m) + }) + it('stops once switched off', () => { const { original, instance, calls } = setup() reportThroughClack()()