Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
50 changes: 34 additions & 16 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, unknown>): 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<void> {
const cli = yargs(hideBin(argv))
const cli = yargs(hideBin(argv).map(protectStdinArg))
.scriptName('trace-engine-cli')
.usage('$0 [command] <file> [options]')
.middleware(restoreStdinArg)
.option('format', {
alias: 'f',
type: 'string',
Expand All @@ -125,7 +143,7 @@ export async function runCli(argv: string[]): Promise<void> {
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,
})
Expand Down Expand Up @@ -159,7 +177,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -220,7 +238,7 @@ export async function runCli(argv: string[]): Promise<void> {
'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,
}),
Expand All @@ -236,7 +254,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -288,7 +306,7 @@ export async function runCli(argv: string[]): Promise<void> {
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,
})
Expand Down Expand Up @@ -351,7 +369,7 @@ export async function runCli(argv: string[]): Promise<void> {
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,
})
Expand Down Expand Up @@ -406,7 +424,7 @@ export async function runCli(argv: string[]): Promise<void> {
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,
})
Expand Down Expand Up @@ -460,7 +478,7 @@ export async function runCli(argv: string[]): Promise<void> {
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,
})
Expand Down Expand Up @@ -521,7 +539,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -553,7 +571,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -612,7 +630,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -644,7 +662,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -684,7 +702,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down Expand Up @@ -753,7 +771,7 @@ export async function runCli(argv: string[]): Promise<void> {
(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,
})
Expand Down
61 changes: 43 additions & 18 deletions src/engine/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -22,6 +24,10 @@ export type ParsedTrace = NonNullable<
ReturnType<InstanceType<TraceEngine['TraceModel']['Model']>['parsedTrace']>
>;

export const STDIN_PATH = '-';

type StdinStream = Readable & { isTTY?: boolean };

export interface LoadedTrace {
engine: TraceEngine;
parsedTrace: ParsedTrace;
Expand Down Expand Up @@ -95,6 +101,35 @@ function isLanternError(arg: unknown): boolean {
return false;
}

async function readStdin(stdin: StdinStream): Promise<Buffer> {
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.
*
Expand All @@ -104,33 +139,23 @@ 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.
*/
export async function loadTraceFromFile(
filePath: string,
customEnginePath?: string,
stdin: StdinStream = process.stdin,
): Promise<LoadedTrace> {
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);
Expand Down
17 changes: 17 additions & 0 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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');
});
});
32 changes: 31 additions & 1 deletion test/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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/,
});
});
});