Best JavaScript code snippet using playwright-internal
extract-ts-config.spec.mjs
Source:extract-ts-config.spec.mjs  
1import { fileURLToPath } from "url";2import { expect } from "chai";3import loadTSConfig from "../../src/config-utl/extract-ts-config.js";4import pathToPosix from "../../src/extract/utl/path-to-posix.js";5function getFullPath(pRelativePath) {6  return fileURLToPath(new URL(pRelativePath, import.meta.url));7}8describe("[I] config-utl/extract-ts-config - flatten typescript config - simple config scenarios", () => {9  it("throws when no config file name is passed", () => {10    expect(() => {11      loadTSConfig();12    }).to.throw();13  });14  it("throws when a non-existing config file is passed", () => {15    expect(() => {16      loadTSConfig("config-does-not-exist");17    }).to.throw();18  });19  it("throws when a config file is passed that does not contain valid json", () => {20    expect(() => {21      loadTSConfig(22        getFullPath("./__mocks__/typescriptconfig/tsconfig.invalid.json")23      );24    }).to.throw();25  });26  it("returns an empty object when an empty config file is passed", () => {27    expect(28      loadTSConfig(29        getFullPath("./__mocks__/typescriptconfig/tsconfig.empty.json")30      ).options31    ).to.deep.equal({32      configFilePath: pathToPosix(33        getFullPath("./__mocks__/typescriptconfig/tsconfig.empty.json")34      ),35    });36  });37  it("returns an empty object when an empty config file with comments is passed", () => {38    expect(39      loadTSConfig(40        getFullPath("./__mocks__/typescriptconfig/tsconfig.withcomments.json")41      ).options42    ).to.deep.equal({43      configFilePath: pathToPosix(44        getFullPath("./__mocks__/typescriptconfig/tsconfig.withcomments.json")45      ),46    });47  });48  it("returns an object with a bunch of options when the default ('--init') config file is passed", () => {49    expect(50      loadTSConfig(51        getFullPath(52          "./__mocks__/typescriptconfig/tsconfig.asgeneratedbydefault.json"53        )54      ).options55    ).to.deep.equal({56      configFilePath: pathToPosix(57        getFullPath(58          "./__mocks__/typescriptconfig/tsconfig.asgeneratedbydefault.json"59        )60      ),61      esModuleInterop: true,62      module: 1,63      strict: true,64      target: 1,65    });66  });67});68describe("[I] config-utl/extract-ts-config - flatten typescript config - 'extend' config scenarios", () => {69  it("throws when a config file is passed that contains a extends to a non-existing file", () => {70    expect(() => {71      loadTSConfig(72        getFullPath(73          "./__mocks__/typescriptconfig/tsconfig.extendsnonexisting.json"74        )75      );76    }).to.throw();77  });78  it("throws when a config file is passed that has a circular reference", () => {79    expect(() => {80      loadTSConfig(81        getFullPath("./__mocks__/typescriptconfig/tsconfig.circular.json")82      );83    }).to.throw(84      "error TS18000: Circularity detected while resolving configuration"85    );86  });87  it("returns an empty object (even no 'extend') when a config with an extend to an empty base is passed", () => {88    expect(89      loadTSConfig(90        getFullPath("./__mocks__/typescriptconfig/tsconfig.simpleextends.json")91      ).options92    ).to.deep.equal({93      configFilePath: pathToPosix(94        getFullPath("./__mocks__/typescriptconfig/tsconfig.simpleextends.json")95      ),96    });97  });98  it("returns an object with properties from base, extends & overrides from extends - non-compilerOptions", () => {99    const lParseResult = loadTSConfig(100      getFullPath(101        "./__mocks__/typescriptconfig/tsconfig.noncompileroptionsextends.json"102      )103    );104    const lWildCardDirectories = {};105    lWildCardDirectories[106      // from TypeScript 4 the key name is lower case ¯\_(ã)_/¯107      pathToPosix(108        getFullPath("./__mocks__/typescriptconfig/override from extends here")109      ).toLowerCase()110    ] = 1;111    /* eslint no-undefined:0 */112    expect(lParseResult).to.deep.equal({113      // only in the base114      // filesSpecs: ["./dummysrc.ts"],115      options: {116        configFilePath: pathToPosix(117          getFullPath(118            "__mocks__/typescriptconfig/tsconfig.noncompileroptionsextends.json"119          )120        ),121      },122      fileNames: [123        pathToPosix(getFullPath("__mocks__/typescriptconfig/dummysrc.ts")),124        // "/Users/sander/prg/js/dependency-cruiser/test/config-utl/__mocks__/typescriptconfig/dummysrc.ts",125      ],126      projectReferences: undefined,127      // validatedIncludeSpecs: ["override from extends here"],128      typeAcquisition: { enable: false, include: [], exclude: [] },129      raw: {130        extends: "./tsconfig.noncompileroptionsbase.json",131        exclude: ["only in the extends"],132        include: ["override from extends here"],133        compileOnSave: false,134        files: ["./dummysrc.ts"],135      },136      watchOptions: undefined,137      errors: [],138      wildcardDirectories: lWildCardDirectories,139      compileOnSave: false,140    });141    // from base:142    // this expect should be ok, but it isn't. For one143    // reason or other typescript's TSConfig parser overrides this again with false144    // even though it isn't specified in the file that extends it =>145    // I suspect a bug in typescripts' TSConfig parser ...146    // expect(lParseResult.compileOnSave).to.equal(true);147  });148  it("returns an object with properties from base, extends & overrides from extends - compilerOptions", () => {149    expect(150      loadTSConfig(151        getFullPath(152          "./__mocks__/typescriptconfig/tsconfig.compileroptionsextends.json"153        )154      ).options155    ).to.deep.equal({156      configFilePath: pathToPosix(157        getFullPath(158          "./__mocks__/typescriptconfig/tsconfig.compileroptionsextends.json"159        )160      ),161      // only in extends:162      allowJs: true,163      // overridden from base:164      allowUnreachableCode: false,165      // only in base:166      rootDirs: [167        pathToPosix(getFullPath("__mocks__/typescriptconfig/foo")),168        pathToPosix(getFullPath("__mocks__/typescriptconfig/bar")),169        pathToPosix(getFullPath("__mocks__/typescriptconfig/baz")),170      ],171    });172  });173  it("returns an object with properties from base, extends compilerOptions.lib array", () => {174    expect(175      loadTSConfig(176        getFullPath(177          "./__mocks__/typescriptconfig/tsconfig.compileroptionsextendslib.json"178        )179      ).options180    ).to.deep.equal({181      configFilePath: pathToPosix(182        getFullPath(183          "./__mocks__/typescriptconfig/tsconfig.compileroptionsextendslib.json"184        )185      ),186      lib: [187        // "dom.iterable",188        "lib.dom.iterable.d.ts",189        // I'd expected these from base as well as per the specification, but190        // apparently the typescript TSConfig parser chooses to override instead of extend ...191        // "es2016.array.include",192        // "dom"193      ],194    });195  });...update-ts-project-refs.js
Source:update-ts-project-refs.js  
1#!/usr/bin/env node2/**3 * This is an internal script to update TypeScript project references based on4 * lerna's local package dependencies.5 *6 * See https://www.typescriptlang.org/docs/handbook/project-references.html7 */8'use strict';9const path = require('path');10const fs = require('fs-extra');11const debug = require('debug')('loopback:build');12const {Project} = require('@lerna/project');13const {PackageGraph} = require('@lerna/package-graph');14const TSCONFIG = 'tsconfig.json';15const TSCONFIG_BUILD = 'tsconfig.build.json';16function loadTsConfig(pkgLocation, dryRun = true) {17  const tsconfigFile = path.join(pkgLocation, TSCONFIG);18  let file = tsconfigFile;19  if (!fs.existsSync(tsconfigFile)) {20    const tsconfigBuildFile = path.join(pkgLocation, TSCONFIG_BUILD);21    if (fs.existsSync(tsconfigBuildFile)) {22      if (!dryRun) {23        fs.moveSync(tsconfigBuildFile, tsconfigFile);24      } else {25        file = tsconfigBuildFile;26      }27    } else {28      return undefined;29    }30  }31  return {32    file,33    tsconfig: require(file),34  };35}36async function updateReferences(options) {37  options = options || {};38  const dryRun = options.dryRun;39  const project = new Project(process.cwd());40  const packages = await project.getPackages();41  const rootRefs = [];42  const graph = new PackageGraph(packages);43  const tsPackages = Array.from(graph.values()).filter(p => {44    debug('Package %s', p.pkg.name);45    const pkgLocation = p.pkg.location;46    return loadTsConfig(pkgLocation, dryRun) != null;47  });48  let changed = false;49  for (const p of tsPackages) {50    const pkgLocation = p.pkg.location;51    const tsconfigMeta = loadTsConfig(pkgLocation, dryRun);52    const tsconfigFile = tsconfigMeta.file;53    rootRefs.push({54      path: path.join(path.relative(project.rootPath, pkgLocation), TSCONFIG).replace(/\\/g, '/'),55    });56    const tsconfig = tsconfigMeta.tsconfig;57    const originalTsconfigJson = JSON.stringify(tsconfig, null, 2);58    const refs = [];59    for (const d of p.localDependencies.keys()) {60      const depPkg = graph.get(d);61      // Skip non-typescript packages62      if (loadTsConfig(depPkg.location, dryRun) == null) continue;63      const relativePath = path.relative(pkgLocation, depPkg.pkg.location);64      refs.push({path: path.join(relativePath, TSCONFIG).replace(/\\/g, '/')});65    }66    tsconfig.compilerOptions = {67      // outDir has to be set in tsconfig instead of CLI for tsc -b68      outDir: 'dist',69      ...tsconfig.compilerOptions,70      // composite must be true for project refs71      composite: true,72    };73    if (!tsconfig.include || p.name.startsWith('@loopback/example-')) {74      // To include ts/json files75      tsconfig.include = ['src/**/*', 'src/**/*.json'];76    }77    // Sort the references so that we will have a consistent output78    tsconfig.references = refs.sort((a, b) => a.path.localeCompare(b.path));79    // Convert to JSON80    const tsconfigJson = JSON.stringify(tsconfig, null, 2);81    if (!dryRun) {82      if (originalTsconfigJson !== tsconfigJson) {83        // Using `-f` to overwrite tsconfig.json84        fs.writeFileSync(tsconfigFile, tsconfigJson + '\n', {85          encoding: 'utf-8',86        });87        changed = true;88        debug('%s has been updated.', tsconfigFile);89      }90    } else {91      // Otherwise write to console92      console.log('- %s', p.pkg.name);93      console.log(tsconfigJson);94    }95  }96  const rootTsconfigFile = path.join(project.rootPath, 'tsconfig.json');97  const rootTsconfig = require(rootTsconfigFile);98  const originalRootTsconfigJson = JSON.stringify(rootTsconfig, null, 2);99  rootTsconfig.compilerOptions = rootTsconfig.compilerOptions || {};100  rootTsconfig.compilerOptions.composite = true;101  rootTsconfig.references = rootRefs;102  // Reset files/include/exclude. The root should use project references now.103  rootTsconfig.files = [];104  delete rootTsconfig.include;105  delete rootTsconfig.exclude;106  // Convert to JSON107  const rootTsconfigJson = JSON.stringify(rootTsconfig, null, 2);108  if (!dryRun) {109    if (originalRootTsconfigJson !== rootTsconfigJson) {110      // Using `-f` to overwrite tsconfig.json111      fs.writeFileSync(rootTsconfigFile, rootTsconfigJson + '\n', {112        encoding: 'utf-8',113      });114      changed = true;115      debug('%s has been updated.', rootTsconfigFile);116    }117    if (changed) {118      console.log('TypeScript project references have been updated.');119    } else {120      console.log('TypeScript project references are up to date.');121    }122  } else {123    console.log('\n%s', path.relative(project.rootPath, rootTsconfigFile));124    console.log(rootTsconfigJson);125    console.log('\nThis is a dry-run. Please use -f option to update tsconfig files.');126  }127}128if (require.main === module) {129  const dryRun = !process.argv.includes('-f');130  updateReferences({dryRun}).catch(err => {131    console.error(err);132    process.exit(1);133  });134}...cli.ts
Source:cli.ts  
1#!/usr/bin/env node2'use strict';3import { ArgumentParser } from 'argparse';4import * as debug from 'debug';5import * as fs from 'fs-extra-promise';6import * as _ from 'lodash';7import { isAbsolute, join } from 'path';8import * as path from 'path';9import * as ts from 'typescript';10import * as YAML from 'yamljs';11import { Config, Specification, SwaggerConfig } from './config';12import { MetadataGenerator } from './metadata/metadataGenerator';13import { SpecGenerator } from './swagger/generator';14const debugLog = debug('typescript-rest-swagger');15const packageJson = require(`../package.json`);16const workingDir: string = process.cwd();17const versionDefault = getPackageJsonValue('version');18const nameDefault = getPackageJsonValue('name');19const descriptionDefault = getPackageJsonValue('description');20const licenseDefault = getPackageJsonValue('license');21const parser = new ArgumentParser({22    addHelp: true,23    description: 'Typescript-REST Swagger tool',24    version: packageJson.version25});26parser.addArgument(27    ['-c', '--config'],28    {29        help: 'The swagger config file (swagger.json or swagger.yml or swaggerCongig.js).'30    }31);32parser.addArgument(33    ['-t', '--tsconfig'],34    {35        action: 'storeTrue',36        defaultValue: false,37        help: 'Load tsconfig.json file',38    }39);40parser.addArgument(41    ['-p', '--tsconfig_path'],42    {43        help: 'The tsconfig file (tsconfig.json) path. Default to {cwd}/tsconfig.json.',44    }45);46const parameters = parser.parseArgs();47const config = getConfig(parameters.config);48const compilerOptions = getCompilerOptions(parameters.tsconfig, parameters.tsconfig_path);49debugLog('Starting Swagger generation tool');50debugLog('Compiler Options: %j', compilerOptions);51const swaggerConfig = validateSwaggerConfig(config.swagger);52debugLog('Swagger Config: %j', swaggerConfig);53debugLog('Processing Services Metadata');54const metadata = new MetadataGenerator(swaggerConfig.entryFile, compilerOptions, swaggerConfig.ignore).generate();55debugLog('Generated Metadata: %j', metadata);56new SpecGenerator(metadata, swaggerConfig).generate()57    .then(() => {58        console.info('Generation completed.');59    })60    .catch((err: any) => {61        console.error(`Error generating swagger. ${err}`);62    });63function getPackageJsonValue(key: string): string {64    try {65        const projectPackageJson = require(`${workingDir}/package.json`);66        return projectPackageJson[key] || '';67    } catch (err) {68        return '';69    }70}71function getConfig(configPath = 'swagger.json'): Config {72    const configFile = `${workingDir}/${configPath}`;73    if (_.endsWith(configFile, '.yml') || _.endsWith(configFile, '.yaml')) {74        return YAML.load(configFile);75    } else if (_.endsWith(configFile, '.js')) {76        return require(path.join(configFile));77    }78    else {79        return fs.readJSONSync(configFile);80    }81}82function validateSwaggerConfig(conf: SwaggerConfig): SwaggerConfig {83    if (!conf.outputDirectory) { throw new Error('Missing outputDirectory: onfiguration most contain output directory'); }84    if (!conf.entryFile) { throw new Error('Missing entryFile: Configuration must contain an entry point file.'); }85    conf.version = conf.version || versionDefault;86    conf.name = conf.name || nameDefault;87    conf.description = conf.description || descriptionDefault;88    conf.license = conf.license || licenseDefault;89    conf.yaml = conf.yaml === false ? false : true;90    conf.outputFormat = conf.outputFormat ? Specification[conf.outputFormat] : Specification.Swagger_2;91    return conf;92}93function getCompilerOptions(loadTsconfig: boolean, tsconfigPath?: string | null): ts.CompilerOptions {94    if (!loadTsconfig && tsconfigPath) {95        loadTsconfig = true;96    }97    if (!loadTsconfig) {98        return {};99    }100    const cwd = process.cwd();101    const defaultTsconfigPath = join(cwd, 'tsconfig.json');102    tsconfigPath = tsconfigPath103        ? getAbsolutePath(tsconfigPath, cwd)104        : defaultTsconfigPath;105    try {106        const tsConfig = require(tsconfigPath);107        if (!tsConfig) {108            throw new Error('Invalid tsconfig');109        }110        return tsConfig.compilerOptions111            ? ts.convertCompilerOptionsFromJson(tsConfig.compilerOptions, cwd).options112            : {};113    } catch (err) {114        if (err.code === 'MODULE_NOT_FOUND') {115            throw Error(`No tsconfig file found at '${tsconfigPath}'`);116        } else if (err.name === 'SyntaxError') {117            throw Error(`Invalid JSON syntax in tsconfig at '${tsconfigPath}': ${err.message}`);118        } else {119            throw Error(`Unhandled error encountered loading tsconfig '${tsconfigPath}': ${err.message}`);120        }121    }122}123function getAbsolutePath(p: string, basePath: string): string {124    if (isAbsolute(p)) {125        return p;126    } else {127        return join(basePath, p);128    }...tsconfig-loader.js
Source:tsconfig-loader.js  
...33            jsxFactory: undefined,34            jsxFragmentFactory: undefined35        };36    }37    var config = loadTsconfig(configPath);38    return {39        tsConfigPath: configPath,40        baseUrl: config && config.compilerOptions && config.compilerOptions.baseUrl,41        paths: config && config.compilerOptions && config.compilerOptions.paths,42        jsx: config && config.compilerOptions && config.compilerOptions.jsx,43        jsxFactory: config && config.compilerOptions && config.compilerOptions.jsxFactory,44        jsxFragmentFactory: config && config.compilerOptions && config.compilerOptions.jsxFragmentFactory45    };46}47function resolveConfigPath(cwd, filename) {48    if (filename) {49        var absolutePath = fs.lstatSync(filename).isDirectory()50            ? path.resolve(filename, "./tsconfig.json")51            : path.resolve(cwd, filename);52        return absolutePath;53    }54    if (fs.statSync(cwd).isFile()) {55        return path.resolve(cwd);56    }57    var configAbsolutePath = walkForTsConfig(cwd);58    return configAbsolutePath ? path.resolve(configAbsolutePath) : undefined;59}60function walkForTsConfig(directory, existsSync) {61    if (existsSync === void 0) { existsSync = fs.existsSync; }62    var configPath = path.join(directory, "./tsconfig.json");63    if (existsSync(configPath)) {64        return configPath;65    }66    var parentDirectory = path.join(directory, "../");67    // If we reached the top68    if (directory === parentDirectory) {69        return undefined;70    }71    return walkForTsConfig(parentDirectory, existsSync);72}73exports.walkForTsConfig = walkForTsConfig;74function loadTsconfig(configFilePath, existsSync, readFileSync) {75    if (existsSync === void 0) { existsSync = fs.existsSync; }76    if (readFileSync === void 0) { readFileSync = function (filename) {77        return fs.readFileSync(filename, "utf8");78    }; }79    if (!existsSync(configFilePath)) {80        return undefined;81    }82    var configString = readFileSync(configFilePath);83    var cleanedJson = StripBom(configString);84    var config = JSON5.parse(cleanedJson);85    var extendedConfig = config.extends;86    if (extendedConfig) {87        if (typeof extendedConfig === "string" &&88            extendedConfig.indexOf(".json") === -1) {89            extendedConfig += ".json";90        }91        var currentDir = path.dirname(configFilePath);92        var base = loadTsconfig(path.join(currentDir, extendedConfig), existsSync, readFileSync) || {};93        // baseUrl should be interpreted as relative to the base tsconfig,94        // but we need to update it so it is relative to the original tsconfig being loaded95        if (base && base.compilerOptions && base.compilerOptions.baseUrl) {96            var extendsDir = path.dirname(extendedConfig);97            base.compilerOptions.baseUrl = path.join(extendsDir, base.compilerOptions.baseUrl);98        }99        return __assign({}, base, config, { compilerOptions: __assign({}, base.compilerOptions, config.compilerOptions) });100    }101    return config;102}...ts_config.test.js
Source:ts_config.test.js  
1import loadTsConfig from './ts_config';2// eslint-disable-next-line global-require3jest.mock('fs', () => require('../../../../__mocks__/fs'));4jest.mock('path', () => ({5  resolve: () => 'tsconfig.json',6}));7const setupFiles = files => {8  // eslint-disable-next-line no-underscore-dangle, global-require9  require('fs').__setMockFiles(files);10};11describe('ts_config', () => {12  it('should return the config with the path to the tsconfig.json', () => {13    setupFiles({ 'tsconfig.json': '{}' });14    const config = loadTsConfig('.foo');15    expect(config).toEqual({16      configFile: 'tsconfig.json',17    });18  });19  it('should return empty object when there is no tsconfig.json', () => {20    setupFiles({});21    const config = loadTsConfig('.foo');22    expect(config).toEqual({});23  });...Using AI Code Generation
1const path = require('path');2const playwright = require('playwright');3const { loadTsConfig } = require('playwright/lib/server/tsconfig');4(async () => {5  const browser = await playwright.chromium.launch();6  const page = await browser.newPage();7  await page.screenshot({ path: 'example.png' });8  await browser.close();9})();10const path = require('path');11const playwright = require('playwright');12const { loadTsConfig } = require('playwright/lib/server/tsconfig');13(async () => {14  const browser = await playwright.chromium.launch();15  const page = await browser.newPage();16  await page.screenshot({ path: 'example.png' });17  await browser.close();18})();19{20  "compilerOptions": {21    "paths": {22    }23  },24}25{26  "compilerOptions": {Using AI Code Generation
1const { loadTsConfig } = require('playwright/lib/server/tsconfig');2const { webkit } = require('playwright');3(async () => {4  const browser = await webkit.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: 'example.png' });8  await browser.close();9})();Using AI Code Generation
1const { loadTsconfig } = require('playwright/lib/server/trace/common/tsconfig');2const tsconfig = await loadTsconfig('/path/to/tsconfig.json');3const { loadTrace } = require('playwright/lib/server/trace/common/traceModel');4const trace = await loadTrace('/path/to/trace.zip');5const { loadSnapshot } = require('playwright/lib/server/snapshot/snapshotter');6const snapshot = await loadSnapshot('/path/to/snapshot.blob');7const { toImpl } = require('playwright/lib/server/frames');8const frame = toImpl(page.mainFrame());9const { toChannel } = require('playwright/lib/server/frames');10const channel = toChannel(frame);11const { toImpl } = require('playwright/lib/server/frames');12const frame = toImpl(page.mainFrame());13const { toChannel } = require('playwright/lib/server/frames');14const channel = toChannel(frame);15const { toImpl } = require('playwright/lib/server/frames');16const frame = toImpl(page.mainFrame());17const { toChannel } = require('playwright/lib/server/frames');18const channel = toChannel(frame);19const { toImpl } = require('playwright/lib/server/frames');20const frame = toImpl(page.mainFrame());21const { toChannel } = require('playwright/lib/server/frames');22const channel = toChannel(frame);23const { toImpl } = require('playwright/lib/server/frames');24const frame = toImpl(page.mainFrame());25const { toChannel } = require('playwright/lib/server/frames');26const channel = toChannel(frame);LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
