How to use wrapInASCIIBox method in Playwright Internal

Best JavaScript code snippet using playwright-internal

registry.js

Source:registry.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Registry = void 0;6exports.buildPlaywrightCLICommand = buildPlaywrightCLICommand;7exports.findChromiumChannel = findChromiumChannel;8exports.installBrowsersForNpmInstall = installBrowsersForNpmInstall;9exports.installDefaultBrowsersForNpmInstall = installDefaultBrowsersForNpmInstall;10exports.registryDirectory = exports.registry = void 0;11var os = _interopRequireWildcard(require("os"));12var _path = _interopRequireDefault(require("path"));13var util = _interopRequireWildcard(require("util"));14var fs = _interopRequireWildcard(require("fs"));15var _properLockfile = _interopRequireDefault(require("proper-lockfile"));16var _ubuntuVersion = require("./ubuntuVersion");17var _utils = require("./utils");18var _dependencies = require("./dependencies");19var _browserFetcher = require("./browserFetcher");20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }21function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }22function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }23/**24 * Copyright 2017 Google Inc. All rights reserved.25 * Modifications copyright (c) Microsoft Corporation.26 *27 * Licensed under the Apache License, Version 2.0 (the "License");28 * you may not use this file except in compliance with the License.29 * You may obtain a copy of the License at30 *31 * http://www.apache.org/licenses/LICENSE-2.032 *33 * Unless required by applicable law or agreed to in writing, software34 * distributed under the License is distributed on an "AS IS" BASIS,35 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.36 * See the License for the specific language governing permissions and37 * limitations under the License.38 */39const PACKAGE_PATH = _path.default.join(__dirname, '..', '..');40const BIN_PATH = _path.default.join(__dirname, '..', '..', 'bin');41const EXECUTABLE_PATHS = {42 'chromium': {43 'linux': ['chrome-linux', 'chrome'],44 'mac': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'],45 'win': ['chrome-win', 'chrome.exe']46 },47 'firefox': {48 'linux': ['firefox', 'firefox'],49 'mac': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'],50 'win': ['firefox', 'firefox.exe']51 },52 'webkit': {53 'linux': ['pw_run.sh'],54 'mac': ['pw_run.sh'],55 'win': ['Playwright.exe']56 },57 'ffmpeg': {58 'linux': ['ffmpeg-linux'],59 'mac': ['ffmpeg-mac'],60 'win': ['ffmpeg-win64.exe']61 }62};63const DOWNLOAD_PATHS = {64 'chromium': {65 'ubuntu18.04': 'builds/chromium/%s/chromium-linux.zip',66 'ubuntu20.04': 'builds/chromium/%s/chromium-linux.zip',67 'ubuntu18.04-arm64': 'builds/chromium/%s/chromium-linux-arm64.zip',68 'ubuntu20.04-arm64': 'builds/chromium/%s/chromium-linux-arm64.zip',69 'mac10.13': 'builds/chromium/%s/chromium-mac.zip',70 'mac10.14': 'builds/chromium/%s/chromium-mac.zip',71 'mac10.15': 'builds/chromium/%s/chromium-mac.zip',72 'mac11': 'builds/chromium/%s/chromium-mac.zip',73 'mac11-arm64': 'builds/chromium/%s/chromium-mac-arm64.zip',74 'mac12': 'builds/chromium/%s/chromium-mac.zip',75 'mac12-arm64': 'builds/chromium/%s/chromium-mac-arm64.zip',76 'win64': 'builds/chromium/%s/chromium-win64.zip'77 },78 'chromium-with-symbols': {79 'ubuntu18.04': 'builds/chromium/%s/chromium-with-symbols-linux.zip',80 'ubuntu20.04': 'builds/chromium/%s/chromium-with-symbols-linux.zip',81 'ubuntu18.04-arm64': 'builds/chromium/%s/chromium-with-symbols-linux-arm64.zip',82 'ubuntu20.04-arm64': 'builds/chromium/%s/chromium-with-symbols-linux-arm64.zip',83 'mac10.13': 'builds/chromium/%s/chromium-with-symbols-mac.zip',84 'mac10.14': 'builds/chromium/%s/chromium-with-symbols-mac.zip',85 'mac10.15': 'builds/chromium/%s/chromium-with-symbols-mac.zip',86 'mac11': 'builds/chromium/%s/chromium-with-symbols-mac.zip',87 'mac11-arm64': 'builds/chromium/%s/chromium-with-symbols-mac-arm64.zip',88 'mac12': 'builds/chromium/%s/chromium-with-symbols-mac.zip',89 'mac12-arm64': 'builds/chromium/%s/chromium-with-symbols-mac-arm64.zip',90 'win64': 'builds/chromium/%s/chromium-with-symbols-win64.zip'91 },92 'firefox': {93 'ubuntu18.04': 'builds/firefox/%s/firefox-ubuntu-18.04.zip',94 'ubuntu20.04': 'builds/firefox/%s/firefox-ubuntu-20.04.zip',95 'ubuntu18.04-arm64': undefined,96 'ubuntu20.04-arm64': 'builds/firefox/%s/firefox-ubuntu-20.04-arm64.zip',97 'mac10.13': 'builds/firefox/%s/firefox-mac-11.zip',98 'mac10.14': 'builds/firefox/%s/firefox-mac-11.zip',99 'mac10.15': 'builds/firefox/%s/firefox-mac-11.zip',100 'mac11': 'builds/firefox/%s/firefox-mac-11.zip',101 'mac11-arm64': 'builds/firefox/%s/firefox-mac-11-arm64.zip',102 'mac12': 'builds/firefox/%s/firefox-mac-11.zip',103 'mac12-arm64': 'builds/firefox/%s/firefox-mac-11-arm64.zip',104 'win64': 'builds/firefox/%s/firefox-win64.zip'105 },106 'firefox-beta': {107 'ubuntu18.04': 'builds/firefox-beta/%s/firefox-beta-ubuntu-18.04.zip',108 'ubuntu20.04': 'builds/firefox-beta/%s/firefox-beta-ubuntu-20.04.zip',109 'ubuntu18.04-arm64': undefined,110 'ubuntu20.04-arm64': undefined,111 'mac10.13': 'builds/firefox-beta/%s/firefox-beta-mac-11.zip',112 'mac10.14': 'builds/firefox-beta/%s/firefox-beta-mac-11.zip',113 'mac10.15': 'builds/firefox-beta/%s/firefox-beta-mac-11.zip',114 'mac11': 'builds/firefox-beta/%s/firefox-beta-mac-11.zip',115 'mac11-arm64': 'builds/firefox-beta/%s/firefox-beta-mac-11-arm64.zip',116 'mac12': 'builds/firefox-beta/%s/firefox-beta-mac-11.zip',117 'mac12-arm64': 'builds/firefox-beta/%s/firefox-beta-mac-11-arm64.zip',118 'win64': 'builds/firefox-beta/%s/firefox-beta-win64.zip'119 },120 'webkit': {121 'ubuntu18.04': 'builds/webkit/%s/webkit-ubuntu-18.04.zip',122 'ubuntu20.04': 'builds/webkit/%s/webkit-ubuntu-20.04.zip',123 'ubuntu18.04-arm64': undefined,124 'ubuntu20.04-arm64': 'builds/webkit/%s/webkit-ubuntu-20.04-arm64.zip',125 'mac10.13': undefined,126 'mac10.14': 'builds/deprecated-webkit-mac-10.14/%s/deprecated-webkit-mac-10.14.zip',127 'mac10.15': 'builds/webkit/%s/webkit-mac-10.15.zip',128 'mac11': 'builds/webkit/%s/webkit-mac-10.15.zip',129 'mac11-arm64': 'builds/webkit/%s/webkit-mac-11-arm64.zip',130 'mac12': 'builds/webkit/%s/webkit-mac-12.zip',131 'mac12-arm64': 'builds/webkit/%s/webkit-mac-12-arm64.zip',132 'win64': 'builds/webkit/%s/webkit-win64.zip'133 },134 'ffmpeg': {135 'ubuntu18.04': 'builds/ffmpeg/%s/ffmpeg-linux.zip',136 'ubuntu20.04': 'builds/ffmpeg/%s/ffmpeg-linux.zip',137 'ubuntu18.04-arm64': 'builds/ffmpeg/%s/ffmpeg-linux-arm64.zip',138 'ubuntu20.04-arm64': 'builds/ffmpeg/%s/ffmpeg-linux-arm64.zip',139 'mac10.13': 'builds/ffmpeg/%s/ffmpeg-mac.zip',140 'mac10.14': 'builds/ffmpeg/%s/ffmpeg-mac.zip',141 'mac10.15': 'builds/ffmpeg/%s/ffmpeg-mac.zip',142 'mac11': 'builds/ffmpeg/%s/ffmpeg-mac.zip',143 'mac11-arm64': 'builds/ffmpeg/%s/ffmpeg-mac-arm64.zip',144 'mac12': 'builds/ffmpeg/%s/ffmpeg-mac.zip',145 'mac12-arm64': 'builds/ffmpeg/%s/ffmpeg-mac-arm64.zip',146 'win64': 'builds/ffmpeg/%s/ffmpeg-win64.zip'147 }148};149const registryDirectory = (() => {150 let result;151 const envDefined = (0, _utils.getFromENV)('PLAYWRIGHT_BROWSERS_PATH');152 if (envDefined === '0') {153 result = _path.default.join(__dirname, '..', '..', '.local-browsers');154 } else if (envDefined) {155 result = envDefined;156 } else {157 let cacheDirectory;158 if (process.platform === 'linux') cacheDirectory = process.env.XDG_CACHE_HOME || _path.default.join(os.homedir(), '.cache');else if (process.platform === 'darwin') cacheDirectory = _path.default.join(os.homedir(), 'Library', 'Caches');else if (process.platform === 'win32') cacheDirectory = process.env.LOCALAPPDATA || _path.default.join(os.homedir(), 'AppData', 'Local');else throw new Error('Unsupported platform: ' + process.platform);159 result = _path.default.join(cacheDirectory, 'ms-playwright');160 }161 if (!_path.default.isAbsolute(result)) {162 // It is important to resolve to the absolute path:163 // - for unzipping to work correctly;164 // - so that registry directory matches between installation and execution.165 // INIT_CWD points to the root of `npm/yarn install` and is probably what166 // the user meant when typing the relative path.167 result = _path.default.resolve((0, _utils.getFromENV)('INIT_CWD') || process.cwd(), result);168 }169 return result;170})();171exports.registryDirectory = registryDirectory;172function isBrowserDirectory(browserDirectory) {173 const baseName = _path.default.basename(browserDirectory);174 for (const browserName of allDownloadable) {175 if (baseName.startsWith(browserName + '-')) return true;176 }177 return false;178}179function readDescriptors(browsersJSON) {180 return browsersJSON['browsers'].map(obj => {181 const name = obj.name;182 const revisionOverride = (obj.revisionOverrides || {})[_utils.hostPlatform];183 const revision = revisionOverride || obj.revision;184 const browserDirectoryPrefix = revisionOverride ? `${name}_${_utils.hostPlatform}_special` : `${name}`;185 const descriptor = {186 name,187 revision,188 installByDefault: !!obj.installByDefault,189 // Method `isBrowserDirectory` determines directory to be browser iff190 // it starts with some browser name followed by '-'. Some browser names191 // are prefixes of others, e.g. 'webkit' is a prefix of `webkit-technology-preview`.192 // To avoid older registries erroneously removing 'webkit-technology-preview', we have to193 // ensure that browser folders to never include dashes inside.194 dir: _path.default.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, '_') + '-' + revision)195 };196 return descriptor;197 });198}199const allDownloadable = ['chromium', 'firefox', 'webkit', 'ffmpeg', 'firefox-beta', 'chromium-with-symbols'];200class Registry {201 constructor(browsersJSON) {202 this._executables = void 0;203 const descriptors = readDescriptors(browsersJSON);204 const findExecutablePath = (dir, name) => {205 let tokens = undefined;206 if (_utils.hostPlatform.startsWith('ubuntu')) tokens = EXECUTABLE_PATHS[name]['linux'];else if (_utils.hostPlatform.startsWith('mac')) tokens = EXECUTABLE_PATHS[name]['mac'];else if (_utils.hostPlatform.startsWith('win')) tokens = EXECUTABLE_PATHS[name]['win'];207 return tokens ? _path.default.join(dir, ...tokens) : undefined;208 };209 const executablePathOrDie = (name, e, installByDefault, sdkLanguage) => {210 if (!e) throw new Error(`${name} is not supported on ${_utils.hostPlatform}`);211 const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install${installByDefault ? '' : ' ' + name}`);212 if (!(0, _utils.canAccessFile)(e)) {213 const prettyMessage = [`Looks like Playwright Test or Playwright was just installed or updated.`, `Please run the following command to download new browser${installByDefault ? 's' : ''}:`, ``, ` ${installCommand}`, ``, `<3 Playwright Team`].join('\n');214 throw new Error(`Executable doesn't exist at ${e}\n${(0, _utils.wrapInASCIIBox)(prettyMessage, 1)}`);215 }216 return e;217 };218 this._executables = [];219 const chromium = descriptors.find(d => d.name === 'chromium');220 const chromiumExecutable = findExecutablePath(chromium.dir, 'chromium');221 this._executables.push({222 type: 'browser',223 name: 'chromium',224 browserName: 'chromium',225 directory: chromium.dir,226 executablePath: () => chromiumExecutable,227 executablePathOrDie: sdkLanguage => executablePathOrDie('chromium', chromiumExecutable, chromium.installByDefault, sdkLanguage),228 installType: chromium.installByDefault ? 'download-by-default' : 'download-on-demand',229 validateHostRequirements: sdkLanguage => this._validateHostRequirements(sdkLanguage, 'chromium', chromium.dir, ['chrome-linux'], [], ['chrome-win']),230 _install: () => this._downloadExecutable(chromium, chromiumExecutable, DOWNLOAD_PATHS['chromium'][_utils.hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'),231 _dependencyGroup: 'chromium'232 });233 const chromiumWithSymbols = descriptors.find(d => d.name === 'chromium-with-symbols');234 const chromiumWithSymbolsExecutable = findExecutablePath(chromiumWithSymbols.dir, 'chromium');235 this._executables.push({236 type: 'tool',237 name: 'chromium-with-symbols',238 browserName: 'chromium',239 directory: chromiumWithSymbols.dir,240 executablePath: () => chromiumWithSymbolsExecutable,241 executablePathOrDie: sdkLanguage => executablePathOrDie('chromium-with-symbols', chromiumWithSymbolsExecutable, chromiumWithSymbols.installByDefault, sdkLanguage),242 installType: chromiumWithSymbols.installByDefault ? 'download-by-default' : 'download-on-demand',243 validateHostRequirements: sdkLanguage => this._validateHostRequirements(sdkLanguage, 'chromium', chromiumWithSymbols.dir, ['chrome-linux'], [], ['chrome-win']),244 _install: () => this._downloadExecutable(chromiumWithSymbols, chromiumWithSymbolsExecutable, DOWNLOAD_PATHS['chromium-with-symbols'][_utils.hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'),245 _dependencyGroup: 'chromium'246 });247 this._executables.push(this._createChromiumChannel('chrome', {248 'linux': '/opt/google/chrome/chrome',249 'darwin': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',250 'win32': `\\Google\\Chrome\\Application\\chrome.exe`251 }, () => this._installChromiumChannel('chrome', {252 'linux': 'reinstall_chrome_stable_linux.sh',253 'darwin': 'reinstall_chrome_stable_mac.sh',254 'win32': 'reinstall_chrome_stable_win.ps1'255 })));256 this._executables.push(this._createChromiumChannel('chrome-beta', {257 'linux': '/opt/google/chrome-beta/chrome',258 'darwin': '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta',259 'win32': `\\Google\\Chrome Beta\\Application\\chrome.exe`260 }, () => this._installChromiumChannel('chrome-beta', {261 'linux': 'reinstall_chrome_beta_linux.sh',262 'darwin': 'reinstall_chrome_beta_mac.sh',263 'win32': 'reinstall_chrome_beta_win.ps1'264 })));265 this._executables.push(this._createChromiumChannel('chrome-dev', {266 'linux': '/opt/google/chrome-unstable/chrome',267 'darwin': '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev',268 'win32': `\\Google\\Chrome Dev\\Application\\chrome.exe`269 }));270 this._executables.push(this._createChromiumChannel('chrome-canary', {271 'linux': '',272 'darwin': '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',273 'win32': `\\Google\\Chrome SxS\\Application\\chrome.exe`274 }));275 this._executables.push(this._createChromiumChannel('msedge', {276 'linux': '/opt/microsoft/msedge/msedge',277 'darwin': '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',278 'win32': `\\Microsoft\\Edge\\Application\\msedge.exe`279 }, () => this._installMSEdgeChannel('msedge', {280 'linux': 'reinstall_msedge_stable_linux.sh',281 'darwin': 'reinstall_msedge_stable_mac.sh',282 'win32': 'reinstall_msedge_stable_win.ps1'283 })));284 this._executables.push(this._createChromiumChannel('msedge-beta', {285 'linux': '/opt/microsoft/msedge-beta/msedge',286 'darwin': '/Applications/Microsoft Edge Beta.app/Contents/MacOS/Microsoft Edge Beta',287 'win32': `\\Microsoft\\Edge Beta\\Application\\msedge.exe`288 }, () => this._installMSEdgeChannel('msedge-beta', {289 'darwin': 'reinstall_msedge_beta_mac.sh',290 'linux': 'reinstall_msedge_beta_linux.sh',291 'win32': 'reinstall_msedge_beta_win.ps1'292 })));293 this._executables.push(this._createChromiumChannel('msedge-dev', {294 'linux': '/opt/microsoft/msedge-dev/msedge',295 'darwin': '/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev',296 'win32': `\\Microsoft\\Edge Dev\\Application\\msedge.exe`297 }, () => this._installMSEdgeChannel('msedge-dev', {298 'darwin': 'reinstall_msedge_dev_mac.sh',299 'linux': 'reinstall_msedge_dev_linux.sh',300 'win32': 'reinstall_msedge_dev_win.ps1'301 })));302 this._executables.push(this._createChromiumChannel('msedge-canary', {303 'linux': '',304 'darwin': '/Applications/Microsoft Edge Canary.app/Contents/MacOS/Microsoft Edge Canary',305 'win32': `\\Microsoft\\Edge SxS\\Application\\msedge.exe`306 }));307 const firefox = descriptors.find(d => d.name === 'firefox');308 const firefoxExecutable = findExecutablePath(firefox.dir, 'firefox');309 this._executables.push({310 type: 'browser',311 name: 'firefox',312 browserName: 'firefox',313 directory: firefox.dir,314 executablePath: () => firefoxExecutable,315 executablePathOrDie: sdkLanguage => executablePathOrDie('firefox', firefoxExecutable, firefox.installByDefault, sdkLanguage),316 installType: firefox.installByDefault ? 'download-by-default' : 'download-on-demand',317 validateHostRequirements: sdkLanguage => this._validateHostRequirements(sdkLanguage, 'firefox', firefox.dir, ['firefox'], [], ['firefox']),318 _install: () => this._downloadExecutable(firefox, firefoxExecutable, DOWNLOAD_PATHS['firefox'][_utils.hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'),319 _dependencyGroup: 'firefox'320 });321 const firefoxBeta = descriptors.find(d => d.name === 'firefox-beta');322 const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, 'firefox');323 this._executables.push({324 type: 'tool',325 name: 'firefox-beta',326 browserName: 'firefox',327 directory: firefoxBeta.dir,328 executablePath: () => firefoxBetaExecutable,329 executablePathOrDie: sdkLanguage => executablePathOrDie('firefox-beta', firefoxBetaExecutable, firefoxBeta.installByDefault, sdkLanguage),330 installType: firefoxBeta.installByDefault ? 'download-by-default' : 'download-on-demand',331 validateHostRequirements: sdkLanguage => this._validateHostRequirements(sdkLanguage, 'firefox', firefoxBeta.dir, ['firefox'], [], ['firefox']),332 _install: () => this._downloadExecutable(firefoxBeta, firefoxBetaExecutable, DOWNLOAD_PATHS['firefox-beta'][_utils.hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'),333 _dependencyGroup: 'firefox'334 });335 const webkit = descriptors.find(d => d.name === 'webkit');336 const webkitExecutable = findExecutablePath(webkit.dir, 'webkit');337 const webkitLinuxLddDirectories = [_path.default.join('minibrowser-gtk'), _path.default.join('minibrowser-gtk', 'bin'), _path.default.join('minibrowser-gtk', 'lib'), _path.default.join('minibrowser-wpe'), _path.default.join('minibrowser-wpe', 'bin'), _path.default.join('minibrowser-wpe', 'lib')];338 this._executables.push({339 type: 'browser',340 name: 'webkit',341 browserName: 'webkit',342 directory: webkit.dir,343 executablePath: () => webkitExecutable,344 executablePathOrDie: sdkLanguage => executablePathOrDie('webkit', webkitExecutable, webkit.installByDefault, sdkLanguage),345 installType: webkit.installByDefault ? 'download-by-default' : 'download-on-demand',346 validateHostRequirements: sdkLanguage => this._validateHostRequirements(sdkLanguage, 'webkit', webkit.dir, webkitLinuxLddDirectories, ['libGLESv2.so.2', 'libx264.so'], ['']),347 _install: () => this._downloadExecutable(webkit, webkitExecutable, DOWNLOAD_PATHS['webkit'][_utils.hostPlatform], 'PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST'),348 _dependencyGroup: 'webkit'349 });350 const ffmpeg = descriptors.find(d => d.name === 'ffmpeg');351 const ffmpegExecutable = findExecutablePath(ffmpeg.dir, 'ffmpeg');352 this._executables.push({353 type: 'tool',354 name: 'ffmpeg',355 browserName: undefined,356 directory: ffmpeg.dir,357 executablePath: () => ffmpegExecutable,358 executablePathOrDie: sdkLanguage => executablePathOrDie('ffmpeg', ffmpegExecutable, ffmpeg.installByDefault, sdkLanguage),359 installType: ffmpeg.installByDefault ? 'download-by-default' : 'download-on-demand',360 validateHostRequirements: () => Promise.resolve(),361 _install: () => this._downloadExecutable(ffmpeg, ffmpegExecutable, DOWNLOAD_PATHS['ffmpeg'][_utils.hostPlatform], 'PLAYWRIGHT_FFMPEG_DOWNLOAD_HOST'),362 _dependencyGroup: 'tools'363 });364 }365 _createChromiumChannel(name, lookAt, install) {366 const executablePath = (sdkLanguage, shouldThrow) => {367 const suffix = lookAt[process.platform];368 if (!suffix) {369 if (shouldThrow) throw new Error(`Chromium distribution '${name}' is not supported on ${process.platform}`);370 return undefined;371 }372 const prefixes = process.platform === 'win32' ? [process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']].filter(Boolean) : [''];373 for (const prefix of prefixes) {374 const executablePath = _path.default.join(prefix, suffix);375 if ((0, _utils.canAccessFile)(executablePath)) return executablePath;376 }377 if (!shouldThrow) return undefined;378 const location = prefixes.length ? ` at ${_path.default.join(prefixes[0], suffix)}` : ``; // TODO: language-specific error message379 const installation = install ? `\nRun "${buildPlaywrightCLICommand(sdkLanguage, 'install ' + name)}"` : '';380 throw new Error(`Chromium distribution '${name}' is not found${location}${installation}`);381 };382 return {383 type: 'channel',384 name,385 browserName: 'chromium',386 directory: undefined,387 executablePath: sdkLanguage => executablePath(sdkLanguage, false),388 executablePathOrDie: sdkLanguage => executablePath(sdkLanguage, true),389 installType: install ? 'install-script' : 'none',390 validateHostRequirements: () => Promise.resolve(),391 _install: install392 };393 }394 executables() {395 return this._executables;396 }397 findExecutable(name) {398 return this._executables.find(b => b.name === name);399 }400 defaultExecutables() {401 return this._executables.filter(e => e.installType === 'download-by-default');402 }403 _addRequirementsAndDedupe(executables) {404 const set = new Set();405 for (const executable of executables) {406 set.add(executable);407 if (executable.browserName === 'chromium') set.add(this.findExecutable('ffmpeg'));408 }409 return Array.from(set);410 }411 async _validateHostRequirements(sdkLanguage, browserName, browserDirectory, linuxLddDirectories, dlOpenLibraries, windowsExeAndDllDirectories) {412 if ((0, _utils.getAsBooleanFromENV)('PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS')) {413 process.stdout.write('Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n');414 return;415 }416 const ubuntuVersion = await (0, _ubuntuVersion.getUbuntuVersion)();417 if (browserName === 'firefox' && ubuntuVersion === '16.04') throw new Error(`Cannot launch Firefox on Ubuntu 16.04! Minimum required Ubuntu version for Firefox browser is 18.04`);418 if (os.platform() === 'linux') return await (0, _dependencies.validateDependenciesLinux)(sdkLanguage, linuxLddDirectories.map(d => _path.default.join(browserDirectory, d)), dlOpenLibraries);419 if (os.platform() === 'win32' && os.arch() === 'x64') return await (0, _dependencies.validateDependenciesWindows)(windowsExeAndDllDirectories.map(d => _path.default.join(browserDirectory, d)));420 }421 async installDeps(executablesToInstallDeps, dryRun) {422 const executables = this._addRequirementsAndDedupe(executablesToInstallDeps);423 const targets = new Set();424 for (const executable of executables) {425 if (executable._dependencyGroup) targets.add(executable._dependencyGroup);426 }427 targets.add('tools');428 if (os.platform() === 'win32') return await (0, _dependencies.installDependenciesWindows)(targets, dryRun);429 if (os.platform() === 'linux') return await (0, _dependencies.installDependenciesLinux)(targets, dryRun);430 }431 async install(executablesToInstall) {432 const executables = this._addRequirementsAndDedupe(executablesToInstall);433 await fs.promises.mkdir(registryDirectory, {434 recursive: true435 });436 const lockfilePath = _path.default.join(registryDirectory, '__dirlock');437 const linksDir = _path.default.join(registryDirectory, '.links');438 let releaseLock;439 try {440 releaseLock = await _properLockfile.default.lock(registryDirectory, {441 retries: {442 // Retry 20 times during 10 minutes with443 // exponential back-off.444 // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions445 retries: 20,446 factor: 1.27579447 },448 onCompromised: err => {449 throw new Error(`${err.message} Path: ${lockfilePath}`);450 },451 lockfilePath452 }); // Create a link first, so that cache validation does not remove our own browsers.453 await fs.promises.mkdir(linksDir, {454 recursive: true455 });456 await fs.promises.writeFile(_path.default.join(linksDir, (0, _utils.calculateSha1)(PACKAGE_PATH)), PACKAGE_PATH); // Remove stale browsers.457 await this._validateInstallationCache(linksDir); // Install browsers for this package.458 for (const executable of executables) {459 if (executable._install) await executable._install();else throw new Error(`ERROR: Playwright does not support installing ${executable.name}`);460 }461 } catch (e) {462 if (e.code === 'ELOCKED') {463 const rmCommand = process.platform === 'win32' ? 'rm -R' : 'rm -rf';464 throw new Error('\n' + (0, _utils.wrapInASCIIBox)([`An active lockfile is found at:`, ``, ` ${lockfilePath}`, ``, `Either:`, `- wait a few minutes if other Playwright is installing browsers in parallel`, `- remove lock manually with:`, ``, ` ${rmCommand} ${lockfilePath}`, ``, `<3 Playwright Team`].join('\n'), 1));465 } else {466 throw e;467 }468 } finally {469 if (releaseLock) await releaseLock();470 }471 }472 async _downloadExecutable(descriptor, executablePath, downloadPathTemplate, downloadHostEnv) {473 if (!downloadPathTemplate || !executablePath) throw new Error(`ERROR: Playwright does not support ${descriptor.name} on ${_utils.hostPlatform}`);474 const downloadHost = downloadHostEnv && (0, _utils.getFromENV)(downloadHostEnv) || (0, _utils.getFromENV)('PLAYWRIGHT_DOWNLOAD_HOST') || 'https://playwright.azureedge.net';475 const downloadPath = util.format(downloadPathTemplate, descriptor.revision);476 const downloadURL = `${downloadHost}/${downloadPath}`;477 const title = `${descriptor.name} v${descriptor.revision}`;478 const downloadFileName = `playwright-download-${descriptor.name}-${_utils.hostPlatform}-${descriptor.revision}.zip`;479 await (0, _browserFetcher.downloadBrowserWithProgressBar)(title, descriptor.dir, executablePath, downloadURL, downloadFileName).catch(e => {480 throw new Error(`Failed to download ${title}, caused by\n${e.stack}`);481 });482 await fs.promises.writeFile(markerFilePath(descriptor.dir), '');483 }484 async _installMSEdgeChannel(channel, scripts) {485 const scriptArgs = [];486 if (process.platform !== 'linux') {487 const products = JSON.parse(await (0, _utils.fetchData)({488 url: 'https://edgeupdates.microsoft.com/api/products'489 }));490 const productName = {491 'msedge': 'Stable',492 'msedge-beta': 'Beta',493 'msedge-dev': 'Dev'494 }[channel];495 const product = products.find(product => product.Product === productName);496 const searchConfig = {497 darwin: {498 platform: 'MacOS',499 arch: 'universal',500 artifact: 'pkg'501 },502 win32: {503 platform: 'Windows',504 arch: 'x64',505 artifact: 'msi'506 }507 }[process.platform];508 const release = searchConfig ? product.Releases.find(release => release.Platform === searchConfig.platform && release.Architecture === searchConfig.arch) : null;509 const artifact = release ? release.Artifacts.find(artifact => artifact.ArtifactName === searchConfig.artifact) : null;510 if (artifact) scriptArgs.push(artifact.Location511 /* url */512 );else throw new Error(`Cannot install ${channel} on ${process.platform}`);513 }514 await this._installChromiumChannel(channel, scripts, scriptArgs);515 }516 async _installChromiumChannel(channel, scripts, scriptArgs = []) {517 const scriptName = scripts[process.platform];518 if (!scriptName) throw new Error(`Cannot install ${channel} on ${process.platform}`);519 const cwd = BIN_PATH;520 const isPowerShell = scriptName.endsWith('.ps1');521 if (isPowerShell) {522 const args = ['-ExecutionPolicy', 'Bypass', '-File', _path.default.join(BIN_PATH, scriptName), ...scriptArgs];523 const {524 code525 } = await (0, _utils.spawnAsync)('powershell.exe', args, {526 cwd,527 stdio: 'inherit'528 });529 if (code !== 0) throw new Error(`Failed to install ${channel}`);530 } else {531 const {532 command,533 args,534 elevatedPermissions535 } = await (0, _utils.transformCommandsForRoot)([`bash ${_path.default.join(BIN_PATH, scriptName)} ${scriptArgs.join('')}`]);536 if (elevatedPermissions) console.log('Switching to root user to install dependencies...'); // eslint-disable-line no-console537 const {538 code539 } = await (0, _utils.spawnAsync)(command, args, {540 cwd,541 stdio: 'inherit'542 });543 if (code !== 0) throw new Error(`Failed to install ${channel}`);544 }545 }546 async _validateInstallationCache(linksDir) {547 // 1. Collect used downloads and package descriptors.548 const usedBrowserPaths = new Set();549 for (const fileName of await fs.promises.readdir(linksDir)) {550 const linkPath = _path.default.join(linksDir, fileName);551 let linkTarget = '';552 try {553 linkTarget = (await fs.promises.readFile(linkPath)).toString();554 const browsersJSON = require(_path.default.join(linkTarget, 'browsers.json'));555 const descriptors = readDescriptors(browsersJSON);556 for (const browserName of allDownloadable) {557 // We retain browsers if they are found in the descriptor.558 // Note, however, that there are older versions out in the wild that rely on559 // the "download" field in the browser descriptor and use its value560 // to retain and download browsers.561 // As of v1.10, we decided to abandon "download" field.562 const descriptor = descriptors.find(d => d.name === browserName);563 if (!descriptor) continue;564 const usedBrowserPath = descriptor.dir;565 const browserRevision = parseInt(descriptor.revision, 10); // Old browser installations don't have marker file.566 const shouldHaveMarkerFile = browserName === 'chromium' && browserRevision >= 786218 || browserName === 'firefox' && browserRevision >= 1128 || browserName === 'webkit' && browserRevision >= 1307 || // All new applications have a marker file right away.567 browserName !== 'firefox' && browserName !== 'chromium' && browserName !== 'webkit';568 if (!shouldHaveMarkerFile || (await (0, _utils.existsAsync)(markerFilePath(usedBrowserPath)))) usedBrowserPaths.add(usedBrowserPath);569 }570 } catch (e) {571 await fs.promises.unlink(linkPath).catch(e => {});572 }573 } // 2. Delete all unused browsers.574 if (!(0, _utils.getAsBooleanFromENV)('PLAYWRIGHT_SKIP_BROWSER_GC')) {575 let downloadedBrowsers = (await fs.promises.readdir(registryDirectory)).map(file => _path.default.join(registryDirectory, file));576 downloadedBrowsers = downloadedBrowsers.filter(file => isBrowserDirectory(file));577 const directories = new Set(downloadedBrowsers);578 for (const browserDirectory of usedBrowserPaths) directories.delete(browserDirectory);579 for (const directory of directories) (0, _browserFetcher.logPolitely)('Removing unused browser at ' + directory);580 await (0, _utils.removeFolders)([...directories]);581 }582 }583}584exports.Registry = Registry;585function markerFilePath(browserDirectory) {586 return _path.default.join(browserDirectory, 'INSTALLATION_COMPLETE');587}588function buildPlaywrightCLICommand(sdkLanguage, parameters) {589 switch (sdkLanguage) {590 case 'python':591 return `playwright ${parameters}`;592 case 'java':593 return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="${parameters}"`;594 case 'csharp':595 return `playwright ${parameters}`;596 default:597 return `npx playwright ${parameters}`;598 }599}600async function installDefaultBrowsersForNpmInstall() {601 const defaultBrowserNames = registry.defaultExecutables().map(e => e.name);602 return installBrowsersForNpmInstall(defaultBrowserNames);603}604async function installBrowsersForNpmInstall(browsers) {605 // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1606 if ((0, _utils.getAsBooleanFromENV)('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {607 (0, _browserFetcher.logPolitely)('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');608 return false;609 }610 const executables = [];611 for (const browserName of browsers) {612 const executable = registry.findExecutable(browserName);613 if (!executable || executable.installType === 'none') throw new Error(`Cannot install ${browserName}`);614 executables.push(executable);615 }616 await registry.install(executables);617}618function findChromiumChannel(sdkLanguage) {619 // Fall back to the stable channels of popular vendors to work out of the box.620 // Null means no installation and no channels found.621 let channel = null;622 for (const name of ['chromium', 'chrome', 'msedge']) {623 try {624 registry.findExecutable(name).executablePathOrDie(sdkLanguage);625 channel = name === 'chromium' ? undefined : name;626 break;627 } catch (e) {}628 }629 if (channel === null) {630 const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install chromium`);631 const prettyMessage = [`No chromium-based browser found on the system.`, `Please run the following command to download one:`, ``, ` ${installCommand}`, ``, `<3 Playwright Team`].join('\n');632 throw new Error('\n' + (0, _utils.wrapInASCIIBox)(prettyMessage, 1));633 }634 return channel;635}636const registry = new Registry(require('../../browsers.json'));...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

...370 if (platform === 'win32') return _os.default.arch() === 'x64' ? 'win64' : 'win32';371 return platform;372})();373exports.hostPlatform = hostPlatform;374function wrapInASCIIBox(text, padding = 0) {375 const lines = text.split('\n');376 const maxLength = Math.max(...lines.map(line => line.length));377 return ['╔' + '═'.repeat(maxLength + padding * 2) + '╗', ...lines.map(line => '║' + ' '.repeat(padding) + line + ' '.repeat(maxLength - line.length + padding) + '║'), '╚' + '═'.repeat(maxLength + padding * 2) + '╝'].join('\n');...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...185 } catch (e) {186 return givenURL;187 }188}189function wrapInASCIIBox(text, padding = 0) {190 const lines = text.split('\n');191 const maxLength = Math.max(...lines.map(line => line.length));192 return ['╔' + '═'.repeat(maxLength + padding * 2) + '╗', ...lines.map(line => '║' + ' '.repeat(padding) + line + ' '.repeat(maxLength - line.length + padding) + '║'), '╚' + '═'.repeat(maxLength + padding * 2) + '╝'].join('\n');193}194function isFilePayload(value) {195 return typeof value === 'object' && value['name'] && value['mimeType'] && value['buffer'];196}197function streamToString(stream) {198 return new Promise((resolve, reject) => {199 const chunks = [];200 stream.on('data', chunk => chunks.push(Buffer.from(chunk)));201 stream.on('error', reject);202 stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));203 });...

Full Screen

Full Screen

dockerGridFactory.js

Source:dockerGridFactory.js Github

copy

Full Screen

...44 var _process$env$PWTEST_I, _info$NetworkSettings;45 const gridPort = new URL(gridURL).port || '80';46 const images = await getJSON('/images/json');47 if (!images) {48 throw new Error(`\n` + utils.wrapInASCIIBox([`Failed to list docker images`, `Please ensure docker is running.`, ``, `<3 Playwright Team`].join('\n'), 1));49 }50 const imageName = (_process$env$PWTEST_I = process.env.PWTEST_IMAGE_NAME) !== null && _process$env$PWTEST_I !== void 0 ? _process$env$PWTEST_I : `mcr.microsoft.com/playwright:v${require('../../package.json').version}-focal`;51 const pwImage = images.find(image => {52 var _image$RepoTags;53 return (_image$RepoTags = image.RepoTags) === null || _image$RepoTags === void 0 ? void 0 : _image$RepoTags.includes(imageName);54 });55 if (!pwImage) {56 throw new Error(`\n` + utils.wrapInASCIIBox([`Failed to find ${imageName} docker image.`, `Please pull docker image with the following command:`, ``, ` npx playwright install docker-image`, ``, `<3 Playwright Team`].join('\n'), 1));57 }58 const Env = ['PW_SOCKS_PROXY_PORT=1' // Enable port forwarding over PlaywrightClient59 ];60 const forwardIfDefined = envName => {61 if (process.env[envName]) Env.push(`CI=${process.env[envName]}`);62 };63 forwardIfDefined('CI');64 forwardIfDefined('PWDEBUG');65 forwardIfDefined('DEBUG');66 forwardIfDefined('DEBUG_FILE');67 forwardIfDefined('SELENIUM_REMOTE_URL');68 const container = await postJSON('/containers/create', {69 Env,70 WorkingDir: '/ms-playwright-agent',...

Full Screen

Full Screen

firefox.js

Source:firefox.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.Firefox = void 0;6var os = _interopRequireWildcard(require("os"));7var _fs = _interopRequireDefault(require("fs"));8var _path = _interopRequireDefault(require("path"));9var _ffBrowser = require("./ffBrowser");10var _ffConnection = require("./ffConnection");11var _browserType = require("../browserType");12var _stackTrace = require("../../utils/stackTrace");13var _utils = require("../../utils");14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }15function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }17/**18 * Copyright 2017 Google Inc. All rights reserved.19 * Modifications copyright (c) Microsoft Corporation.20 *21 * Licensed under the Apache License, Version 2.0 (the "License");22 * you may not use this file except in compliance with the License.23 * You may obtain a copy of the License at24 *25 * http://www.apache.org/licenses/LICENSE-2.026 *27 * Unless required by applicable law or agreed to in writing, software28 * distributed under the License is distributed on an "AS IS" BASIS,29 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.30 * See the License for the specific language governing permissions and31 * limitations under the License.32 */33class Firefox extends _browserType.BrowserType {34 constructor(playwrightOptions) {35 super('firefox', playwrightOptions);36 }37 _connectToTransport(transport, options) {38 return _ffBrowser.FFBrowser.connect(transport, options);39 }40 _rewriteStartupError(error) {41 if (error.message.includes('no DISPLAY environment variable specified')) return (0, _stackTrace.rewriteErrorMessage)(error, '\n' + (0, _utils.wrapInASCIIBox)(_browserType.kNoXServerRunningError, 1));42 return error;43 }44 _amendEnvironment(env, userDataDir, executable, browserArguments) {45 if (!_path.default.isAbsolute(os.homedir())) throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${os.platform() === 'win32' ? 'USERPROFILE' : 'HOME'} to a relative path?`);46 if (os.platform() === 'linux') {47 return { ...env,48 // On linux Juggler ships the libstdc++ it was linked against.49 LD_LIBRARY_PATH: `${_path.default.dirname(executable)}:${process.env.LD_LIBRARY_PATH}`50 };51 }52 return env;53 }54 _attemptToGracefullyCloseBrowser(transport) {55 const message = {56 method: 'Browser.close',57 params: {},58 id: _ffConnection.kBrowserCloseMessageId59 };60 transport.send(message);61 }62 _defaultArgs(options, isPersistent, userDataDir) {63 const {64 args = [],65 headless66 } = options;67 const userDataDirArg = args.find(arg => arg.startsWith('-profile') || arg.startsWith('--profile'));68 if (userDataDirArg) throw new Error('Pass userDataDir parameter to `browserType.launchPersistentContext(userDataDir, ...)` instead of specifying --profile argument');69 if (args.find(arg => arg.startsWith('-juggler'))) throw new Error('Use the port parameter instead of -juggler argument');70 const firefoxUserPrefs = isPersistent ? undefined : options.firefoxUserPrefs;71 if (firefoxUserPrefs) {72 const lines = [];73 for (const [name, value] of Object.entries(firefoxUserPrefs)) lines.push(`user_pref(${JSON.stringify(name)}, ${JSON.stringify(value)});`);74 _fs.default.writeFileSync(_path.default.join(userDataDir, 'user.js'), lines.join('\n'));75 }76 const firefoxArguments = ['-no-remote'];77 if (headless) {78 firefoxArguments.push('-headless');79 } else {80 firefoxArguments.push('-wait-for-browser');81 firefoxArguments.push('-foreground');82 }83 firefoxArguments.push(`-profile`, userDataDir);84 firefoxArguments.push('-juggler-pipe');85 firefoxArguments.push(...args);86 if (isPersistent) firefoxArguments.push('about:blank');else firefoxArguments.push('-silent');87 return firefoxArguments;88 }89}...

Full Screen

Full Screen

webkit.js

Source:webkit.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.WebKit = void 0;6var _wkBrowser = require("../webkit/wkBrowser");7var _path = _interopRequireDefault(require("path"));8var _wkConnection = require("./wkConnection");9var _browserType = require("../browserType");10var _stackTrace = require("../../utils/stackTrace");11var _utils = require("../../utils");12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }13/**14 * Copyright 2017 Google Inc. All rights reserved.15 * Modifications copyright (c) Microsoft Corporation.16 *17 * Licensed under the Apache License, Version 2.0 (the "License");18 * you may not use this file except in compliance with the License.19 * You may obtain a copy of the License at20 *21 * http://www.apache.org/licenses/LICENSE-2.022 *23 * Unless required by applicable law or agreed to in writing, software24 * distributed under the License is distributed on an "AS IS" BASIS,25 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26 * See the License for the specific language governing permissions and27 * limitations under the License.28 */29class WebKit extends _browserType.BrowserType {30 constructor(playwrightOptions) {31 super('webkit', playwrightOptions);32 }33 _connectToTransport(transport, options) {34 return _wkBrowser.WKBrowser.connect(transport, options);35 }36 _amendEnvironment(env, userDataDir, executable, browserArguments) {37 return { ...env,38 CURL_COOKIE_JAR_PATH: _path.default.join(userDataDir, 'cookiejar.db')39 };40 }41 _rewriteStartupError(error) {42 if (error.message.includes('cannot open display')) return (0, _stackTrace.rewriteErrorMessage)(error, '\n' + (0, _utils.wrapInASCIIBox)(_browserType.kNoXServerRunningError, 1));43 return error;44 }45 _attemptToGracefullyCloseBrowser(transport) {46 transport.send({47 method: 'Playwright.close',48 params: {},49 id: _wkConnection.kBrowserCloseMessageId50 });51 }52 _defaultArgs(options, isPersistent, userDataDir) {53 const {54 args = [],55 proxy,56 headless57 } = options;58 const userDataDirArg = args.find(arg => arg.startsWith('--user-data-dir'));59 if (userDataDirArg) throw new Error('Pass userDataDir parameter to `browserType.launchPersistentContext(userDataDir, ...)` instead of specifying --user-data-dir argument');60 if (args.find(arg => !arg.startsWith('-'))) throw new Error('Arguments can not specify page to be opened');61 const webkitArguments = ['--inspector-pipe'];62 if (process.platform === 'win32') webkitArguments.push('--disable-accelerated-compositing');63 if (headless) webkitArguments.push('--headless');64 if (isPersistent) webkitArguments.push(`--user-data-dir=${userDataDir}`);else webkitArguments.push(`--no-startup-window`);65 if (proxy) {66 if (process.platform === 'darwin') {67 webkitArguments.push(`--proxy=${proxy.server}`);68 if (proxy.bypass) webkitArguments.push(`--proxy-bypass-list=${proxy.bypass}`);69 } else if (process.platform === 'linux') {70 webkitArguments.push(`--proxy=${proxy.server}`);71 if (proxy.bypass) webkitArguments.push(...proxy.bypass.split(',').map(t => `--ignore-host=${t}`));72 } else if (process.platform === 'win32') {73 webkitArguments.push(`--curl-proxy=${proxy.server}`);74 if (proxy.bypass) webkitArguments.push(`--curl-noproxy=${proxy.bypass}`);75 }76 }77 webkitArguments.push(...args);78 if (isPersistent) webkitArguments.push('about:blank');79 return webkitArguments;80 }81}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const text = await page.evaluate(() => {7 return document.querySelector('text=Playwright').textContent;8 });9 const box = await page._delegate.wrapInASCIIBox(text);10 console.log(box);11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wrapInASCIIBox } = require('@playwright/test');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.textContent('h1');5 console.log(wrapInASCIIBox(title));6});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wrapInASCIIBox } = require('playwright-core/lib/utils/asciiBox');2console.log(wrapInASCIIBox('Hello World!'));3const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');4console.log(wrapInASCIIBox('Hello World!'));5const { wrapInASCIIBox } = require('playwright-chromium/lib/utils/asciiBox');6console.log(wrapInASCIIBox('Hello World!'));7const { wrapInASCIIBox } = require('playwright-firefox/lib/utils/asciiBox');8console.log(wrapInASCIIBox('Hello World!'));9const { wrapInASCIIBox } = require('playwright-webkit/lib/utils/asciiBox');10console.log(wrapInASCIIBox('Hello World!'));11const { wrapInASCIIBox } = require('playwright-aws-lambda/lib/utils/asciiBox');12console.log(wrapInASCIIBox('Hello World!'));13const { wrapInASCIIBox } = require('playwright-core/lib/utils/asciiBox');14console.log(wrapInASCIIBox('Hello World!'));15const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');16console.log(wrapInASCIIBox('Hello World!'));17const { wrapInASCIIBox } = require('playwright-chromium/lib/utils/asciiBox');18console.log(wrapInASCIIBox('Hello World!'));19const { wrapInASCIIBox } = require('playwright-firefox/lib/utils/asciiBox');20console.log(wrapInASCIIBox('Hello World!'));21const { wrapInASCIIBox } = require('playwright-webkit/lib/utils/asciiBox');22console.log(wrapInASCIIBox('Hello World!

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wrapInASCIIBox } = require('@playwright/test/lib/utils/asciiBox');2console.log(wrapInASCIIBox('Hello World'));3console.log(message);4console.log('Hello World');53. Using console.table()6console.table(data[, properties]);7 { name: 'John', age: 25 },8 { name: 'Peter', age: 30 },9];10console.table(data);11│ (index) │ name │ age │124. Using console.dir()13console.dir(obj[, options]);14const obj = { name: 'John', age: 25 };15console.dir(obj);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');2const box = wrapInASCIIBox('Hello World', {3});4console.log(box);5const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');6const box = wrapInASCIIBox('Hello World', {7});8console.log(box);9const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');10const box = wrapInASCIIBox('Hello World', {11});12console.log(box);13const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');14const box = wrapInASCIIBox('Hello World', {15});16console.log(box);17const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');18const box = wrapInASCIIBox('Hello World', {19});20console.log(box);21const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');22const box = wrapInASCIIBox('Hello World', {23});24console.log(box);25const { wrapInASCIIBox } = require('playwright/lib/utils/asciiBox');26const box = wrapInASCIIBox('Hello World', {27});28console.log(box);29const { wrapInASCIIBox } = require('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');2const text = wrapInASCIIBox('Hello World', 20, 10);3console.log(text);4const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');5const text = wrapInASCIIBox('Hello World', 20, 10, 'green');6console.log(text);7const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');8const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red');9console.log(text);10const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');11const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white');12console.log(text);13const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');14const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white', 'yellow');15console.log(text);16const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');17const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white', 'yellow', 'blue');18console.log(text);19const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');20const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white', 'yellow', 'blue', 'magenta');21console.log(text);22const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');23const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white', 'yellow', 'blue', 'magenta', 'cyan');24console.log(text);25const { wrapInASCIIBox } = require('playwright/lib/utils/ascii');26const text = wrapInASCIIBox('Hello World', 20, 10, 'green', 'red', 'white', 'yellow', 'blue', 'magenta', 'cyan', 'black');

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful