Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

7.2 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as z from 'zod';
import { commands } from './commands';
import { isVariadicArg } from './command';

import type zodType from 'zod';
import type { AnyCommandSchema, Category } from './command';

type CommandArg = { name: string, description: string, optional: boolean, variadic: boolean };

function commandArgs(command: AnyCommandSchema): CommandArg[] {
  const args: CommandArg[] = [];
  const shape = command.args ? (command.args as zodType.ZodObject<any>).shape : {};
  const names = Object.keys(shape);
  for (const [name, schema] of Object.entries(shape)) {
    const zodSchema = schema as zodType.ZodTypeAny;
    const description = zodSchema.description ?? '';
    const variadic = name === names[names.length - 1] && isVariadicArg(zodSchema);
    args.push({ name, description, optional: zodSchema.safeParse(undefined).success, variadic });
  }
  return args;
}

function commandArgText(a: CommandArg) {
  const name = a.variadic ? `${a.name}...` : a.name;
  return a.optional ? `[${name}]` : `<${name}>`;
}

function commandArgsText(args: CommandArg[]) {
  return args.map(commandArgText).join(' ');
}

function generateCommandHelp(command: AnyCommandSchema) {
  const args = commandArgs(command);
  const lines: string[] = [
    `playwright-cli ${command.name} ${commandArgsText(args)}`,
    '',
    command.description,
    '',
  ];

  if (args.length) {
    lines.push('Arguments:');
    lines.push(...args.map(a => formatWithGap(`  ${commandArgText(a)}`, a.description.toLowerCase())));
  }

  if (command.options) {
    lines.push('Options:');
    const optionsShape = (command.options as zodType.ZodObject<any>).shape;
    for (const [name, schema] of Object.entries(optionsShape)) {
      const zodSchema = schema as zodType.ZodTypeAny;
      let description = (zodSchema.description ?? '').toLowerCase();
      const unwrapped = unwrapZodType(zodSchema);
      if (unwrapped instanceof z.ZodEnum)
        description = `${description} (one of: ${unwrapped.options.join(', ')})`.trim();
      lines.push(formatWithGap(`  --${name}`, description));
    }
  }

  return lines.join('\n');
}

const categories: { name: Category, title: string }[] = [
  { name: 'core', title: 'Core' },
  { name: 'navigation', title: 'Navigation' },
  { name: 'keyboard', title: 'Keyboard' },
  { name: 'mouse', title: 'Mouse' },
  { name: 'export', title: 'Save as' },
  { name: 'tabs', title: 'Tabs' },
  { name: 'storage', title: 'Storage' },
  { name: 'emulation', title: 'Emulation' },
  { name: 'network', title: 'Network' },
  { name: 'devtools', title: 'DevTools' },
  { name: 'webmcp', title: 'WebMCP' },
  { name: 'install', title: 'Install' },
  { name: 'config', title: 'Configuration' },
  { name: 'browsers', title: 'Browser sessions' },
] as const;

export function generateHelp() {
  const lines: string[] = [];
  lines.push('Usage: playwright-cli <command> [args] [options]');
  lines.push('Usage: playwright-cli -s=<session> <command> [args] [options]');

  const commandsByCategory = new Map<string, AnyCommandSchema[]>();
  for (const c of categories)
    commandsByCategory.set(c.name, []);
  for (const command of Object.values(commands)) {
    if (command.hidden)
      continue;
    commandsByCategory.get(command.category)!.push(command);
  }

  for (const c of categories) {
    const cc = commandsByCategory.get(c.name)!;
    if (!cc.length)
      continue;
    lines.push(`\n${c.title}:`);
    for (const command of cc)
      lines.push(generateHelpEntry(command));
  }

  lines.push('\nGlobal options:');
  lines.push(formatWithGap('  --help [command]', 'print help'));
  lines.push(formatWithGap('  --json', 'output response as JSON'));
  lines.push(formatWithGap('  --raw', 'output only the result value, without status and code'));
  lines.push(formatWithGap('  --version', 'print version'));

  return lines.join('\n');
}


export function generateReadme() {
  const lines: string[] = [];
  lines.push('\n## Commands');

  const commandsByCategory = new Map<string, AnyCommandSchema[]>();
  for (const c of categories)
    commandsByCategory.set(c.name, []);
  for (const command of Object.values(commands))
    commandsByCategory.get(command.category)!.push(command);

  for (const c of categories) {
    const cc = commandsByCategory.get(c.name)!;
    if (!cc.length)
      continue;
    lines.push(`\n### ${c.title}\n`);
    lines.push('```bash');
    for (const command of cc)
      lines.push(generateReadmeEntry(command));
    lines.push('```');
  }
  return lines.join('\n');
}

function generateHelpEntry(command: AnyCommandSchema): string {
  const args = commandArgs(command);
  const prefix = `  ${command.name} ${commandArgsText(args)}`;
  const suffix = command.description.toLowerCase();
  return formatWithGap(prefix, suffix);
}

function generateReadmeEntry(command: AnyCommandSchema): string {
  const args = commandArgs(command);
  const prefix = `playwright-cli ${command.name} ${commandArgsText(args)}`;
  const suffix = '# ' + command.description.toLowerCase();
  return formatWithGap(prefix, suffix, 40);
}

function unwrapZodType(schema: zodType.ZodTypeAny): zodType.ZodTypeAny {
  if ('unwrap' in schema && typeof schema.unwrap === 'function')
    return unwrapZodType(schema.unwrap());
  return schema;
}

function isBooleanSchema(schema: zodType.ZodTypeAny): boolean {
  return unwrapZodType(schema) instanceof z.ZodBoolean;
}

export function generateHelpJSON() {
  const booleanOptions = new Set<string>();

  const commandEntries: Record<string, { help: string, flags: Record<string, 'boolean' | 'string'>, args: string[], variadicArg?: boolean, raw?: boolean }> = {};
  for (const [name, command] of Object.entries(commands)) {
    const flags: Record<string, 'boolean' | 'string'> = {};
    if (command.options) {
      const optionsShape = (command.options as zodType.ZodObject<any>).shape;
      for (const [flagName, schema] of Object.entries(optionsShape)) {
        const isBoolean = isBooleanSchema(schema as zodType.ZodTypeAny);
        flags[flagName] = isBoolean ? 'boolean' : 'string';
        if (isBoolean)
          booleanOptions.add(flagName);
      }
    }
    const args = commandArgs(command);
    commandEntries[name] = { help: generateCommandHelp(command), flags, args: args.map(a => a.name) };
    if (args.some(a => a.variadic))
      commandEntries[name].variadicArg = true;
    if (command.raw)
      commandEntries[name].raw = true;
  }

  return {
    global: generateHelp(),
    commands: commandEntries,
    booleanOptions: [...booleanOptions],
  };
}

function formatWithGap(prefix: string, text: string, threshold: number = 30) {
  const indent = Math.max(1, threshold - prefix.length);
  return prefix + ' '.repeat(indent) + text;
}