Skip to content

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

21.2 KB
Raw Blame
#!/usr/bin/env node
/**
 * 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.
 */

// @ts-check

const fs = require('fs');
const path = require('path');

const channels = new Map();
const mixins = new Map();

function raise(item) {
  throw new Error('Invalid item: ' + JSON.stringify(item, null, 2));
}

function titleCase(name) {
  return name[0].toUpperCase() + name.substring(1);
}

function inlineType(type, indent, wrapEnums = false) {
  if (typeof type === 'string') {
    const optional = type.endsWith('?');
    if (optional)
      type = type.substring(0, type.length - 1);
    if (type === 'binary')
      return { ts: 'Binary', scheme: 'tBinary', optional };
    if (type === 'json')
      return { ts: 'any', scheme: 'tAny', optional };
    if (['string', 'boolean', 'undefined'].includes(type))
      return { ts: type, scheme: `t${titleCase(type)}`, optional };
    if (type === 'number')
      throw new Error('Use "int" or "float" instead of "number" in protocol.yml');
    if (type === 'int' || type === 'float')
      return { ts: 'number', scheme: `t${titleCase(type)}`, optional };
    if (channels.has(type)) {
      let derived = derivedClasses.get(type) || [];
      derived = [...derived, type];
      return { ts: `${type}Channel`, scheme: `tChannel([${derived.map(c => `'${c}'`).join(', ')}])` , optional };
    }
    if (type === 'Channel')
      return { ts: `Channel`, scheme: `tChannel('*')`, optional };
    return { ts: type, scheme: `tType('${type}')`, optional };
  }
  if (type.type.startsWith('array')) {
    const optional = type.type.endsWith('?');
    const inner = inlineType(type.items, indent, true);
    return { ts: `${inner.ts}[]`, scheme: `tArray(${inner.scheme})`, optional };
  }
  if (type.type.startsWith('enum')) {
    const optional = type.type.endsWith('?');
    const ts = type.literals.map(literal => `'${literal}'`).join(' | ');
    return {
      ts: wrapEnums ? `(${ts})` : ts,
      scheme: `tEnum([${type.literals.map(literal => `'${literal}'`).join(', ')}])`,
      optional
    };
  }
  if (type.type.startsWith('object')) {
    const optional = type.type.endsWith('?');
    const inner = properties(type.properties, indent + '  ');
    return {
      ts: `{\n${inner.ts}\n${indent}}`,
      scheme: `tObject({\n${inner.scheme}\n${indent}})`,
      optional
    };
  }
  raise(type);
}

function properties(properties, indent, onlyOptional) {
  const ts = [];
  const scheme = [];
  const visitProperties = props => {
    for (const [name, value] of Object.entries(props)) {
      if (name.startsWith('$mixin')) {
        visitProperties(mixins.get(value).properties);
        continue;
      }
      const inner = inlineType(value, indent);
      if (onlyOptional && !inner.optional)
        continue;
      ts.push(`${indent}${name}${inner.optional ? '?' : ''}: ${inner.ts},`);
      const wrapped = inner.optional ? `tOptional(${inner.scheme})` : inner.scheme;
      scheme.push(`${indent}${name}: ${wrapped},`);
    }
  };
  visitProperties(properties);
  return { ts: ts.join('\n'), scheme: scheme.join('\n') };
}

function objectType(props, indent, onlyOptional = false) {
  if (!Object.entries(props).length)
    return { ts: `{}`, scheme: `tObject({})` };
  const inner = properties(props, indent + '  ', onlyOptional);
  return { ts: `{\n${inner.ts}\n${indent}}`, scheme: `tObject({\n${inner.scheme}\n${indent}})` };
}

function channelsHeader(target) {
  return [
`/**
 * 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.
 */

// This file is generated by ${path.basename(__filename).split(path.sep).join(path.posix.sep)}, do not edit manually.` + (target === 'Dispatcher' ? `

import type { Progress } from './progress';
` : '') + `
import type { Binary, Channel, ${structNames.join(', ')} } from '@protocol/structs';
export type { Binary, Channel, ${structNames.join(', ')} } from '@protocol/structs';
` + (target === 'Dispatcher' ? '' : `
export type TimeoutOptions = { signal: AbortSignal | undefined, timeout: number };
`)];
}

const validator_ts = [
`/**
 * 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.
 */

// This file is generated by ${path.basename(__filename)}, do not edit manually.

import { scheme, tOptional, tObject, tBoolean, tInt, tFloat, tString, tAny, tEnum, tArray, tBinary, tChannel, tType } from './validatorPrimitives';
export type { Validator, ValidatorContext } from './validatorPrimitives';
export { ValidationError, findValidator, maybeFindValidator, createMetadataValidator, createWaitInfoValidator } from './validatorPrimitives';
`];

const metainfo_ts = [
`/**
 * 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.
 */

// This file is generated by ${path.basename(__filename).split(path.sep).join(path.posix.sep)}, do not edit manually.
`];

const methodMetainfo = [];

const protocol = require('./protocol_spec').loadProtocol();

function addScheme(name, s) {
  validator_ts.push(`scheme.${name} = ${s};`);
}

for (const [name, value] of Object.entries(protocol)) {
  if (value.type === 'interface')
    channels.set(name, value);
  if (value.type === 'mixin')
    mixins.set(name, value);
}

// Struct types (objects and enums) are identical for the client and the server,
// so they are generated once into a shared structs.d.ts file that both the
// client and the server channels.d.ts import and re-export.
const structNames = Object.entries(protocol)
  .filter(([, value]) => value.type === 'object' || value.type === 'enum')
  .map(([name]) => name);

const derivedClasses = new Map();
for (const [name, item] of Object.entries(protocol)) {
  if (item.type === 'interface' && item.extends) {
    let items = derivedClasses.get(item.extends);
    if (!items) {
      items = [];
      derivedClasses.set(item.extends, items);
    }
    items.push(name);
  }
}

// Trait-cascade order: each `T extends FooChannel ?` must be tested before any
// of its ancestors via `extends`. Sort interfaces children-first so the cascade
// is correct regardless of how the spec files are ordered on disk.
const interfaceEntries = Object.entries(protocol).filter(([, v]) => v.type === 'interface');
const interfaceDepth = new Map();
function depthOf(name) {
  if (interfaceDepth.has(name)) return interfaceDepth.get(name);
  const ancestor = protocol[name] && protocol[name].extends;
  const d = ancestor && protocol[ancestor] && protocol[ancestor].type === 'interface'
    ? depthOf(ancestor) + 1 : 0;
  interfaceDepth.set(name, d);
  return d;
}
for (const [name] of interfaceEntries) depthOf(name);
// Stable sort by descending depth — children before ancestors.
const entriesInReverse = interfaceEntries
  .map((e, i) => ({ e, i }))
  .sort((a, b) => depthOf(b.e[0]) - depthOf(a.e[0]) || a.i - b.i)
  .map(x => x.e);

function generateChannels(target) {
  const channels_ts = channelsHeader(target);
  const isDispatcher = target === 'Dispatcher';

  channels_ts.push(`// ----------- Initializer Traits -----------`);
  channels_ts.push(`export type InitializerTraits<T> =`);
  for (const [name, item] of entriesInReverse) {
    if (item.type !== 'interface')
      continue;
    channels_ts.push(`    T extends ${name}Channel ? ${name}Initializer :`);
  }
  channels_ts.push(`    object;`);
  channels_ts.push(``);
  channels_ts.push(`// ----------- Event Traits -----------`);
  channels_ts.push(`export type EventsTraits<T> =`);
  for (const [name, item] of entriesInReverse) {
    if (item.type !== 'interface')
      continue;
    channels_ts.push(`    T extends ${name}Channel ? ${name}Events :`);
  }
  channels_ts.push(`    undefined;`);
  channels_ts.push(``);
  channels_ts.push(`// ----------- EventTarget Traits -----------`);
  channels_ts.push(`export type EventTargetTraits<T> =`);
  for (const [name, item] of entriesInReverse) {
    if (item.type !== 'interface')
      continue;
    channels_ts.push(`    T extends ${name}Channel ? ${name}EventTarget :`);
  }
  channels_ts.push(`    undefined;`);
  channels_ts.push(``);

  for (const [name, item] of Object.entries(protocol)) {
    if (item.type === 'interface') {
      const channelName = name;
      channels_ts.push(`// ----------- ${channelName} -----------`);
      const init = objectType(item.initializer || {}, '');
      const initializerName = channelName + 'Initializer';
      channels_ts.push(`export type ${initializerName} = ${init.ts};`);

      let ancestorInit = init;
      let ancestor = item;
      while (!ancestor.initializer) {
        if (!ancestor.extends)
          break;
        ancestor = channels.get(ancestor.extends);
        ancestorInit = objectType(ancestor.initializer || {}, '');
      }
      addScheme(`${channelName}Initializer`, ancestor.initializer ? ancestorInit.scheme : `tOptional(tObject({}))`);

      channels_ts.push(`export interface ${channelName}EventTarget {`);
      const ts_types = new Map();

      /** @type{{eventName: string, eventType: string}[]} */
      const eventTypes = [];
      for (let [eventName, event] of Object.entries(item.events || {})) {
        if (event === null)
          event = {};
        const parameters = objectType(event.parameters || {}, '');
        const paramsName = `${channelName}${titleCase(eventName)}Event`;
        ts_types.set(paramsName, parameters.ts);
        if (isDispatcher)
          channels_ts.push(`  _dispatchEvent(event: '${eventName}', params?: ${paramsName}): void;`);
        else
          channels_ts.push(`  on(event: '${eventName}', callback: (params: ${paramsName}) => void): this;`);
        eventTypes.push({eventName, eventType: paramsName});
        addScheme(paramsName, event.parameters ? parameters.scheme : `tOptional(tObject({}))`);
        for (const derived of derivedClasses.get(channelName) || [])
          addScheme(`${derived}${titleCase(eventName)}Event`, `tType('${paramsName}')`);
      }
      channels_ts.push(`}`);

      channels_ts.push(`export interface ${channelName}Channel extends ${channelName}EventTarget, ${(item.extends || '') + 'Channel'} {`);
      channels_ts.push(`  _type_${channelName}: boolean;`);
      for (let [methodName, method] of Object.entries(item.commands || {})) {
        if (method === null)
          method = {};

        for (const className of [name, ...(derivedClasses.get(name) || [])]) {
          if (method.flags?.slowMo && method.internal)
            throw new Error(`Method "${className}.${methodName}" has "slowMo" flag, so cannot be "internal" in protocol.yml`);
          if (method.flags?.snapshot && method.internal)
            throw new Error(`Method "${className}.${methodName}" has "snapshot" flag, so cannot be "internal" in protocol.yml`);
          if (method.flags?.pause && method.internal)
            throw new Error(`Method "${className}.${methodName}" has "pause" flag, so cannot be "internal" in protocol.yml`);
          if (!method.title && !method.internal)
            throw new Error(`Method "${className}.${methodName}" must have a "title" because it is not "internal" in protocol.yml`);
          if (method.group && method.internal)
            throw new Error(`Method "${className}.${methodName}" must should not specify "group" because it is "internal" in protocol.yml`);
          if (method.group && !['getter', 'configuration', 'route', 'default'].includes(method.group))
            throw new Error(`Unknown group "${method.group}" for method "${className}.${methodName}" in protocol.yml`);
          if (method.subtitle && method.internal)
            throw new Error(`Method "${className}.${methodName}" should not specify "subtitle" because it is "internal" in protocol.yml`);
          if (!method.subtitle && !method.internal && (method.parameters || {}).selector)
            throw new Error(`Method "${className}.${methodName}" has a "selector" parameter, so it must have an explicit "subtitle" in protocol.yml`);
          if (method.renderParams) {
            if (method.internal)
              throw new Error(`Method "${className}.${methodName}" should not specify "renderParams" because it is "internal" in protocol.yml`);
            if (!Array.isArray(method.renderParams) || method.renderParams.some(entry => typeof entry !== 'string'))
              throw new Error(`Method "${className}.${methodName}" must specify "renderParams" as a list of strings in protocol.yml`);
            for (const entry of method.renderParams) {
              // Each entry is "[key=]path[:selector]", path root must be a parameter.
              const paramName = entry.split(':')[0].split('=').pop().split('.')[0];
              if (!(method.parameters || {})[paramName])
                throw new Error(`Method "${className}.${methodName}" renderParams entry "${entry}" does not match any parameter in protocol.yml`);
            }
          }
          const internalProp = method.internal ? ` internal: ${method.internal},` : '';
          const titleProp = method.title ? ` title: '${method.title}',` : '';
          const subtitleProp = method.subtitle ? ` subtitle: '${method.subtitle}',` : '';
          const renderParamsProp = method.renderParams ? ` renderParams: [${method.renderParams.map(entry => `'${entry}'`).join(', ')}],` : '';
          const groupProp = method.group ? ` group: '${method.group}',` : '';
          const slowMoProp = method.flags?.slowMo ? ` slowMo: ${method.flags.slowMo},` : '';
          const snapshotProp = method.flags?.snapshot ? ` snapshot: ${method.flags.snapshot},` : '';
          const pauseProp = method.flags?.pause ? ` pause: ${method.flags.pause},` : '';
          const inputProp = method.flags?.input ? ` input: ${method.flags.input},` : '';
          const isAutoWaitingProp = method.flags?.isAutoWaiting ? ` isAutoWaiting: ${method.flags.isAutoWaiting},` : '';
          methodMetainfo.push(`['${className + '.' + methodName}', {${internalProp}${titleProp}${subtitleProp}${renderParamsProp}${slowMoProp}${snapshotProp}${pauseProp}${inputProp}${isAutoWaitingProp}${groupProp} }]`);
        }

        const parameters = objectType(method.parameters || {}, '');
        const paramsName = `${channelName}${titleCase(methodName)}Params`;
        const optionsName = `${channelName}${titleCase(methodName)}Options`;
        ts_types.set(paramsName, parameters.ts);
        ts_types.set(optionsName, objectType(method.parameters || {}, '', true).ts);
        addScheme(paramsName, method.parameters ? parameters.scheme : `tOptional(tObject({}))`);
        for (const derived of derivedClasses.get(channelName) || [])
          addScheme(`${derived}${titleCase(methodName)}Params`, `tType('${paramsName}')`);

        const resultName = `${channelName}${titleCase(methodName)}Result`;
        const returns = objectType(method.returns || {}, '');
        ts_types.set(resultName, method.returns ? returns.ts : 'void');
        addScheme(resultName, method.returns ? returns.scheme : `tOptional(tObject({}))`);
        for (const derived of derivedClasses.get(channelName) || [])
          addScheme(`${derived}${titleCase(methodName)}Result`, `tType('${resultName}')`);

        if (method.errorDetails) {
          const errorDetailsName = `${channelName}${titleCase(methodName)}ErrorDetails`;
          const details = objectType(method.errorDetails, '');
          ts_types.set(errorDetailsName, details.ts);
          addScheme(errorDetailsName, details.scheme);
          for (const derived of derivedClasses.get(channelName) || [])
            addScheme(`${derived}${titleCase(methodName)}ErrorDetails`, `tType('${errorDetailsName}')`);
        }
        channels_ts.push(`  ${methodName}(params: ${paramsName}, ${isDispatcher ? `progress: Progress` : `options: TimeoutOptions`}): Promise<${resultName}>;`);
      }

      channels_ts.push(`}`);
      for (const [typeName, typeValue] of ts_types)
        channels_ts.push(`export type ${typeName} = ${typeValue};`);
      channels_ts.push(``);

      channels_ts.push(`export interface ${channelName}Events {`);
      for (const {eventName, eventType} of eventTypes)
          channels_ts.push(`  '${eventName}': ${eventType};`);
      channels_ts.push(`}\n`);

    } else if (item.type === 'object') {
      const inner = objectType(item.properties, '');
      addScheme(name, inner.scheme);
    } else if (item.type === 'enum') {
      addScheme(name, `tEnum([${item.literals.map(literal => `'${literal}'`).join(', ')}])`);
    }
  }

  return channels_ts;
}

function structsHeader() {
  return `/**
 * 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.
 */

// This file is generated by ${path.basename(__filename).split(path.sep).join(path.posix.sep)}, do not edit manually.

export type Binary = Buffer;

export interface Channel {
}
`;
}

function generateStructs() {
  const structs_ts = [structsHeader()];
  for (const [name, item] of Object.entries(protocol)) {
    if (item.type === 'object') {
      const inner = objectType(item.properties, '');
      structs_ts.push(`export type ${name} = ${inner.ts};`);
      structs_ts.push(``);
    } else if (item.type === 'enum') {
      const ts = item.literals.map(literal => `'${literal}'`).join(' | ');
      structs_ts.push(`export type ${name} = ${ts};`);
      structs_ts.push(``);
    }
  }
  return structs_ts;
}

const structs_ts = generateStructs();

const client_channels_ts = generateChannels('Channel');

metainfo_ts.push(`export type MethodMetainfo = { internal?: boolean, title?: string, subtitle?: string, renderParams?: string[], slowMo?: boolean, snapshot?: boolean, pause?: boolean, isAutoWaiting?: boolean, input?: boolean, group?: string };

export const methodMetainfo = new Map<string, MethodMetainfo>([
  ${methodMetainfo.join(`,\n  `)}
]);

export function getMetainfo(metadata: { type: string, method: string }): MethodMetainfo | undefined {
  return methodMetainfo.get(metadata.type + '.' + metadata.method);
}`);
const metainfoContent = metainfo_ts.join('\n') + '\n';
const validatorContent = validator_ts.join('\n') + '\n';

const server_channels_ts = generateChannels('Dispatcher');

let hasChanges = false;

function writeFile(filePath, content) {
  try {
    const existing = fs.readFileSync(filePath, 'utf8');
    if (existing === content)
      return;
  } catch (e) {
  }
  hasChanges = true;
  const root = path.join(__dirname, '..');
  console.log(`Writing //${path.relative(root, filePath)}`);
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
  fs.writeFileSync(filePath, content, 'utf8');
}

writeFile(path.join(__dirname, '..', 'packages', 'protocol', 'src', 'structs.d.ts'), structs_ts.join('\n') + '\n');
writeFile(path.join(__dirname, '..', 'packages', 'playwright-core', 'src', 'client', 'channels.d.ts'), client_channels_ts.join('\n') + '\n');
writeFile(path.join(__dirname, '..', 'packages', 'playwright-core', 'src', 'server', 'channels.d.ts'), server_channels_ts.join('\n') + '\n');
writeFile(path.join(__dirname, '..', 'packages', 'isomorphic', 'protocolMetainfo.ts'), metainfoContent);
writeFile(path.join(__dirname, '..', 'packages', 'protocol', 'src', 'validator.ts'), validatorContent);
process.exit(hasChanges ? 1 : 0);