diff --git a/docs/cli.md b/docs/cli.md index 6434e6dd4c..f6e7912e2e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -109,6 +109,16 @@ chrome-devtools evaluate_script "() => self.registration.scope" --serviceWorkerI chrome-devtools lighthouse_audit 1 --mode snapshot ``` +**Logpoints:** + +```sh +# Set a logpoint on page 1 +chrome-devtools set_logpoints 1 "src/app.ts:42 'total', cart.total" + +# Remove all logpoints on page 1 +chrome-devtools set_logpoints 1 +``` + ## Output format By default, the CLI outputs a human-readable summary of the tool's result. For programmatic use, you can request raw JSON: diff --git a/scripts/generate-cli.ts b/scripts/generate-cli.ts index f83e965514..32213de561 100644 --- a/scripts/generate-cli.ts +++ b/scripts/generate-cli.ts @@ -39,6 +39,7 @@ interface CliOption { description: string; required: boolean; positional: boolean; + minItems?: number; default?: unknown; enum?: unknown[]; } @@ -48,6 +49,7 @@ interface JsonSchema { description?: string; properties?: Record; required?: string[]; + minItems?: number; default?: unknown; enum?: unknown[]; } @@ -73,6 +75,7 @@ function schemaToCLIOptions(toolName: string, schema: JsonSchema): CliOption[] { required: isRequired, positional: isRequired || OPTIONAL_POSITIONAL_ARGS.has(`${toolName}:${name}`), + minItems: prop.minItems, default: prop.default, enum: prop.enum, }; @@ -189,6 +192,8 @@ export interface ArgDef { required: boolean; /** Whether the arg is a positional on the command line, otherwise a flag. */ positional: boolean; + /** Minimum number of items for array args, from JSON Schema minItems. */ + minItems?: number; default?: string | number | boolean; enum?: ReadonlyArray; } diff --git a/skills/chrome-devtools-cli/SKILL.md b/skills/chrome-devtools-cli/SKILL.md index 0e028ba767..e0965576e8 100644 --- a/skills/chrome-devtools-cli/SKILL.md +++ b/skills/chrome-devtools-cli/SKILL.md @@ -158,6 +158,8 @@ chrome-devtools list_console_messages 1 # List all console messages chrome-devtools list_console_messages 1 --pageSize 20 --pageIdx 1 # List console messages with pagination chrome-devtools list_console_messages 1 --types error --types info # Filter console messages by type chrome-devtools list_console_messages 1 --includePreservedMessages true # Include preserved messages +chrome-devtools set_logpoints 1 "src/app.ts:42 'total', cart.total" # Set logpoints on page 1 +chrome-devtools set_logpoints 1 # Remove all logpoints on page 1 chrome-devtools take_screenshot 1 # Take a screenshot of the page viewport chrome-devtools take_screenshot 1 --fullPage true --format "jpeg" --quality 80 # Take a full page screenshot as JPEG with quality chrome-devtools take_screenshot 1 --uid "id" --filePath "s.png" # Take a screenshot of an element diff --git a/src/bin/chrome-devtools.ts b/src/bin/chrome-devtools.ts index 82edf8e260..841ee668f3 100644 --- a/src/bin/chrome-devtools.ts +++ b/src/bin/chrome-devtools.ts @@ -8,8 +8,6 @@ import process from 'node:process'; -import type {Options, PositionalOptions} from 'yargs'; - import { startDaemon, stopDaemon, @@ -33,6 +31,7 @@ import {VERSION} from '../version.js'; import { buildCommand, getCommandArgSpec, + registerCommandArgs, shieldLiteralArgs, } from '../config/cli-commands.js'; import {commands} from '../config/cli-options.js'; @@ -216,44 +215,7 @@ for (const [commandName, commandDef] of Object.entries(commands)) { choices: ['md', 'json'], default: 'md', }); - for (const [argName, opt] of Object.entries(args)) { - const type = - opt.type === 'integer' || opt.type === 'number' - ? 'number' - : opt.type === 'boolean' - ? 'boolean' - : opt.type === 'array' - ? 'array' - : 'string'; - - if (opt.positional) { - const options: PositionalOptions = { - describe: opt.description, - type: type as PositionalOptions['type'], - }; - if (opt.default !== undefined) { - options.default = opt.default; - } - if (opt.enum) { - options.choices = opt.enum as Array; - } - y.positional(argName, options); - } else { - const options: Options = { - describe: opt.description, - type: type as Options['type'], - }; - if (opt.default !== undefined) { - // Document the default in --help without populating argv, so the - // daemon applies its current tool schema and config defaults. - options.defaultDescription = JSON.stringify(opt.default); - } - if (opt.enum) { - options.choices = opt.enum as Array; - } - y.option(argName, options); - } - } + registerCommandArgs(y, args); }, async argv => { const sessionId = argv.sessionId as string; diff --git a/src/config/cli-commands.ts b/src/config/cli-commands.ts index 4dab7f1f22..564cf5ab10 100644 --- a/src/config/cli-commands.ts +++ b/src/config/cli-commands.ts @@ -4,6 +4,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +import type {Argv, Options, PositionalOptions} from 'yargs'; + import type {ArgDef} from './cli-options.js'; /** @@ -13,6 +15,9 @@ import type {ArgDef} from './cli-options.js'; * part of the command string yargs parses each one as a trailing positional, * and a variadic positional has to be the last one. Which args are positional * is decided at build time by `scripts/generate-cli.ts`. + * + * A required positional array without `minItems > 0` is rendered as `[name..]` + * so omitting it passes an empty array instead of failing yargs validation. */ export function buildCommand( commandName: string, @@ -23,16 +28,70 @@ export function buildCommand( for (const [name, arg] of Object.entries(args)) { if (!arg.positional) { flags += ` [--${name}]`; + } else if (arg.type === 'array') { + const requiresItem = arg.required && (arg.minItems ?? 0) > 0; + command += requiresItem ? ` <${name}..>` : ` [${name}..]`; } else if (arg.required) { - command += arg.type === 'array' ? ` <${name}..>` : ` <${name}>`; + command += ` <${name}>`; } else { - command += arg.type === 'array' ? ` [${name}..]` : ` [${name}]`; + command += ` [${name}]`; } } return {command, usage: `$0 ${command}${flags}`}; } +/** Maps a non-array JSON Schema type to the yargs type that parses it. */ +function toYargsScalarType(type: string): 'number' | 'boolean' | 'string' { + if (type === 'integer' || type === 'number') { + return 'number'; + } + return type === 'boolean' ? 'boolean' : 'string'; +} + +/** + * Registers positional and flag definitions for a tool command on a yargs + * builder instance. + */ +export function registerCommandArgs( + y: Argv, + args: Record, +): void { + for (const [argName, opt] of Object.entries(args)) { + if (opt.positional) { + const options: PositionalOptions = { + describe: opt.description, + }; + if (opt.type === 'array') { + options.array = true; + } else { + options.type = toYargsScalarType(opt.type); + } + if (opt.default !== undefined) { + options.default = opt.default; + } + if (opt.enum) { + options.choices = opt.enum; + } + y.positional(argName, options); + } else { + const options: Options = { + describe: opt.description, + type: opt.type === 'array' ? 'array' : toYargsScalarType(opt.type), + }; + if (opt.default !== undefined) { + // Document the default in --help without populating argv, so the + // daemon applies its current tool schema and config defaults. + options.defaultDescription = JSON.stringify(opt.default); + } + if (opt.enum) { + options.choices = opt.enum; + } + y.option(argName, options); + } + } +} + /** * How an option takes its value. `text` is a free-form string, which can start * with `-`. `value` is any other single value: a number or one of a fixed set diff --git a/src/config/cli-options.ts b/src/config/cli-options.ts index d811c7b45b..54f256a149 100644 --- a/src/config/cli-options.ts +++ b/src/config/cli-options.ts @@ -17,6 +17,8 @@ export interface ArgDef { required: boolean; /** Whether the arg is a positional on the command line, otherwise a flag. */ positional: boolean; + /** Minimum number of items for array args, from JSON Schema minItems. */ + minItems?: number; default?: string | number | boolean; enum?: ReadonlyArray; } @@ -2297,6 +2299,7 @@ export const commands: Commands = { 'One or more files paths to upload. File paths have to be local to the browser instance (not the MCP).', required: true, positional: true, + minItems: 1, }, includeSnapshot: { name: 'includeSnapshot', diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 303a523305..31309fe3d7 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -22,9 +22,11 @@ import { import { buildCommand, getCommandArgSpec, + registerCommandArgs, shieldLiteralArgs, } from '../src/config/cli-commands.js'; import {commands} from '../src/config/cli-options.js'; +import {yargs} from '../src/third_party/cli.js'; import {computeFlagUsage} from '../src/telemetry/flagUtils.js'; import {puppeteerOptions} from '../src/config/puppeteer-options.js'; @@ -1366,6 +1368,11 @@ describe('cli args parsing', () => { describe('cli command strings', () => { const required = {description: '', required: true, positional: true}; const dummyArgsVariadic = { + arg1: {name: 'arg1', type: 'string', ...required}, + arrArg: {name: 'arrArg', type: 'array', minItems: 1, ...required}, + }; + + const dummyArgsVariadicAllowEmpty = { arg1: {name: 'arg1', type: 'string', ...required}, arrArg: {name: 'arrArg', type: 'array', ...required}, }; @@ -1386,11 +1393,16 @@ describe('cli command strings', () => { }, }; - it('renders a required array arg as a variadic positional', () => { + it('renders a required array arg with minItems > 0 as a required variadic positional', () => { const {command} = buildCommand('dummy_cmd', dummyArgsVariadic); assert.strictEqual(command, 'dummy_cmd '); }); + it('renders a required array arg without minItems as an optional variadic positional', () => { + const {command} = buildCommand('dummy_cmd', dummyArgsVariadicAllowEmpty); + assert.strictEqual(command, 'dummy_cmd [arrArg..]'); + }); + it('renders required non-array args as plain positionals', () => { const {command} = buildCommand('dummy_cmd', dummyArgsPlain); assert.strictEqual(command, 'dummy_cmd '); @@ -1424,7 +1436,7 @@ describe('cli command strings', () => { ); // yargs only allows a variadic positional as the last one. - const variadic = command.indexOf('..>'); + const variadic = command.search(/\.\.[>\]]/); assert.ok( variadic === -1 || variadic === command.length - 3, `${name}: a variadic positional must be last`, @@ -1433,9 +1445,11 @@ describe('cli command strings', () => { // A required array arg the daemon receives as a string fails validation. for (const [argName, arg] of Object.entries(args)) { if (arg.required && arg.type === 'array') { + const expected = + (arg.minItems ?? 0) > 0 ? `<${argName}..>` : `[${argName}..]`; assert.ok( - command.includes(`<${argName}..>`), - `${name}: required array arg ${argName} must be variadic`, + command.includes(expected), + `${name}: required array arg ${argName} must be variadic (${expected})`, ); } } @@ -1443,6 +1457,132 @@ describe('cli command strings', () => { }); }); +describe('cli command parsing', () => { + const mockCommands: typeof commands = { + allow_empty_array: { + description: 'Command whose required array arg allows empty arrays', + category: 'Test', + args: { + id: { + name: 'id', + type: 'number', + description: '', + required: true, + positional: true, + }, + items: { + name: 'items', + type: 'array', + description: '', + required: true, + positional: true, + }, + }, + }, + require_non_empty_array: { + description: + 'Command whose required array arg requires at least one item', + category: 'Test', + args: { + id: { + name: 'id', + type: 'number', + description: '', + required: true, + positional: true, + }, + items: { + name: 'items', + type: 'array', + description: '', + required: true, + positional: true, + minItems: 1, + }, + }, + }, + }; + + function parseToolCommand(rawArgs: string[]): Record { + const {argv: cliArgs, restore} = shieldLiteralArgs(rawArgs, commandName => { + const commandDef = mockCommands[commandName]; + return commandDef ? getCommandArgSpec(commandDef.args) : undefined; + }); + + let parsedArgs: Record | undefined; + const parser = yargs(cliArgs) + .locale('en') + .exitProcess(false) + .strict() + .fail((msg, err) => { + throw err ?? new Error(msg); + }); + + for (const [commandName, commandDef] of Object.entries(mockCommands)) { + const {command, usage} = buildCommand(commandName, commandDef.args); + parser.command( + command, + commandDef.description, + y => { + y.usage(usage); + y.option('output-format', { + choices: ['md', 'json'], + default: 'md', + }); + registerCommandArgs(y, commandDef.args); + }, + argv => { + const commandArgs: Record = {}; + for (const argName of Object.keys(commandDef.args)) { + if (argName in argv) { + commandArgs[argName] = restore(argv[argName]); + } + } + parsedArgs = commandArgs; + }, + ); + } + + parser.parse(); + assert.ok(parsedArgs, `Command did not match: ${rawArgs.join(' ')}`); + return parsedArgs; + } + + it('parses an omitted variadic array arg without minItems as an empty array', () => { + assert.deepStrictEqual(parseToolCommand(['allow_empty_array', '2']), { + id: 2, + items: [], + }); + }); + + it('parses an omitted variadic array arg as empty when followed by flags', () => { + assert.deepStrictEqual( + parseToolCommand(['allow_empty_array', '2', '--output-format', 'json']), + { + id: 2, + items: [], + }, + ); + }); + + it('parses multiple items for an optional variadic array arg', () => { + assert.deepStrictEqual( + parseToolCommand(['allow_empty_array', '2', 'first', 'second']), + { + id: 2, + items: ['first', 'second'], + }, + ); + }); + + it('rejects an omitted variadic array arg when minItems > 0', () => { + assert.throws( + () => parseToolCommand(['require_non_empty_array', '2']), + /Not enough non-option arguments/, + ); + }); +}); + describe('cli literal args', () => { const getSpec = (name: string) => name in commands ? getCommandArgSpec(commands[name].args) : undefined;