diff --git a/README.md b/README.md index fb40acc..c5c0d73 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,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 970e38c..9d835f4 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 { type ExtractTasksOptions, 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'; @@ -103,10 +103,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', @@ -125,7 +143,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, }) @@ -159,7 +177,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, }) @@ -220,7 +238,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, }), @@ -236,7 +254,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, }) @@ -288,7 +306,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, }) @@ -351,7 +369,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, }) @@ -406,7 +424,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, }) @@ -460,7 +478,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, }) @@ -521,7 +539,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, }) @@ -553,7 +571,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, }) @@ -612,7 +630,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, }) @@ -644,7 +662,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, }) @@ -684,7 +702,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, }) @@ -753,7 +771,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, }) diff --git a/src/engine/loader.ts b/src/engine/loader.ts index 11782e4..fc752bc 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; @@ -95,6 +101,35 @@ function isLanternError(arg: unknown): boolean { return false; } +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 { + return fs.readFileSync(absolutePath); + } catch (err: unknown) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') { + throw new Error(`Trace file not found: ${absolutePath}`); + } + if ((err as NodeJS.ErrnoException).code === 'EISDIR') { + throw new Error( + `'${filePath}' is a directory. Trace engine commands accept a single trace file. To search across multiple files or directories, use: trace-engine-cli scan "${filePath}" [options]`, + ); + } + throw err; + } +} + /** * Loads, decompresses, and parses a Chromium performance trace file using DevTools Trace Engine. * @@ -104,7 +139,7 @@ function isLanternError(arg: unknown): boolean { * - Normalizes `parsedTrace` retrieval via `model.parsedTrace(0)`. * - Filters internal non-fatal Lantern simulation errors during model parsing. * - * @param filePath - Relative or absolute path to the trace file. + * @param filePath - Relative or absolute path to the trace file, or `-` to read from stdin. * @param customEnginePath - Optional custom Trace Engine bundle path. * @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. @@ -112,25 +147,15 @@ function isLanternError(arg: unknown): boolean { export async function loadTraceFromFile( filePath: string, customEnginePath?: string, + stdin: StdinStream = process.stdin, ): Promise { - const absolutePath = path.resolve(process.cwd(), filePath); - let rawBuffer: Buffer; - - try { - rawBuffer = fs.readFileSync(absolutePath); - } catch (err: unknown) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') { - throw new Error(`Trace file not found: ${absolutePath}`); - } - if ((err as NodeJS.ErrnoException).code === 'EISDIR') { - throw new Error( - `'${filePath}' is a directory. Trace engine commands accept a single trace file. To search across multiple files or directories, use: trace-engine-cli scan "${filePath}" [options]`, - ); - } - throw err; + 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 jsonContent = decompressTraceBuffer(rawBuffer, absolutePath); const rawEvents = parseTraceJson(jsonContent); const engine = await loadTraceEngine(customEnginePath); diff --git a/test/cli.test.ts b/test/cli.test.ts index 993a26b..8786516 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'; @@ -623,3 +625,18 @@ describe('CLI option validation', () => { ); }); }); + +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/, + }); + }); });