From fd021d5059d563b341bb62610b502ccca29c70d3 Mon Sep 17 00:00:00 2001 From: Joan Leon Date: Tue, 24 Nov 2026 19:35:35 +0100 Subject: [PATCH] Read the trace from stdin when the file argument is - Every command that takes a single trace file accepts `-` to read the trace from stdin, as plain JSON or gzip data. An empty stdin or an interactive terminal fails with a clear message instead of waiting for input. yargs re-parses positionals as `--file -` and does not take a lone `-` as a value, so the CLI replaces it with a placeholder before parsing and restores it in a middleware. --- README.md | 7 +++++++ src/cli.ts | 50 ++++++++++++++++++++++++++++++-------------- src/engine/loader.ts | 41 +++++++++++++++++++++++++++++------- test/cli.test.ts | 17 +++++++++++++++ test/loader.test.ts | 32 +++++++++++++++++++++++++++- 5 files changed, 122 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 4802c86..4e22099 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,13 @@ trace-engine-cli trace.json.gz --format md trace-engine-cli --help ``` +Pass `-` as the file to read the trace from stdin. Plain JSON and gzip data are both accepted. `scan` reads files and directories only. + +```bash +cat trace.json.gz | trace-engine-cli - +curl -s https://example.com/trace.json | trace-engine-cli tasks - --top 5 +``` + ### Global Options | Option | Type | Default | Description | diff --git a/src/cli.ts b/src/cli.ts index c9238da..cba546a 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -34,7 +34,7 @@ import { extractScheduling } from './engine/extractors/scheduling.js'; import { extractShifts } from './engine/extractors/shifts.js'; import { extractTasks } from './engine/extractors/tasks.js'; import { listRendererThreads } from './engine/helpers.js'; -import { loadTraceFromFile } from './engine/loader.js'; +import { loadTraceFromFile, STDIN_PATH } from './engine/loader.js'; import type { ThreadsResult } from './engine/types.js'; import { type FormatOptions, formatResult } from './formatters/index.js'; import { parseTimeRange, parseTimeValue, resolveTimeRange } from './utils/filter.js'; @@ -83,10 +83,28 @@ function parseReportSections(value?: string): ReportSection[] { }); } +// yargs re-parses positionals as `--file -` and never takes a lone `-` as a value. +const STDIN_ARG_PLACEHOLDER = '\0stdin'; + +function protectStdinArg(arg: string): string { + return arg === STDIN_PATH ? STDIN_ARG_PLACEHOLDER : arg; +} + +function restoreStdinArg(argv: Record): void { + for (const [key, value] of Object.entries(argv)) { + if (value === STDIN_ARG_PLACEHOLDER) { + argv[key] = STDIN_PATH; + } else if (Array.isArray(value)) { + argv[key] = value.map((item) => (item === STDIN_ARG_PLACEHOLDER ? STDIN_PATH : item)); + } + } +} + export async function runCli(argv: string[]): Promise { - const cli = yargs(hideBin(argv)) + const cli = yargs(hideBin(argv).map(protectStdinArg)) .scriptName('trace-engine-cli') .usage('$0 [command] [options]') + .middleware(restoreStdinArg) .option('format', { alias: 'f', type: 'string', @@ -114,7 +132,7 @@ export async function runCli(argv: string[]): Promise { 'High-level trace metadata, Core Web Vitals, and main thread category breakdown (default command)', (y) => y.option('thread', THREAD_OPTION).positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }), @@ -146,7 +164,7 @@ export async function runCli(argv: string[]): Promise { (y) => y .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -187,7 +205,7 @@ export async function runCli(argv: string[]): Promise { 'List renderer threads, their frame URLs, and CPU sample availability', (y) => y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }), @@ -203,7 +221,7 @@ export async function runCli(argv: string[]): Promise { (y) => y .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -253,7 +271,7 @@ export async function runCli(argv: string[]): Promise { y .option('thread', THREAD_OPTION) .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -313,7 +331,7 @@ export async function runCli(argv: string[]): Promise { y .option('thread', THREAD_OPTION) .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -366,7 +384,7 @@ export async function runCli(argv: string[]): Promise { y .option('thread', THREAD_OPTION) .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -418,7 +436,7 @@ export async function runCli(argv: string[]): Promise { y .option('thread', THREAD_OPTION) .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -477,7 +495,7 @@ export async function runCli(argv: string[]): Promise { 'Async task and animation frame scheduling, cancellation, and churn metrics', (y) => y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }), @@ -507,7 +525,7 @@ export async function runCli(argv: string[]): Promise { (y) => y .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -563,7 +581,7 @@ export async function runCli(argv: string[]): Promise { 'User interaction latencies and target DOM elements', (y) => y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }), @@ -593,7 +611,7 @@ export async function runCli(argv: string[]): Promise { (y) => y .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -631,7 +649,7 @@ export async function runCli(argv: string[]): Promise { (y) => y .positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }) @@ -697,7 +715,7 @@ export async function runCli(argv: string[]): Promise { 'List all navigations in the trace and their InsightSet mappings', (y) => y.positional('file', { - describe: 'Path to trace file (.json or .json.gz)', + describe: 'Path to trace file (.json or .json.gz), or - to read from stdin', type: 'string', demandOption: true, }), diff --git a/src/engine/loader.ts b/src/engine/loader.ts index 11782e4..9370596 100644 --- a/src/engine/loader.ts +++ b/src/engine/loader.ts @@ -14,6 +14,8 @@ import fs from 'node:fs'; import path from 'node:path'; +import type { Readable } from 'node:stream'; +import { buffer as readStream } from 'node:stream/consumers'; import zlib from 'node:zlib'; import { loadTraceEngine, type TraceEngine } from './adapter.js'; import { PAGE_TRACE_CAPTURE_HINT } from './helpers.js'; @@ -22,6 +24,10 @@ export type ParsedTrace = NonNullable< ReturnType['parsedTrace']> >; +export const STDIN_PATH = '-'; + +type StdinStream = Readable & { isTTY?: boolean }; + export interface LoadedTrace { engine: TraceEngine; parsedTrace: ParsedTrace; @@ -109,15 +115,22 @@ function isLanternError(arg: unknown): boolean { * @returns Object containing the TraceEngine instance, parsedTrace data, and rawEvents. * @throws {Error} If the file does not exist, is invalid JSON, or lacks trace events. */ -export async function loadTraceFromFile( - filePath: string, - customEnginePath?: string, -): Promise { - const absolutePath = path.resolve(process.cwd(), filePath); - let rawBuffer: Buffer; +async function readStdin(stdin: StdinStream): Promise { + if (stdin.isTTY) { + throw new Error( + 'No trace data on stdin. Pipe a trace into the command, for example: cat trace.json.gz | trace-engine-cli -', + ); + } + const data = await readStream(stdin); + if (data.length === 0) { + throw new Error('No trace data received on stdin.'); + } + return data; +} +function readTraceFile(filePath: string, absolutePath: string): Buffer { try { - rawBuffer = fs.readFileSync(absolutePath); + return fs.readFileSync(absolutePath); } catch (err: unknown) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') { throw new Error(`Trace file not found: ${absolutePath}`); @@ -129,8 +142,20 @@ export async function loadTraceFromFile( } throw err; } +} - const jsonContent = decompressTraceBuffer(rawBuffer, absolutePath); +export async function loadTraceFromFile( + filePath: string, + customEnginePath?: string, + stdin: StdinStream = process.stdin, +): Promise { + let jsonContent: string; + if (filePath === STDIN_PATH) { + jsonContent = decompressTraceBuffer(await readStdin(stdin)); + } else { + const absolutePath = path.resolve(process.cwd(), filePath); + jsonContent = decompressTraceBuffer(readTraceFile(filePath, absolutePath), absolutePath); + } const rawEvents = parseTraceJson(jsonContent); const engine = await loadTraceEngine(customEnginePath); diff --git a/test/cli.test.ts b/test/cli.test.ts index 142515c..a811764 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -13,6 +13,8 @@ // limitations under the License. import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; @@ -442,3 +444,18 @@ describe('CLI Dispatcher', () => { ); }); }); + +describe('CLI stdin input', () => { + test('reads a piped trace when the file argument is -', () => { + const repoRoot = path.resolve(import.meta.dirname, '..'); + const fixturePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json.gz'); + const result = spawnSync( + process.execPath, + ['--import', 'tsx/esm', 'bin/trace-engine-cli.ts', 'overview', '-', '--format', 'json'], + { cwd: repoRoot, input: readFileSync(fixturePath), encoding: 'utf-8' }, + ); + + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout).mainUrl, 'https://example.com/test'); + }); +}); diff --git a/test/loader.test.ts b/test/loader.test.ts index 08d1eb9..1585ae6 100644 --- a/test/loader.test.ts +++ b/test/loader.test.ts @@ -13,9 +13,10 @@ // limitations under the License. import assert from 'node:assert/strict'; -import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; +import { Readable } from 'node:stream'; import test, { describe } from 'node:test'; import { isGzipBuffer, loadTraceFromFile, parseTraceJson } from '../src/engine/loader.js'; @@ -100,4 +101,33 @@ describe('Trace Loader', () => { message: /Trace file not found/, }); }); + + test('loadTraceFromFile reads JSON from stdin when the path is -', async () => { + const fixturePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json'); + const stdin = Readable.from([await readFile(fixturePath)]); + const loaded = await loadTraceFromFile('-', undefined, stdin); + + assert.equal(loaded.parsedTrace.data.Meta.mainFrameURL, 'https://example.com/test'); + }); + + test('loadTraceFromFile reads gzip data from stdin when the path is -', async () => { + const fixturePath = path.resolve(import.meta.dirname, 'fixtures/basic-trace.json.gz'); + const stdin = Readable.from([await readFile(fixturePath)]); + const loaded = await loadTraceFromFile('-', undefined, stdin); + + assert.equal(loaded.parsedTrace.data.Meta.mainFrameURL, 'https://example.com/test'); + }); + + test('loadTraceFromFile rejects empty stdin', async () => { + await assert.rejects(() => loadTraceFromFile('-', undefined, Readable.from([])), { + message: /^No trace data received on stdin\./, + }); + }); + + test('loadTraceFromFile rejects stdin from an interactive terminal', async () => { + const stdin = Object.assign(Readable.from([]), { isTTY: true }); + await assert.rejects(() => loadTraceFromFile('-', undefined, stdin), { + message: /^No trace data on stdin\. Pipe a trace into the command/, + }); + }); });