diff --git a/capture/README.md b/capture/README.md index 1f94f3ec1..d8e631f28 100644 --- a/capture/README.md +++ b/capture/README.md @@ -32,7 +32,7 @@ The first time you run this, it will copy `capture/fixture/` into a work directo ## Scenarios -Defined in `captures.config.ts`, currently: `nuxt-dev`, `nuxt-dev-static`, `nuxt-dev-restart`, `nuxt-dev-install-module` (interactive dev UI, pinned with `NUXT_TUI=1`), `nuxt-dev-plain`, `nuxt-dev-plain-static`, `nuxt-dev-plain-restart` (classic log output, pinned with `NUXT_TUI=plain`), `nuxt-init`, `nuxt-curl`, `nuxt-task-list`, `nuxt-module-search`. +Defined in `captures.config.ts`, currently: `nuxt-dev`, `nuxt-dev-static`, `nuxt-dev-restart`, `nuxt-dev-install-module`, `nuxt-dev-logs` (interactive dev UI, pinned with `NUXT_TUI=1`), `nuxt-dev-plain`, `nuxt-dev-plain-static`, `nuxt-dev-plain-restart` (classic log output, pinned with `NUXT_TUI=plain`), `nuxt-init`, `nuxt-curl`, `nuxt-task-list`, `nuxt-module-search`. Dev captures pin the UI mode explicitly because the dev UI otherwise decides based on the environment (CI, test, terminal size), which would make recordings machine-dependent. @@ -42,6 +42,8 @@ A scenario is a command plus an optional `drive` function that types into the se Each SVG is scrubbed of ports, LAN addresses, home and temporary directories, and (for dev scenarios) the QR code. Each capture's `` records which rules were applied. +Whether a re-recording replaces the committed SVG is decided by its `.txt` fingerprint, which also pins versions, timings, dates and spinner phases. A scenario can add rules that apply only to the fingerprint with `fingerprint`; `nuxt-dev-logs` uses `clock`, since which log rows print a time depends on where the seconds fell. + ## Stubbed APIs `nuxt module search` is recorded against `capture/fixture-data/modules.json` instead of the live `api.nuxt.com`. You can refresh the fixture when the docs should show newer modules. diff --git a/capture/captures.config.ts b/capture/captures.config.ts index bf575ee74..44b1a4656 100644 --- a/capture/captures.config.ts +++ b/capture/captures.config.ts @@ -24,6 +24,8 @@ export interface Capture { animated?: boolean /** Rules from `lib/scrub.ts` applied to the captured bytes. */ scrub?: string[] + /** Rules from `lib/scrub.ts` applied only when deciding whether the committed SVG is stale. */ + fingerprint?: string[] /** Drives the session: waits, keystrokes, file edits. */ drive?: (context: CaptureContext) => Promise /** Extra environment for the pty. */ @@ -188,6 +190,41 @@ export const captures: Capture[] = [ } }, }, + { + id: 'nuxt-dev-logs', + title: 'nuxt dev (browsing logs)', + command: '$NUXT dev --no-clear --takeover', + cwd: 'app', + animated: true, + rows: 26, + scrub: DEV_SCRUB, + fingerprint: ['clock'], + stopAfterDrive: true, + env: TUI_ENV, + async drive({ session }) { + await session.waitFor(/ready in \d/, 180_000) + const port = session.output().match(/localhost:(\d+)/)?.[1] ?? '3000' + for (const cart of ['c_8f3a21', 'c_19be07']) { + await fetch(`http://localhost:${port}/api/checkout?cart=${cart}`) + await session.wait(500) + } + await session.waitFor(/✖ 2 errors/, 30_000) + await session.wait(1000) + // Relative to the last error: other logs can still arrive after it. + session.send('e') + await session.wait(3500) + session.send('\u001B') + await session.wait(2000) + for (const key of ['\u001B[A', '\u001B[A', '\u001B[B', '\u001B[B']) { + session.send(key) + await session.wait(1500) + } + session.send('T') + await session.wait(2500) + session.send('q') + await session.wait(1000) + }, + }, { id: 'nuxt-dev-plain', title: 'nuxt dev (plain output)', diff --git a/capture/fixture/server/api/checkout.ts b/capture/fixture/server/api/checkout.ts new file mode 100644 index 000000000..562f2ab16 --- /dev/null +++ b/capture/fixture/server/api/checkout.ts @@ -0,0 +1,10 @@ +function applyDiscount(cart: string, code: string) { + throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pricing service responded with 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot be combined with items already on sale)`) +} + +export default defineEventHandler((event) => { + const cart = String(getQuery(event).cart ?? 'guest') + console.log(`[checkout] loading cart ${cart} with options ${JSON.stringify({ currency: 'EUR', locale: 'en-GB', include: ['items', 'discounts', 'shipping', 'tax'], expand: true })}`) + console.warn(`[checkout] prices for cart ${cart} were cached more than 10 minutes ago, recalculating totals against https://pricing.example.com/v2/carts/${cart}/recalculate?currency=EUR&include=tax`) + applyDiscount(cart, 'SUMMER-2026') +}) diff --git a/capture/lib/frames.spec.ts b/capture/lib/frames.spec.ts index 93a2cf78f..709f28c26 100644 --- a/capture/lib/frames.spec.ts +++ b/capture/lib/frames.spec.ts @@ -59,6 +59,28 @@ describe('capture fingerprint', () => { } }) +describe('scrubbing the log view clock', () => { + const muted = '\u001B[90m' + const reset = '\u001B[39m' + const log = (rows: string[]) => buildFingerprint([{ at: 0, data: rows.join('\r\n') }], { rows: 24, scrubRules: ['dates', 'clock'] }) + + it('should not depend on which rows the time was printed on', () => { + const shown = log([` ${muted}14:42:32${reset} Vite server built`, ` ${muted}14:42:33${reset} [nitro] built`]) + const blank = log([` ${muted}14:42:32${reset} Vite server built`, `${' '.repeat(11)}[nitro] built`]) + expect(blank).toBe(shown) + }) + + it('should blank the time before an indented message', () => { + expect(log([` ${muted}14:42:32${reset} ➜ DevTools`])).toBe(log([`${' '.repeat(13)}➜ DevTools`])) + }) + + it('should keep the gutter and indentation of continuation rows', () => { + const lines = log([`\u001B[32m▎ \u001B[39m${muted}14:42:32${reset} selected`, `${' '.repeat(13)}continued`]).split('\n') + expect(lines).toContain(`▎${' '.repeat(10)}selected`) + expect(lines).toContain(`${' '.repeat(13)}continued`) + }) +}) + describe('scrubbing a right-aligned tag', () => { const TAG = 'nitro' const WIDTH = 96 diff --git a/capture/lib/scrub.ts b/capture/lib/scrub.ts index e24eec22b..f6c1f7a73 100644 --- a/capture/lib/scrub.ts +++ b/capture/lib/scrub.ts @@ -4,6 +4,8 @@ import { homedir } from 'node:os' interface ScrubStep { pattern: RegExp replacement: (match: RegExpMatchArray) => string + /** Leave the replacement unstyled instead of inheriting the first replaced character's style. */ + unstyled?: boolean } interface ScrubRule { @@ -78,6 +80,15 @@ const RULES: Record = { { pattern: /\b\d{2}:\d{2}:\d{2}\b/g, replacement: () => '12:00:00' }, ], }, + clock: { + id: 'clock', + description: 'log view clock column blanked', + steps: [ + // The log view only prints a time that differs from the row above, so + // which rows carry one depends on where the seconds fell. + { pattern: /(?<=^.{2})(?:\d{2}:\d{2}:\d{2}| {8}) (?= *\S)/g, replacement: () => ' '.repeat(9), unstyled: true }, + ], + }, spinner: { id: 'spinner', description: 'spinner glyphs pinned to one phase', @@ -172,7 +183,7 @@ function applyStep(line: string, styles: (Style | undefined)[], step: ScrubStep) const replacement = step.replacement(match) out += replacement for (let index = 0; index < replacement.length; index++) { - outStyles.push(styles[start]) + outStyles.push(step.unstyled ? undefined : styles[start]) } last = start + match[0].length } diff --git a/capture/output/nuxt-dev-logs.svg b/capture/output/nuxt-dev-logs.svg new file mode 100644 index 000000000..6e656ecce --- /dev/null +++ b/capture/output/nuxt-dev-logs.svg @@ -0,0 +1,46 @@ + +nuxt dev (browsing logs) +Terminal capture. Scrubbing applied: ports (dev server ports pinned to 3000); hostnames (LAN addresses replaced with a fixed private address); paths (home directory and temporary paths collapsed); qr (QR code re-rendered for the scrubbed network URL) + + + + + + + + +nuxt dev (browsing logs) +⣠⣦⣠⡀Nuxt4.6.2━━━━━━━━━━━━━━━━━━━━0% · 0.0ms STARTING preparing your apprrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/⠋━━━━━━━━━━━━━━━━━━━━0% · 0.0ms STARTING starting Nuxt...oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━17% · 95ms STARTING setting up modulesoopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━33% · 191ms STARTING preparing appoopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━33% · 301ms STARTING preparing appoopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━50% · 432ms STARTING generating typesoopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━67% · 577ms STARTING bundling appoopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━83% · 731ms STARTING building serveroopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━83% · 822ms STARTING building serveroopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━83% · 963ms STARTING building serveroopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━83% · 1.08s STARTING building serveroopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/━━━━━━━━━━━━━━━━━━━━83% · 1.20s STARTING building serveroopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2ready in 1.61sLocalhttp://localhost:3000/⚠ 1 warning READY watching for changesrrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/⚠ 2 warnings✖ 1 error ERROR failed to apply discount code SUMMER-2026 to cart c_8f3a21: the pricing service respo…elast error · rrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/✔ 1 request 713ms median ⚠ 2 warnings✖ 1 error✖ 1 failed request ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_8f3a21 · 500 · 713mselast error · rrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/✔ 1 request 713ms median ⚠ 3 warnings✖ 2 errors✖ 1 failed request ERROR failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing service respo…elast error · rrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/✔ 2 requests 713ms median ⚠ 3 warnings✖ 2 errors✖ 2 failed requests ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_19be07 · 500 · 52mselast error · rrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +⣠⣦⣠⡀Nuxt4.6.2Localhttp://localhost:3000/✔ 2 requests 713ms median ⚠ 3 warnings✖ 2 errors✖ 2 failed requests ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_19be07 · 500 · 52mselast error · rrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit +logs› 12 of 12 · error · runtime · 19:38:55────────────────────────────────────────────────────────────────────────────────────────────────GET /api/checkout?cart=c_19be07✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07: the pricingservice respondedwith 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot be combined withitems already on sale)1│function applyDiscount(cart: string, code: string) {›2│ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pricin…│^3│}4│atapplyDiscountserver/api/checkout.ts:2:1atObject.handlerserver/api/checkout.ts:9:1… 5 framework frames↑/↓scroll · ←/→previous/next · ycopy · escback +logs · follow paused · cli+build+runtime · all levels──────────────────────────────────────────────────────────────────────────────────────────────── Vite server built in 17ms19:38:54[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines19:38:55GET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_19be07 were cached more than 10 minutes ago, … +2 lines▎ ✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07: the▎ pricing service▎ responded with 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot▎ be combined with items already on sale)▎▎ 1│function applyDiscount(cart: string, code: string) {▎ ›2│ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: t…▎ │^▎ 3│}▎ 4│▎▎ atapplyDiscountserver/api/checkout.ts:2:1▎ atObject.handlerserver/api/checkout.ts:9:1▎ … 5 framework frames↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +logs · follow paused · cli+build+runtime · all levels────────────────────────────────────────────────────────────────────────────────────────────────19:38:52 ➜ DevTools: press Shift + Alt + D in the browser (v3.4.3)19:38:53Plugin "nuxt:devtools:config-retriever" defines Vite-specific hooks (co… +2 lines ×2 Re-optimizing dependencies because vite config has changed Vite client built in 39ms Vite server built in 17ms19:38:54[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines19:38:55GET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"… +2 lines▎ [checkout] prices for cart c_19be07 were cached more than 10 minutes ago,▎ recalculating totals against▎ https://pricing.example.com/v2/carts/c_19be07/recalculate?currency=EUR&include=tax✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07… +13 lines↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +logs · follow paused · cli+build+runtime · all levels────────────────────────────────────────────────────────────────────────────────────────────────19:38:52 ➜ DevTools: press Shift + Alt + D in the browser (v3.4.3)19:38:53Plugin "nuxt:devtools:config-retriever" defines Vite-specific hooks (co… +2 lines ×2 Re-optimizing dependencies because vite config has changed Vite client built in 39ms Vite server built in 17ms19:38:54[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines▎ 19:38:55GET /api/checkout?cart=c_19be07▎ [checkout] loading cart c_19be07 with options▎ {"currency":"EUR","locale":"en-GB","include":["items","discounts","shipping","tax"],▎ "expand":true}[checkout] prices for cart c_19be07 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07… +13 lines↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +logs · follow paused · cli+build+runtime · all levels────────────────────────────────────────────────────────────────────────────────────────────────19:38:52 ➜ DevTools: press Shift + Alt + D in the browser (v3.4.3)19:38:53Plugin "nuxt:devtools:config-retriever" defines Vite-specific hooks (co… +2 lines ×2 Re-optimizing dependencies because vite config has changed Vite client built in 39ms Vite server built in 17ms19:38:54[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines19:38:55GET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"… +2 lines▎ [checkout] prices for cart c_19be07 were cached more than 10 minutes ago,▎ recalculating totals against▎ https://pricing.example.com/v2/carts/c_19be07/recalculate?currency=EUR&include=tax✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07… +13 lines↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +logs · follow paused · cli+build+runtime · all levels──────────────────────────────────────────────────────────────────────────────────────────────── Vite server built in 17ms19:38:54[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines19:38:55GET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"… +2 lines[checkout] prices for cart c_19be07 were cached more than 10 minutes ago, … +2 lines▎ ✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07: the▎ pricing service▎ responded with 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot▎ be combined with items already on sale)▎▎ 1│function applyDiscount(cart: string, code: string) {▎ ›2│ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: t…▎ │^▎ 3│}▎ 4│▎▎ atapplyDiscountserver/api/checkout.ts:2:1▎ atObject.handlerserver/api/checkout.ts:9:1▎ … 5 framework frames↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +logs · follow paused · cli+build+runtime · all levels──────────────────────────────────────────────────────────────────────────────────────────────── Vite server built in 17ms[nitro] Nuxt Nitro server built in 681msGET /api/checkout?cart=c_8f3a21 [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"en-GB",… +2 lines[checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, recalcu… +2 lines✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21: the p… +13 linesGET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"en-GB",… +2 lines[checkout] prices for cart c_19be07 were cached more than 10 minutes ago, recalcu… +2 lines▎ ✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing▎ service responded▎ with 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot be combined with▎ items already on sale)▎▎ 1│function applyDiscount(cart: string, code: string) {▎ ›2│ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pric…▎ │^▎ 3│}▎ 4│▎▎ atapplyDiscountserver/api/checkout.ts:2:1▎ atObject.handlerserver/api/checkout.ts:9:1▎ … 5 framework frames↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose +✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_8f3a21: the p… +13 linesGET /api/checkout?cart=c_19be07 [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"en-GB",… +2 lines[checkout] prices for cart c_19be07 were cached more than 10 minutes ago, recalcu… +2 lines▎ ✖Error(500):Failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing▎ service responded▎ with 422 Unprocessable Entity (the code expired on 2026-09-01 and cannot be combined with▎ items already on sale)▎▎ 1│function applyDiscount(cart: string, code: string) {▎ ›2│ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pric…▎ │^▎ 3│}▎ 4│▎▎ atapplyDiscountserver/api/checkout.ts:2:1▎ atObject.handlerserver/api/checkout.ts:9:1▎ … 5 framework frames↑/↓select · enterdetails · Home/Endtop/live · PgUp/PgDnscroll · eerrors · qclose⣠⣦⣠⡀NuxLocalhttp://localhost:3000/✔ 2 requests 713ms median ✖ 2 failed requests ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_19be07 · 500 · 52msrrestart · oopen · iinfo · llogs · nnetwork · proutes · ?help · qquit + + diff --git a/capture/output/nuxt-dev-logs.txt b/capture/output/nuxt-dev-logs.txt new file mode 100644 index 000000000..fc7cd7cac --- /dev/null +++ b/capture/output/nuxt-dev-logs.txt @@ -0,0 +1,108 @@ +styles: 9b9e87c47014c335 + ➜ DevTools: press Shift + Alt + D in the browser (x.y.z) + GET /api/checkout?cart=c_19be07 + GET /api/checkout?cart=c_8f3a21 + Plugin "nuxt:devtools:config-retriever" defines Vite-specific hooks (co… +2 lines ×2 + Re-optimizing dependencies because vite config has changed + Vite client built in 42 ms + Vite server built in 42 ms + [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"… +2 lines + [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"… +2 lines + [checkout] prices for cart c_19be07 were cached more than 10 minutes ago, … +2 lines + [checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, … +2 lines + [nitro] Nuxt Nitro server built in 42 ms + ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_19be07… +13 lines + ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_8f3a21… +13 lines + │ ^ + 1 │ function applyDiscount(cart: string, code: string) { + 3 │ } + 4 │ + [checkout] loading cart c_19be07 with options {"currency":"EUR","locale":"en-GB",… +2 lines + [checkout] loading cart c_8f3a21 with options {"currency":"EUR","locale":"en-GB",… +2 lines + [checkout] prices for cart c_19be07 were cached more than 10 minutes ago, recalcu… +2 lines + [checkout] prices for cart c_8f3a21 were cached more than 10 minutes ago, recalcu… +2 lines + at Object.handler server/api/checkout.ts:9:1 + at applyDiscount server/api/checkout.ts:2:1 + items already on sale) + with 422 Unprocessable Entity (the code expired on 2026-01-01 and cannot be combined with + … 5 framework frames + › 2 │ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pricin… + ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_8f3a21: the p… +13 lines + Local http://localhost:3000/ + Local http://localhost:3000/ ⠋ + ━━━━━━━━━━━━━━━━━━━━ 0% · 42 ms + ━━━━━━━━━━━━━━━━━━━━ 17% · 42 ms + ━━━━━━━━━━━━━━━━━━━━ 33% · 42 ms + ━━━━━━━━━━━━━━━━━━━━ 50% · 42 ms + ━━━━━━━━━━━━━━━━━━━━ 67% · 42 ms + ━━━━━━━━━━━━━━━━━━━━ 83% · 42 ms + ⚠ 1 warning + ⚠ 2 warnings + ⚠ 2 warnings ✖ 1 error + ✔ 1 request 42 ms median ⚠ 2 warnings ✖ 1 error ✖ 1 failed request + ✔ 1 request 42 ms median ⚠ 3 warnings ✖ 1 error ✖ 1 failed request + ✔ 1 request 42 ms median ⚠ 3 warnings ✖ 2 errors ✖ 1 failed request + ✔ 2 requests 42 ms median ⚠ 3 warnings ✖ 2 errors ✖ 2 failed requests + ✔ 2 requests 42 ms median ✖ 2 failed requests + ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_19be07 · 500 · 42 ms + ERROR a request failed · press n to trace it · GET /api/checkout?cart=c_8f3a21 · 500 · 42 ms + ERROR failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing service respo… + ERROR failed to apply discount code SUMMER-2026 to cart c_8f3a21: the pricing service respo… + GET /api/checkout?cart=c_19be07 + GET /api/checkout?cart=c_8f3a21 + READY watching for changes + STARTING building server + STARTING bundling app + STARTING generating types + STARTING preparing app + STARTING preparing your app + STARTING setting up modules + STARTING starting Nuxt... + Vite server built in 42 ms + [nitro] Nuxt Nitro server built in 42 ms + service responded + ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing + e last error · r restart · o open · i info · l logs · n network · p routes · ? help · q quit + logs · cli+build+runtime · all levels + logs · follow paused · cli+build+runtime · all levels + logs › 12 of 12 · error · runtime · 12:00:00 + o open · i info · l logs · n network · p routes · ? help · q quit + r restart · o open · i info · l logs · n network · p routes · ? help · q quit + ⣠⣦⣠⡀ Nuxt x.y.z + ⣠⣦⣠⡀ Nuxt x.y.z ready in 42 ms +↑/↓ scroll · ←/→ previous/next · y copy · esc back +↑/↓ select · enter details · Home/End top/live · PgUp/PgDn scroll · e errors · q close +↑/↓ select · enter details · Home/End top/live · PgUp/PgDn scroll · e errors · q close ⣠⣦⣠⡀ Nuxt x.y.z +──────────────────────────────────────────────────────────────────────────────────────────────── +▎ +▎ │ ^ +▎ 1 │ function applyDiscount(cart: string, code: string) { +▎ 3 │ } +▎ 4 │ +▎ at Object.handler server/api/checkout.ts:9:1 +▎ at applyDiscount server/api/checkout.ts:2:1 +▎ be combined with items already on sale) +▎ responded with 422 Unprocessable Entity (the code expired on 2026-01-01 and cannot +▎ … 5 framework frames +▎ › 2 │ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: t… +▎ "expand":true} +▎ GET /api/checkout?cart=c_19be07 +▎ [checkout] loading cart c_19be07 with options +▎ [checkout] prices for cart c_19be07 were cached more than 10 minutes ago, +▎ https://pricing.example.com/v2/carts/c_19be07/recalculate?currency=EUR&include=tax +▎ pricing service +▎ recalculating totals against +▎ {"currency":"EUR","locale":"en-GB","include":["items","discounts","shipping","tax"], +▎ ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_19be07: the +▎ │ ^ +▎ 1 │ function applyDiscount(cart: string, code: string) { +▎ 3 │ } +▎ 4 │ +▎ at Object.handler server/api/checkout.ts:9:1 +▎ at applyDiscount server/api/checkout.ts:2:1 +▎ items already on sale) +▎ with 422 Unprocessable Entity (the code expired on 2026-01-01 and cannot be combined with +▎ … 5 framework frames +▎ › 2 │ throw new Error(`Failed to apply discount code ${code} to cart ${cart}: the pric… +▎ service responded +▎ ✖ Error (500): Failed to apply discount code SUMMER-2026 to cart c_19be07: the pricing diff --git a/capture/record.ts b/capture/record.ts index 2845f9c1f..7c47bd5a0 100644 --- a/capture/record.ts +++ b/capture/record.ts @@ -158,7 +158,7 @@ async function runCapture(capture: Capture): Promise { // the SVG deliberately keeps real, so a re-recording only replaces the SVG // when the CLI's actual content changed. if (!values['no-scrub']) { - const fingerprintRules = [...new Set([...scrubRules, ...FINGERPRINT_RULES])] + const fingerprintRules = [...new Set([...scrubRules, ...FINGERPRINT_RULES, ...capture.fingerprint ?? []])] const fingerprint = buildFingerprint(session.chunks, { rows, scrubRules: fingerprintRules }) const fingerprintTarget = join(values.out!, `${capture.id}.txt`) let existing: string | undefined diff --git a/docs/dev.md b/docs/dev.md index 5a159c2a4..63d05d5f1 100644 --- a/docs/dev.md +++ b/docs/dev.md @@ -81,7 +81,7 @@ In an interactive terminal, `nuxt dev` renders a pinned panel: the server URLs, | `y` | Copy the server URL to the clipboard | | `i` | Show versions, URLs, QR code and session info | | `l` | Browse the log history | -| `e` | Open the logs at the last error | +| `e` | Show the last error in full | | `n` | Browse served requests | | `p` | Browse pages and server routes | | `c` | Clear logs, requests and the console | @@ -90,6 +90,14 @@ In an interactive terminal, `nuxt dev` renders a pinned panel: the server URLs, Inside a view, `y` copies the selected row and `shift-y` copies every row the filters and search leave, keeping the newest when there is too much to paste. In the info view, `shift-y` copies the [`nuxt info`](/docs/api/commands/info) table instead. +### Reading logs + +In the log view (`l`), each log takes one row, ending with how many more rows it has. The selected log expands in place, wrapped to the terminal, so moving through the list with `↑`/`↓` reads each one in full. Press `enter` to show the selected log on its own: `↑`/`↓` scroll it, `←`/`→` step to the previous or next log, and `esc` goes back to the list. + +A log's time is shown when it differs from the row above. Press `shift-t` to hide timestamps and give the logs the full width. + +![nuxt dev browsing logs](/capture/output/nuxt-dev-logs.svg) + ### Tracing a request In the network view (`n`), select a request and press `enter` to see where its time went. The trace draws everything the server did for that request on one timeline: route middleware, server route handlers, Nuxt plugins, hooks, data fetching, rendering, and requests your app made to other servers. Below the timeline, it lists how long Vite spent compiling modules for the request, broken down by Vite plugin and slowest module, followed by the logs the request produced. diff --git a/packages/nuxt-cli/src/dev/error-channel.ts b/packages/nuxt-cli/src/dev/error-channel.ts index fd7b4276c..70ef71720 100644 --- a/packages/nuxt-cli/src/dev/error-channel.ts +++ b/packages/nuxt-cli/src/dev/error-channel.ts @@ -267,9 +267,9 @@ function isBuildProgress(progress: unknown): progress is BuildProgress { } /** - * A report as it crosses to the supervisor: the rendering to show it with, plus - * enough to summarise it on a status line. The report itself stays in the - * channel, which serves it from `/history/`. + * A report as it crosses to the supervisor: the rendering to show it with, + * enough to summarise it on a status line, and the report itself so it can be + * laid out again for another width. */ export interface DevReportSummary { id: string @@ -286,6 +286,9 @@ export interface DevReportSummary { request?: string /** The report rendered for a terminal. */ ansi: string + report?: ErrorReport + /** The `cwd` paths in `ansi` are relative to. */ + cwd?: string } /** The compile error a report was caused by, when there is one. */ @@ -327,6 +330,8 @@ export async function summariseReport(report: ErrorReport, context: ReportContex requestId: context.requestId, request: context.request && stripControlChars(context.request), ansi: renderAnsi(report, { cwd }), + report, + cwd, } } diff --git a/packages/nuxt-cli/src/dev/tui/events.ts b/packages/nuxt-cli/src/dev/tui/events.ts index b09a0be21..360589dbe 100644 --- a/packages/nuxt-cli/src/dev/tui/events.ts +++ b/packages/nuxt-cli/src/dev/tui/events.ts @@ -20,6 +20,8 @@ export interface DevLogEvent { rendered?: string /** The message carries its own colours, so severity styling must not be applied. */ styled?: boolean + /** The message laid out for `columns`, for a message its producer wraps to a width. */ + format?: (columns: number) => string /** * Arrivals by each route. One occurrence is one arrival from each, so a log * heard three ways is one entry and two logs that say the same thing stay @@ -359,6 +361,8 @@ export class DevEventLog { if (normaliseMessage(candidate.message).length < normaliseMessage(event.message).length) { candidate.message = event.message candidate.rendered = event.rendered ?? candidate.rendered + candidate.format = event.format + candidate.styled = event.styled } candidate.requestId ??= event.requestId candidate.request ??= event.request diff --git a/packages/nuxt-cli/src/dev/tui/index.ts b/packages/nuxt-cli/src/dev/tui/index.ts index 4ff1d79f4..d097caf35 100644 --- a/packages/nuxt-cli/src/dev/tui/index.ts +++ b/packages/nuxt-cli/src/dev/tui/index.ts @@ -36,6 +36,7 @@ import { LOGO_FRAME_MS } from './logo' import { LogOverlay } from './overlay' import { describeListenURLs, URL_LABELS, URL_STYLES } from './panel' import { readProjectReport } from './project-report' +import { formatReport } from './report-format' import { RequestOverlay } from './request-overlay' import { RequestLog } from './requests' import { RouteOverlay } from './route-overlay' @@ -357,7 +358,7 @@ export function setupDevUI(context: ShortcutContext, options: DevUIOptions = {}) { keys: ['y'], description: 'copy the server URL to the clipboard', action: () => void copyURL(context, showNotice) }, { keys: ['c'], description: 'clear the console without deleting history', action: () => clearConsole(surface) }, { keys: ['x'], description: 'delete log and request history', action: clearHistory }, - { keys: ['e'], description: 'open the logs at the last error', action: () => { + { keys: ['e'], description: 'show the last error in full', action: () => { surface.screenMode = 'alternate-screen' overlay.openAtLastError() } }, @@ -425,7 +426,8 @@ export function setupDevUI(context: ShortcutContext, options: DevUIOptions = {}) for (const held of [...heldNotices]) { dismissHeld(held) } - if (key.meta) { + // Node reports a lone escape with `meta` set. + if (key.meta && key.name !== 'escape') { return } if (key.ctrl) { @@ -643,6 +645,7 @@ export function setupDevUI(context: ShortcutContext, options: DevUIOptions = {}) type: 'error', message: report.ansi, rendered: report.ansi, + format: formatReport(report), styled: true, source: 'runtime', request: report.request, diff --git a/packages/nuxt-cli/src/dev/tui/overlay.ts b/packages/nuxt-cli/src/dev/tui/overlay.ts index 98a97fc4a..ac2e3f268 100644 --- a/packages/nuxt-cli/src/dev/tui/overlay.ts +++ b/packages/nuxt-cli/src/dev/tui/overlay.ts @@ -5,7 +5,7 @@ import type { OverlayEntry } from './screen' import { styleText } from 'node:util' -import { truncate, visibleWidth } from '../../utils/formatting' +import { stripAnsi, truncate, visibleWidth, wrapText } from '../../utils/formatting' import { MUTED, paint } from '../../utils/terminal-theme' import { formatHints, ScreenOverlay } from './screen' @@ -29,6 +29,8 @@ export class LogOverlay extends ScreenOverlay { #events: DevEventLog #sources: Record = { cli: true, build: true, runtime: true } #level: LevelFilter = 'all' + #detail?: DevLogEvent + #timestamps = true constructor(events: DevEventLog, write: (chunk: string) => void, onClose: () => void) { super({ write, onClose, subscribe: listener => events.onEvent(listener) }) @@ -39,17 +41,84 @@ export class LogOverlay extends ScreenOverlay { return ['l'] } - /** Open with the newest error selected. */ + /** Open on the newest error in full. */ openAtLastError(): void { + this.#detail = undefined this.open() - const index = this.#matching().findLastIndex(event => event.level <= 0) - if (index >= 0) { - this.select(index) + const error = this.#matching().findLast(event => event.level <= 0) + if (error) { + this.#showDetail(error) this.repaint() } } + override close(): void { + this.#detail = undefined + super.close() + } + + protected override get scrollsByRow(): boolean { + return !!this.#detail + } + + protected override activate(index: number): boolean { + const event = this.#detail ? undefined : this.#matching()[index] + if (!event) { + return false + } + this.#showDetail(event) + return true + } + + protected override handleNavigationKey(key: Key): boolean { + if (!this.#detail) { + return false + } + switch (key.name) { + case 'escape': + case 'q': + case 'backspace': { + const index = this.#matching().indexOf(this.#detail) + this.#detail = undefined + this.resetScroll() + this.resetSelection() + if (index >= 0) { + this.select(index) + } + break + } + case 'left': + case 'right': { + const matching = this.#matching() + const index = matching.indexOf(this.#detail) + const next = index < 0 ? undefined : matching[index + (key.name === 'left' ? -1 : 1)] + if (!next) { + return true + } + this.#showDetail(next) + break + } + case 'y': + void this.copy(copyText(this.#detail), 'copied') + return true + default: + return false + } + this.repaint() + return true + } + + #showDetail(event: DevLogEvent): void { + this.#detail = event + this.resetSelection() + this.resetScroll() + this.scrollToTop() + } + protected handleViewKey(key: Key): boolean { + if (this.#detail) { + return false + } switch (key.name) { case 'a': return this.#setLevel('all') @@ -58,6 +127,10 @@ export class LogOverlay extends ScreenOverlay { case 'e': return this.#setLevel('error') case 't': + if (key.sequence === 'T') { + this.#timestamps = !this.#timestamps + return true + } return this.#toggleSource('cli') case 'b': return this.#toggleSource('build') @@ -74,6 +147,9 @@ export class LogOverlay extends ScreenOverlay { } protected renderTitle(): string { + if (this.#detail) { + return this.#renderDetailTitle(this.#detail) + } const sources = (['cli', 'build', 'runtime'] as const) .map(source => this.#sources[source] ? styleText('bold', source) : styleText([MUTED, 'strikethrough'], source)) .join(styleText(MUTED, '+')) @@ -84,28 +160,51 @@ export class LogOverlay extends ScreenOverlay { } protected renderEntries(columns: number): OverlayEntry[] { + if (this.#detail) { + return renderDetail(this.#detail, columns) + } const events = this.#matching() let heading: string | undefined + let shownClock: string | undefined return events.map((event) => { const repeated = event.requestId !== undefined && event.requestId === heading heading = event.requestId + let timestamp: FormatEventOptions['timestamp'] = 'hidden' + if (this.#timestamps) { + const clock = formatClock(event.time) + timestamp = clock === shownClock ? 'blank' : 'shown' + if (!repeated) { + shownClock = clock + } + } return { key: event, - lines: formatEvent(event, columns, repeated), - copy: [formatTime(event.time), event.request, event.message].filter(Boolean).join(' '), + lines: formatEvent(event, columns, repeated, { timestamp }), + expand: () => formatEvent(event, columns, repeated, { expanded: true, timestamp }), + copy: copyText(event), } }) } protected renderHints(columns: number): string { + if (this.#detail) { + return formatHints([ + ['↑/↓', 'scroll'], + ['←/→', 'previous/next'], + ['y', 'copy'], + ['esc', 'back'], + ], columns) + } return formatHints([ ['↑/↓', 'select'], + ['enter', 'details'], ['Home/End', 'top/live'], ['PgUp/PgDn', 'scroll'], ['e', 'errors'], ['w', 'warnings'], ['a', 'all'], ['t/b/r', 'cli/build/runtime'], + ['T', 'timestamps'], ['/', 'search'], ['x', 'delete logs'], ['y', 'copy'], @@ -114,6 +213,15 @@ export class LogOverlay extends ScreenOverlay { ], columns) } + #renderDetailTitle(event: DevLogEvent): string { + const matching = this.#matching() + const index = matching.indexOf(event) + const position = index < 0 ? '' : ` ${styleText(MUTED, `› ${index + 1} of ${matching.length}`)}` + const level = colorBySeverity(event.type, { ...event, styled: false }) + const parts = [level, event.source, formatClock(event.time), ...event.tag ? [event.tag] : [], ...event.repeats && event.repeats > 1 ? [`×${event.repeats}`] : []] + return ` ${styleText('bold', 'logs')}${position} · ${parts.join(styleText(MUTED, ' · '))}` + } + #matching(): DevLogEvent[] { const query = this.query return this.#events.recent(SCAN_LIMIT, event => @@ -148,39 +256,101 @@ export function formatTime(time: number): string { return new Date(time).toLocaleTimeString() } -/** Format log rows with timestamps and request headings. */ -export function formatEvent(event: DevLogEvent, columns: number, sameRequest = false): string[] { - const messageColumn = 9 - const date = new Date(event.time) - const clock = [date.getHours(), date.getMinutes(), date.getSeconds()].map(part => String(part).padStart(2, '0')).join(':') - const time = styleText(MUTED, clock) +function formatClock(time: number): string { + const date = new Date(time) + return [date.getHours(), date.getMinutes(), date.getSeconds()].map(part => String(part).padStart(2, '0')).join(':') +} + +function copyText(event: DevLogEvent): string { + return [formatTime(event.time), event.request, event.message].filter(Boolean).join(' ') +} + +/** One log in full, wrapped to the view: its request, then every line of the message. */ +function renderDetail(event: DevLogEvent, columns: number): OverlayEntry[] { + const width = Math.max(1, columns - 1) + const lines = [ + ...event.request ? [...wrapText(event.request, width).map(line => styleText(['magenta', 'bold'], line)), ''] : [], + ...wrapText(trimBlankLines(event.format?.(width) ?? event.message), width).map(line => colorBySeverity(line, event)), + ] + return lines.map(line => ({ lines: [line] })) +} + +function trimBlankLines(message: string): string { + const lines = message.split('\n') + const blank = (line: string) => !stripAnsi(line).trim() + const start = lines.findIndex(line => !blank(line)) + const end = lines.findLastIndex(line => !blank(line)) + if (start < 0) { + return '' + } + const escapes = (rows: string[]) => rows.join('').replace(/\s/g, '') + return escapes(lines.slice(0, start)) + lines.slice(start, end + 1).join('\n') + escapes(lines.slice(end + 1)) +} + +export interface FormatEventOptions { + /** Show every line of the log, wrapped, rather than one row. */ + expanded?: boolean + /** `blank` keeps the column for a time already shown on the row above. */ + timestamp?: 'shown' | 'blank' | 'hidden' +} + +/** + * Format log rows with timestamps and request headings. + * + * Collapsed, a log takes one row (and its request heading), ending with how + * many more rows it has. Expanded, every line of it is shown, wrapped. + */ +export function formatEvent(event: DevLogEvent, columns: number, sameRequest = false, options: FormatEventOptions = {}): string[] { + const timestamp = options.timestamp ?? 'shown' + const messageColumn = timestamp !== 'hidden' ? 9 : event.request ? 2 : 0 + const clock = formatClock(event.time) + const time = timestamp === 'hidden' ? '' : timestamp === 'blank' ? `${' '.repeat(clock.length)} ` : `${styleText(MUTED, clock)} ` const budget = columns - messageColumn - 1 const indent = ' '.repeat(messageColumn) const marker = event.repeats && event.repeats > 1 ? styleText(MUTED, ` ×${event.repeats}`) : '' const markerWidth = event.repeats && event.repeats > 1 ? ` ×${event.repeats}`.length : 0 - const firstLineWidth = visibleWidth(event.message.split('\n', 1)[0] ?? '') - const tagRoom = Math.max(Math.floor(budget / 2), budget - markerWidth - firstLineWidth - 1) - const tag = event.tag && !event.request ? styleText(MUTED, `[${truncate(event.tag, Math.max(1, tagRoom - 2))}] `) : '' + const [first = '', ...rest] = trimBlankLines(event.format?.(Math.max(1, budget)) ?? event.message).split('\n') + const tagRoom = Math.max(Math.floor(budget / 2), budget - markerWidth - visibleWidth(first) - 1) + let tag = event.tag && !event.request ? styleText(MUTED, `[${truncate(event.tag, Math.max(1, tagRoom - 2))}] `) : '' const tagWidth = visibleWidth(tag) - const lines = event.message - .split('\n') - .map((line, index) => { - const room = Math.max(1, budget - (index === 0 ? markerWidth + tagWidth : 0)) - const text = colorBySeverity(truncate(line, room), event) - return index === 0 ? `${text}${marker}` : text - }) + const firstRoom = Math.max(1, budget - markerWidth - tagWidth) + const head = wrapText(first, firstRoom) + const body = rest.flatMap(line => wrapText(line, Math.max(1, budget))) + + let lines: string[] + if (options.expanded) { + lines = [ + ...head.map((row, index) => index === 0 ? `${colorBySeverity(row, event)}${marker}` : ' '.repeat(tagWidth) + colorBySeverity(row, event)), + ...body.map(row => colorBySeverity(row, event)), + ] + } + else { + const hidden = head.length - 1 + body.length + let more = hidden ? ` +${hidden} ${hidden === 1 ? 'line' : 'lines'}` : '' + if (more && firstRoom - more.length < 1) { + more = ` +${hidden}` + } + const shortfall = 1 - (firstRoom - more.length) + if (shortfall > 0 && tag) { + const room = tagWidth - shortfall - 3 + tag = room >= 1 ? styleText(MUTED, `[${truncate(event.tag!, room)}] `) : '' + } + const textRoom = Math.max(1, budget - markerWidth - visibleWidth(tag) - more.length) + const text = colorBySeverity(truncate(first, textRoom), event) + lines = [`${text}${more ? styleText(MUTED, more) : ''}${marker}`] + } if (event.request) { return [ - ...sameRequest ? [] : [`${time} ${styleText(['magenta', 'bold'], event.request)}`], + ...sameRequest ? [] : [`${time}${styleText(['magenta', 'bold'], event.request)}`], ...lines.map(line => `${indent}${line}`), ] } - return lines.map((line, index) => index === 0 ? `${time} ${tag}${line}` : `${indent}${line}`) + return lines.map((line, index) => index === 0 ? `${time}${tag}${line}` : `${indent}${line}`) } /** Colour a message by its level, unless it already carries its own colour. */ diff --git a/packages/nuxt-cli/src/dev/tui/report-format.ts b/packages/nuxt-cli/src/dev/tui/report-format.ts new file mode 100644 index 000000000..31bcda255 --- /dev/null +++ b/packages/nuxt-cli/src/dev/tui/report-format.ts @@ -0,0 +1,29 @@ +import type { DevReportSummary } from '../error-channel' + +let renderAnsi: typeof import('my-bad').renderAnsi | undefined + +/** + * Lay a report out for `columns`. Its own rendering stands in until `my-bad` + * has loaded, and for a summary that arrived without its report. + */ +export function formatReport(summary: DevReportSummary): (columns: number) => string { + const report = summary.report + if (!report) { + return () => summary.ansi + } + if (!renderAnsi) { + void import('my-bad').then((module) => { + renderAnsi = module.renderAnsi + }).catch(() => {}) + } + let last: { columns: number, text: string } | undefined + return (columns) => { + if (!renderAnsi) { + return summary.ansi + } + if (last?.columns !== columns) { + last = { columns, text: renderAnsi(report, { cwd: summary.cwd, width: columns }) } + } + return last.text + } +} diff --git a/packages/nuxt-cli/src/dev/tui/request-overlay.ts b/packages/nuxt-cli/src/dev/tui/request-overlay.ts index d34903cc6..c87323a59 100644 --- a/packages/nuxt-cli/src/dev/tui/request-overlay.ts +++ b/packages/nuxt-cli/src/dev/tui/request-overlay.ts @@ -174,6 +174,7 @@ export class RequestOverlay extends ScreenOverlay { return [...summary, ...events.map(event => ({ key: event, lines: formatEvent(event, columns, true), + expand: () => formatEvent(event, columns, true, { expanded: true }), copy: [formatTime(event.time), event.message].filter(Boolean).join(' '), }))] } diff --git a/packages/nuxt-cli/src/dev/tui/screen.ts b/packages/nuxt-cli/src/dev/tui/screen.ts index 0eeb2c6d3..2edaefd9f 100644 --- a/packages/nuxt-cli/src/dev/tui/screen.ts +++ b/packages/nuxt-cli/src/dev/tui/screen.ts @@ -20,6 +20,8 @@ const GUTTER_WIDTH = 2 export interface OverlayEntry { lines: string[] + /** Lines shown in place of `lines` while the entry is selected. */ + expand?: () => string[] /** Stable entry identity. */ key?: object | string /** Plain text put on the clipboard when this entry is copied. */ @@ -73,6 +75,11 @@ export abstract class ScreenOverlay { return false } + /** Arrow and page keys scroll rows instead of moving a selection. */ + protected get scrollsByRow(): boolean { + return false + } + /** Handle enter on the selected entry; return `true` to consume it. Copy is the fallback. */ protected activate(_index: number): boolean { return false @@ -125,13 +132,13 @@ export abstract class ScreenOverlay { } handleKey(key: Key): void { - if (key.ctrl || key.meta) { + if (key.ctrl || (key.meta && key.name !== 'escape')) { return } if (this.#searching) { return this.#handleSearchKey(key) } - if (key.sequence === '/') { + if (key.sequence === '/' && !this.scrollsByRow) { this.#searching = true return this.render() } @@ -141,6 +148,9 @@ export abstract class ScreenOverlay { } const page = Math.max(1, this.bodyRows() - 1) + if (this.scrollsByRow && this.#handleScrollKey(key, page)) { + return this.render() + } switch (key.name) { case 'q': case 'escape': @@ -195,6 +205,41 @@ export abstract class ScreenOverlay { this.render() } + #handleScrollKey(key: Key, page: number): boolean { + switch (key.name) { + case 'up': + case 'k': + this.#scroll(-1) + return true + case 'down': + case 'j': + this.#scroll(1) + return true + case 'pageup': + this.#scroll(-page) + return true + case 'pagedown': + this.#scroll(page) + return true + case 'home': + this.#scroll(Number.NEGATIVE_INFINITY) + return true + case 'end': + this.resetScroll() + return true + case 'g': + if (key.sequence === 'G') { + this.resetScroll() + } + else { + this.#scroll(Number.NEGATIVE_INFINITY) + } + return true + default: + return false + } + } + /** Rows available for content, once the title, rule and hints are taken. */ protected bodyRows(): number { return Math.max(1, (process.stdout.rows || 24) - 3) @@ -247,6 +292,13 @@ export abstract class ScreenOverlay { this.#revealSelection = false } + /** Stop following and show the first row. */ + protected scrollToTop(): void { + this.#following = false + this.#top = 0 + this.#anchor = undefined + } + protected resetSelection(): void { this.#selected = undefined this.#selectedKey = undefined @@ -263,7 +315,7 @@ export abstract class ScreenOverlay { const columns = process.stdout.columns || 80 const bodyRows = this.bodyRows() - const entries = this.#entries() + let entries = this.#entries() if (!this.#revealSelection && this.#selectedKey !== undefined) { const index = entries.findIndex(entry => entry.key === this.#selectedKey) this.#selected = index < 0 ? undefined : index @@ -272,6 +324,7 @@ export abstract class ScreenOverlay { this.#selected = entries.length ? Math.min(this.#selected, entries.length - 1) : undefined } this.#selectedKey = this.#selected === undefined ? undefined : entries[this.#selected]?.key + entries = this.#expandSelected(entries) const rows: string[] = [] let selectedRows: { start: number, end: number } | undefined @@ -333,8 +386,17 @@ export abstract class ScreenOverlay { return this.renderEntries((process.stdout.columns || 80) - GUTTER_WIDTH) } + /** The entries with the selected one in its expanded form. */ + #expandSelected(entries: OverlayEntry[]): OverlayEntry[] { + const selected = this.#selected === undefined ? undefined : entries[this.#selected] + if (!selected?.expand) { + return entries + } + return entries.with(this.#selected!, { ...selected, lines: selected.expand() }) + } + #move(delta: number): void { - const entries = this.#entries() + const entries = this.#expandSelected(this.#entries()) if (!entries.length) { return } @@ -346,12 +408,26 @@ export abstract class ScreenOverlay { this.select(Math.min(Math.max(this.#selected + delta, 0), entries.length - 1)) } - #page(delta: number): void { - const entries = this.#entries() + #scroll(delta: number, entries = this.#entries()): number { const rows = entries.reduce((total, entry) => total + entry.lines.length, 0) this.#following = false this.#top = Math.min(Math.max(0, this.#top + delta), Math.max(0, rows - this.bodyRows())) this.#anchor = this.#rowAnchor(entries, this.#top) + return rows + } + + #page(delta: number): void { + const entries = this.#expandSelected(this.#entries()) + const rows = this.#scroll(delta, entries) + if (this.#selected !== undefined) { + const start = entries.slice(0, this.#selected).reduce((total, entry) => total + entry.lines.length, 0) + const end = start + (entries[this.#selected]?.lines.length ?? 0) + const visible = start < this.#top + this.bodyRows() && end > this.#top + if (visible && end - start > this.bodyRows()) { + this.#revealSelection = false + return + } + } this.#selected = this.#rowAnchor(entries, delta < 0 ? this.#top : Math.min(rows - 1, this.#top + this.bodyRows() - 1))?.index this.#selectedKey = this.#selected === undefined ? undefined : entries[this.#selected]?.key this.#revealSelection = false @@ -374,7 +450,7 @@ export abstract class ScreenOverlay { this.notify('nothing selected to copy') return } - await this.#copy(text, 'copied') + await this.copy(text, 'copied') } async #copyAll(): Promise { @@ -387,7 +463,7 @@ export abstract class ScreenOverlay { return } if (custom) { - return this.#copy(custom.slice(0, COPY_ALL_MAX_CHARS), 'copied') + return this.copy(custom.slice(0, COPY_ALL_MAX_CHARS), 'copied') } const texts = this.#entries().map(entry => entry.copy).filter(text => !!text) as string[] if (!texts.length) { @@ -401,10 +477,11 @@ export abstract class ScreenOverlay { } const kept = start === texts.length ? [texts.at(-1)!.slice(0, COPY_ALL_MAX_CHARS)] : texts.slice(start) const count = kept.length === texts.length ? `${kept.length}` : `the last ${kept.length} of ${texts.length}` - await this.#copy(kept.join('\n'), `copied ${count} ${texts.length === 1 ? 'entry' : 'entries'}`) + await this.copy(kept.join('\n'), `copied ${count} ${texts.length === 1 ? 'entry' : 'entries'}`) } - async #copy(text: string, done: string): Promise { + /** Put `text` on the clipboard and report `done` in the hint line. */ + protected async copy(text: string, done: string): Promise { this.notify(await writeClipboard(stripAnsi(text)) ? `${done} to clipboard` : 'no clipboard available') } diff --git a/packages/nuxt-cli/src/utils/formatting.ts b/packages/nuxt-cli/src/utils/formatting.ts index c09ed0f07..71083eb48 100644 --- a/packages/nuxt-cli/src/utils/formatting.ts +++ b/packages/nuxt-cli/src/utils/formatting.ts @@ -13,6 +13,7 @@ export function terminalLink(label: string, url: string, options: { stream?: { i // eslint-disable-next-line no-control-regex const ANSI_RE = /\u001B\[[0-9;]*m|\u001B\]8;[^\u0007]*\u0007/g +const ANSI_AT_RE = new RegExp(ANSI_RE.source, 'y') // eslint-disable-next-line no-control-regex const CONTROL_RE = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g // eslint-disable-next-line no-control-regex @@ -102,6 +103,146 @@ export function truncate(text: string, columns: number): string { return `${text.slice(0, index)}\u2026${linked ? LINK_TERMINATOR : ''}${styled ? '\u001B[0m' : ''}` } +/** + * Wrap each line of `text` to `columns`, breaking at spaces where possible. + * Continuation rows keep the line's own indentation, and styling or a link + * that spans a break is closed at the end of the row and reopened on the next. + */ +export function wrapText(text: string, columns: number): string[] { + const width = Math.max(1, columns) + return text.split('\n').flatMap(line => wrapLine(line, width)) +} + +interface Atom { + text: string + /** Absent on an escape sequence. */ + width?: number +} + +function atomise(line: string): Atom[] { + const atoms: Atom[] = [] + let index = 0 + while (index < line.length) { + ANSI_AT_RE.lastIndex = index + const match = ANSI_AT_RE.exec(line) + if (match) { + atoms.push({ text: match[0] }) + index += match[0].length + continue + } + const char = String.fromCodePoint(line.codePointAt(index)!) + atoms.push({ text: char, width: char.charCodeAt(0) < 0x300 ? 1 : charWidth(char) }) + index += char.length + } + return atoms +} + +type SgrState = ReadonlyMap + +const SGR_ON: Record = { 1: 'bold', 2: 'dim', 3: 'italic', 4: 'underline', 5: 'blink', 7: 'inverse', 8: 'hidden', 9: 'strike' } +const SGR_OFF: Record = { 22: ['bold', 'dim'], 23: ['italic'], 24: ['underline'], 25: ['blink'], 27: ['inverse'], 28: ['hidden'], 29: ['strike'], 39: ['fg'], 49: ['bg'] } + +/** The attributes still active after `sequence`, keyed by what each one sets. */ +function applySgr(state: SgrState, sequence: string): SgrState { + const params = sequence.slice(2, -1).split(';').map(param => Number(param || 0)) + const next = new Map(state) + for (let index = 0; index < params.length; index++) { + const code = params[index]! + if (code === 0) { + next.clear() + } + else if (SGR_ON[code]) { + next.set(SGR_ON[code], String(code)) + } + else if (SGR_OFF[code]) { + SGR_OFF[code].forEach(slot => next.delete(slot)) + } + else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) { + next.set('fg', String(code)) + } + else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) { + next.set('bg', String(code)) + } + else if ((code === 38 || code === 48) && (params[index + 1] === 5 || params[index + 1] === 2)) { + const length = params[index + 1] === 5 ? 3 : 5 + next.set(code === 38 ? 'fg' : 'bg', params.slice(index, index + length).join(';')) + index += length - 1 + } + else { + next.set(`other:${code}`, String(code)) + } + } + return next +} + +function wrapLine(line: string, columns: number): string[] { + if (visibleWidth(line) <= columns) { + return [line] + } + const leading = /^\s*/.exec(stripAnsi(line))![0].length + const hanging = ' '.repeat(leading < columns / 2 ? leading : 0) + + const rows: string[] = [] + let sgr: SgrState = new Map() + let link: string | undefined + let row = '' + let used = 0 + /** The row holds something other than spaces, so breaking it makes progress. */ + let worded = false + /** Where the row can be broken at its last space, and the state to resume with. */ + let breakpoint: { at: number, used: number, atom: number, sgr: SgrState, link?: string } | undefined + + const atoms = atomise(line) + const closing = (state: { sgr: SgrState, link?: string }) => `${state.link ? LINK_TERMINATOR : ''}${state.sgr.size ? '\u001B[0m' : ''}` + const reopen = (state: { sgr: SgrState, link?: string }) => `${hanging}${state.sgr.size ? `\u001B[${[...state.sgr.values()].join(';')}m` : ''}${state.link ?? ''}` + + for (let index = 0; index < atoms.length; index++) { + const atom = atoms[index]! + if (atom.width === undefined) { + if (atom.text.startsWith('\u001B]8;')) { + link = atom.text === LINK_TERMINATOR ? undefined : atom.text + } + else { + sgr = applySgr(sgr, atom.text) + } + row += atom.text + continue + } + if (used + atom.width > columns && used > hanging.length) { + if (atom.text !== ' ' && breakpoint && breakpoint.used > hanging.length) { + const state = { sgr: breakpoint.sgr, link: breakpoint.link } + rows.push(row.slice(0, breakpoint.at).trimEnd() + closing(state)) + row = reopen(state) + used = hanging.length + worded = false + sgr = state.sgr + link = state.link + index = breakpoint.atom + breakpoint = undefined + continue + } + rows.push(row.trimEnd() + closing({ sgr, link })) + row = reopen({ sgr, link }) + used = hanging.length + worded = false + breakpoint = undefined + if (atom.text === ' ') { + continue + } + } + row += atom.text + used += atom.width + if (atom.text !== ' ') { + worded = true + } + else if (worded) { + breakpoint = { at: row.length, used, atom: index, sgr, link } + } + } + rows.push(row) + return rows +} + /** Lower-case a leading capital, leaving acronyms alone. */ export function decapitalise(text: string): string { return /^[A-Z][a-z]/.test(text) ? text[0]!.toLowerCase() + text.slice(1) : text diff --git a/packages/nuxt-cli/test/unit/dev-tui.spec.ts b/packages/nuxt-cli/test/unit/dev-tui.spec.ts index 22da1e7d3..4383746be 100644 --- a/packages/nuxt-cli/test/unit/dev-tui.spec.ts +++ b/packages/nuxt-cli/test/unit/dev-tui.spec.ts @@ -613,6 +613,16 @@ describe('dev event log', () => { expect(log.recent(10)).toHaveLength(1) }) + it('should keep the layout of the longer wording a repeated error is folded into', () => { + const log = new DevEventLog() + const now = Date.now() + const format = () => 'laid out' + log.push(event({ time: now, level: 0, type: 'error', message: 'Failed to apply the discount code', source: 'runtime' })) + log.push(event({ time: now, level: 0, type: 'error', message: 'Failed to apply the discount code\n at handler (server/api/x.ts:3:9)', source: 'runtime', format, styled: true })) + expect(log.recent(10)).toHaveLength(1) + expect(log.recent(10)[0]).toMatchObject({ format, styled: true }) + }) + it('should pair a forwarded log with its own printed log and leave the rest', () => { const log = new DevEventLog() log.push(event({ time: Date.now(), level: 0, type: 'error', message: 'boom happened here today', source: 'build' })) @@ -938,7 +948,47 @@ describe('log overlay', () => { it('counts the tag against the width a message is cut to', () => { const [line] = formatEvent(event({ tag: '@nuxt/content', message: 'Processed 2 collections and 0 files in 59.89ms (0 cached, 0 parsed)' }), 60) expect(strip(line!).length).toBeLessThanOrEqual(60) - expect(strip(line!)).toMatch(/^\d{2}:\d{2}:\d{2} \[@nuxt\/content\] Processed .*…$/) + expect(strip(line!)).toMatch(/^\d{2}:\d{2}:\d{2} \[@nuxt\/content\] Processed .*… \+2 lines$/) + }) + + it('collapses a log to one row that says how many more it has', () => { + const lines = formatEvent(event({ message: `${'word '.repeat(20)}\n second\n third\n` }), 60) + expect(lines).toHaveLength(1) + expect(strip(lines[0]!).length).toBeLessThanOrEqual(60) + expect(strip(lines[0]!)).toMatch(/^\d{2}:\d{2}:\d{2} word .*… \+3 lines$/) + }) + + it('wraps every line of an expanded log instead of cutting it', () => { + const message = `${'word '.repeat(20).trim()}\n ${'more '.repeat(20).trim()}` + const lines = formatEvent(event({ message }), 60, false, { expanded: true }).map(strip) + expect(lines.length).toBeGreaterThan(2) + expect(lines.join('')).not.toContain('…') + expect(lines.join(' ').replace(/\s+/g, ' ')).toContain(message.replace(/\s+/g, ' ')) + for (const line of lines) { + expect(line.length).toBeLessThanOrEqual(60) + } + }) + + it('lays out a log for the width it is shown at, when it can be', () => { + const widths: number[] = [] + const format = (columns: number) => { + widths.push(columns) + return `laid out for ${columns}` + } + const [line] = formatEvent(event({ message: 'laid out for 80', format }), 60) + expect(strip(line!)).toContain(`laid out for ${widths[0]}`) + expect(widths[0]).toBeLessThan(60) + }) + + it('lays an error report out again for the width it is shown at', async () => { + const { createCliReport, summariseReport } = await import('../../src/dev/error-channel') + const { formatReport } = await import('../../src/dev/tui/report-format') + const summary = await summariseReport(await createCliReport(new Error(`Failed to apply discount code SUMMER-2026: ${'the pricing service declined it '.repeat(6)}`))) + const format = formatReport(summary) + await vi.waitFor(() => expect(format(120)).not.toBe(summary.ansi)) + const rows = (columns: number) => format(columns).split('\n').length + expect(rows(50)).toBeGreaterThan(rows(120)) + expect(strip(format(50))).toContain('SUMMER-2026') }) it('keeps the repeat marker when a long tag leaves little room', () => { @@ -947,6 +997,19 @@ describe('log overlay', () => { expect(strip(line!)).toMatch(/^\d{2}:\d{2}:\d{2} \[nuxt:\S*…\] \S.* ×12$/) }) + it('fits the hidden line count and repeat marker on a narrow collapsed row', () => { + for (let columns = 22; columns <= 40; columns++) { + const [line] = formatEvent(event({ tag: 'nuxt:devtools:config-retriever', message: 'defines Vite-specific options', repeats: 12 }), columns) + expect(strip(line!).length).toBeLessThanOrEqual(columns) + expect(strip(line!)).toMatch(/ \+\d.* ×12$/) + } + }) + + it('keeps the styling of blank rows it trims', () => { + const styled = event({ message: '\u001B[31m\nboom\n\u001B[39m', styled: true }) + expect(formatEvent(styled, 40, false, { timestamp: 'hidden' })).toEqual(['\u001B[31mboom\u001B[39m']) + }) + it('keeps a long tag whole when the message leaves room for it', () => { const [line] = formatEvent(event({ tag: 'nuxt:devtools:config-retriever', message: 'ok' }), 58) expect(strip(line!)).toMatch(/^\d{2}:\d{2}:\d{2} \[nuxt:devtools:config-retriever\] ok$/) @@ -978,16 +1041,167 @@ describe('log overlay', () => { } }) - it('opens focused on the newest error', () => { + it('opens on the newest error in full', () => { const events = new DevEventLog() events.push(event({ message: 'all fine' })) events.push(event({ message: 'boom', level: 0, type: 'error' })) events.push(event({ message: 'afterwards' })) const { overlay, lastFrame } = create(events) overlay.openAtLastError() + expect(strip(lastFrame()).split('\n')[0]).toContain('2 of 3 · error') + expect(strip(lastFrame())).toContain('boom') + expect(strip(lastFrame())).not.toContain('afterwards') + + overlay.handleKey({ name: 'escape' }) const selected = strip(lastFrame()).split('\n').filter(line => line.startsWith('▎')) expect(selected.join('\n')).toContain('boom') - expect(selected.join('\n')).not.toContain('afterwards') + expect(overlay.isOpen).toBe(true) + + overlay.handleKey({ name: 'return' }) + overlay.handleKey({ name: 'l' }) + expect(overlay.isOpen).toBe(false) + overlay.open() + expect(strip(lastFrame())).toContain('afterwards') + overlay.close() + }) + + it('wraps a long request in the detail view', () => { + const events = new DevEventLog() + events.push(event({ request: `GET /api/${'c'.repeat(60)}?cart=last`, requestId: '1', message: 'boom', level: 0, type: 'error' })) + const columns = Object.getOwnPropertyDescriptor(process.stdout, 'columns') + Object.defineProperty(process.stdout, 'columns', { value: 40, configurable: true }) + const { overlay, lastFrame } = create(events) + try { + overlay.openAtLastError() + expect(strip(lastFrame()).replace(/\n\s*/g, '')).toContain(`GET/api/${'c'.repeat(60)}?cart=last`) + } + finally { + overlay.close() + if (columns) { + Object.defineProperty(process.stdout, 'columns', columns) + } + else { + Reflect.deleteProperty(process.stdout, 'columns') + } + } + }) + + it('keeps a tall selected entry expanded while paging through it', () => { + const events = new DevEventLog() + const rows = (process.stdout.rows || 24) - 3 + events.push(event({ message: 'short' })) + events.push(event({ message: Array.from({ length: rows * 3 }, (_, i) => `stack ${i}`).join('\n') })) + events.push(event({ message: 'last' })) + const { overlay, lastFrame } = create(events) + overlay.open() + overlay.handleKey({ name: 'home' }) + overlay.handleKey({ name: 'down' }) + for (let page = 0; page < 3; page++) { + overlay.handleKey({ name: 'pagedown' }) + } + const body = strip(lastFrame()).split('\n').slice(2, 2 + rows) + expect(body.at(-2)).toContain(`stack ${rows * 3 - 1}`) + expect(body.at(-1)).toContain('last') + overlay.close() + }) + + it('shows a time only where it differs from the row above', () => { + const events = new DevEventLog() + events.push(event({ time: 1000, message: 'first' })) + events.push(event({ time: 1500, message: 'same second', request: 'GET /x', requestId: 'r1' })) + events.push(event({ time: 3000, message: 'still in request', request: 'GET /x', requestId: 'r1' })) + events.push(event({ time: 3000, message: 'later' })) + const { overlay, lastFrame } = create(events) + overlay.open() + const rows = strip(lastFrame()).split('\n').slice(2, 7) + expect(rows[0]).toMatch(/^ {2}\d{2}:\d{2}:01 first$/) + expect(rows.slice(1, 4)).toEqual([`${' '.repeat(11)}GET /x`, `${' '.repeat(11)}same second`, `${' '.repeat(11)}still in request`]) + expect(rows[4]).toMatch(/^ {2}\d{2}:\d{2}:03 later$/) + overlay.close() + }) + + it('hides timestamps with shift-t and keeps t for cli logs', () => { + const events = new DevEventLog() + events.push(event({ message: 'plain' })) + events.push(event({ message: 'handled', request: 'GET /x', requestId: 'r1', source: 'runtime' })) + const { overlay, lastFrame } = create(events) + overlay.open() + overlay.handleKey({ name: 't', sequence: 'T' }) + const rows = strip(lastFrame()).split('\n').slice(2, 5) + expect(rows).toEqual([' plain', ' GET /x', ' handled']) + expect(strip(lastFrame()).split('\n')[0]).toContain('cli+build+runtime') + + overlay.handleKey({ name: 't', sequence: 'T' }) + expect(strip(lastFrame()).split('\n')[2]).toMatch(/^ {2}\d{2}:\d{2}:\d{2} plain$/) + overlay.close() + }) + + it('expands only the selected entry', () => { + const events = new DevEventLog() + events.push(event({ message: 'first\nfirst more' })) + events.push(event({ message: 'second\nsecond more' })) + const { overlay, lastFrame } = create(events) + overlay.open() + expect(strip(lastFrame())).not.toContain(' more') + overlay.handleKey({ name: 'up' }) + expect(strip(lastFrame())).toContain('second more') + expect(strip(lastFrame())).toContain('first +1 line') + overlay.handleKey({ name: 'up' }) + expect(strip(lastFrame())).toContain('first more') + expect(strip(lastFrame())).toContain('second +1 line') + overlay.close() + }) + + it('shows a log in full on enter, scrolling by row and stepping between logs', async () => { + const events = new DevEventLog() + const rows = (process.stdout.rows || 24) - 3 + events.push(event({ message: 'before' })) + events.push(event({ message: Array.from({ length: rows * 2 }, (_, i) => `row ${i}`).join('\n'), request: 'GET /tall', requestId: 'r1' })) + events.push(event({ message: 'after' })) + const { overlay, lastFrame } = create(events) + const body = () => strip(lastFrame()).split('\n').slice(2, 2 + rows) + overlay.open() + overlay.handleKey({ name: 'up' }) + overlay.handleKey({ name: 'up' }) + overlay.handleKey({ name: 'return' }) + expect(strip(lastFrame()).split('\n')[0]).toContain('2 of 3') + expect(body()[0]).toContain('GET /tall') + expect(body()).toContain(' row 0') + + overlay.handleKey({ name: 'down' }) + overlay.handleKey({ name: 'down' }) + expect(body()[0]).toBe(' row 0') + overlay.handleKey({ name: 'up' }) + expect(body()[0]).toBe(' ') + overlay.handleKey({ name: 'pagedown' }) + expect(body()[0]).toBe(` row ${rows - 2}`) + overlay.handleKey({ name: 'pageup' }) + expect(body()[0]).toBe(' ') + overlay.handleKey({ sequence: '/' }) + overlay.handleKey({ name: 'x', sequence: 'x' }) + expect(strip(lastFrame())).not.toContain('search') + expect(body()[0]).toBe(' ') + overlay.handleKey({ name: 'end' }) + expect(body().at(-1)).toBe(` row ${rows * 2 - 1}`) + overlay.handleKey({ name: 'home' }) + expect(body()[0]).toContain('GET /tall') + expect(lastFrame()).not.toContain('\u258E') + + overlay.handleKey({ name: 'right' }) + expect(strip(lastFrame()).split('\n')[0]).toContain('3 of 3') + expect(body()[0]).toContain('after') + overlay.handleKey({ name: 'right' }) + expect(strip(lastFrame()).split('\n')[0]).toContain('3 of 3') + + overlay.handleKey({ name: 'y' }) + await vi.waitFor(() => expect(copied).toEqual([expect.stringContaining('after')])) + + overlay.handleKey({ name: 'left' }) + overlay.handleKey({ name: 'escape' }) + const selected = strip(lastFrame()).split('\n').filter(line => line.startsWith('▎')) + expect(selected.join('\n')).toContain('GET /tall') + expect(selected.join('\n')).toContain('row 1') + overlay.close() }) it('closes a hyperlink cut in half, so the rest of the line is not linked', () => { @@ -1002,8 +1216,8 @@ describe('log overlay', () => { const [line] = formatEvent(styled as any, 40) expect(strip(line!).length).toBeLessThanOrEqual(40) // The cut must not swallow the reset, or everything after stays green. - expect(line!.endsWith('\u001B[0m')).toBe(true) - expect(strip(line!)).toContain('DevTools: press Shift') + expect(line).toContain('…\u001B[0m') + expect(strip(line!)).toContain('DevTools: press') }) function create(events = new DevEventLog()) { @@ -1285,7 +1499,7 @@ describe('log overlay', () => { overlay.handleKey({ name: 'pageup' }) expect(body()[0]).toContain(`row ${rows - 1}`) overlay.handleKey({ name: 'end' }) - expect(body().at(-1)).toContain(`row ${rows * 3 - 1}`) + expect(body().filter(Boolean)).toEqual([expect.stringMatching(new RegExp(`row 0 \\+${rows * 3 - 1} lines$`))]) expect(strip(lastFrame())).not.toContain('paused') overlay.close() }) @@ -1299,8 +1513,12 @@ describe('log overlay', () => { const { overlay, lastFrame } = create(events) overlay.open() overlay.handleKey({ name: 'home' }) + overlay.handleKey({ name: 'down' }) + expect(strip(lastFrame()).split('\n')[2]).toContain('stack 0') overlay.handleKey({ name: 'pagedown' }) - expect(strip(lastFrame()).split('\n')[2]).toContain(`stack ${rows - 2}`) + expect(strip(lastFrame()).split('\n')[2]).toContain(`stack ${rows - 1}`) + overlay.handleKey({ name: 'pageup' }) + expect(strip(lastFrame()).split('\n')[2]).toContain('stack 0') overlay.handleKey({ name: 'pageup' }) expect(strip(lastFrame()).split('\n')[2]).toContain('short') overlay.close() @@ -1318,7 +1536,7 @@ describe('log overlay', () => { overlay.handleKey({ name: 'pageup' }) const before = body() events.push(event({ message: 'new arrival\nsecond row' })) - await vi.waitFor(() => expect(strip(lastFrame())).toContain(`↓${rows + 1} rows below`)) + await vi.waitFor(() => expect(strip(lastFrame())).toContain(`↓${rows} rows below`)) expect(body()).toBe(before) overlay.handleKey({ name: 'end' }) expect(body()).toContain('new arrival') @@ -1521,7 +1739,7 @@ describe('log overlay', () => { const { overlay, lastFrame } = create(events) overlay.open() overlay.handleKey({ name: 'up' }) - overlay.handleKey({ name: 'return' }) + overlay.handleKey({ name: 'y' }) await vi.waitFor(() => expect(copied).toHaveLength(1)) expect(copied[0]).toContain('GET /x') @@ -1765,7 +1983,7 @@ describe('request overlay', () => { const { log, overlay, lastFrame } = create({ events }) const now = Date.now() events.push({ time: now, level: 2, type: 'log', message: 'rendering /', source: 'runtime', request: 'GET /', requestId: 'r7' }) - events.push({ time: now, level: 0, type: 'error', message: 'Invalid end tag.', source: 'runtime', request: 'GET /', requestId: 'r7' }) + events.push({ time: now, level: 0, type: 'error', message: 'Invalid end tag.\n at index.vue:1:1', source: 'runtime', request: 'GET /', requestId: 'r7' }) events.push({ time: now, level: 2, type: 'log', message: 'unrelated', source: 'runtime', request: 'GET /other', requestId: 'r8' }) log.push([{ id: 'r7', time: now, method: 'GET', url: '/', status: 500, duration: 20 }]) overlay.open() @@ -1773,7 +1991,10 @@ describe('request overlay', () => { overlay.handleKey({ name: 'down' }) overlay.handleKey({ name: 'return' }) expect(lastFrame()).toContain('trace') - expect(lastFrame()).toContain('Invalid end tag.') + expect(strip(lastFrame())).toContain('Invalid end tag. +1 line') + expect(strip(lastFrame())).not.toContain('at index.vue:1:1') + overlay.handleKey({ name: 'up' }) + expect(strip(lastFrame())).toContain('at index.vue:1:1') expect(lastFrame()).toContain('rendering /') expect(lastFrame()).not.toContain('unrelated') @@ -3061,6 +3282,17 @@ describe('panel shortcut routing', () => { } }) + it('closes a view with escape as the terminal reports it', async () => { + await withPanel(async (_ui, settle) => { + const leaves = (frame: string) => frame.split('\u001B[?1049l').length - 1 + process.stdin.emit('keypress', 'l', { name: 'l', sequence: 'l' }) + const open = await settle() + expect(open).toContain('cli+build+runtime') + process.stdin.emit('keypress', '\u001B', { name: 'escape', meta: true, sequence: '\u001B' }) + expect(leaves(await settle())).toBe(leaves(open) + 1) + }) + }) + it('quits with Ctrl-D from search inside a view', async () => { const interrupt = vi.fn() process.on('SIGINT', interrupt) diff --git a/packages/nuxt-cli/test/unit/dev/tui-fuzz.spec.ts b/packages/nuxt-cli/test/unit/dev/tui-fuzz.spec.ts index 71916d848..58392f8fb 100644 --- a/packages/nuxt-cli/test/unit/dev/tui-fuzz.spec.ts +++ b/packages/nuxt-cli/test/unit/dev/tui-fuzz.spec.ts @@ -4,7 +4,7 @@ import fc from 'fast-check' import { describe, expect, it } from 'vitest' import { renderPanel } from '../../../src/dev/tui/panel' -import { stripAnsi, truncate, visibleWidth } from '../../../src/utils/formatting' +import { stripAnsi, truncate, visibleWidth, wrapText } from '../../../src/utils/formatting' const RUNS = Number(process.env.NUXT_CLI_FUZZ_RUNS) || 500 @@ -69,6 +69,34 @@ describe('truncate', () => { }) }) +describe('wrapText', () => { + const lines = fc.array(fc.tuple(fc.constantFrom('', ' ', ' '), styledText).map(([indent, text]) => indent + text), { maxLength: 4 }).map(parts => parts.join('\n')) + + it('should never exceed the requested number of columns', () => { + fc.assert(fc.property(lines, fc.integer({ min: 2, max: 40 }), (text, columns) => { + for (const row of wrapText(text, columns)) { + expect(visibleWidth(row)).toBeLessThanOrEqual(columns) + } + }), { numRuns: RUNS }) + }) + + it('should keep every visible character', () => { + fc.assert(fc.property(lines, fc.integer({ min: 2, max: 40 }), (text, columns) => { + const visible = (value: string) => stripAnsi(value).replace(/\s+/g, '') + expect(visible(wrapText(text, columns).join('\n'))).toBe(visible(text)) + }), { numRuns: RUNS }) + }) + + it('should close a hyperlink on every row it breaks', () => { + fc.assert(fc.property(styledText, fc.integer({ min: 2, max: 40 }), (text, columns) => { + fc.pre(!leavesLinkOpen(text)) + for (const row of wrapText(text, columns)) { + expect(leavesLinkOpen(row)).toBe(false) + } + }), { numRuns: RUNS }) + }) +}) + const url = fc.record({ label: fc.constantFrom('Local', 'Network', 'Tunnel', 'Public', 'A rather long label'), url: fc.constantFrom('http://localhost:3000/', 'http://192.168.1.4:3000/', `http://${'x'.repeat(60)}.example.com:3000/some/deep/path`), diff --git a/packages/nuxt-cli/test/unit/utils/formatting.spec.ts b/packages/nuxt-cli/test/unit/utils/formatting.spec.ts index 313974a60..57cb38cb5 100644 --- a/packages/nuxt-cli/test/unit/utils/formatting.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/formatting.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { formatBytes, formatDuration, stripControlChars, truncate, visibleWidth } from '../../../src/utils/formatting' +import { formatBytes, formatDuration, stripControlChars, truncate, visibleWidth, wrapText } from '../../../src/utils/formatting' describe('stripControlChars', () => { it('should leave no escape sequence behind, nested or not', () => { @@ -50,6 +50,39 @@ describe('formatBytes', () => { }) }) +describe('wrapText', () => { + it('should break at spaces and keep the line\'s indentation', () => { + expect(wrapText(' at handler (server/api/checkout.ts:9:1)', 24)).toEqual([ + ' at handler', + ' (server/api/checkout', + ' .ts:9:1)', + ]) + }) + + it('should break continuation rows at spaces when the indentation is too deep to keep', () => { + expect(wrapText(' aa bbbbb cccccc', 10)).toEqual([' aa', 'bbbbb', 'cccccc']) + }) + + it('should reopen styling and links on the next row', () => { + const link = '\u001B]8;;file:///a.ts\u0007' + expect(wrapText(`\u001B[31m${link}one two\u001B]8;;\u0007\u001B[39m`, 4)).toEqual([ + `\u001B[31m${link}one\u001B]8;;\u0007\u001B[0m`, + `\u001B[31m${link}two\u001B]8;;\u0007\u001B[39m`, + ]) + }) + + it('should reopen only the styling still active at the break', () => { + expect(wrapText('\u001B[1m\u001B[31mone\u001B[39m two', 4)).toEqual([ + '\u001B[1m\u001B[31mone\u001B[39m\u001B[0m', + '\u001B[1mtwo', + ]) + expect(wrapText('\u001B[38;5;208;4mone two', 4)).toEqual([ + '\u001B[38;5;208;4mone\u001B[0m', + '\u001B[38;5;208;4mtwo', + ]) + }) +}) + describe('formatDuration', () => { it('should render milliseconds below a second', () => { expect(formatDuration(-1)).toBe('0.0ms')