First Commit

This commit is contained in:
2025-08-28 19:35:28 -07:00
commit 264e65006a
488 changed files with 155661 additions and 0 deletions

65
node_modules/playwright-core/lib/androidServerImpl.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var androidServerImpl_exports = {};
__export(androidServerImpl_exports, {
AndroidServerLauncherImpl: () => AndroidServerLauncherImpl
});
module.exports = __toCommonJS(androidServerImpl_exports);
var import_playwrightServer = require("./remote/playwrightServer");
var import_playwright = require("./server/playwright");
var import_crypto = require("./server/utils/crypto");
var import_utilsBundle = require("./utilsBundle");
var import_progress = require("./server/progress");
class AndroidServerLauncherImpl {
async launchServer(options = {}) {
const playwright = (0, import_playwright.createPlaywright)({ sdkLanguage: "javascript", isServer: true });
const controller = new import_progress.ProgressController();
let devices = await controller.run((progress) => playwright.android.devices(progress, {
host: options.adbHost,
port: options.adbPort,
omitDriverInstall: options.omitDriverInstall
}));
if (devices.length === 0)
throw new Error("No devices found");
if (options.deviceSerialNumber) {
devices = devices.filter((d) => d.serial === options.deviceSerialNumber);
if (devices.length === 0)
throw new Error(`No device with serial number '${options.deviceSerialNumber}' was found`);
}
if (devices.length > 1)
throw new Error(`More than one device found. Please specify deviceSerialNumber`);
const device = devices[0];
const path = options.wsPath ? options.wsPath.startsWith("/") ? options.wsPath : `/${options.wsPath}` : `/${(0, import_crypto.createGuid)()}`;
const server = new import_playwrightServer.PlaywrightServer({ mode: "launchServer", path, maxConnections: 1, preLaunchedAndroidDevice: device });
const wsEndpoint = await server.listen(options.port, options.host);
const browserServer = new import_utilsBundle.ws.EventEmitter();
browserServer.wsEndpoint = () => wsEndpoint;
browserServer.close = () => device.close();
browserServer.kill = () => device.close();
device.on("close", () => {
server.close();
browserServer.emit("close");
});
return browserServer;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AndroidServerLauncherImpl
});

123
node_modules/playwright-core/lib/browserServerImpl.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserServerImpl_exports = {};
__export(browserServerImpl_exports, {
BrowserServerLauncherImpl: () => BrowserServerLauncherImpl
});
module.exports = __toCommonJS(browserServerImpl_exports);
var import_playwrightServer = require("./remote/playwrightServer");
var import_helper = require("./server/helper");
var import_playwright = require("./server/playwright");
var import_crypto = require("./server/utils/crypto");
var import_debug = require("./server/utils/debug");
var import_stackTrace = require("./utils/isomorphic/stackTrace");
var import_time = require("./utils/isomorphic/time");
var import_utilsBundle = require("./utilsBundle");
var validatorPrimitives = __toESM(require("./protocol/validatorPrimitives"));
var import_progress = require("./server/progress");
class BrowserServerLauncherImpl {
constructor(browserName) {
this._browserName = browserName;
}
async launchServer(options = {}) {
const playwright = (0, import_playwright.createPlaywright)({ sdkLanguage: "javascript", isServer: true });
const metadata = { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true };
const validatorContext = {
tChannelImpl: (names, arg, path) => {
throw new validatorPrimitives.ValidationError(`${path}: channels are not expected in launchServer`);
},
binary: "buffer",
isUnderTest: import_debug.isUnderTest
};
let launchOptions = {
...options,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : void 0,
ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),
env: options.env ? envObjectToArray(options.env) : void 0,
timeout: options.timeout ?? import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT
};
let browser;
try {
const controller = new import_progress.ProgressController(metadata);
browser = await controller.run(async (progress) => {
if (options._userDataDir !== void 0) {
const validator = validatorPrimitives.scheme["BrowserTypeLaunchPersistentContextParams"];
launchOptions = validator({ ...launchOptions, userDataDir: options._userDataDir }, "", validatorContext);
const context = await playwright[this._browserName].launchPersistentContext(progress, options._userDataDir, launchOptions);
return context._browser;
} else {
const validator = validatorPrimitives.scheme["BrowserTypeLaunchParams"];
launchOptions = validator(launchOptions, "", validatorContext);
return await playwright[this._browserName].launch(progress, launchOptions, toProtocolLogger(options.logger));
}
});
} catch (e) {
const log = import_helper.helper.formatBrowserLogs(metadata.log);
(0, import_stackTrace.rewriteErrorMessage)(e, `${e.message} Failed to launch browser.${log}`);
throw e;
}
return this.launchServerOnExistingBrowser(browser, options);
}
async launchServerOnExistingBrowser(browser, options) {
const path = options.wsPath ? options.wsPath.startsWith("/") ? options.wsPath : `/${options.wsPath}` : `/${(0, import_crypto.createGuid)()}`;
const server = new import_playwrightServer.PlaywrightServer({ mode: options._sharedBrowser ? "launchServerShared" : "launchServer", path, maxConnections: Infinity, preLaunchedBrowser: browser, debugController: options._debugController });
const wsEndpoint = await server.listen(options.port, options.host);
const browserServer = new import_utilsBundle.ws.EventEmitter();
browserServer.process = () => browser.options.browserProcess.process;
browserServer.wsEndpoint = () => wsEndpoint;
browserServer.close = () => browser.options.browserProcess.close();
browserServer[Symbol.asyncDispose] = browserServer.close;
browserServer.kill = () => browser.options.browserProcess.kill();
browserServer._disconnectForTest = () => server.close();
browserServer._userDataDirForTest = browser._userDataDirForTest;
browser.options.browserProcess.onclose = (exitCode, signal) => {
server.close();
browserServer.emit("close", exitCode, signal);
};
return browserServer;
}
}
function toProtocolLogger(logger) {
return logger ? (direction, message) => {
if (logger.isEnabled("protocol", "verbose"))
logger.log("protocol", "verbose", (direction === "send" ? "SEND \u25BA " : "\u25C0 RECV ") + JSON.stringify(message), [], {});
} : void 0;
}
function envObjectToArray(env) {
const result = [];
for (const name in env) {
if (!Object.is(env[name], void 0))
result.push({ name, value: String(env[name]) });
}
return result;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserServerLauncherImpl
});

97
node_modules/playwright-core/lib/cli/driver.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var driver_exports = {};
__export(driver_exports, {
launchBrowserServer: () => launchBrowserServer,
printApiJson: () => printApiJson,
runDriver: () => runDriver,
runServer: () => runServer
});
module.exports = __toCommonJS(driver_exports);
var import_fs = __toESM(require("fs"));
var playwright = __toESM(require("../.."));
var import_pipeTransport = require("../server/utils/pipeTransport");
var import_playwrightServer = require("../remote/playwrightServer");
var import_server = require("../server");
var import_processLauncher = require("../server/utils/processLauncher");
function printApiJson() {
console.log(JSON.stringify(require("../../api.json")));
}
function runDriver() {
const dispatcherConnection = new import_server.DispatcherConnection();
new import_server.RootDispatcher(dispatcherConnection, async (rootScope, { sdkLanguage }) => {
const playwright2 = (0, import_server.createPlaywright)({ sdkLanguage });
return new import_server.PlaywrightDispatcher(rootScope, playwright2);
});
const transport = new import_pipeTransport.PipeTransport(process.stdout, process.stdin);
transport.onmessage = (message) => dispatcherConnection.dispatch(JSON.parse(message));
const isJavaScriptLanguageBinding = !process.env.PW_LANG_NAME || process.env.PW_LANG_NAME === "javascript";
const replacer = !isJavaScriptLanguageBinding && String.prototype.toWellFormed ? (key, value) => {
if (typeof value === "string")
return value.toWellFormed();
return value;
} : void 0;
dispatcherConnection.onmessage = (message) => transport.send(JSON.stringify(message, replacer));
transport.onclose = () => {
dispatcherConnection.onmessage = () => {
};
(0, import_processLauncher.gracefullyProcessExitDoNotHang)(0);
};
process.on("SIGINT", () => {
});
}
async function runServer(options) {
const {
port,
host,
path = "/",
maxConnections = Infinity,
extension
} = options;
const server = new import_playwrightServer.PlaywrightServer({ mode: extension ? "extension" : "default", path, maxConnections });
const wsEndpoint = await server.listen(port, host);
process.on("exit", () => server.close().catch(console.error));
console.log("Listening on " + wsEndpoint);
process.stdin.on("close", () => (0, import_processLauncher.gracefullyProcessExitDoNotHang)(0));
}
async function launchBrowserServer(browserName, configFile) {
let options = {};
if (configFile)
options = JSON.parse(import_fs.default.readFileSync(configFile).toString());
const browserType = playwright[browserName];
const server = await browserType.launchServer(options);
console.log(server.wsEndpoint());
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
launchBrowserServer,
printApiJson,
runDriver,
runServer
});

633
node_modules/playwright-core/lib/cli/program.js generated vendored Normal file
View File

@@ -0,0 +1,633 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var program_exports = {};
__export(program_exports, {
program: () => import_utilsBundle2.program
});
module.exports = __toCommonJS(program_exports);
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var playwright = __toESM(require("../.."));
var import_driver = require("./driver");
var import_server = require("../server");
var import_utils = require("../utils");
var import_traceViewer = require("../server/trace/viewer/traceViewer");
var import_utils2 = require("../utils");
var import_ascii = require("../server/utils/ascii");
var import_utilsBundle = require("../utilsBundle");
var import_utilsBundle2 = require("../utilsBundle");
const packageJSON = require("../../package.json");
import_utilsBundle.program.version("Version " + (process.env.PW_CLI_DISPLAY_VERSION || packageJSON.version)).name(buildBasePlaywrightCLICommand(process.env.PW_LANG_NAME));
import_utilsBundle.program.command("mark-docker-image [dockerImageNameTemplate]", { hidden: true }).description("mark docker image").allowUnknownOption(true).action(function(dockerImageNameTemplate) {
(0, import_utils2.assert)(dockerImageNameTemplate, "dockerImageNameTemplate is required");
(0, import_server.writeDockerVersion)(dockerImageNameTemplate).catch(logErrorAndExit);
});
commandWithOpenOptions("open [url]", "open page in browser specified via -b, --browser", []).action(function(url, options) {
open(options, url).catch(logErrorAndExit);
}).addHelpText("afterAll", `
Examples:
$ open
$ open -b webkit https://example.com`);
commandWithOpenOptions(
"codegen [url]",
"open page and generate code for user actions",
[
["-o, --output <file name>", "saves the generated script to a file"],
["--target <language>", `language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, java, java-junit`, codegenId()],
["--test-id-attribute <attributeName>", "use the specified attribute to generate data test ID selectors"]
]
).action(async function(url, options) {
await codegen(options, url);
}).addHelpText("afterAll", `
Examples:
$ codegen
$ codegen --target=python
$ codegen -b webkit https://example.com`);
function suggestedBrowsersToInstall() {
return import_server.registry.executables().filter((e) => e.installType !== "none" && e.type !== "tool").map((e) => e.name).join(", ");
}
function defaultBrowsersToInstall(options) {
let executables = import_server.registry.defaultExecutables();
if (options.noShell)
executables = executables.filter((e) => e.name !== "chromium-headless-shell");
if (options.onlyShell)
executables = executables.filter((e) => e.name !== "chromium");
return executables;
}
function checkBrowsersToInstall(args, options) {
if (options.noShell && options.onlyShell)
throw new Error(`Only one of --no-shell and --only-shell can be specified`);
const faultyArguments = [];
const executables = [];
const handleArgument = (arg) => {
const executable = import_server.registry.findExecutable(arg);
if (!executable || executable.installType === "none")
faultyArguments.push(arg);
else
executables.push(executable);
if (executable?.browserName === "chromium")
executables.push(import_server.registry.findExecutable("ffmpeg"));
};
for (const arg of args) {
if (arg === "chromium") {
if (!options.onlyShell)
handleArgument("chromium");
if (!options.noShell)
handleArgument("chromium-headless-shell");
} else {
handleArgument(arg);
}
}
if (process.platform === "win32")
executables.push(import_server.registry.findExecutable("winldd"));
if (faultyArguments.length)
throw new Error(`Invalid installation targets: ${faultyArguments.map((name) => `'${name}'`).join(", ")}. Expecting one of: ${suggestedBrowsersToInstall()}`);
return executables;
}
function printInstalledBrowsers(browsers2) {
const browserPaths = /* @__PURE__ */ new Set();
for (const browser of browsers2)
browserPaths.add(browser.browserPath);
console.log(` Browsers:`);
for (const browserPath of [...browserPaths].sort())
console.log(` ${browserPath}`);
console.log(` References:`);
const references = /* @__PURE__ */ new Set();
for (const browser of browsers2)
references.add(browser.referenceDir);
for (const reference of [...references].sort())
console.log(` ${reference}`);
}
function printGroupedByPlaywrightVersion(browsers2) {
const dirToVersion = /* @__PURE__ */ new Map();
for (const browser of browsers2) {
if (dirToVersion.has(browser.referenceDir))
continue;
const packageJSON2 = require(import_path.default.join(browser.referenceDir, "package.json"));
const version = packageJSON2.version;
dirToVersion.set(browser.referenceDir, version);
}
const groupedByPlaywrightMinorVersion = /* @__PURE__ */ new Map();
for (const browser of browsers2) {
const version = dirToVersion.get(browser.referenceDir);
let entries = groupedByPlaywrightMinorVersion.get(version);
if (!entries) {
entries = [];
groupedByPlaywrightMinorVersion.set(version, entries);
}
entries.push(browser);
}
const sortedVersions = [...groupedByPlaywrightMinorVersion.keys()].sort((a, b) => {
const aComponents = a.split(".");
const bComponents = b.split(".");
const aMajor = parseInt(aComponents[0], 10);
const bMajor = parseInt(bComponents[0], 10);
if (aMajor !== bMajor)
return aMajor - bMajor;
const aMinor = parseInt(aComponents[1], 10);
const bMinor = parseInt(bComponents[1], 10);
if (aMinor !== bMinor)
return aMinor - bMinor;
return aComponents.slice(2).join(".").localeCompare(bComponents.slice(2).join("."));
});
for (const version of sortedVersions) {
console.log(`
Playwright version: ${version}`);
printInstalledBrowsers(groupedByPlaywrightMinorVersion.get(version));
}
}
import_utilsBundle.program.command("install [browser...]").description("ensure browsers necessary for this version of Playwright are installed").option("--with-deps", "install system dependencies for browsers").option("--dry-run", "do not execute installation, only print information").option("--list", "prints list of browsers from all playwright installations").option("--force", "force reinstall of stable browser channels").option("--only-shell", "only install headless shell when installing chromium").option("--no-shell", "do not install chromium headless shell").action(async function(args, options) {
if (options.shell === false)
options.noShell = true;
if ((0, import_utils.isLikelyNpxGlobal)()) {
console.error((0, import_ascii.wrapInASCIIBox)([
`WARNING: It looks like you are running 'npx playwright install' without first`,
`installing your project's dependencies.`,
``,
`To avoid unexpected behavior, please install your dependencies first, and`,
`then run Playwright's install command:`,
``,
` npm install`,
` npx playwright install`,
``,
`If your project does not yet depend on Playwright, first install the`,
`applicable npm package (most commonly @playwright/test), and`,
`then run Playwright's install command to download the browsers:`,
``,
` npm install @playwright/test`,
` npx playwright install`,
``
].join("\n"), 1));
}
try {
const hasNoArguments = !args.length;
const executables = hasNoArguments ? defaultBrowsersToInstall(options) : checkBrowsersToInstall(args, options);
if (options.withDeps)
await import_server.registry.installDeps(executables, !!options.dryRun);
if (options.dryRun && options.list)
throw new Error(`Only one of --dry-run and --list can be specified`);
if (options.dryRun) {
for (const executable of executables) {
const version = executable.browserVersion ? `version ` + executable.browserVersion : "";
console.log(`browser: ${executable.name}${version ? " " + version : ""}`);
console.log(` Install location: ${executable.directory ?? "<system>"}`);
if (executable.downloadURLs?.length) {
const [url, ...fallbacks] = executable.downloadURLs;
console.log(` Download url: ${url}`);
for (let i = 0; i < fallbacks.length; ++i)
console.log(` Download fallback ${i + 1}: ${fallbacks[i]}`);
}
console.log(``);
}
} else if (options.list) {
const browsers2 = await import_server.registry.listInstalledBrowsers();
printGroupedByPlaywrightVersion(browsers2);
} else {
const forceReinstall = hasNoArguments ? false : !!options.force;
await import_server.registry.install(executables, forceReinstall);
await import_server.registry.validateHostRequirementsForExecutablesIfNeeded(executables, process.env.PW_LANG_NAME || "javascript").catch((e) => {
e.name = "Playwright Host validation warning";
console.error(e);
});
}
} catch (e) {
console.log(`Failed to install browsers
${e}`);
(0, import_utils.gracefullyProcessExitDoNotHang)(1);
}
}).addHelpText("afterAll", `
Examples:
- $ install
Install default browsers.
- $ install chrome firefox
Install custom browsers, supports ${suggestedBrowsersToInstall()}.`);
import_utilsBundle.program.command("uninstall").description("Removes browsers used by this installation of Playwright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.").option("--all", "Removes all browsers used by any Playwright installation from the system.").action(async (options) => {
delete process.env.PLAYWRIGHT_SKIP_BROWSER_GC;
await import_server.registry.uninstall(!!options.all).then(({ numberOfBrowsersLeft }) => {
if (!options.all && numberOfBrowsersLeft > 0) {
console.log("Successfully uninstalled Playwright browsers for the current Playwright installation.");
console.log(`There are still ${numberOfBrowsersLeft} browsers left, used by other Playwright installations.
To uninstall Playwright browsers for all installations, re-run with --all flag.`);
}
}).catch(logErrorAndExit);
});
import_utilsBundle.program.command("install-deps [browser...]").description("install dependencies necessary to run browsers (will ask for sudo permissions)").option("--dry-run", "Do not execute installation commands, only print them").action(async function(args, options) {
try {
if (!args.length)
await import_server.registry.installDeps(defaultBrowsersToInstall({}), !!options.dryRun);
else
await import_server.registry.installDeps(checkBrowsersToInstall(args, {}), !!options.dryRun);
} catch (e) {
console.log(`Failed to install browser dependencies
${e}`);
(0, import_utils.gracefullyProcessExitDoNotHang)(1);
}
}).addHelpText("afterAll", `
Examples:
- $ install-deps
Install dependencies for default browsers.
- $ install-deps chrome firefox
Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`);
const browsers = [
{ alias: "cr", name: "Chromium", type: "chromium" },
{ alias: "ff", name: "Firefox", type: "firefox" },
{ alias: "wk", name: "WebKit", type: "webkit" }
];
for (const { alias, name, type } of browsers) {
commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []).action(function(url, options) {
open({ ...options, browser: type }, url).catch(logErrorAndExit);
}).addHelpText("afterAll", `
Examples:
$ ${alias} https://example.com`);
}
commandWithOpenOptions(
"screenshot <url> <filename>",
"capture a page screenshot",
[
["--wait-for-selector <selector>", "wait for selector before taking a screenshot"],
["--wait-for-timeout <timeout>", "wait for timeout in milliseconds before taking a screenshot"],
["--full-page", "whether to take a full page screenshot (entire scrollable area)"]
]
).action(function(url, filename, command) {
screenshot(command, command, url, filename).catch(logErrorAndExit);
}).addHelpText("afterAll", `
Examples:
$ screenshot -b webkit https://example.com example.png`);
commandWithOpenOptions(
"pdf <url> <filename>",
"save page as pdf",
[
["--paper-format <format>", "paper format: Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6"],
["--wait-for-selector <selector>", "wait for given selector before saving as pdf"],
["--wait-for-timeout <timeout>", "wait for given timeout in milliseconds before saving as pdf"]
]
).action(function(url, filename, options) {
pdf(options, options, url, filename).catch(logErrorAndExit);
}).addHelpText("afterAll", `
Examples:
$ pdf https://example.com example.pdf`);
import_utilsBundle.program.command("run-driver", { hidden: true }).action(function(options) {
(0, import_driver.runDriver)();
});
import_utilsBundle.program.command("run-server").option("--port <port>", "Server port").option("--host <host>", "Server host").option("--path <path>", "Endpoint Path", "/").option("--max-clients <maxClients>", "Maximum clients").option("--mode <mode>", 'Server mode, either "default" or "extension"').action(function(options) {
(0, import_driver.runServer)({
port: options.port ? +options.port : void 0,
host: options.host,
path: options.path,
maxConnections: options.maxClients ? +options.maxClients : Infinity,
extension: options.mode === "extension" || !!process.env.PW_EXTENSION_MODE
}).catch(logErrorAndExit);
});
import_utilsBundle.program.command("print-api-json", { hidden: true }).action(function(options) {
(0, import_driver.printApiJson)();
});
import_utilsBundle.program.command("launch-server", { hidden: true }).requiredOption("--browser <browserName>", 'Browser name, one of "chromium", "firefox" or "webkit"').option("--config <path-to-config-file>", "JSON file with launchServer options").action(function(options) {
(0, import_driver.launchBrowserServer)(options.browser, options.config);
});
import_utilsBundle.program.command("show-trace [trace...]").option("-b, --browser <browserType>", "browser to use, one of cr, chromium, ff, firefox, wk, webkit", "chromium").option("-h, --host <host>", "Host to serve trace on; specifying this option opens trace in a browser tab").option("-p, --port <port>", "Port to serve trace on, 0 for any free port; specifying this option opens trace in a browser tab").option("--stdin", "Accept trace URLs over stdin to update the viewer").description("show trace viewer").action(function(traces, options) {
if (options.browser === "cr")
options.browser = "chromium";
if (options.browser === "ff")
options.browser = "firefox";
if (options.browser === "wk")
options.browser = "webkit";
const openOptions = {
host: options.host,
port: +options.port,
isServer: !!options.stdin
};
if (options.port !== void 0 || options.host !== void 0)
(0, import_traceViewer.runTraceInBrowser)(traces, openOptions).catch(logErrorAndExit);
else
(0, import_traceViewer.runTraceViewerApp)(traces, options.browser, openOptions, true).catch(logErrorAndExit);
}).addHelpText("afterAll", `
Examples:
$ show-trace https://example.com/trace.zip`);
async function launchContext(options, extraOptions) {
validateOptions(options);
const browserType = lookupBrowserType(options);
const launchOptions = extraOptions;
if (options.channel)
launchOptions.channel = options.channel;
launchOptions.handleSIGINT = false;
const contextOptions = (
// Copy the device descriptor since we have to compare and modify the options.
options.device ? { ...playwright.devices[options.device] } : {}
);
if (!extraOptions.headless)
contextOptions.deviceScaleFactor = import_os.default.platform() === "darwin" ? 2 : 1;
if (browserType.name() === "webkit" && process.platform === "linux") {
delete contextOptions.hasTouch;
delete contextOptions.isMobile;
}
if (contextOptions.isMobile && browserType.name() === "firefox")
contextOptions.isMobile = void 0;
if (options.blockServiceWorkers)
contextOptions.serviceWorkers = "block";
if (options.proxyServer) {
launchOptions.proxy = {
server: options.proxyServer
};
if (options.proxyBypass)
launchOptions.proxy.bypass = options.proxyBypass;
}
if (options.viewportSize) {
try {
const [width, height] = options.viewportSize.split(",").map((n) => +n);
if (isNaN(width) || isNaN(height))
throw new Error("bad values");
contextOptions.viewport = { width, height };
} catch (e) {
throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
}
}
if (options.geolocation) {
try {
const [latitude, longitude] = options.geolocation.split(",").map((n) => parseFloat(n.trim()));
contextOptions.geolocation = {
latitude,
longitude
};
} catch (e) {
throw new Error('Invalid geolocation format, should be "lat,long". For example --geolocation="37.819722,-122.478611"');
}
contextOptions.permissions = ["geolocation"];
}
if (options.userAgent)
contextOptions.userAgent = options.userAgent;
if (options.lang)
contextOptions.locale = options.lang;
if (options.colorScheme)
contextOptions.colorScheme = options.colorScheme;
if (options.timezone)
contextOptions.timezoneId = options.timezone;
if (options.loadStorage)
contextOptions.storageState = options.loadStorage;
if (options.ignoreHttpsErrors)
contextOptions.ignoreHTTPSErrors = true;
if (options.saveHar) {
contextOptions.recordHar = { path: import_path.default.resolve(process.cwd(), options.saveHar), mode: "minimal" };
if (options.saveHarGlob)
contextOptions.recordHar.urlFilter = options.saveHarGlob;
contextOptions.serviceWorkers = "block";
}
let browser;
let context;
if (options.userDataDir) {
context = await browserType.launchPersistentContext(options.userDataDir, { ...launchOptions, ...contextOptions });
browser = context.browser();
} else {
browser = await browserType.launch(launchOptions);
context = await browser.newContext(contextOptions);
}
let closingBrowser = false;
async function closeBrowser() {
if (closingBrowser)
return;
closingBrowser = true;
if (options.saveStorage)
await context.storageState({ path: options.saveStorage }).catch((e) => null);
if (options.saveHar)
await context.close();
await browser.close();
}
context.on("page", (page) => {
page.on("dialog", () => {
});
page.on("close", () => {
const hasPage = browser.contexts().some((context2) => context2.pages().length > 0);
if (hasPage)
return;
closeBrowser().catch(() => {
});
});
});
process.on("SIGINT", async () => {
await closeBrowser();
(0, import_utils.gracefullyProcessExitDoNotHang)(130);
});
const timeout = options.timeout ? parseInt(options.timeout, 10) : 0;
context.setDefaultTimeout(timeout);
context.setDefaultNavigationTimeout(timeout);
delete launchOptions.headless;
delete launchOptions.executablePath;
delete launchOptions.handleSIGINT;
delete contextOptions.deviceScaleFactor;
return { browser, browserName: browserType.name(), context, contextOptions, launchOptions, closeBrowser };
}
async function openPage(context, url) {
let page = context.pages()[0];
if (!page)
page = await context.newPage();
if (url) {
if (import_fs.default.existsSync(url))
url = "file://" + import_path.default.resolve(url);
else if (!url.startsWith("http") && !url.startsWith("file://") && !url.startsWith("about:") && !url.startsWith("data:"))
url = "http://" + url;
await page.goto(url);
}
return page;
}
async function open(options, url) {
const { context } = await launchContext(options, { headless: !!process.env.PWTEST_CLI_HEADLESS, executablePath: process.env.PWTEST_CLI_EXECUTABLE_PATH });
await openPage(context, url);
}
async function codegen(options, url) {
const { target: language, output: outputFile, testIdAttribute: testIdAttributeName } = options;
const tracesDir = import_path.default.join(import_os.default.tmpdir(), `playwright-recorder-trace-${Date.now()}`);
const { context, browser, launchOptions, contextOptions, closeBrowser } = await launchContext(options, {
headless: !!process.env.PWTEST_CLI_HEADLESS,
executablePath: process.env.PWTEST_CLI_EXECUTABLE_PATH,
tracesDir
});
const donePromise = new import_utils.ManualPromise();
maybeSetupTestHooks(browser, closeBrowser, donePromise);
import_utilsBundle.dotenv.config({ path: "playwright.env" });
await context._enableRecorder({
language,
launchOptions,
contextOptions,
device: options.device,
saveStorage: options.saveStorage,
mode: "recording",
testIdAttributeName,
outputFile: outputFile ? import_path.default.resolve(outputFile) : void 0,
handleSIGINT: false
});
await openPage(context, url);
donePromise.resolve();
}
async function maybeSetupTestHooks(browser, closeBrowser, donePromise) {
if (!process.env.PWTEST_CLI_IS_UNDER_TEST)
return;
const logs = [];
require("playwright-core/lib/utilsBundle").debug.log = (...args) => {
const line = require("util").format(...args) + "\n";
logs.push(line);
process.stderr.write(line);
};
browser.on("disconnected", () => {
const hasCrashLine = logs.some((line) => line.includes("process did exit:") && !line.includes("process did exit: exitCode=0, signal=null"));
if (hasCrashLine) {
process.stderr.write("Detected browser crash.\n");
(0, import_utils.gracefullyProcessExitDoNotHang)(1);
}
});
const close = async () => {
await donePromise;
await closeBrowser();
};
if (process.env.PWTEST_CLI_EXIT_AFTER_TIMEOUT) {
setTimeout(close, +process.env.PWTEST_CLI_EXIT_AFTER_TIMEOUT);
return;
}
let stdin = "";
process.stdin.on("data", (data) => {
stdin += data.toString();
if (stdin.startsWith("exit")) {
process.stdin.destroy();
close();
}
});
}
async function waitForPage(page, captureOptions) {
if (captureOptions.waitForSelector) {
console.log(`Waiting for selector ${captureOptions.waitForSelector}...`);
await page.waitForSelector(captureOptions.waitForSelector);
}
if (captureOptions.waitForTimeout) {
console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`);
await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10));
}
}
async function screenshot(options, captureOptions, url, path2) {
const { context } = await launchContext(options, { headless: true });
console.log("Navigating to " + url);
const page = await openPage(context, url);
await waitForPage(page, captureOptions);
console.log("Capturing screenshot into " + path2);
await page.screenshot({ path: path2, fullPage: !!captureOptions.fullPage });
await page.close();
}
async function pdf(options, captureOptions, url, path2) {
if (options.browser !== "chromium")
throw new Error("PDF creation is only working with Chromium");
const { context } = await launchContext({ ...options, browser: "chromium" }, { headless: true });
console.log("Navigating to " + url);
const page = await openPage(context, url);
await waitForPage(page, captureOptions);
console.log("Saving as pdf into " + path2);
await page.pdf({ path: path2, format: captureOptions.paperFormat });
await page.close();
}
function lookupBrowserType(options) {
let name = options.browser;
if (options.device) {
const device = playwright.devices[options.device];
name = device.defaultBrowserType;
}
let browserType;
switch (name) {
case "chromium":
browserType = playwright.chromium;
break;
case "webkit":
browserType = playwright.webkit;
break;
case "firefox":
browserType = playwright.firefox;
break;
case "cr":
browserType = playwright.chromium;
break;
case "wk":
browserType = playwright.webkit;
break;
case "ff":
browserType = playwright.firefox;
break;
}
if (browserType)
return browserType;
import_utilsBundle.program.help();
}
function validateOptions(options) {
if (options.device && !(options.device in playwright.devices)) {
const lines = [`Device descriptor not found: '${options.device}', available devices are:`];
for (const name in playwright.devices)
lines.push(` "${name}"`);
throw new Error(lines.join("\n"));
}
if (options.colorScheme && !["light", "dark"].includes(options.colorScheme))
throw new Error('Invalid color scheme, should be one of "light", "dark"');
}
function logErrorAndExit(e) {
if (process.env.PWDEBUGIMPL)
console.error(e);
else
console.error(e.name + ": " + e.message);
(0, import_utils.gracefullyProcessExitDoNotHang)(1);
}
function codegenId() {
return process.env.PW_LANG_NAME || "playwright-test";
}
function commandWithOpenOptions(command, description, options) {
let result = import_utilsBundle.program.command(command).description(description);
for (const option of options)
result = result.option(option[0], ...option.slice(1));
return result.option("-b, --browser <browserType>", "browser to use, one of cr, chromium, ff, firefox, wk, webkit", "chromium").option("--block-service-workers", "block service workers").option("--channel <channel>", 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc').option("--color-scheme <scheme>", 'emulate preferred color scheme, "light" or "dark"').option("--device <deviceName>", 'emulate device, for example "iPhone 11"').option("--geolocation <coordinates>", 'specify geolocation coordinates, for example "37.819722,-122.478611"').option("--ignore-https-errors", "ignore https errors").option("--load-storage <filename>", "load context storage state from the file, previously saved with --save-storage").option("--lang <language>", 'specify language / locale, for example "en-GB"').option("--proxy-server <proxy>", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"').option("--proxy-bypass <bypass>", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option("--save-har <filename>", "save HAR file with all network activity at the end").option("--save-har-glob <glob pattern>", "filter entries in the HAR by matching url against this glob pattern").option("--save-storage <filename>", "save context storage state at the end, for later use with --load-storage").option("--timezone <time zone>", 'time zone to emulate, for example "Europe/Rome"').option("--timeout <timeout>", "timeout for Playwright actions in milliseconds, no timeout by default").option("--user-agent <ua string>", "specify user agent string").option("--user-data-dir <directory>", "use the specified user data directory instead of a new context").option("--viewport-size <size>", 'specify browser viewport size in pixels, for example "1280, 720"');
}
function buildBasePlaywrightCLICommand(cliTargetLang) {
switch (cliTargetLang) {
case "python":
return `playwright`;
case "java":
return `mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="...options.."`;
case "csharp":
return `pwsh bin/Debug/netX/playwright.ps1`;
default: {
const packageManagerCommand = (0, import_utils2.getPackageManagerExecCommand)();
return `${packageManagerCommand} playwright`;
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
program
});

View File

@@ -0,0 +1,74 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var programWithTestStub_exports = {};
__export(programWithTestStub_exports, {
program: () => import_program2.program
});
module.exports = __toCommonJS(programWithTestStub_exports);
var import_processLauncher = require("../server/utils/processLauncher");
var import_utils = require("../utils");
var import_program = require("./program");
var import_program2 = require("./program");
function printPlaywrightTestError(command) {
const packages = [];
for (const pkg of ["playwright", "playwright-chromium", "playwright-firefox", "playwright-webkit"]) {
try {
require.resolve(pkg);
packages.push(pkg);
} catch (e) {
}
}
if (!packages.length)
packages.push("playwright");
const packageManager = (0, import_utils.getPackageManager)();
if (packageManager === "yarn") {
console.error(`Please install @playwright/test package before running "yarn playwright ${command}"`);
console.error(` yarn remove ${packages.join(" ")}`);
console.error(" yarn add -D @playwright/test");
} else if (packageManager === "pnpm") {
console.error(`Please install @playwright/test package before running "pnpm exec playwright ${command}"`);
console.error(` pnpm remove ${packages.join(" ")}`);
console.error(" pnpm add -D @playwright/test");
} else {
console.error(`Please install @playwright/test package before running "npx playwright ${command}"`);
console.error(` npm uninstall ${packages.join(" ")}`);
console.error(" npm install -D @playwright/test");
}
}
const kExternalPlaywrightTestCommands = [
["test", "Run tests with Playwright Test."],
["show-report", "Show Playwright Test HTML report."],
["merge-reports", "Merge Playwright Test Blob reports"]
];
function addExternalPlaywrightTestCommands() {
for (const [command, description] of kExternalPlaywrightTestCommands) {
const playwrightTest = import_program.program.command(command).allowUnknownOption(true).allowExcessArguments(true);
playwrightTest.description(`${description} Available in @playwright/test package.`);
playwrightTest.action(async () => {
printPlaywrightTestError(command);
(0, import_processLauncher.gracefullyProcessExitDoNotHang)(1);
});
}
}
if (!process.env.PW_LANG_NAME)
addExternalPlaywrightTestCommands();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
program
});

View File

@@ -0,0 +1,49 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var accessibility_exports = {};
__export(accessibility_exports, {
Accessibility: () => Accessibility
});
module.exports = __toCommonJS(accessibility_exports);
function axNodeFromProtocol(axNode) {
const result = {
...axNode,
value: axNode.valueNumber !== void 0 ? axNode.valueNumber : axNode.valueString,
checked: axNode.checked === "checked" ? true : axNode.checked === "unchecked" ? false : axNode.checked,
pressed: axNode.pressed === "pressed" ? true : axNode.pressed === "released" ? false : axNode.pressed,
children: axNode.children ? axNode.children.map(axNodeFromProtocol) : void 0
};
delete result.valueNumber;
delete result.valueString;
return result;
}
class Accessibility {
constructor(channel) {
this._channel = channel;
}
async snapshot(options = {}) {
const root = options.root ? options.root._elementChannel : void 0;
const result = await this._channel.accessibilitySnapshot({ interestingOnly: options.interestingOnly, root });
return result.rootAXNode ? axNodeFromProtocol(result.rootAXNode) : null;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Accessibility
});

361
node_modules/playwright-core/lib/client/android.js generated vendored Normal file
View File

@@ -0,0 +1,361 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var android_exports = {};
__export(android_exports, {
Android: () => Android,
AndroidDevice: () => AndroidDevice,
AndroidInput: () => AndroidInput,
AndroidSocket: () => AndroidSocket,
AndroidWebView: () => AndroidWebView
});
module.exports = __toCommonJS(android_exports);
var import_eventEmitter = require("./eventEmitter");
var import_browserContext = require("./browserContext");
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_events = require("./events");
var import_waiter = require("./waiter");
var import_timeoutSettings = require("./timeoutSettings");
var import_rtti = require("../utils/isomorphic/rtti");
var import_time = require("../utils/isomorphic/time");
var import_timeoutRunner = require("../utils/isomorphic/timeoutRunner");
var import_webSocket = require("./webSocket");
class Android extends import_channelOwner.ChannelOwner {
static from(android) {
return android._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform);
}
setDefaultTimeout(timeout) {
this._timeoutSettings.setDefaultTimeout(timeout);
}
async devices(options = {}) {
const { devices } = await this._channel.devices(options);
return devices.map((d) => AndroidDevice.from(d));
}
async launchServer(options = {}) {
if (!this._serverLauncher)
throw new Error("Launching server is not supported");
return await this._serverLauncher.launchServer(options);
}
async connect(wsEndpoint, options = {}) {
return await this._wrapApiCall(async () => {
const deadline = options.timeout ? (0, import_time.monotonicTime)() + options.timeout : 0;
const headers = { "x-playwright-browser": "android", ...options.headers };
const connectParams = { wsEndpoint, headers, slowMo: options.slowMo, timeout: options.timeout || 0 };
const connection = await (0, import_webSocket.connectOverWebSocket)(this._connection, connectParams);
let device;
connection.on("close", () => {
device?._didClose();
});
const result = await (0, import_timeoutRunner.raceAgainstDeadline)(async () => {
const playwright = await connection.initializePlaywright();
if (!playwright._initializer.preConnectedAndroidDevice) {
connection.close();
throw new Error("Malformed endpoint. Did you use Android.launchServer method?");
}
device = AndroidDevice.from(playwright._initializer.preConnectedAndroidDevice);
device._shouldCloseConnectionOnClose = true;
device.on(import_events.Events.AndroidDevice.Close, () => connection.close());
return device;
}, deadline);
if (!result.timedOut) {
return result.result;
} else {
connection.close();
throw new Error(`Timeout ${options.timeout}ms exceeded`);
}
});
}
}
class AndroidDevice extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._webViews = /* @__PURE__ */ new Map();
this._shouldCloseConnectionOnClose = false;
this._android = parent;
this.input = new AndroidInput(this);
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform, parent._timeoutSettings);
this._channel.on("webViewAdded", ({ webView }) => this._onWebViewAdded(webView));
this._channel.on("webViewRemoved", ({ socketName }) => this._onWebViewRemoved(socketName));
this._channel.on("close", () => this._didClose());
}
static from(androidDevice) {
return androidDevice._object;
}
_onWebViewAdded(webView) {
const view = new AndroidWebView(this, webView);
this._webViews.set(webView.socketName, view);
this.emit(import_events.Events.AndroidDevice.WebView, view);
}
_onWebViewRemoved(socketName) {
const view = this._webViews.get(socketName);
this._webViews.delete(socketName);
if (view)
view.emit(import_events.Events.AndroidWebView.Close);
}
setDefaultTimeout(timeout) {
this._timeoutSettings.setDefaultTimeout(timeout);
}
serial() {
return this._initializer.serial;
}
model() {
return this._initializer.model;
}
webViews() {
return [...this._webViews.values()];
}
async webView(selector, options) {
const predicate = (v) => {
if (selector.pkg)
return v.pkg() === selector.pkg;
if (selector.socketName)
return v._socketName() === selector.socketName;
return false;
};
const webView = [...this._webViews.values()].find(predicate);
if (webView)
return webView;
return await this.waitForEvent("webview", { ...options, predicate });
}
async wait(selector, options = {}) {
await this._channel.wait({ androidSelector: toSelectorChannel(selector), ...options, timeout: this._timeoutSettings.timeout(options) });
}
async fill(selector, text, options = {}) {
await this._channel.fill({ androidSelector: toSelectorChannel(selector), text, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async press(selector, key, options = {}) {
await this.tap(selector, options);
await this.input.press(key);
}
async tap(selector, options = {}) {
await this._channel.tap({ androidSelector: toSelectorChannel(selector), ...options, timeout: this._timeoutSettings.timeout(options) });
}
async drag(selector, dest, options = {}) {
await this._channel.drag({ androidSelector: toSelectorChannel(selector), dest, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async fling(selector, direction, options = {}) {
await this._channel.fling({ androidSelector: toSelectorChannel(selector), direction, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async longTap(selector, options = {}) {
await this._channel.longTap({ androidSelector: toSelectorChannel(selector), ...options, timeout: this._timeoutSettings.timeout(options) });
}
async pinchClose(selector, percent, options = {}) {
await this._channel.pinchClose({ androidSelector: toSelectorChannel(selector), percent, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async pinchOpen(selector, percent, options = {}) {
await this._channel.pinchOpen({ androidSelector: toSelectorChannel(selector), percent, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async scroll(selector, direction, percent, options = {}) {
await this._channel.scroll({ androidSelector: toSelectorChannel(selector), direction, percent, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async swipe(selector, direction, percent, options = {}) {
await this._channel.swipe({ androidSelector: toSelectorChannel(selector), direction, percent, ...options, timeout: this._timeoutSettings.timeout(options) });
}
async info(selector) {
return (await this._channel.info({ androidSelector: toSelectorChannel(selector) })).info;
}
async screenshot(options = {}) {
const { binary } = await this._channel.screenshot();
if (options.path)
await this._platform.fs().promises.writeFile(options.path, binary);
return binary;
}
async [Symbol.asyncDispose]() {
await this.close();
}
async close() {
try {
if (this._shouldCloseConnectionOnClose)
this._connection.close();
else
await this._channel.close();
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
return;
throw e;
}
}
_didClose() {
this.emit(import_events.Events.AndroidDevice.Close, this);
}
async shell(command) {
const { result } = await this._channel.shell({ command });
return result;
}
async open(command) {
return AndroidSocket.from((await this._channel.open({ command })).socket);
}
async installApk(file, options) {
await this._channel.installApk({ file: await loadFile(this._platform, file), args: options && options.args });
}
async push(file, path, options) {
await this._channel.push({ file: await loadFile(this._platform, file), path, mode: options ? options.mode : void 0 });
}
async launchBrowser(options = {}) {
const contextOptions = await (0, import_browserContext.prepareBrowserContextParams)(this._platform, options);
const result = await this._channel.launchBrowser(contextOptions);
const context = import_browserContext.BrowserContext.from(result.context);
const selectors = this._android._playwright.selectors;
selectors._contextsForSelectors.add(context);
context.once(import_events.Events.BrowserContext.Close, () => selectors._contextsForSelectors.delete(context));
await context._initializeHarFromOptions(options.recordHar);
return context;
}
async waitForEvent(event, optionsOrPredicate = {}) {
return await this._wrapApiCall(async () => {
const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
const waiter = import_waiter.Waiter.createForEvent(this, event);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
if (event !== import_events.Events.AndroidDevice.Close)
waiter.rejectOnEvent(this, import_events.Events.AndroidDevice.Close, () => new import_errors.TargetClosedError());
const result = await waiter.waitForEvent(this, event, predicate);
waiter.dispose();
return result;
});
}
}
class AndroidSocket extends import_channelOwner.ChannelOwner {
static from(androidDevice) {
return androidDevice._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._channel.on("data", ({ data }) => this.emit(import_events.Events.AndroidSocket.Data, data));
this._channel.on("close", () => this.emit(import_events.Events.AndroidSocket.Close));
}
async write(data) {
await this._channel.write({ data });
}
async close() {
await this._channel.close();
}
async [Symbol.asyncDispose]() {
await this.close();
}
}
async function loadFile(platform, file) {
if ((0, import_rtti.isString)(file))
return await platform.fs().promises.readFile(file);
return file;
}
class AndroidInput {
constructor(device) {
this._device = device;
}
async type(text) {
await this._device._channel.inputType({ text });
}
async press(key) {
await this._device._channel.inputPress({ key });
}
async tap(point) {
await this._device._channel.inputTap({ point });
}
async swipe(from, segments, steps) {
await this._device._channel.inputSwipe({ segments, steps });
}
async drag(from, to, steps) {
await this._device._channel.inputDrag({ from, to, steps });
}
}
function toSelectorChannel(selector) {
const {
checkable,
checked,
clazz,
clickable,
depth,
desc,
enabled,
focusable,
focused,
hasChild,
hasDescendant,
longClickable,
pkg,
res,
scrollable,
selected,
text
} = selector;
const toRegex = (value) => {
if (value === void 0)
return void 0;
if ((0, import_rtti.isRegExp)(value))
return value.source;
return "^" + value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d") + "$";
};
return {
checkable,
checked,
clazz: toRegex(clazz),
pkg: toRegex(pkg),
desc: toRegex(desc),
res: toRegex(res),
text: toRegex(text),
clickable,
depth,
enabled,
focusable,
focused,
hasChild: hasChild ? { androidSelector: toSelectorChannel(hasChild.selector) } : void 0,
hasDescendant: hasDescendant ? { androidSelector: toSelectorChannel(hasDescendant.selector), maxDepth: hasDescendant.maxDepth } : void 0,
longClickable,
scrollable,
selected
};
}
class AndroidWebView extends import_eventEmitter.EventEmitter {
constructor(device, data) {
super(device._platform);
this._device = device;
this._data = data;
}
pid() {
return this._data.pid;
}
pkg() {
return this._data.pkg;
}
_socketName() {
return this._data.socketName;
}
async page() {
if (!this._pagePromise)
this._pagePromise = this._fetchPage();
return await this._pagePromise;
}
async _fetchPage() {
const { context } = await this._device._channel.connectToWebView({ socketName: this._data.socketName });
return import_browserContext.BrowserContext.from(context).pages()[0];
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Android,
AndroidDevice,
AndroidInput,
AndroidSocket,
AndroidWebView
});

137
node_modules/playwright-core/lib/client/api.js generated vendored Normal file
View File

@@ -0,0 +1,137 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var api_exports = {};
__export(api_exports, {
APIRequest: () => import_fetch.APIRequest,
APIRequestContext: () => import_fetch.APIRequestContext,
APIResponse: () => import_fetch.APIResponse,
Accessibility: () => import_accessibility.Accessibility,
Android: () => import_android.Android,
AndroidDevice: () => import_android.AndroidDevice,
AndroidInput: () => import_android.AndroidInput,
AndroidSocket: () => import_android.AndroidSocket,
AndroidWebView: () => import_android.AndroidWebView,
Browser: () => import_browser.Browser,
BrowserContext: () => import_browserContext.BrowserContext,
BrowserType: () => import_browserType.BrowserType,
CDPSession: () => import_cdpSession.CDPSession,
Clock: () => import_clock.Clock,
ConsoleMessage: () => import_consoleMessage.ConsoleMessage,
Coverage: () => import_coverage.Coverage,
Dialog: () => import_dialog.Dialog,
Download: () => import_download.Download,
Electron: () => import_electron.Electron,
ElectronApplication: () => import_electron.ElectronApplication,
ElementHandle: () => import_elementHandle.ElementHandle,
FileChooser: () => import_fileChooser.FileChooser,
Frame: () => import_frame.Frame,
FrameLocator: () => import_locator.FrameLocator,
JSHandle: () => import_jsHandle.JSHandle,
Keyboard: () => import_input.Keyboard,
Locator: () => import_locator.Locator,
Mouse: () => import_input.Mouse,
Page: () => import_page.Page,
Playwright: () => import_playwright.Playwright,
Request: () => import_network.Request,
Response: () => import_network.Response,
Route: () => import_network.Route,
Selectors: () => import_selectors.Selectors,
TimeoutError: () => import_errors.TimeoutError,
Touchscreen: () => import_input.Touchscreen,
Tracing: () => import_tracing.Tracing,
Video: () => import_video.Video,
WebError: () => import_webError.WebError,
WebSocket: () => import_network.WebSocket,
WebSocketRoute: () => import_network.WebSocketRoute,
Worker: () => import_worker.Worker
});
module.exports = __toCommonJS(api_exports);
var import_accessibility = require("./accessibility");
var import_android = require("./android");
var import_browser = require("./browser");
var import_browserContext = require("./browserContext");
var import_browserType = require("./browserType");
var import_clock = require("./clock");
var import_consoleMessage = require("./consoleMessage");
var import_coverage = require("./coverage");
var import_dialog = require("./dialog");
var import_download = require("./download");
var import_electron = require("./electron");
var import_locator = require("./locator");
var import_elementHandle = require("./elementHandle");
var import_fileChooser = require("./fileChooser");
var import_errors = require("./errors");
var import_frame = require("./frame");
var import_input = require("./input");
var import_jsHandle = require("./jsHandle");
var import_network = require("./network");
var import_fetch = require("./fetch");
var import_page = require("./page");
var import_selectors = require("./selectors");
var import_tracing = require("./tracing");
var import_video = require("./video");
var import_worker = require("./worker");
var import_cdpSession = require("./cdpSession");
var import_playwright = require("./playwright");
var import_webError = require("./webError");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
APIRequest,
APIRequestContext,
APIResponse,
Accessibility,
Android,
AndroidDevice,
AndroidInput,
AndroidSocket,
AndroidWebView,
Browser,
BrowserContext,
BrowserType,
CDPSession,
Clock,
ConsoleMessage,
Coverage,
Dialog,
Download,
Electron,
ElectronApplication,
ElementHandle,
FileChooser,
Frame,
FrameLocator,
JSHandle,
Keyboard,
Locator,
Mouse,
Page,
Playwright,
Request,
Response,
Route,
Selectors,
TimeoutError,
Touchscreen,
Tracing,
Video,
WebError,
WebSocket,
WebSocketRoute,
Worker
});

79
node_modules/playwright-core/lib/client/artifact.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var artifact_exports = {};
__export(artifact_exports, {
Artifact: () => Artifact
});
module.exports = __toCommonJS(artifact_exports);
var import_channelOwner = require("./channelOwner");
var import_stream = require("./stream");
var import_fileUtils = require("./fileUtils");
class Artifact extends import_channelOwner.ChannelOwner {
static from(channel) {
return channel._object;
}
async pathAfterFinished() {
if (this._connection.isRemote())
throw new Error(`Path is not available when connecting remotely. Use saveAs() to save a local copy.`);
return (await this._channel.pathAfterFinished()).value;
}
async saveAs(path) {
if (!this._connection.isRemote()) {
await this._channel.saveAs({ path });
return;
}
const result = await this._channel.saveAsStream();
const stream = import_stream.Stream.from(result.stream);
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, path);
await new Promise((resolve, reject) => {
stream.stream().pipe(this._platform.fs().createWriteStream(path)).on("finish", resolve).on("error", reject);
});
}
async failure() {
return (await this._channel.failure()).error || null;
}
async createReadStream() {
const result = await this._channel.stream();
const stream = import_stream.Stream.from(result.stream);
return stream.stream();
}
async readIntoBuffer() {
const stream = await this.createReadStream();
return await new Promise((resolve, reject) => {
const chunks = [];
stream.on("data", (chunk) => {
chunks.push(chunk);
});
stream.on("end", () => {
resolve(Buffer.concat(chunks));
});
stream.on("error", reject);
});
}
async cancel() {
return await this._channel.cancel();
}
async delete() {
return await this._channel.delete();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Artifact
});

173
node_modules/playwright-core/lib/client/browser.js generated vendored Normal file
View File

@@ -0,0 +1,173 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browser_exports = {};
__export(browser_exports, {
Browser: () => Browser
});
module.exports = __toCommonJS(browser_exports);
var import_artifact = require("./artifact");
var import_browserContext = require("./browserContext");
var import_cdpSession = require("./cdpSession");
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_events = require("./events");
var import_fileUtils = require("./fileUtils");
class Browser extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._contexts = /* @__PURE__ */ new Set();
this._isConnected = true;
this._shouldCloseConnectionOnClose = false;
this._options = {};
this._name = initializer.name;
this._channel.on("context", ({ context }) => this._didCreateContext(import_browserContext.BrowserContext.from(context)));
this._channel.on("close", () => this._didClose());
this._closedPromise = new Promise((f) => this.once(import_events.Events.Browser.Disconnected, f));
}
static from(browser) {
return browser._object;
}
browserType() {
return this._browserType;
}
async newContext(options = {}) {
return await this._innerNewContext(options, false);
}
async _newContextForReuse(options = {}) {
return await this._innerNewContext(options, true);
}
async _disconnectFromReusedContext(reason) {
const context = [...this._contexts].find((context2) => context2._forReuse);
if (!context)
return;
await this._instrumentation.runBeforeCloseBrowserContext(context);
for (const page of context.pages())
page._onClose();
context._onClose();
await this._channel.disconnectFromReusedContext({ reason });
}
async _innerNewContext(options = {}, forReuse) {
options = this._browserType._playwright.selectors._withSelectorOptions({
...this._browserType._playwright._defaultContextOptions,
...options
});
const contextOptions = await (0, import_browserContext.prepareBrowserContextParams)(this._platform, options);
const response = forReuse ? await this._channel.newContextForReuse(contextOptions) : await this._channel.newContext(contextOptions);
const context = import_browserContext.BrowserContext.from(response.context);
if (forReuse)
context._forReuse = true;
if (options.logger)
context._logger = options.logger;
await context._initializeHarFromOptions(options.recordHar);
await this._instrumentation.runAfterCreateBrowserContext(context);
return context;
}
_connectToBrowserType(browserType, browserOptions, logger) {
this._browserType = browserType;
this._options = browserOptions;
this._logger = logger;
for (const context of this._contexts)
this._setupBrowserContext(context);
}
_didCreateContext(context) {
context._browser = this;
this._contexts.add(context);
if (this._browserType)
this._setupBrowserContext(context);
}
_setupBrowserContext(context) {
context._logger = this._logger;
context.tracing._tracesDir = this._options.tracesDir;
this._browserType._contexts.add(context);
this._browserType._playwright.selectors._contextsForSelectors.add(context);
context.setDefaultTimeout(this._browserType._playwright._defaultContextTimeout);
context.setDefaultNavigationTimeout(this._browserType._playwright._defaultContextNavigationTimeout);
}
contexts() {
return [...this._contexts];
}
version() {
return this._initializer.version;
}
async newPage(options = {}) {
return await this._wrapApiCall(async () => {
const context = await this.newContext(options);
const page = await context.newPage();
page._ownedContext = context;
context._ownerPage = page;
return page;
}, { title: "Create page" });
}
isConnected() {
return this._isConnected;
}
async newBrowserCDPSession() {
return import_cdpSession.CDPSession.from((await this._channel.newBrowserCDPSession()).session);
}
async _launchServer(options = {}) {
const serverLauncher = this._browserType._serverLauncher;
const browserImpl = this._connection.toImpl?.(this);
if (!serverLauncher || !browserImpl)
throw new Error("Launching server is not supported");
return await serverLauncher.launchServerOnExistingBrowser(browserImpl, {
_sharedBrowser: true,
...options
});
}
async startTracing(page, options = {}) {
this._path = options.path;
await this._channel.startTracing({ ...options, page: page ? page._channel : void 0 });
}
async stopTracing() {
const artifact = import_artifact.Artifact.from((await this._channel.stopTracing()).artifact);
const buffer = await artifact.readIntoBuffer();
await artifact.delete();
if (this._path) {
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, this._path);
await this._platform.fs().promises.writeFile(this._path, buffer);
this._path = void 0;
}
return buffer;
}
async [Symbol.asyncDispose]() {
await this.close();
}
async close(options = {}) {
this._closeReason = options.reason;
try {
if (this._shouldCloseConnectionOnClose)
this._connection.close();
else
await this._channel.close(options);
await this._closedPromise;
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
return;
throw e;
}
}
_didClose() {
this._isConnected = false;
this.emit(import_events.Events.Browser.Disconnected, this);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Browser
});

View File

@@ -0,0 +1,535 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserContext_exports = {};
__export(browserContext_exports, {
BrowserContext: () => BrowserContext,
prepareBrowserContextParams: () => prepareBrowserContextParams,
toClientCertificatesProtocol: () => toClientCertificatesProtocol
});
module.exports = __toCommonJS(browserContext_exports);
var import_artifact = require("./artifact");
var import_cdpSession = require("./cdpSession");
var import_channelOwner = require("./channelOwner");
var import_clientHelper = require("./clientHelper");
var import_clock = require("./clock");
var import_consoleMessage = require("./consoleMessage");
var import_dialog = require("./dialog");
var import_errors = require("./errors");
var import_events = require("./events");
var import_fetch = require("./fetch");
var import_frame = require("./frame");
var import_harRouter = require("./harRouter");
var network = __toESM(require("./network"));
var import_page = require("./page");
var import_tracing = require("./tracing");
var import_waiter = require("./waiter");
var import_webError = require("./webError");
var import_worker = require("./worker");
var import_timeoutSettings = require("./timeoutSettings");
var import_fileUtils = require("./fileUtils");
var import_headers = require("../utils/isomorphic/headers");
var import_urlMatch = require("../utils/isomorphic/urlMatch");
var import_rtti = require("../utils/isomorphic/rtti");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
class BrowserContext extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._pages = /* @__PURE__ */ new Set();
this._routes = [];
this._webSocketRoutes = [];
// Browser is null for browser contexts created outside of normal browser, e.g. android or electron.
this._browser = null;
this._bindings = /* @__PURE__ */ new Map();
this._forReuse = false;
this._backgroundPages = /* @__PURE__ */ new Set();
this._serviceWorkers = /* @__PURE__ */ new Set();
this._harRecorders = /* @__PURE__ */ new Map();
this._closingStatus = "none";
this._harRouters = [];
this._options = initializer.options;
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform);
this.tracing = import_tracing.Tracing.from(initializer.tracing);
this.request = import_fetch.APIRequestContext.from(initializer.requestContext);
this.request._timeoutSettings = this._timeoutSettings;
this.clock = new import_clock.Clock(this);
this._channel.on("bindingCall", ({ binding }) => this._onBinding(import_page.BindingCall.from(binding)));
this._channel.on("close", () => this._onClose());
this._channel.on("page", ({ page }) => this._onPage(import_page.Page.from(page)));
this._channel.on("route", ({ route }) => this._onRoute(network.Route.from(route)));
this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(network.WebSocketRoute.from(webSocketRoute)));
this._channel.on("backgroundPage", ({ page }) => {
const backgroundPage = import_page.Page.from(page);
this._backgroundPages.add(backgroundPage);
this.emit(import_events.Events.BrowserContext.BackgroundPage, backgroundPage);
});
this._channel.on("serviceWorker", ({ worker }) => {
const serviceWorker = import_worker.Worker.from(worker);
serviceWorker._context = this;
this._serviceWorkers.add(serviceWorker);
this.emit(import_events.Events.BrowserContext.ServiceWorker, serviceWorker);
});
this._channel.on("console", (event) => {
const consoleMessage = new import_consoleMessage.ConsoleMessage(this._platform, event);
this.emit(import_events.Events.BrowserContext.Console, consoleMessage);
const page = consoleMessage.page();
if (page)
page.emit(import_events.Events.Page.Console, consoleMessage);
});
this._channel.on("pageError", ({ error, page }) => {
const pageObject = import_page.Page.from(page);
const parsedError = (0, import_errors.parseError)(error);
this.emit(import_events.Events.BrowserContext.WebError, new import_webError.WebError(pageObject, parsedError));
if (pageObject)
pageObject.emit(import_events.Events.Page.PageError, parsedError);
});
this._channel.on("dialog", ({ dialog }) => {
const dialogObject = import_dialog.Dialog.from(dialog);
let hasListeners = this.emit(import_events.Events.BrowserContext.Dialog, dialogObject);
const page = dialogObject.page();
if (page)
hasListeners = page.emit(import_events.Events.Page.Dialog, dialogObject) || hasListeners;
if (!hasListeners) {
if (dialogObject.type() === "beforeunload")
dialog.accept({}).catch(() => {
});
else
dialog.dismiss().catch(() => {
});
}
});
this._channel.on("request", ({ request, page }) => this._onRequest(network.Request.from(request), import_page.Page.fromNullable(page)));
this._channel.on("requestFailed", ({ request, failureText, responseEndTiming, page }) => this._onRequestFailed(network.Request.from(request), responseEndTiming, failureText, import_page.Page.fromNullable(page)));
this._channel.on("requestFinished", (params) => this._onRequestFinished(params));
this._channel.on("response", ({ response, page }) => this._onResponse(network.Response.from(response), import_page.Page.fromNullable(page)));
this._channel.on("recorderEvent", ({ event, data, page, code }) => {
if (event === "actionAdded")
this._onRecorderEventSink?.actionAdded?.(import_page.Page.from(page), data, code);
else if (event === "actionUpdated")
this._onRecorderEventSink?.actionUpdated?.(import_page.Page.from(page), data, code);
else if (event === "signalAdded")
this._onRecorderEventSink?.signalAdded?.(import_page.Page.from(page), data);
});
this._closedPromise = new Promise((f) => this.once(import_events.Events.BrowserContext.Close, f));
this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([
[import_events.Events.BrowserContext.Console, "console"],
[import_events.Events.BrowserContext.Dialog, "dialog"],
[import_events.Events.BrowserContext.Request, "request"],
[import_events.Events.BrowserContext.Response, "response"],
[import_events.Events.BrowserContext.RequestFinished, "requestFinished"],
[import_events.Events.BrowserContext.RequestFailed, "requestFailed"]
]));
}
static from(context) {
return context._object;
}
static fromNullable(context) {
return context ? BrowserContext.from(context) : null;
}
async _initializeHarFromOptions(recordHar) {
if (!recordHar)
return;
const defaultContent = recordHar.path.endsWith(".zip") ? "attach" : "embed";
await this._recordIntoHAR(recordHar.path, null, {
url: recordHar.urlFilter,
updateContent: recordHar.content ?? (recordHar.omitContent ? "omit" : defaultContent),
updateMode: recordHar.mode ?? "full"
});
}
_onPage(page) {
this._pages.add(page);
this.emit(import_events.Events.BrowserContext.Page, page);
if (page._opener && !page._opener.isClosed())
page._opener.emit(import_events.Events.Page.Popup, page);
}
_onRequest(request, page) {
this.emit(import_events.Events.BrowserContext.Request, request);
if (page)
page.emit(import_events.Events.Page.Request, request);
}
_onResponse(response, page) {
this.emit(import_events.Events.BrowserContext.Response, response);
if (page)
page.emit(import_events.Events.Page.Response, response);
}
_onRequestFailed(request, responseEndTiming, failureText, page) {
request._failureText = failureText || null;
request._setResponseEndTiming(responseEndTiming);
this.emit(import_events.Events.BrowserContext.RequestFailed, request);
if (page)
page.emit(import_events.Events.Page.RequestFailed, request);
}
_onRequestFinished(params) {
const { responseEndTiming } = params;
const request = network.Request.from(params.request);
const response = network.Response.fromNullable(params.response);
const page = import_page.Page.fromNullable(params.page);
request._setResponseEndTiming(responseEndTiming);
this.emit(import_events.Events.BrowserContext.RequestFinished, request);
if (page)
page.emit(import_events.Events.Page.RequestFinished, request);
if (response)
response._finishedPromise.resolve(null);
}
async _onRoute(route) {
route._context = this;
const page = route.request()._safePage();
const routeHandlers = this._routes.slice();
for (const routeHandler of routeHandlers) {
if (page?._closeWasCalled || this._closingStatus !== "none")
return;
if (!routeHandler.matches(route.request().url()))
continue;
const index = this._routes.indexOf(routeHandler);
if (index === -1)
continue;
if (routeHandler.willExpire())
this._routes.splice(index, 1);
const handled = await routeHandler.handle(route);
if (!this._routes.length)
this._updateInterceptionPatterns({ internal: true }).catch(() => {
});
if (handled)
return;
}
await route._innerContinue(
true
/* isFallback */
).catch(() => {
});
}
async _onWebSocketRoute(webSocketRoute) {
const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url()));
if (routeHandler)
await routeHandler.handle(webSocketRoute);
else
webSocketRoute.connectToServer();
}
async _onBinding(bindingCall) {
const func = this._bindings.get(bindingCall._initializer.name);
if (!func)
return;
await bindingCall.call(func);
}
setDefaultNavigationTimeout(timeout) {
this._timeoutSettings.setDefaultNavigationTimeout(timeout);
}
setDefaultTimeout(timeout) {
this._timeoutSettings.setDefaultTimeout(timeout);
}
browser() {
return this._browser;
}
pages() {
return [...this._pages];
}
async newPage() {
if (this._ownerPage)
throw new Error("Please use browser.newContext()");
return import_page.Page.from((await this._channel.newPage()).page);
}
async cookies(urls) {
if (!urls)
urls = [];
if (urls && typeof urls === "string")
urls = [urls];
return (await this._channel.cookies({ urls })).cookies;
}
async addCookies(cookies) {
await this._channel.addCookies({ cookies });
}
async clearCookies(options = {}) {
await this._channel.clearCookies({
name: (0, import_rtti.isString)(options.name) ? options.name : void 0,
nameRegexSource: (0, import_rtti.isRegExp)(options.name) ? options.name.source : void 0,
nameRegexFlags: (0, import_rtti.isRegExp)(options.name) ? options.name.flags : void 0,
domain: (0, import_rtti.isString)(options.domain) ? options.domain : void 0,
domainRegexSource: (0, import_rtti.isRegExp)(options.domain) ? options.domain.source : void 0,
domainRegexFlags: (0, import_rtti.isRegExp)(options.domain) ? options.domain.flags : void 0,
path: (0, import_rtti.isString)(options.path) ? options.path : void 0,
pathRegexSource: (0, import_rtti.isRegExp)(options.path) ? options.path.source : void 0,
pathRegexFlags: (0, import_rtti.isRegExp)(options.path) ? options.path.flags : void 0
});
}
async grantPermissions(permissions, options) {
await this._channel.grantPermissions({ permissions, ...options });
}
async clearPermissions() {
await this._channel.clearPermissions();
}
async setGeolocation(geolocation) {
await this._channel.setGeolocation({ geolocation: geolocation || void 0 });
}
async setExtraHTTPHeaders(headers) {
network.validateHeaders(headers);
await this._channel.setExtraHTTPHeaders({ headers: (0, import_headers.headersObjectToArray)(headers) });
}
async setOffline(offline) {
await this._channel.setOffline({ offline });
}
async setHTTPCredentials(httpCredentials) {
await this._channel.setHTTPCredentials({ httpCredentials: httpCredentials || void 0 });
}
async addInitScript(script, arg) {
const source = await (0, import_clientHelper.evaluationScript)(this._platform, script, arg);
await this._channel.addInitScript({ source });
}
async exposeBinding(name, callback, options = {}) {
await this._channel.exposeBinding({ name, needsHandle: options.handle });
this._bindings.set(name, callback);
}
async exposeFunction(name, callback) {
await this._channel.exposeBinding({ name });
const binding = (source, ...args) => callback(...args);
this._bindings.set(name, binding);
}
async route(url, handler, options = {}) {
this._routes.unshift(new network.RouteHandler(this._platform, this._options.baseURL, url, handler, options.times));
await this._updateInterceptionPatterns({ title: "Route requests" });
}
async routeWebSocket(url, handler) {
this._webSocketRoutes.unshift(new network.WebSocketRouteHandler(this._options.baseURL, url, handler));
await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" });
}
async _recordIntoHAR(har, page, options = {}) {
const { harId } = await this._channel.harStart({
page: page?._channel,
options: {
zip: har.endsWith(".zip"),
content: options.updateContent ?? "attach",
urlGlob: (0, import_rtti.isString)(options.url) ? options.url : void 0,
urlRegexSource: (0, import_rtti.isRegExp)(options.url) ? options.url.source : void 0,
urlRegexFlags: (0, import_rtti.isRegExp)(options.url) ? options.url.flags : void 0,
mode: options.updateMode ?? "minimal"
}
});
this._harRecorders.set(harId, { path: har, content: options.updateContent ?? "attach" });
}
async routeFromHAR(har, options = {}) {
const localUtils = this._connection.localUtils();
if (!localUtils)
throw new Error("Route from har is not supported in thin clients");
if (options.update) {
await this._recordIntoHAR(har, null, options);
return;
}
const harRouter = await import_harRouter.HarRouter.create(localUtils, har, options.notFound || "abort", { urlMatch: options.url });
this._harRouters.push(harRouter);
await harRouter.addContextRoute(this);
}
_disposeHarRouters() {
this._harRouters.forEach((router) => router.dispose());
this._harRouters = [];
}
async unrouteAll(options) {
await this._unrouteInternal(this._routes, [], options?.behavior);
this._disposeHarRouters();
}
async unroute(url, handler) {
const removed = [];
const remaining = [];
for (const route of this._routes) {
if ((0, import_urlMatch.urlMatchesEqual)(route.url, url) && (!handler || route.handler === handler))
removed.push(route);
else
remaining.push(route);
}
await this._unrouteInternal(removed, remaining, "default");
}
async _unrouteInternal(removed, remaining, behavior) {
this._routes = remaining;
if (behavior && behavior !== "default") {
const promises = removed.map((routeHandler) => routeHandler.stop(behavior));
await Promise.all(promises);
}
await this._updateInterceptionPatterns({ title: "Unroute requests" });
}
async _updateInterceptionPatterns(options) {
const patterns = network.RouteHandler.prepareInterceptionPatterns(this._routes);
await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }), options);
}
async _updateWebSocketInterceptionPatterns(options) {
const patterns = network.WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);
await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }), options);
}
_effectiveCloseReason() {
return this._closeReason || this._browser?._closeReason;
}
async waitForEvent(event, optionsOrPredicate = {}) {
return await this._wrapApiCall(async () => {
const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
const waiter = import_waiter.Waiter.createForEvent(this, event);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
if (event !== import_events.Events.BrowserContext.Close)
waiter.rejectOnEvent(this, import_events.Events.BrowserContext.Close, () => new import_errors.TargetClosedError(this._effectiveCloseReason()));
const result = await waiter.waitForEvent(this, event, predicate);
waiter.dispose();
return result;
});
}
async storageState(options = {}) {
const state = await this._channel.storageState({ indexedDB: options.indexedDB });
if (options.path) {
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
await this._platform.fs().promises.writeFile(options.path, JSON.stringify(state, void 0, 2), "utf8");
}
return state;
}
backgroundPages() {
return [...this._backgroundPages];
}
serviceWorkers() {
return [...this._serviceWorkers];
}
async newCDPSession(page) {
if (!(page instanceof import_page.Page) && !(page instanceof import_frame.Frame))
throw new Error("page: expected Page or Frame");
const result = await this._channel.newCDPSession(page instanceof import_page.Page ? { page: page._channel } : { frame: page._channel });
return import_cdpSession.CDPSession.from(result.session);
}
_onClose() {
this._closingStatus = "closed";
this._browser?._contexts.delete(this);
this._browser?._browserType._contexts.delete(this);
this._browser?._browserType._playwright.selectors._contextsForSelectors.delete(this);
this._disposeHarRouters();
this.tracing._resetStackCounter();
this.emit(import_events.Events.BrowserContext.Close, this);
}
async [Symbol.asyncDispose]() {
await this.close();
}
async close(options = {}) {
if (this._closingStatus !== "none")
return;
this._closeReason = options.reason;
this._closingStatus = "closing";
await this.request.dispose(options);
await this._instrumentation.runBeforeCloseBrowserContext(this);
await this._wrapApiCall(async () => {
for (const [harId, harParams] of this._harRecorders) {
const har = await this._channel.harExport({ harId });
const artifact = import_artifact.Artifact.from(har.artifact);
const isCompressed = harParams.content === "attach" || harParams.path.endsWith(".zip");
const needCompressed = harParams.path.endsWith(".zip");
if (isCompressed && !needCompressed) {
const localUtils = this._connection.localUtils();
if (!localUtils)
throw new Error("Uncompressed har is not supported in thin clients");
await artifact.saveAs(harParams.path + ".tmp");
await localUtils.harUnzip({ zipFile: harParams.path + ".tmp", harFile: harParams.path });
} else {
await artifact.saveAs(harParams.path);
}
await artifact.delete();
}
}, { internal: true });
await this._channel.close(options);
await this._closedPromise;
}
async _enableRecorder(params, eventSink) {
if (eventSink)
this._onRecorderEventSink = eventSink;
await this._channel.enableRecorder(params);
}
async _disableRecorder() {
this._onRecorderEventSink = void 0;
await this._channel.disableRecorder();
}
}
async function prepareStorageState(platform, storageState) {
if (typeof storageState !== "string")
return storageState;
try {
return JSON.parse(await platform.fs().promises.readFile(storageState, "utf8"));
} catch (e) {
(0, import_stackTrace.rewriteErrorMessage)(e, `Error reading storage state from ${storageState}:
` + e.message);
throw e;
}
}
async function prepareBrowserContextParams(platform, options) {
if (options.videoSize && !options.videosPath)
throw new Error(`"videoSize" option requires "videosPath" to be specified`);
if (options.extraHTTPHeaders)
network.validateHeaders(options.extraHTTPHeaders);
const contextParams = {
...options,
viewport: options.viewport === null ? void 0 : options.viewport,
noDefaultViewport: options.viewport === null,
extraHTTPHeaders: options.extraHTTPHeaders ? (0, import_headers.headersObjectToArray)(options.extraHTTPHeaders) : void 0,
storageState: options.storageState ? await prepareStorageState(platform, options.storageState) : void 0,
serviceWorkers: options.serviceWorkers,
colorScheme: options.colorScheme === null ? "no-override" : options.colorScheme,
reducedMotion: options.reducedMotion === null ? "no-override" : options.reducedMotion,
forcedColors: options.forcedColors === null ? "no-override" : options.forcedColors,
contrast: options.contrast === null ? "no-override" : options.contrast,
acceptDownloads: toAcceptDownloadsProtocol(options.acceptDownloads),
clientCertificates: await toClientCertificatesProtocol(platform, options.clientCertificates)
};
if (!contextParams.recordVideo && options.videosPath) {
contextParams.recordVideo = {
dir: options.videosPath,
size: options.videoSize
};
}
if (contextParams.recordVideo && contextParams.recordVideo.dir)
contextParams.recordVideo.dir = platform.path().resolve(contextParams.recordVideo.dir);
return contextParams;
}
function toAcceptDownloadsProtocol(acceptDownloads) {
if (acceptDownloads === void 0)
return void 0;
if (acceptDownloads)
return "accept";
return "deny";
}
async function toClientCertificatesProtocol(platform, certs) {
if (!certs)
return void 0;
const bufferizeContent = async (value, path) => {
if (value)
return value;
if (path)
return await platform.fs().promises.readFile(path);
};
return await Promise.all(certs.map(async (cert) => ({
origin: cert.origin,
cert: await bufferizeContent(cert.cert, cert.certPath),
key: await bufferizeContent(cert.key, cert.keyPath),
pfx: await bufferizeContent(cert.pfx, cert.pfxPath),
passphrase: cert.passphrase
})));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserContext,
prepareBrowserContextParams,
toClientCertificatesProtocol
});

184
node_modules/playwright-core/lib/client/browserType.js generated vendored Normal file
View File

@@ -0,0 +1,184 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserType_exports = {};
__export(browserType_exports, {
BrowserType: () => BrowserType
});
module.exports = __toCommonJS(browserType_exports);
var import_browser = require("./browser");
var import_browserContext = require("./browserContext");
var import_channelOwner = require("./channelOwner");
var import_clientHelper = require("./clientHelper");
var import_events = require("./events");
var import_assert = require("../utils/isomorphic/assert");
var import_headers = require("../utils/isomorphic/headers");
var import_time = require("../utils/isomorphic/time");
var import_timeoutRunner = require("../utils/isomorphic/timeoutRunner");
var import_webSocket = require("./webSocket");
var import_timeoutSettings = require("./timeoutSettings");
class BrowserType extends import_channelOwner.ChannelOwner {
constructor() {
super(...arguments);
this._contexts = /* @__PURE__ */ new Set();
}
static from(browserType) {
return browserType._object;
}
executablePath() {
if (!this._initializer.executablePath)
throw new Error("Browser is not supported on current platform");
return this._initializer.executablePath;
}
name() {
return this._initializer.name;
}
async launch(options = {}) {
(0, import_assert.assert)(!options.userDataDir, "userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead");
(0, import_assert.assert)(!options.port, "Cannot specify a port without launching as a server.");
const logger = options.logger || this._playwright._defaultLaunchOptions?.logger;
options = { ...this._playwright._defaultLaunchOptions, ...options };
const launchOptions = {
...options,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : void 0,
ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),
env: options.env ? (0, import_clientHelper.envObjectToArray)(options.env) : void 0,
timeout: new import_timeoutSettings.TimeoutSettings(this._platform).launchTimeout(options)
};
return await this._wrapApiCall(async () => {
const browser = import_browser.Browser.from((await this._channel.launch(launchOptions)).browser);
browser._connectToBrowserType(this, options, logger);
return browser;
});
}
async launchServer(options = {}) {
if (!this._serverLauncher)
throw new Error("Launching server is not supported");
options = { ...this._playwright._defaultLaunchOptions, ...options };
return await this._serverLauncher.launchServer(options);
}
async launchPersistentContext(userDataDir, options = {}) {
const logger = options.logger || this._playwright._defaultLaunchOptions?.logger;
(0, import_assert.assert)(!options.port, "Cannot specify a port without launching as a server.");
options = this._playwright.selectors._withSelectorOptions({
...this._playwright._defaultLaunchOptions,
...this._playwright._defaultContextOptions,
...options
});
const contextParams = await (0, import_browserContext.prepareBrowserContextParams)(this._platform, options);
const persistentParams = {
...contextParams,
ignoreDefaultArgs: Array.isArray(options.ignoreDefaultArgs) ? options.ignoreDefaultArgs : void 0,
ignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),
env: options.env ? (0, import_clientHelper.envObjectToArray)(options.env) : void 0,
channel: options.channel,
userDataDir: this._platform.path().isAbsolute(userDataDir) || !userDataDir ? userDataDir : this._platform.path().resolve(userDataDir),
timeout: new import_timeoutSettings.TimeoutSettings(this._platform).launchTimeout(options)
};
const context = await this._wrapApiCall(async () => {
const result = await this._channel.launchPersistentContext(persistentParams);
const browser = import_browser.Browser.from(result.browser);
browser._connectToBrowserType(this, options, logger);
const context2 = import_browserContext.BrowserContext.from(result.context);
await context2._initializeHarFromOptions(options.recordHar);
return context2;
});
await this._instrumentation.runAfterCreateBrowserContext(context);
return context;
}
async connect(optionsOrWsEndpoint, options) {
if (typeof optionsOrWsEndpoint === "string")
return await this._connect({ ...options, wsEndpoint: optionsOrWsEndpoint });
(0, import_assert.assert)(optionsOrWsEndpoint.wsEndpoint, "options.wsEndpoint is required");
return await this._connect(optionsOrWsEndpoint);
}
async _connect(params) {
const logger = params.logger;
return await this._wrapApiCall(async () => {
const deadline = params.timeout ? (0, import_time.monotonicTime)() + params.timeout : 0;
const headers = { "x-playwright-browser": this.name(), ...params.headers };
const connectParams = {
wsEndpoint: params.wsEndpoint,
headers,
exposeNetwork: params.exposeNetwork ?? params._exposeNetwork,
slowMo: params.slowMo,
timeout: params.timeout || 0
};
if (params.__testHookRedirectPortForwarding)
connectParams.socksProxyRedirectPortForTest = params.__testHookRedirectPortForwarding;
const connection = await (0, import_webSocket.connectOverWebSocket)(this._connection, connectParams);
let browser;
connection.on("close", () => {
for (const context of browser?.contexts() || []) {
for (const page of context.pages())
page._onClose();
context._onClose();
}
setTimeout(() => browser?._didClose(), 0);
});
const result = await (0, import_timeoutRunner.raceAgainstDeadline)(async () => {
if (params.__testHookBeforeCreateBrowser)
await params.__testHookBeforeCreateBrowser();
const playwright = await connection.initializePlaywright();
if (!playwright._initializer.preLaunchedBrowser) {
connection.close();
throw new Error("Malformed endpoint. Did you use BrowserType.launchServer method?");
}
playwright.selectors = this._playwright.selectors;
browser = import_browser.Browser.from(playwright._initializer.preLaunchedBrowser);
browser._connectToBrowserType(this, {}, logger);
browser._shouldCloseConnectionOnClose = true;
browser.on(import_events.Events.Browser.Disconnected, () => connection.close());
return browser;
}, deadline);
if (!result.timedOut) {
return result.result;
} else {
connection.close();
throw new Error(`Timeout ${params.timeout}ms exceeded`);
}
});
}
async connectOverCDP(endpointURLOrOptions, options) {
if (typeof endpointURLOrOptions === "string")
return await this._connectOverCDP(endpointURLOrOptions, options);
const endpointURL = "endpointURL" in endpointURLOrOptions ? endpointURLOrOptions.endpointURL : endpointURLOrOptions.wsEndpoint;
(0, import_assert.assert)(endpointURL, "Cannot connect over CDP without wsEndpoint.");
return await this.connectOverCDP(endpointURL, endpointURLOrOptions);
}
async _connectOverCDP(endpointURL, params = {}) {
if (this.name() !== "chromium")
throw new Error("Connecting over CDP is only supported in Chromium.");
const headers = params.headers ? (0, import_headers.headersObjectToArray)(params.headers) : void 0;
const result = await this._channel.connectOverCDP({
endpointURL,
headers,
slowMo: params.slowMo,
timeout: new import_timeoutSettings.TimeoutSettings(this._platform).timeout(params)
});
const browser = import_browser.Browser.from(result.browser);
browser._connectToBrowserType(this, {}, params.logger);
if (result.defaultContext)
await this._instrumentation.runAfterCreateBrowserContext(import_browserContext.BrowserContext.from(result.defaultContext));
return browser;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserType
});

51
node_modules/playwright-core/lib/client/cdpSession.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cdpSession_exports = {};
__export(cdpSession_exports, {
CDPSession: () => CDPSession
});
module.exports = __toCommonJS(cdpSession_exports);
var import_channelOwner = require("./channelOwner");
class CDPSession extends import_channelOwner.ChannelOwner {
static from(cdpSession) {
return cdpSession._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._channel.on("event", ({ method, params }) => {
this.emit(method, params);
});
this.on = super.on;
this.addListener = super.addListener;
this.off = super.removeListener;
this.removeListener = super.removeListener;
this.once = super.once;
}
async send(method, params) {
const result = await this._channel.send({ method, params });
return result.result;
}
async detach() {
return await this._channel.detach();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CDPSession
});

201
node_modules/playwright-core/lib/client/channelOwner.js generated vendored Normal file
View File

@@ -0,0 +1,201 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var channelOwner_exports = {};
__export(channelOwner_exports, {
ChannelOwner: () => ChannelOwner
});
module.exports = __toCommonJS(channelOwner_exports);
var import_eventEmitter = require("./eventEmitter");
var import_validator = require("../protocol/validator");
var import_protocolMetainfo = require("../utils/isomorphic/protocolMetainfo");
var import_clientStackTrace = require("./clientStackTrace");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
class ChannelOwner extends import_eventEmitter.EventEmitter {
constructor(parent, type, guid, initializer) {
const connection = parent instanceof ChannelOwner ? parent._connection : parent;
super(connection._platform);
this._objects = /* @__PURE__ */ new Map();
this._eventToSubscriptionMapping = /* @__PURE__ */ new Map();
this._wasCollected = false;
this.setMaxListeners(0);
this._connection = connection;
this._type = type;
this._guid = guid;
this._parent = parent instanceof ChannelOwner ? parent : void 0;
this._instrumentation = this._connection._instrumentation;
this._connection._objects.set(guid, this);
if (this._parent) {
this._parent._objects.set(guid, this);
this._logger = this._parent._logger;
}
this._channel = this._createChannel(new import_eventEmitter.EventEmitter(connection._platform));
this._initializer = initializer;
}
_setEventToSubscriptionMapping(mapping) {
this._eventToSubscriptionMapping = mapping;
}
_updateSubscription(event, enabled) {
const protocolEvent = this._eventToSubscriptionMapping.get(String(event));
if (protocolEvent)
this._channel.updateSubscription({ event: protocolEvent, enabled }).catch(() => {
});
}
on(event, listener) {
if (!this.listenerCount(event))
this._updateSubscription(event, true);
super.on(event, listener);
return this;
}
addListener(event, listener) {
if (!this.listenerCount(event))
this._updateSubscription(event, true);
super.addListener(event, listener);
return this;
}
prependListener(event, listener) {
if (!this.listenerCount(event))
this._updateSubscription(event, true);
super.prependListener(event, listener);
return this;
}
off(event, listener) {
super.off(event, listener);
if (!this.listenerCount(event))
this._updateSubscription(event, false);
return this;
}
removeListener(event, listener) {
super.removeListener(event, listener);
if (!this.listenerCount(event))
this._updateSubscription(event, false);
return this;
}
_adopt(child) {
child._parent._objects.delete(child._guid);
this._objects.set(child._guid, child);
child._parent = this;
}
_dispose(reason) {
if (this._parent)
this._parent._objects.delete(this._guid);
this._connection._objects.delete(this._guid);
this._wasCollected = reason === "gc";
for (const object of [...this._objects.values()])
object._dispose(reason);
this._objects.clear();
}
_debugScopeState() {
return {
_guid: this._guid,
objects: Array.from(this._objects.values()).map((o) => o._debugScopeState())
};
}
_validatorToWireContext() {
return {
tChannelImpl: tChannelImplToWire,
binary: this._connection.rawBuffers() ? "buffer" : "toBase64",
isUnderTest: () => this._platform.isUnderTest()
};
}
_createChannel(base) {
const channel = new Proxy(base, {
get: (obj, prop) => {
if (typeof prop === "string") {
const validator = (0, import_validator.maybeFindValidator)(this._type, prop, "Params");
const { internal } = import_protocolMetainfo.methodMetainfo.get(this._type + "." + prop) || {};
if (validator) {
return async (params) => {
return await this._wrapApiCall(async (apiZone) => {
const validatedParams = validator(params, "", this._validatorToWireContext());
if (!apiZone.internal && !apiZone.reported) {
apiZone.reported = true;
this._instrumentation.onApiCallBegin(apiZone, { type: this._type, method: prop, params });
logApiCall(this._platform, this._logger, `=> ${apiZone.apiName} started`);
return await this._connection.sendMessageToServer(this, prop, validatedParams, apiZone);
}
return await this._connection.sendMessageToServer(this, prop, validatedParams, { internal: true });
}, { internal });
};
}
}
return obj[prop];
}
});
channel._object = this;
return channel;
}
async _wrapApiCall(func, options) {
const logger = this._logger;
const existingApiZone = this._platform.zones.current().data();
if (existingApiZone)
return await func(existingApiZone);
const stackTrace = (0, import_clientStackTrace.captureLibraryStackTrace)(this._platform);
const apiZone = { title: options?.title, apiName: stackTrace.apiName, frames: stackTrace.frames, internal: options?.internal ?? false, reported: false, userData: void 0, stepId: void 0 };
try {
const result = await this._platform.zones.current().push(apiZone).run(async () => await func(apiZone));
if (!options?.internal) {
logApiCall(this._platform, logger, `<= ${apiZone.apiName} succeeded`);
this._instrumentation.onApiCallEnd(apiZone);
}
return result;
} catch (e) {
const innerError = (this._platform.showInternalStackFrames() || this._platform.isUnderTest()) && e.stack ? "\n<inner error>\n" + e.stack : "";
if (apiZone.apiName && !apiZone.apiName.includes("<anonymous>"))
e.message = apiZone.apiName + ": " + e.message;
const stackFrames = "\n" + (0, import_stackTrace.stringifyStackFrames)(stackTrace.frames).join("\n") + innerError;
if (stackFrames.trim())
e.stack = e.message + stackFrames;
else
e.stack = "";
if (!options?.internal) {
const recoveryHandlers = [];
apiZone.error = e;
this._instrumentation.onApiCallRecovery(apiZone, e, recoveryHandlers);
for (const handler of recoveryHandlers) {
const recoverResult = await handler();
if (recoverResult.status === "recovered")
return recoverResult.value;
}
logApiCall(this._platform, logger, `<= ${apiZone.apiName} failed`);
this._instrumentation.onApiCallEnd(apiZone);
}
throw e;
}
}
toJSON() {
return {
_type: this._type,
_guid: this._guid
};
}
}
function logApiCall(platform, logger, message) {
if (logger && logger.isEnabled("api", "info"))
logger.log("api", "info", message, [], { color: "cyan" });
platform.log("api", message);
}
function tChannelImplToWire(names, arg, path, context) {
if (arg._object instanceof ChannelOwner && (names === "*" || names.includes(arg._object._type)))
return { guid: arg._object._guid };
throw new import_validator.ValidationError(`${path}: expected channel ${names.toString()}`);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ChannelOwner
});

View File

@@ -0,0 +1,64 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clientHelper_exports = {};
__export(clientHelper_exports, {
addSourceUrlToScript: () => addSourceUrlToScript,
envObjectToArray: () => envObjectToArray,
evaluationScript: () => evaluationScript
});
module.exports = __toCommonJS(clientHelper_exports);
var import_rtti = require("../utils/isomorphic/rtti");
function envObjectToArray(env) {
const result = [];
for (const name in env) {
if (!Object.is(env[name], void 0))
result.push({ name, value: String(env[name]) });
}
return result;
}
async function evaluationScript(platform, fun, arg, addSourceUrl = true) {
if (typeof fun === "function") {
const source = fun.toString();
const argString = Object.is(arg, void 0) ? "undefined" : JSON.stringify(arg);
return `(${source})(${argString})`;
}
if (arg !== void 0)
throw new Error("Cannot evaluate a string with arguments");
if ((0, import_rtti.isString)(fun))
return fun;
if (fun.content !== void 0)
return fun.content;
if (fun.path !== void 0) {
let source = await platform.fs().promises.readFile(fun.path, "utf8");
if (addSourceUrl)
source = addSourceUrlToScript(source, fun.path);
return source;
}
throw new Error("Either path or content property must be present");
}
function addSourceUrlToScript(source, path) {
return `${source}
//# sourceURL=${path.replace(/\n/g, "")}`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
addSourceUrlToScript,
envObjectToArray,
evaluationScript
});

View File

@@ -0,0 +1,55 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clientInstrumentation_exports = {};
__export(clientInstrumentation_exports, {
createInstrumentation: () => createInstrumentation
});
module.exports = __toCommonJS(clientInstrumentation_exports);
function createInstrumentation() {
const listeners = [];
return new Proxy({}, {
get: (obj, prop) => {
if (typeof prop !== "string")
return obj[prop];
if (prop === "addListener")
return (listener) => listeners.push(listener);
if (prop === "removeListener")
return (listener) => listeners.splice(listeners.indexOf(listener), 1);
if (prop === "removeAllListeners")
return () => listeners.splice(0, listeners.length);
if (prop.startsWith("run")) {
return async (...params) => {
for (const listener of listeners)
await listener[prop]?.(...params);
};
}
if (prop.startsWith("on")) {
return (...params) => {
for (const listener of listeners)
listener[prop]?.(...params);
};
}
return obj[prop];
}
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createInstrumentation
});

View File

@@ -0,0 +1,69 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clientStackTrace_exports = {};
__export(clientStackTrace_exports, {
captureLibraryStackTrace: () => captureLibraryStackTrace
});
module.exports = __toCommonJS(clientStackTrace_exports);
var import_stackTrace = require("../utils/isomorphic/stackTrace");
function captureLibraryStackTrace(platform) {
const stack = (0, import_stackTrace.captureRawStack)();
let parsedFrames = stack.map((line) => {
const frame = (0, import_stackTrace.parseStackFrame)(line, platform.pathSeparator, platform.showInternalStackFrames());
if (!frame || !frame.file)
return null;
const isPlaywrightLibrary = !!platform.coreDir && frame.file.startsWith(platform.coreDir);
const parsed = {
frame,
frameText: line,
isPlaywrightLibrary
};
return parsed;
}).filter(Boolean);
let apiName = "";
for (let i = 0; i < parsedFrames.length - 1; i++) {
const parsedFrame = parsedFrames[i];
if (parsedFrame.isPlaywrightLibrary && !parsedFrames[i + 1].isPlaywrightLibrary) {
apiName = apiName || normalizeAPIName(parsedFrame.frame.function);
break;
}
}
function normalizeAPIName(name) {
if (!name)
return "";
const match = name.match(/(API|JS|CDP|[A-Z])(.*)/);
if (!match)
return name;
return match[1].toLowerCase() + match[2];
}
const filterPrefixes = platform.boxedStackPrefixes();
parsedFrames = parsedFrames.filter((f) => {
if (filterPrefixes.some((prefix) => f.frame.file.startsWith(prefix)))
return false;
return true;
});
return {
frames: parsedFrames.map((p) => p.frame),
apiName
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
captureLibraryStackTrace
});

68
node_modules/playwright-core/lib/client/clock.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clock_exports = {};
__export(clock_exports, {
Clock: () => Clock
});
module.exports = __toCommonJS(clock_exports);
class Clock {
constructor(browserContext) {
this._browserContext = browserContext;
}
async install(options = {}) {
await this._browserContext._channel.clockInstall(options.time !== void 0 ? parseTime(options.time) : {});
}
async fastForward(ticks) {
await this._browserContext._channel.clockFastForward(parseTicks(ticks));
}
async pauseAt(time) {
await this._browserContext._channel.clockPauseAt(parseTime(time));
}
async resume() {
await this._browserContext._channel.clockResume({});
}
async runFor(ticks) {
await this._browserContext._channel.clockRunFor(parseTicks(ticks));
}
async setFixedTime(time) {
await this._browserContext._channel.clockSetFixedTime(parseTime(time));
}
async setSystemTime(time) {
await this._browserContext._channel.clockSetSystemTime(parseTime(time));
}
}
function parseTime(time) {
if (typeof time === "number")
return { timeNumber: time };
if (typeof time === "string")
return { timeString: time };
if (!isFinite(time.getTime()))
throw new Error(`Invalid date: ${time}`);
return { timeNumber: time.getTime() };
}
function parseTicks(ticks) {
return {
ticksNumber: typeof ticks === "number" ? ticks : void 0,
ticksString: typeof ticks === "string" ? ticks : void 0
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Clock
});

314
node_modules/playwright-core/lib/client/connection.js generated vendored Normal file
View File

@@ -0,0 +1,314 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var connection_exports = {};
__export(connection_exports, {
Connection: () => Connection
});
module.exports = __toCommonJS(connection_exports);
var import_eventEmitter = require("./eventEmitter");
var import_android = require("./android");
var import_artifact = require("./artifact");
var import_browser = require("./browser");
var import_browserContext = require("./browserContext");
var import_browserType = require("./browserType");
var import_cdpSession = require("./cdpSession");
var import_channelOwner = require("./channelOwner");
var import_clientInstrumentation = require("./clientInstrumentation");
var import_dialog = require("./dialog");
var import_electron = require("./electron");
var import_elementHandle = require("./elementHandle");
var import_errors = require("./errors");
var import_fetch = require("./fetch");
var import_frame = require("./frame");
var import_jsHandle = require("./jsHandle");
var import_jsonPipe = require("./jsonPipe");
var import_localUtils = require("./localUtils");
var import_network = require("./network");
var import_page = require("./page");
var import_playwright = require("./playwright");
var import_stream = require("./stream");
var import_tracing = require("./tracing");
var import_worker = require("./worker");
var import_writableStream = require("./writableStream");
var import_validator = require("../protocol/validator");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
class Root extends import_channelOwner.ChannelOwner {
constructor(connection) {
super(connection, "Root", "", {});
}
async initialize() {
return import_playwright.Playwright.from((await this._channel.initialize({
sdkLanguage: "javascript"
})).playwright);
}
}
class DummyChannelOwner extends import_channelOwner.ChannelOwner {
}
class Connection extends import_eventEmitter.EventEmitter {
constructor(platform, localUtils, instrumentation, headers = []) {
super(platform);
this._objects = /* @__PURE__ */ new Map();
this.onmessage = (message) => {
};
this._lastId = 0;
this._callbacks = /* @__PURE__ */ new Map();
this._isRemote = false;
this._rawBuffers = false;
this._tracingCount = 0;
this._instrumentation = instrumentation || (0, import_clientInstrumentation.createInstrumentation)();
this._localUtils = localUtils;
this._rootObject = new Root(this);
this.headers = headers;
}
markAsRemote() {
this._isRemote = true;
}
isRemote() {
return this._isRemote;
}
useRawBuffers() {
this._rawBuffers = true;
}
rawBuffers() {
return this._rawBuffers;
}
localUtils() {
return this._localUtils;
}
async initializePlaywright() {
return await this._rootObject.initialize();
}
getObjectWithKnownName(guid) {
return this._objects.get(guid);
}
setIsTracing(isTracing) {
if (isTracing)
this._tracingCount++;
else
this._tracingCount--;
}
async sendMessageToServer(object, method, params, options) {
if (this._closedError)
throw this._closedError;
if (object._wasCollected)
throw new Error("The object has been collected to prevent unbounded heap growth.");
const guid = object._guid;
const type = object._type;
const id = ++this._lastId;
const message = { id, guid, method, params };
if (this._platform.isLogEnabled("channel")) {
this._platform.log("channel", "SEND> " + JSON.stringify(message));
}
const location = options.frames?.[0] ? { file: options.frames[0].file, line: options.frames[0].line, column: options.frames[0].column } : void 0;
const metadata = { title: options.title, location, internal: options.internal, stepId: options.stepId };
if (this._tracingCount && options.frames && type !== "LocalUtils")
this._localUtils?.addStackToTracingNoReply({ callData: { stack: options.frames ?? [], id } }).catch(() => {
});
this._platform.zones.empty.run(() => this.onmessage({ ...message, metadata }));
return await new Promise((resolve, reject) => this._callbacks.set(id, { resolve, reject, title: options.title, type, method }));
}
_validatorFromWireContext() {
return {
tChannelImpl: this._tChannelImplFromWire.bind(this),
binary: this._rawBuffers ? "buffer" : "fromBase64",
isUnderTest: () => this._platform.isUnderTest()
};
}
dispatch(message) {
if (this._closedError)
return;
const { id, guid, method, params, result, error, log } = message;
if (id) {
if (this._platform.isLogEnabled("channel"))
this._platform.log("channel", "<RECV " + JSON.stringify(message));
const callback = this._callbacks.get(id);
if (!callback)
throw new Error(`Cannot find command to respond: ${id}`);
this._callbacks.delete(id);
if (error && !result) {
const parsedError = (0, import_errors.parseError)(error);
(0, import_stackTrace.rewriteErrorMessage)(parsedError, parsedError.message + formatCallLog(this._platform, log));
callback.reject(parsedError);
} else {
const validator2 = (0, import_validator.findValidator)(callback.type, callback.method, "Result");
callback.resolve(validator2(result, "", this._validatorFromWireContext()));
}
return;
}
if (this._platform.isLogEnabled("channel"))
this._platform.log("channel", "<EVENT " + JSON.stringify(message));
if (method === "__create__") {
this._createRemoteObject(guid, params.type, params.guid, params.initializer);
return;
}
const object = this._objects.get(guid);
if (!object)
throw new Error(`Cannot find object to "${method}": ${guid}`);
if (method === "__adopt__") {
const child = this._objects.get(params.guid);
if (!child)
throw new Error(`Unknown new child: ${params.guid}`);
object._adopt(child);
return;
}
if (method === "__dispose__") {
object._dispose(params.reason);
return;
}
const validator = (0, import_validator.findValidator)(object._type, method, "Event");
object._channel.emit(method, validator(params, "", this._validatorFromWireContext()));
}
close(cause) {
if (this._closedError)
return;
this._closedError = new import_errors.TargetClosedError(cause);
for (const callback of this._callbacks.values())
callback.reject(this._closedError);
this._callbacks.clear();
this.emit("close");
}
_tChannelImplFromWire(names, arg, path, context) {
if (arg && typeof arg === "object" && typeof arg.guid === "string") {
const object = this._objects.get(arg.guid);
if (!object)
throw new Error(`Object with guid ${arg.guid} was not bound in the connection`);
if (names !== "*" && !names.includes(object._type))
throw new import_validator.ValidationError(`${path}: expected channel ${names.toString()}`);
return object._channel;
}
throw new import_validator.ValidationError(`${path}: expected channel ${names.toString()}`);
}
_createRemoteObject(parentGuid, type, guid, initializer) {
const parent = this._objects.get(parentGuid);
if (!parent)
throw new Error(`Cannot find parent object ${parentGuid} to create ${guid}`);
let result;
const validator = (0, import_validator.findValidator)(type, "", "Initializer");
initializer = validator(initializer, "", this._validatorFromWireContext());
switch (type) {
case "Android":
result = new import_android.Android(parent, type, guid, initializer);
break;
case "AndroidSocket":
result = new import_android.AndroidSocket(parent, type, guid, initializer);
break;
case "AndroidDevice":
result = new import_android.AndroidDevice(parent, type, guid, initializer);
break;
case "APIRequestContext":
result = new import_fetch.APIRequestContext(parent, type, guid, initializer);
break;
case "Artifact":
result = new import_artifact.Artifact(parent, type, guid, initializer);
break;
case "BindingCall":
result = new import_page.BindingCall(parent, type, guid, initializer);
break;
case "Browser":
result = new import_browser.Browser(parent, type, guid, initializer);
break;
case "BrowserContext":
result = new import_browserContext.BrowserContext(parent, type, guid, initializer);
break;
case "BrowserType":
result = new import_browserType.BrowserType(parent, type, guid, initializer);
break;
case "CDPSession":
result = new import_cdpSession.CDPSession(parent, type, guid, initializer);
break;
case "Dialog":
result = new import_dialog.Dialog(parent, type, guid, initializer);
break;
case "Electron":
result = new import_electron.Electron(parent, type, guid, initializer);
break;
case "ElectronApplication":
result = new import_electron.ElectronApplication(parent, type, guid, initializer);
break;
case "ElementHandle":
result = new import_elementHandle.ElementHandle(parent, type, guid, initializer);
break;
case "Frame":
result = new import_frame.Frame(parent, type, guid, initializer);
break;
case "JSHandle":
result = new import_jsHandle.JSHandle(parent, type, guid, initializer);
break;
case "JsonPipe":
result = new import_jsonPipe.JsonPipe(parent, type, guid, initializer);
break;
case "LocalUtils":
result = new import_localUtils.LocalUtils(parent, type, guid, initializer);
if (!this._localUtils)
this._localUtils = result;
break;
case "Page":
result = new import_page.Page(parent, type, guid, initializer);
break;
case "Playwright":
result = new import_playwright.Playwright(parent, type, guid, initializer);
break;
case "Request":
result = new import_network.Request(parent, type, guid, initializer);
break;
case "Response":
result = new import_network.Response(parent, type, guid, initializer);
break;
case "Route":
result = new import_network.Route(parent, type, guid, initializer);
break;
case "Stream":
result = new import_stream.Stream(parent, type, guid, initializer);
break;
case "SocksSupport":
result = new DummyChannelOwner(parent, type, guid, initializer);
break;
case "Tracing":
result = new import_tracing.Tracing(parent, type, guid, initializer);
break;
case "WebSocket":
result = new import_network.WebSocket(parent, type, guid, initializer);
break;
case "WebSocketRoute":
result = new import_network.WebSocketRoute(parent, type, guid, initializer);
break;
case "Worker":
result = new import_worker.Worker(parent, type, guid, initializer);
break;
case "WritableStream":
result = new import_writableStream.WritableStream(parent, type, guid, initializer);
break;
default:
throw new Error("Missing type " + type);
}
return result;
}
}
function formatCallLog(platform, log) {
if (!log || !log.some((l) => !!l))
return "";
return `
Call log:
${platform.colors.dim(log.join("\n"))}
`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Connection
});

View File

@@ -0,0 +1,55 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var consoleMessage_exports = {};
__export(consoleMessage_exports, {
ConsoleMessage: () => ConsoleMessage
});
module.exports = __toCommonJS(consoleMessage_exports);
var import_jsHandle = require("./jsHandle");
var import_page = require("./page");
class ConsoleMessage {
constructor(platform, event) {
this._page = "page" in event && event.page ? import_page.Page.from(event.page) : null;
this._event = event;
if (platform.inspectCustom)
this[platform.inspectCustom] = () => this._inspect();
}
page() {
return this._page;
}
type() {
return this._event.type;
}
text() {
return this._event.text;
}
args() {
return this._event.args.map(import_jsHandle.JSHandle.from);
}
location() {
return this._event.location;
}
_inspect() {
return this.text();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ConsoleMessage
});

44
node_modules/playwright-core/lib/client/coverage.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var coverage_exports = {};
__export(coverage_exports, {
Coverage: () => Coverage
});
module.exports = __toCommonJS(coverage_exports);
class Coverage {
constructor(channel) {
this._channel = channel;
}
async startJSCoverage(options = {}) {
await this._channel.startJSCoverage(options);
}
async stopJSCoverage() {
return (await this._channel.stopJSCoverage()).entries;
}
async startCSSCoverage(options = {}) {
await this._channel.startCSSCoverage(options);
}
async stopCSSCoverage() {
return (await this._channel.stopCSSCoverage()).entries;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Coverage
});

56
node_modules/playwright-core/lib/client/dialog.js generated vendored Normal file
View File

@@ -0,0 +1,56 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var dialog_exports = {};
__export(dialog_exports, {
Dialog: () => Dialog
});
module.exports = __toCommonJS(dialog_exports);
var import_channelOwner = require("./channelOwner");
var import_page = require("./page");
class Dialog extends import_channelOwner.ChannelOwner {
static from(dialog) {
return dialog._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._page = import_page.Page.fromNullable(initializer.page);
}
page() {
return this._page;
}
type() {
return this._initializer.type;
}
message() {
return this._initializer.message;
}
defaultValue() {
return this._initializer.defaultValue;
}
async accept(promptText) {
await this._channel.accept({ promptText });
}
async dismiss() {
await this._channel.dismiss();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Dialog
});

62
node_modules/playwright-core/lib/client/download.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var download_exports = {};
__export(download_exports, {
Download: () => Download
});
module.exports = __toCommonJS(download_exports);
class Download {
constructor(page, url, suggestedFilename, artifact) {
this._page = page;
this._url = url;
this._suggestedFilename = suggestedFilename;
this._artifact = artifact;
}
page() {
return this._page;
}
url() {
return this._url;
}
suggestedFilename() {
return this._suggestedFilename;
}
async path() {
return await this._artifact.pathAfterFinished();
}
async saveAs(path) {
return await this._artifact.saveAs(path);
}
async failure() {
return await this._artifact.failure();
}
async createReadStream() {
return await this._artifact.createReadStream();
}
async cancel() {
return await this._artifact.cancel();
}
async delete() {
return await this._artifact.delete();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Download
});

138
node_modules/playwright-core/lib/client/electron.js generated vendored Normal file
View File

@@ -0,0 +1,138 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var electron_exports = {};
__export(electron_exports, {
Electron: () => Electron,
ElectronApplication: () => ElectronApplication
});
module.exports = __toCommonJS(electron_exports);
var import_browserContext = require("./browserContext");
var import_channelOwner = require("./channelOwner");
var import_clientHelper = require("./clientHelper");
var import_consoleMessage = require("./consoleMessage");
var import_errors = require("./errors");
var import_events = require("./events");
var import_jsHandle = require("./jsHandle");
var import_waiter = require("./waiter");
var import_timeoutSettings = require("./timeoutSettings");
class Electron extends import_channelOwner.ChannelOwner {
static from(electron) {
return electron._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
}
async launch(options = {}) {
options = this._playwright.selectors._withSelectorOptions(options);
const params = {
...await (0, import_browserContext.prepareBrowserContextParams)(this._platform, options),
env: (0, import_clientHelper.envObjectToArray)(options.env ? options.env : this._platform.env),
tracesDir: options.tracesDir,
timeout: new import_timeoutSettings.TimeoutSettings(this._platform).launchTimeout(options)
};
const app = ElectronApplication.from((await this._channel.launch(params)).electronApplication);
this._playwright.selectors._contextsForSelectors.add(app._context);
app.once(import_events.Events.ElectronApplication.Close, () => this._playwright.selectors._contextsForSelectors.delete(app._context));
await app._context._initializeHarFromOptions(options.recordHar);
app._context.tracing._tracesDir = options.tracesDir;
return app;
}
}
class ElectronApplication extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._windows = /* @__PURE__ */ new Set();
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform);
this._context = import_browserContext.BrowserContext.from(initializer.context);
for (const page of this._context._pages)
this._onPage(page);
this._context.on(import_events.Events.BrowserContext.Page, (page) => this._onPage(page));
this._channel.on("close", () => {
this.emit(import_events.Events.ElectronApplication.Close);
});
this._channel.on("console", (event) => this.emit(import_events.Events.ElectronApplication.Console, new import_consoleMessage.ConsoleMessage(this._platform, event)));
this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([
[import_events.Events.ElectronApplication.Console, "console"]
]));
}
static from(electronApplication) {
return electronApplication._object;
}
process() {
return this._connection.toImpl?.(this)?.process();
}
_onPage(page) {
this._windows.add(page);
this.emit(import_events.Events.ElectronApplication.Window, page);
page.once(import_events.Events.Page.Close, () => this._windows.delete(page));
}
windows() {
return [...this._windows];
}
async firstWindow(options) {
if (this._windows.size)
return this._windows.values().next().value;
return await this.waitForEvent("window", options);
}
context() {
return this._context;
}
async [Symbol.asyncDispose]() {
await this.close();
}
async close() {
try {
await this._context.close();
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
return;
throw e;
}
}
async waitForEvent(event, optionsOrPredicate = {}) {
return await this._wrapApiCall(async () => {
const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
const waiter = import_waiter.Waiter.createForEvent(this, event);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
if (event !== import_events.Events.ElectronApplication.Close)
waiter.rejectOnEvent(this, import_events.Events.ElectronApplication.Close, () => new import_errors.TargetClosedError());
const result = await waiter.waitForEvent(this, event, predicate);
waiter.dispose();
return result;
});
}
async browserWindow(page) {
const result = await this._channel.browserWindow({ page: page._channel });
return import_jsHandle.JSHandle.from(result.handle);
}
async evaluate(pageFunction, arg) {
const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async evaluateHandle(pageFunction, arg) {
const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return import_jsHandle.JSHandle.from(result.handle);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Electron,
ElectronApplication
});

View File

@@ -0,0 +1,281 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var elementHandle_exports = {};
__export(elementHandle_exports, {
ElementHandle: () => ElementHandle,
convertInputFiles: () => convertInputFiles,
convertSelectOptionValues: () => convertSelectOptionValues,
determineScreenshotType: () => determineScreenshotType
});
module.exports = __toCommonJS(elementHandle_exports);
var import_frame = require("./frame");
var import_jsHandle = require("./jsHandle");
var import_assert = require("../utils/isomorphic/assert");
var import_fileUtils = require("./fileUtils");
var import_rtti = require("../utils/isomorphic/rtti");
var import_writableStream = require("./writableStream");
var import_mimeType = require("../utils/isomorphic/mimeType");
class ElementHandle extends import_jsHandle.JSHandle {
static from(handle) {
return handle._object;
}
static fromNullable(handle) {
return handle ? ElementHandle.from(handle) : null;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._frame = parent;
this._elementChannel = this._channel;
}
asElement() {
return this;
}
async ownerFrame() {
return import_frame.Frame.fromNullable((await this._elementChannel.ownerFrame()).frame);
}
async contentFrame() {
return import_frame.Frame.fromNullable((await this._elementChannel.contentFrame()).frame);
}
async getAttribute(name) {
const value = (await this._elementChannel.getAttribute({ name })).value;
return value === void 0 ? null : value;
}
async inputValue() {
return (await this._elementChannel.inputValue()).value;
}
async textContent() {
const value = (await this._elementChannel.textContent()).value;
return value === void 0 ? null : value;
}
async innerText() {
return (await this._elementChannel.innerText()).value;
}
async innerHTML() {
return (await this._elementChannel.innerHTML()).value;
}
async isChecked() {
return (await this._elementChannel.isChecked()).value;
}
async isDisabled() {
return (await this._elementChannel.isDisabled()).value;
}
async isEditable() {
return (await this._elementChannel.isEditable()).value;
}
async isEnabled() {
return (await this._elementChannel.isEnabled()).value;
}
async isHidden() {
return (await this._elementChannel.isHidden()).value;
}
async isVisible() {
return (await this._elementChannel.isVisible()).value;
}
async dispatchEvent(type, eventInit = {}) {
await this._elementChannel.dispatchEvent({ type, eventInit: (0, import_jsHandle.serializeArgument)(eventInit) });
}
async scrollIntoViewIfNeeded(options = {}) {
await this._elementChannel.scrollIntoViewIfNeeded({ ...options, timeout: this._frame._timeout(options) });
}
async hover(options = {}) {
await this._elementChannel.hover({ ...options, timeout: this._frame._timeout(options) });
}
async click(options = {}) {
return await this._elementChannel.click({ ...options, timeout: this._frame._timeout(options) });
}
async dblclick(options = {}) {
return await this._elementChannel.dblclick({ ...options, timeout: this._frame._timeout(options) });
}
async tap(options = {}) {
return await this._elementChannel.tap({ ...options, timeout: this._frame._timeout(options) });
}
async selectOption(values, options = {}) {
const result = await this._elementChannel.selectOption({ ...convertSelectOptionValues(values), ...options, timeout: this._frame._timeout(options) });
return result.values;
}
async fill(value, options = {}) {
return await this._elementChannel.fill({ value, ...options, timeout: this._frame._timeout(options) });
}
async selectText(options = {}) {
await this._elementChannel.selectText({ ...options, timeout: this._frame._timeout(options) });
}
async setInputFiles(files, options = {}) {
const frame = await this.ownerFrame();
if (!frame)
throw new Error("Cannot set input files to detached element");
const converted = await convertInputFiles(this._platform, files, frame.page().context());
await this._elementChannel.setInputFiles({ ...converted, ...options, timeout: this._frame._timeout(options) });
}
async focus() {
await this._elementChannel.focus();
}
async type(text, options = {}) {
await this._elementChannel.type({ text, ...options, timeout: this._frame._timeout(options) });
}
async press(key, options = {}) {
await this._elementChannel.press({ key, ...options, timeout: this._frame._timeout(options) });
}
async check(options = {}) {
return await this._elementChannel.check({ ...options, timeout: this._frame._timeout(options) });
}
async uncheck(options = {}) {
return await this._elementChannel.uncheck({ ...options, timeout: this._frame._timeout(options) });
}
async setChecked(checked, options) {
if (checked)
await this.check(options);
else
await this.uncheck(options);
}
async boundingBox() {
const value = (await this._elementChannel.boundingBox()).value;
return value === void 0 ? null : value;
}
async screenshot(options = {}) {
const mask = options.mask;
const copy = { ...options, mask: void 0, timeout: this._frame._timeout(options) };
if (!copy.type)
copy.type = determineScreenshotType(options);
if (mask) {
copy.mask = mask.map((locator) => ({
frame: locator._frame._channel,
selector: locator._selector
}));
}
const result = await this._elementChannel.screenshot(copy);
if (options.path) {
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
await this._platform.fs().promises.writeFile(options.path, result.binary);
}
return result.binary;
}
async $(selector) {
return ElementHandle.fromNullable((await this._elementChannel.querySelector({ selector })).element);
}
async $$(selector) {
const result = await this._elementChannel.querySelectorAll({ selector });
return result.elements.map((h) => ElementHandle.from(h));
}
async $eval(selector, pageFunction, arg) {
const result = await this._elementChannel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async $$eval(selector, pageFunction, arg) {
const result = await this._elementChannel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async waitForElementState(state, options = {}) {
return await this._elementChannel.waitForElementState({ state, ...options, timeout: this._frame._timeout(options) });
}
async waitForSelector(selector, options = {}) {
const result = await this._elementChannel.waitForSelector({ selector, ...options, timeout: this._frame._timeout(options) });
return ElementHandle.fromNullable(result.element);
}
}
function convertSelectOptionValues(values) {
if (values === null)
return {};
if (!Array.isArray(values))
values = [values];
if (!values.length)
return {};
for (let i = 0; i < values.length; i++)
(0, import_assert.assert)(values[i] !== null, `options[${i}]: expected object, got null`);
if (values[0] instanceof ElementHandle)
return { elements: values.map((v) => v._elementChannel) };
if ((0, import_rtti.isString)(values[0]))
return { options: values.map((valueOrLabel) => ({ valueOrLabel })) };
return { options: values };
}
function filePayloadExceedsSizeLimit(payloads) {
return payloads.reduce((size, item) => size + (item.buffer ? item.buffer.byteLength : 0), 0) >= import_fileUtils.fileUploadSizeLimit;
}
async function resolvePathsAndDirectoryForInputFiles(platform, items) {
let localPaths;
let localDirectory;
for (const item of items) {
const stat = await platform.fs().promises.stat(item);
if (stat.isDirectory()) {
if (localDirectory)
throw new Error("Multiple directories are not supported");
localDirectory = platform.path().resolve(item);
} else {
localPaths ??= [];
localPaths.push(platform.path().resolve(item));
}
}
if (localPaths?.length && localDirectory)
throw new Error("File paths must be all files or a single directory");
return [localPaths, localDirectory];
}
async function convertInputFiles(platform, files, context) {
const items = Array.isArray(files) ? files.slice() : [files];
if (items.some((item) => typeof item === "string")) {
if (!items.every((item) => typeof item === "string"))
throw new Error("File paths cannot be mixed with buffers");
const [localPaths, localDirectory] = await resolvePathsAndDirectoryForInputFiles(platform, items);
if (context._connection.isRemote()) {
const files2 = localDirectory ? (await platform.fs().promises.readdir(localDirectory, { withFileTypes: true, recursive: true })).filter((f) => f.isFile()).map((f) => platform.path().join(f.path, f.name)) : localPaths;
const { writableStreams, rootDir } = await context._wrapApiCall(async () => context._channel.createTempFiles({
rootDirName: localDirectory ? platform.path().basename(localDirectory) : void 0,
items: await Promise.all(files2.map(async (file) => {
const lastModifiedMs = (await platform.fs().promises.stat(file)).mtimeMs;
return {
name: localDirectory ? platform.path().relative(localDirectory, file) : platform.path().basename(file),
lastModifiedMs
};
}))
}), { internal: true });
for (let i = 0; i < files2.length; i++) {
const writable = import_writableStream.WritableStream.from(writableStreams[i]);
await platform.streamFile(files2[i], writable.stream());
}
return {
directoryStream: rootDir,
streams: localDirectory ? void 0 : writableStreams
};
}
return {
localPaths,
localDirectory
};
}
const payloads = items;
if (filePayloadExceedsSizeLimit(payloads))
throw new Error("Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead.");
return { payloads };
}
function determineScreenshotType(options) {
if (options.path) {
const mimeType = (0, import_mimeType.getMimeTypeForPath)(options.path);
if (mimeType === "image/png")
return "png";
else if (mimeType === "image/jpeg")
return "jpeg";
throw new Error(`path: unsupported mime type "${mimeType}"`);
}
return options.type;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ElementHandle,
convertInputFiles,
convertSelectOptionValues,
determineScreenshotType
});

77
node_modules/playwright-core/lib/client/errors.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var errors_exports = {};
__export(errors_exports, {
TargetClosedError: () => TargetClosedError,
TimeoutError: () => TimeoutError,
isTargetClosedError: () => isTargetClosedError,
parseError: () => parseError,
serializeError: () => serializeError
});
module.exports = __toCommonJS(errors_exports);
var import_serializers = require("../protocol/serializers");
var import_rtti = require("../utils/isomorphic/rtti");
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = "TimeoutError";
}
}
class TargetClosedError extends Error {
constructor(cause) {
super(cause || "Target page, context or browser has been closed");
}
}
function isTargetClosedError(error) {
return error instanceof TargetClosedError;
}
function serializeError(e) {
if ((0, import_rtti.isError)(e))
return { error: { message: e.message, stack: e.stack, name: e.name } };
return { value: (0, import_serializers.serializeValue)(e, (value) => ({ fallThrough: value })) };
}
function parseError(error) {
if (!error.error) {
if (error.value === void 0)
throw new Error("Serialized error must have either an error or a value");
return (0, import_serializers.parseSerializedValue)(error.value, void 0);
}
if (error.error.name === "TimeoutError") {
const e2 = new TimeoutError(error.error.message);
e2.stack = error.error.stack || "";
return e2;
}
if (error.error.name === "TargetClosedError") {
const e2 = new TargetClosedError(error.error.message);
e2.stack = error.error.stack || "";
return e2;
}
const e = new Error(error.error.message);
e.stack = error.error.stack || "";
e.name = error.error.name;
return e;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TargetClosedError,
TimeoutError,
isTargetClosedError,
parseError,
serializeError
});

314
node_modules/playwright-core/lib/client/eventEmitter.js generated vendored Normal file
View File

@@ -0,0 +1,314 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var eventEmitter_exports = {};
__export(eventEmitter_exports, {
EventEmitter: () => EventEmitter
});
module.exports = __toCommonJS(eventEmitter_exports);
class EventEmitter {
constructor(platform) {
this._events = void 0;
this._eventsCount = 0;
this._maxListeners = void 0;
this._pendingHandlers = /* @__PURE__ */ new Map();
this._platform = platform;
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || void 0;
this.on = this.addListener;
this.off = this.removeListener;
}
setMaxListeners(n) {
if (typeof n !== "number" || n < 0 || Number.isNaN(n))
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
this._maxListeners = n;
return this;
}
getMaxListeners() {
return this._maxListeners === void 0 ? this._platform.defaultMaxListeners() : this._maxListeners;
}
emit(type, ...args) {
const events = this._events;
if (events === void 0)
return false;
const handler = events?.[type];
if (handler === void 0)
return false;
if (typeof handler === "function") {
this._callHandler(type, handler, args);
} else {
const len = handler.length;
const listeners = handler.slice();
for (let i = 0; i < len; ++i)
this._callHandler(type, listeners[i], args);
}
return true;
}
_callHandler(type, handler, args) {
const promise = Reflect.apply(handler, this, args);
if (!(promise instanceof Promise))
return;
let set = this._pendingHandlers.get(type);
if (!set) {
set = /* @__PURE__ */ new Set();
this._pendingHandlers.set(type, set);
}
set.add(promise);
promise.catch((e) => {
if (this._rejectionHandler)
this._rejectionHandler(e);
else
throw e;
}).finally(() => set.delete(promise));
}
addListener(type, listener) {
return this._addListener(type, listener, false);
}
on(type, listener) {
return this._addListener(type, listener, false);
}
_addListener(type, listener, prepend) {
checkListener(listener);
let events = this._events;
let existing;
if (events === void 0) {
events = this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
} else {
if (events.newListener !== void 0) {
this.emit("newListener", type, unwrapListener(listener));
events = this._events;
}
existing = events[type];
}
if (existing === void 0) {
existing = events[type] = listener;
++this._eventsCount;
} else {
if (typeof existing === "function") {
existing = events[type] = prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
const m = this.getMaxListeners();
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
const w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
w.name = "MaxListenersExceededWarning";
w.emitter = this;
w.type = type;
w.count = existing.length;
if (!this._platform.isUnderTest()) {
console.warn(w);
}
}
}
return this;
}
prependListener(type, listener) {
return this._addListener(type, listener, true);
}
once(type, listener) {
checkListener(listener);
this.on(type, new OnceWrapper(this, type, listener).wrapperFunction);
return this;
}
prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, new OnceWrapper(this, type, listener).wrapperFunction);
return this;
}
removeListener(type, listener) {
checkListener(listener);
const events = this._events;
if (events === void 0)
return this;
const list = events[type];
if (list === void 0)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0) {
this._events = /* @__PURE__ */ Object.create(null);
} else {
delete events[type];
if (events.removeListener)
this.emit("removeListener", type, list.listener ?? listener);
}
} else if (typeof list !== "function") {
let position = -1;
let originalListener;
for (let i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || wrappedListener(list[i]) === listener) {
originalListener = wrappedListener(list[i]);
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else
list.splice(position, 1);
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== void 0)
this.emit("removeListener", type, originalListener || listener);
}
return this;
}
off(type, listener) {
return this.removeListener(type, listener);
}
removeAllListeners(type, options) {
this._removeAllListeners(type);
if (!options)
return this;
if (options.behavior === "wait") {
const errors = [];
this._rejectionHandler = (error) => errors.push(error);
return this._waitFor(type).then(() => {
if (errors.length)
throw errors[0];
});
}
if (options.behavior === "ignoreErrors")
this._rejectionHandler = () => {
};
return Promise.resolve();
}
_removeAllListeners(type) {
const events = this._events;
if (!events)
return;
if (!events.removeListener) {
if (type === void 0) {
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== void 0) {
if (--this._eventsCount === 0)
this._events = /* @__PURE__ */ Object.create(null);
else
delete events[type];
}
return;
}
if (type === void 0) {
const keys = Object.keys(events);
let key;
for (let i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === "removeListener")
continue;
this._removeAllListeners(key);
}
this._removeAllListeners("removeListener");
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
return;
}
const listeners = events[type];
if (typeof listeners === "function") {
this.removeListener(type, listeners);
} else if (listeners !== void 0) {
for (let i = listeners.length - 1; i >= 0; i--)
this.removeListener(type, listeners[i]);
}
}
listeners(type) {
return this._listeners(this, type, true);
}
rawListeners(type) {
return this._listeners(this, type, false);
}
listenerCount(type) {
const events = this._events;
if (events !== void 0) {
const listener = events[type];
if (typeof listener === "function")
return 1;
if (listener !== void 0)
return listener.length;
}
return 0;
}
eventNames() {
return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : [];
}
async _waitFor(type) {
let promises = [];
if (type) {
promises = [...this._pendingHandlers.get(type) || []];
} else {
promises = [];
for (const [, pending] of this._pendingHandlers)
promises.push(...pending);
}
await Promise.all(promises);
}
_listeners(target, type, unwrap) {
const events = target._events;
if (events === void 0)
return [];
const listener = events[type];
if (listener === void 0)
return [];
if (typeof listener === "function")
return unwrap ? [unwrapListener(listener)] : [listener];
return unwrap ? unwrapListeners(listener) : listener.slice();
}
}
function checkListener(listener) {
if (typeof listener !== "function")
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
class OnceWrapper {
constructor(eventEmitter, eventType, listener) {
this._fired = false;
this._eventEmitter = eventEmitter;
this._eventType = eventType;
this._listener = listener;
this.wrapperFunction = this._handle.bind(this);
this.wrapperFunction.listener = listener;
}
_handle(...args) {
if (this._fired)
return;
this._fired = true;
this._eventEmitter.removeListener(this._eventType, this.wrapperFunction);
return this._listener.apply(this._eventEmitter, args);
}
}
function unwrapListener(l) {
return wrappedListener(l) ?? l;
}
function unwrapListeners(arr) {
return arr.map((l) => wrappedListener(l) ?? l);
}
function wrappedListener(l) {
return l.listener;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
EventEmitter
});

98
node_modules/playwright-core/lib/client/events.js generated vendored Normal file
View File

@@ -0,0 +1,98 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var events_exports = {};
__export(events_exports, {
Events: () => Events
});
module.exports = __toCommonJS(events_exports);
const Events = {
AndroidDevice: {
WebView: "webview",
Close: "close"
},
AndroidSocket: {
Data: "data",
Close: "close"
},
AndroidWebView: {
Close: "close"
},
Browser: {
Disconnected: "disconnected"
},
BrowserContext: {
Console: "console",
Close: "close",
Dialog: "dialog",
Page: "page",
// Can't use just 'error' due to node.js special treatment of error events.
// @see https://nodejs.org/api/events.html#events_error_events
WebError: "weberror",
BackgroundPage: "backgroundpage",
ServiceWorker: "serviceworker",
Request: "request",
Response: "response",
RequestFailed: "requestfailed",
RequestFinished: "requestfinished"
},
BrowserServer: {
Close: "close"
},
Page: {
Close: "close",
Crash: "crash",
Console: "console",
Dialog: "dialog",
Download: "download",
FileChooser: "filechooser",
DOMContentLoaded: "domcontentloaded",
// Can't use just 'error' due to node.js special treatment of error events.
// @see https://nodejs.org/api/events.html#events_error_events
PageError: "pageerror",
Request: "request",
Response: "response",
RequestFailed: "requestfailed",
RequestFinished: "requestfinished",
FrameAttached: "frameattached",
FrameDetached: "framedetached",
FrameNavigated: "framenavigated",
Load: "load",
Popup: "popup",
WebSocket: "websocket",
Worker: "worker"
},
WebSocket: {
Close: "close",
Error: "socketerror",
FrameReceived: "framereceived",
FrameSent: "framesent"
},
Worker: {
Close: "close"
},
ElectronApplication: {
Close: "close",
Console: "console",
Window: "window"
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Events
});

369
node_modules/playwright-core/lib/client/fetch.js generated vendored Normal file
View File

@@ -0,0 +1,369 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var fetch_exports = {};
__export(fetch_exports, {
APIRequest: () => APIRequest,
APIRequestContext: () => APIRequestContext,
APIResponse: () => APIResponse
});
module.exports = __toCommonJS(fetch_exports);
var import_browserContext = require("./browserContext");
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_network = require("./network");
var import_tracing = require("./tracing");
var import_assert = require("../utils/isomorphic/assert");
var import_fileUtils = require("./fileUtils");
var import_headers = require("../utils/isomorphic/headers");
var import_rtti = require("../utils/isomorphic/rtti");
var import_timeoutSettings = require("./timeoutSettings");
class APIRequest {
constructor(playwright) {
this._contexts = /* @__PURE__ */ new Set();
this._playwright = playwright;
}
async newContext(options = {}) {
options = {
...this._playwright._defaultContextOptions,
...options
};
const storageState = typeof options.storageState === "string" ? JSON.parse(await this._playwright._platform.fs().promises.readFile(options.storageState, "utf8")) : options.storageState;
const context = APIRequestContext.from((await this._playwright._channel.newRequest({
...options,
extraHTTPHeaders: options.extraHTTPHeaders ? (0, import_headers.headersObjectToArray)(options.extraHTTPHeaders) : void 0,
storageState,
tracesDir: this._playwright._defaultLaunchOptions?.tracesDir,
// We do not expose tracesDir in the API, so do not allow options to accidentally override it.
clientCertificates: await (0, import_browserContext.toClientCertificatesProtocol)(this._playwright._platform, options.clientCertificates)
})).request);
this._contexts.add(context);
context._request = this;
context._timeoutSettings.setDefaultTimeout(options.timeout ?? this._playwright._defaultContextTimeout);
context._tracing._tracesDir = this._playwright._defaultLaunchOptions?.tracesDir;
await context._instrumentation.runAfterCreateRequestContext(context);
return context;
}
}
class APIRequestContext extends import_channelOwner.ChannelOwner {
static from(channel) {
return channel._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._tracing = import_tracing.Tracing.from(initializer.tracing);
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform);
}
async [Symbol.asyncDispose]() {
await this.dispose();
}
async dispose(options = {}) {
this._closeReason = options.reason;
await this._instrumentation.runBeforeCloseRequestContext(this);
try {
await this._channel.dispose(options);
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
return;
throw e;
}
this._tracing._resetStackCounter();
this._request?._contexts.delete(this);
}
async delete(url, options) {
return await this.fetch(url, {
...options,
method: "DELETE"
});
}
async head(url, options) {
return await this.fetch(url, {
...options,
method: "HEAD"
});
}
async get(url, options) {
return await this.fetch(url, {
...options,
method: "GET"
});
}
async patch(url, options) {
return await this.fetch(url, {
...options,
method: "PATCH"
});
}
async post(url, options) {
return await this.fetch(url, {
...options,
method: "POST"
});
}
async put(url, options) {
return await this.fetch(url, {
...options,
method: "PUT"
});
}
async fetch(urlOrRequest, options = {}) {
const url = (0, import_rtti.isString)(urlOrRequest) ? urlOrRequest : void 0;
const request = (0, import_rtti.isString)(urlOrRequest) ? void 0 : urlOrRequest;
return await this._innerFetch({ url, request, ...options });
}
async _innerFetch(options = {}) {
return await this._wrapApiCall(async () => {
if (this._closeReason)
throw new import_errors.TargetClosedError(this._closeReason);
(0, import_assert.assert)(options.request || typeof options.url === "string", "First argument must be either URL string or Request");
(0, import_assert.assert)((options.data === void 0 ? 0 : 1) + (options.form === void 0 ? 0 : 1) + (options.multipart === void 0 ? 0 : 1) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`);
(0, import_assert.assert)(options.maxRedirects === void 0 || options.maxRedirects >= 0, `'maxRedirects' must be greater than or equal to '0'`);
(0, import_assert.assert)(options.maxRetries === void 0 || options.maxRetries >= 0, `'maxRetries' must be greater than or equal to '0'`);
const url = options.url !== void 0 ? options.url : options.request.url();
const method = options.method || options.request?.method();
let encodedParams = void 0;
if (typeof options.params === "string")
encodedParams = options.params;
else if (options.params instanceof URLSearchParams)
encodedParams = options.params.toString();
const headersObj = options.headers || options.request?.headers();
const headers = headersObj ? (0, import_headers.headersObjectToArray)(headersObj) : void 0;
let jsonData;
let formData;
let multipartData;
let postDataBuffer;
if (options.data !== void 0) {
if ((0, import_rtti.isString)(options.data)) {
if (isJsonContentType(headers))
jsonData = isJsonParsable(options.data) ? options.data : JSON.stringify(options.data);
else
postDataBuffer = Buffer.from(options.data, "utf8");
} else if (Buffer.isBuffer(options.data)) {
postDataBuffer = options.data;
} else if (typeof options.data === "object" || typeof options.data === "number" || typeof options.data === "boolean") {
jsonData = JSON.stringify(options.data);
} else {
throw new Error(`Unexpected 'data' type`);
}
} else if (options.form) {
if (globalThis.FormData && options.form instanceof FormData) {
formData = [];
for (const [name, value] of options.form.entries()) {
if (typeof value !== "string")
throw new Error(`Expected string for options.form["${name}"], found File. Please use options.multipart instead.`);
formData.push({ name, value });
}
} else {
formData = objectToArray(options.form);
}
} else if (options.multipart) {
multipartData = [];
if (globalThis.FormData && options.multipart instanceof FormData) {
const form = options.multipart;
for (const [name, value] of form.entries()) {
if ((0, import_rtti.isString)(value)) {
multipartData.push({ name, value });
} else {
const file = {
name: value.name,
mimeType: value.type,
buffer: Buffer.from(await value.arrayBuffer())
};
multipartData.push({ name, file });
}
}
} else {
for (const [name, value] of Object.entries(options.multipart))
multipartData.push(await toFormField(this._platform, name, value));
}
}
if (postDataBuffer === void 0 && jsonData === void 0 && formData === void 0 && multipartData === void 0)
postDataBuffer = options.request?.postDataBuffer() || void 0;
const fixtures = {
__testHookLookup: options.__testHookLookup
};
const result = await this._channel.fetch({
url,
params: typeof options.params === "object" ? objectToArray(options.params) : void 0,
encodedParams,
method,
headers,
postData: postDataBuffer,
jsonData,
formData,
multipartData,
timeout: this._timeoutSettings.timeout(options),
failOnStatusCode: options.failOnStatusCode,
ignoreHTTPSErrors: options.ignoreHTTPSErrors,
maxRedirects: options.maxRedirects,
maxRetries: options.maxRetries,
...fixtures
});
return new APIResponse(this, result.response);
});
}
async storageState(options = {}) {
const state = await this._channel.storageState({ indexedDB: options.indexedDB });
if (options.path) {
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
await this._platform.fs().promises.writeFile(options.path, JSON.stringify(state, void 0, 2), "utf8");
}
return state;
}
}
async function toFormField(platform, name, value) {
const typeOfValue = typeof value;
if (isFilePayload(value)) {
const payload = value;
if (!Buffer.isBuffer(payload.buffer))
throw new Error(`Unexpected buffer type of 'data.${name}'`);
return { name, file: filePayloadToJson(payload) };
} else if (typeOfValue === "string" || typeOfValue === "number" || typeOfValue === "boolean") {
return { name, value: String(value) };
} else {
return { name, file: await readStreamToJson(platform, value) };
}
}
function isJsonParsable(value) {
if (typeof value !== "string")
return false;
try {
JSON.parse(value);
return true;
} catch (e) {
if (e instanceof SyntaxError)
return false;
else
throw e;
}
}
class APIResponse {
constructor(context, initializer) {
this._request = context;
this._initializer = initializer;
this._headers = new import_network.RawHeaders(this._initializer.headers);
if (context._platform.inspectCustom)
this[context._platform.inspectCustom] = () => this._inspect();
}
ok() {
return this._initializer.status >= 200 && this._initializer.status <= 299;
}
url() {
return this._initializer.url;
}
status() {
return this._initializer.status;
}
statusText() {
return this._initializer.statusText;
}
headers() {
return this._headers.headers();
}
headersArray() {
return this._headers.headersArray();
}
async body() {
return await this._request._wrapApiCall(async () => {
try {
const result = await this._request._channel.fetchResponseBody({ fetchUid: this._fetchUid() });
if (result.binary === void 0)
throw new Error("Response has been disposed");
return result.binary;
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
throw new Error("Response has been disposed");
throw e;
}
}, { internal: true });
}
async text() {
const content = await this.body();
return content.toString("utf8");
}
async json() {
const content = await this.text();
return JSON.parse(content);
}
async [Symbol.asyncDispose]() {
await this.dispose();
}
async dispose() {
await this._request._channel.disposeAPIResponse({ fetchUid: this._fetchUid() });
}
_inspect() {
const headers = this.headersArray().map(({ name, value }) => ` ${name}: ${value}`);
return `APIResponse: ${this.status()} ${this.statusText()}
${headers.join("\n")}`;
}
_fetchUid() {
return this._initializer.fetchUid;
}
async _fetchLog() {
const { log } = await this._request._channel.fetchLog({ fetchUid: this._fetchUid() });
return log;
}
}
function filePayloadToJson(payload) {
return {
name: payload.name,
mimeType: payload.mimeType,
buffer: payload.buffer
};
}
async function readStreamToJson(platform, stream) {
const buffer = await new Promise((resolve, reject) => {
const chunks = [];
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", (err) => reject(err));
});
const streamPath = Buffer.isBuffer(stream.path) ? stream.path.toString("utf8") : stream.path;
return {
name: platform.path().basename(streamPath),
buffer
};
}
function isJsonContentType(headers) {
if (!headers)
return false;
for (const { name, value } of headers) {
if (name.toLocaleLowerCase() === "content-type")
return value === "application/json";
}
return false;
}
function objectToArray(map) {
if (!map)
return void 0;
const result = [];
for (const [name, value] of Object.entries(map)) {
if (value !== void 0)
result.push({ name, value: String(value) });
}
return result;
}
function isFilePayload(value) {
return typeof value === "object" && value["name"] && value["mimeType"] && value["buffer"];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
APIRequest,
APIRequestContext,
APIResponse
});

46
node_modules/playwright-core/lib/client/fileChooser.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var fileChooser_exports = {};
__export(fileChooser_exports, {
FileChooser: () => FileChooser
});
module.exports = __toCommonJS(fileChooser_exports);
class FileChooser {
constructor(page, elementHandle, isMultiple) {
this._page = page;
this._elementHandle = elementHandle;
this._isMultiple = isMultiple;
}
element() {
return this._elementHandle;
}
isMultiple() {
return this._isMultiple;
}
page() {
return this._page;
}
async setFiles(files, options) {
return await this._elementHandle.setInputFiles(files, options);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FileChooser
});

34
node_modules/playwright-core/lib/client/fileUtils.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var fileUtils_exports = {};
__export(fileUtils_exports, {
fileUploadSizeLimit: () => fileUploadSizeLimit,
mkdirIfNeeded: () => mkdirIfNeeded
});
module.exports = __toCommonJS(fileUtils_exports);
const fileUploadSizeLimit = 50 * 1024 * 1024;
async function mkdirIfNeeded(platform, filePath) {
await platform.fs().promises.mkdir(platform.path().dirname(filePath), { recursive: true }).catch(() => {
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
fileUploadSizeLimit,
mkdirIfNeeded
});

408
node_modules/playwright-core/lib/client/frame.js generated vendored Normal file
View File

@@ -0,0 +1,408 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var frame_exports = {};
__export(frame_exports, {
Frame: () => Frame,
verifyLoadState: () => verifyLoadState
});
module.exports = __toCommonJS(frame_exports);
var import_eventEmitter = require("./eventEmitter");
var import_channelOwner = require("./channelOwner");
var import_clientHelper = require("./clientHelper");
var import_elementHandle = require("./elementHandle");
var import_events = require("./events");
var import_jsHandle = require("./jsHandle");
var import_locator = require("./locator");
var network = __toESM(require("./network"));
var import_types = require("./types");
var import_waiter = require("./waiter");
var import_assert = require("../utils/isomorphic/assert");
var import_locatorUtils = require("../utils/isomorphic/locatorUtils");
var import_urlMatch = require("../utils/isomorphic/urlMatch");
var import_timeoutSettings = require("./timeoutSettings");
class Frame extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._parentFrame = null;
this._url = "";
this._name = "";
this._detached = false;
this._childFrames = /* @__PURE__ */ new Set();
this._eventEmitter = new import_eventEmitter.EventEmitter(parent._platform);
this._eventEmitter.setMaxListeners(0);
this._parentFrame = Frame.fromNullable(initializer.parentFrame);
if (this._parentFrame)
this._parentFrame._childFrames.add(this);
this._name = initializer.name;
this._url = initializer.url;
this._loadStates = new Set(initializer.loadStates);
this._channel.on("loadstate", (event) => {
if (event.add) {
this._loadStates.add(event.add);
this._eventEmitter.emit("loadstate", event.add);
}
if (event.remove)
this._loadStates.delete(event.remove);
if (!this._parentFrame && event.add === "load" && this._page)
this._page.emit(import_events.Events.Page.Load, this._page);
if (!this._parentFrame && event.add === "domcontentloaded" && this._page)
this._page.emit(import_events.Events.Page.DOMContentLoaded, this._page);
});
this._channel.on("navigated", (event) => {
this._url = event.url;
this._name = event.name;
this._eventEmitter.emit("navigated", event);
if (!event.error && this._page)
this._page.emit(import_events.Events.Page.FrameNavigated, this);
});
}
static from(frame) {
return frame._object;
}
static fromNullable(frame) {
return frame ? Frame.from(frame) : null;
}
page() {
return this._page;
}
_timeout(options) {
const timeoutSettings = this._page?._timeoutSettings || new import_timeoutSettings.TimeoutSettings(this._platform);
return timeoutSettings.timeout(options || {});
}
_navigationTimeout(options) {
const timeoutSettings = this._page?._timeoutSettings || new import_timeoutSettings.TimeoutSettings(this._platform);
return timeoutSettings.navigationTimeout(options || {});
}
async goto(url, options = {}) {
const waitUntil = verifyLoadState("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
return network.Response.fromNullable((await this._channel.goto({ url, ...options, waitUntil, timeout: this._navigationTimeout(options) })).response);
}
_setupNavigationWaiter(options) {
const waiter = new import_waiter.Waiter(this._page, "");
if (this._page.isClosed())
waiter.rejectImmediately(this._page._closeErrorWithReason());
waiter.rejectOnEvent(this._page, import_events.Events.Page.Close, () => this._page._closeErrorWithReason());
waiter.rejectOnEvent(this._page, import_events.Events.Page.Crash, new Error("Navigation failed because page crashed!"));
waiter.rejectOnEvent(this._page, import_events.Events.Page.FrameDetached, new Error("Navigating frame was detached!"), (frame) => frame === this);
const timeout = this._page._timeoutSettings.navigationTimeout(options);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`);
return waiter;
}
async waitForNavigation(options = {}) {
return await this._page._wrapApiCall(async () => {
const waitUntil = verifyLoadState("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
const waiter = this._setupNavigationWaiter(options);
const toUrl = typeof options.url === "string" ? ` to "${options.url}"` : "";
waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);
const navigatedEvent = await waiter.waitForEvent(this._eventEmitter, "navigated", (event) => {
if (event.error)
return true;
waiter.log(` navigated to "${event.url}"`);
return (0, import_urlMatch.urlMatches)(this._page?.context()._options.baseURL, event.url, options.url);
});
if (navigatedEvent.error) {
const e = new Error(navigatedEvent.error);
e.stack = "";
await waiter.waitForPromise(Promise.reject(e));
}
if (!this._loadStates.has(waitUntil)) {
await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => {
waiter.log(` "${s}" event fired`);
return s === waitUntil;
});
}
const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;
const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;
waiter.dispose();
return response;
}, { title: "Wait for navigation" });
}
async waitForLoadState(state = "load", options = {}) {
state = verifyLoadState("state", state);
return await this._page._wrapApiCall(async () => {
const waiter = this._setupNavigationWaiter(options);
if (this._loadStates.has(state)) {
waiter.log(` not waiting, "${state}" event already fired`);
} else {
await waiter.waitForEvent(this._eventEmitter, "loadstate", (s) => {
waiter.log(` "${s}" event fired`);
return s === state;
});
}
waiter.dispose();
}, { title: `Wait for load state "${state}"` });
}
async waitForURL(url, options = {}) {
if ((0, import_urlMatch.urlMatches)(this._page?.context()._options.baseURL, this.url(), url))
return await this.waitForLoadState(options.waitUntil, options);
await this.waitForNavigation({ url, ...options });
}
async frameElement() {
return import_elementHandle.ElementHandle.from((await this._channel.frameElement()).element);
}
async evaluateHandle(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return import_jsHandle.JSHandle.from(result.handle);
}
async evaluate(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async _evaluateFunction(functionDeclaration) {
const result = await this._channel.evaluateExpression({ expression: functionDeclaration, isFunction: true, arg: (0, import_jsHandle.serializeArgument)(void 0) });
return (0, import_jsHandle.parseResult)(result.value);
}
async _evaluateExposeUtilityScript(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async $(selector, options) {
const result = await this._channel.querySelector({ selector, ...options });
return import_elementHandle.ElementHandle.fromNullable(result.element);
}
async waitForSelector(selector, options = {}) {
if (options.visibility)
throw new Error("options.visibility is not supported, did you mean options.state?");
if (options.waitFor && options.waitFor !== "visible")
throw new Error("options.waitFor is not supported, did you mean options.state?");
const result = await this._channel.waitForSelector({ selector, ...options, timeout: this._timeout(options) });
return import_elementHandle.ElementHandle.fromNullable(result.element);
}
async dispatchEvent(selector, type, eventInit, options = {}) {
await this._channel.dispatchEvent({ selector, type, eventInit: (0, import_jsHandle.serializeArgument)(eventInit), ...options, timeout: this._timeout(options) });
}
async $eval(selector, pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
const result = await this._channel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async $$eval(selector, pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
const result = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async $$(selector) {
const result = await this._channel.querySelectorAll({ selector });
return result.elements.map((e) => import_elementHandle.ElementHandle.from(e));
}
async _queryCount(selector, options) {
return (await this._channel.queryCount({ selector, ...options })).value;
}
async content() {
return (await this._channel.content()).value;
}
async setContent(html, options = {}) {
const waitUntil = verifyLoadState("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
await this._channel.setContent({ html, ...options, waitUntil, timeout: this._navigationTimeout(options) });
}
name() {
return this._name || "";
}
url() {
return this._url;
}
parentFrame() {
return this._parentFrame;
}
childFrames() {
return Array.from(this._childFrames);
}
isDetached() {
return this._detached;
}
async addScriptTag(options = {}) {
const copy = { ...options };
if (copy.path) {
copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString();
copy.content = (0, import_clientHelper.addSourceUrlToScript)(copy.content, copy.path);
}
return import_elementHandle.ElementHandle.from((await this._channel.addScriptTag({ ...copy })).element);
}
async addStyleTag(options = {}) {
const copy = { ...options };
if (copy.path) {
copy.content = (await this._platform.fs().promises.readFile(copy.path)).toString();
copy.content += "/*# sourceURL=" + copy.path.replace(/\n/g, "") + "*/";
}
return import_elementHandle.ElementHandle.from((await this._channel.addStyleTag({ ...copy })).element);
}
async click(selector, options = {}) {
return await this._channel.click({ selector, ...options, timeout: this._timeout(options) });
}
async dblclick(selector, options = {}) {
return await this._channel.dblclick({ selector, ...options, timeout: this._timeout(options) });
}
async dragAndDrop(source, target, options = {}) {
return await this._channel.dragAndDrop({ source, target, ...options, timeout: this._timeout(options) });
}
async tap(selector, options = {}) {
return await this._channel.tap({ selector, ...options, timeout: this._timeout(options) });
}
async fill(selector, value, options = {}) {
return await this._channel.fill({ selector, value, ...options, timeout: this._timeout(options) });
}
async _highlight(selector) {
return await this._channel.highlight({ selector });
}
locator(selector, options) {
return new import_locator.Locator(this, selector, options);
}
getByTestId(testId) {
return this.locator((0, import_locatorUtils.getByTestIdSelector)((0, import_locator.testIdAttributeName)(), testId));
}
getByAltText(text, options) {
return this.locator((0, import_locatorUtils.getByAltTextSelector)(text, options));
}
getByLabel(text, options) {
return this.locator((0, import_locatorUtils.getByLabelSelector)(text, options));
}
getByPlaceholder(text, options) {
return this.locator((0, import_locatorUtils.getByPlaceholderSelector)(text, options));
}
getByText(text, options) {
return this.locator((0, import_locatorUtils.getByTextSelector)(text, options));
}
getByTitle(text, options) {
return this.locator((0, import_locatorUtils.getByTitleSelector)(text, options));
}
getByRole(role, options = {}) {
return this.locator((0, import_locatorUtils.getByRoleSelector)(role, options));
}
frameLocator(selector) {
return new import_locator.FrameLocator(this, selector);
}
async focus(selector, options = {}) {
await this._channel.focus({ selector, ...options, timeout: this._timeout(options) });
}
async textContent(selector, options = {}) {
const value = (await this._channel.textContent({ selector, ...options, timeout: this._timeout(options) })).value;
return value === void 0 ? null : value;
}
async innerText(selector, options = {}) {
return (await this._channel.innerText({ selector, ...options, timeout: this._timeout(options) })).value;
}
async innerHTML(selector, options = {}) {
return (await this._channel.innerHTML({ selector, ...options, timeout: this._timeout(options) })).value;
}
async getAttribute(selector, name, options = {}) {
const value = (await this._channel.getAttribute({ selector, name, ...options, timeout: this._timeout(options) })).value;
return value === void 0 ? null : value;
}
async inputValue(selector, options = {}) {
return (await this._channel.inputValue({ selector, ...options, timeout: this._timeout(options) })).value;
}
async isChecked(selector, options = {}) {
return (await this._channel.isChecked({ selector, ...options, timeout: this._timeout(options) })).value;
}
async isDisabled(selector, options = {}) {
return (await this._channel.isDisabled({ selector, ...options, timeout: this._timeout(options) })).value;
}
async isEditable(selector, options = {}) {
return (await this._channel.isEditable({ selector, ...options, timeout: this._timeout(options) })).value;
}
async isEnabled(selector, options = {}) {
return (await this._channel.isEnabled({ selector, ...options, timeout: this._timeout(options) })).value;
}
async isHidden(selector, options = {}) {
return (await this._channel.isHidden({ selector, ...options })).value;
}
async isVisible(selector, options = {}) {
return (await this._channel.isVisible({ selector, ...options })).value;
}
async hover(selector, options = {}) {
await this._channel.hover({ selector, ...options, timeout: this._timeout(options) });
}
async selectOption(selector, values, options = {}) {
return (await this._channel.selectOption({ selector, ...(0, import_elementHandle.convertSelectOptionValues)(values), ...options, timeout: this._timeout(options) })).values;
}
async setInputFiles(selector, files, options = {}) {
const converted = await (0, import_elementHandle.convertInputFiles)(this._platform, files, this.page().context());
await this._channel.setInputFiles({ selector, ...converted, ...options, timeout: this._timeout(options) });
}
async type(selector, text, options = {}) {
await this._channel.type({ selector, text, ...options, timeout: this._timeout(options) });
}
async press(selector, key, options = {}) {
await this._channel.press({ selector, key, ...options, timeout: this._timeout(options) });
}
async check(selector, options = {}) {
await this._channel.check({ selector, ...options, timeout: this._timeout(options) });
}
async uncheck(selector, options = {}) {
await this._channel.uncheck({ selector, ...options, timeout: this._timeout(options) });
}
async setChecked(selector, checked, options) {
if (checked)
await this.check(selector, options);
else
await this.uncheck(selector, options);
}
async waitForTimeout(timeout) {
await this._channel.waitForTimeout({ waitTimeout: timeout });
}
async waitForFunction(pageFunction, arg, options = {}) {
if (typeof options.polling === "string")
(0, import_assert.assert)(options.polling === "raf", "Unknown polling option: " + options.polling);
const result = await this._channel.waitForFunction({
...options,
pollingInterval: options.polling === "raf" ? void 0 : options.polling,
expression: String(pageFunction),
isFunction: typeof pageFunction === "function",
arg: (0, import_jsHandle.serializeArgument)(arg),
timeout: this._timeout(options)
});
return import_jsHandle.JSHandle.from(result.handle);
}
async title() {
return (await this._channel.title()).value;
}
async _expect(expression, options) {
const params = { expression, ...options, isNot: !!options.isNot };
params.expectedValue = (0, import_jsHandle.serializeArgument)(options.expectedValue);
const result = await this._channel.expect(params);
if (result.received !== void 0)
result.received = (0, import_jsHandle.parseResult)(result.received);
return result;
}
}
function verifyLoadState(name, waitUntil) {
if (waitUntil === "networkidle0")
waitUntil = "networkidle";
if (!import_types.kLifecycleEvents.has(waitUntil))
throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`);
return waitUntil;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Frame,
verifyLoadState
});

87
node_modules/playwright-core/lib/client/harRouter.js generated vendored Normal file
View File

@@ -0,0 +1,87 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var harRouter_exports = {};
__export(harRouter_exports, {
HarRouter: () => HarRouter
});
module.exports = __toCommonJS(harRouter_exports);
class HarRouter {
static async create(localUtils, file, notFoundAction, options) {
const { harId, error } = await localUtils.harOpen({ file });
if (error)
throw new Error(error);
return new HarRouter(localUtils, harId, notFoundAction, options);
}
constructor(localUtils, harId, notFoundAction, options) {
this._localUtils = localUtils;
this._harId = harId;
this._options = options;
this._notFoundAction = notFoundAction;
}
async _handle(route) {
const request = route.request();
const response = await this._localUtils.harLookup({
harId: this._harId,
url: request.url(),
method: request.method(),
headers: await request.headersArray(),
postData: request.postDataBuffer() || void 0,
isNavigationRequest: request.isNavigationRequest()
});
if (response.action === "redirect") {
route._platform.log("api", `HAR: ${route.request().url()} redirected to ${response.redirectURL}`);
await route._redirectNavigationRequest(response.redirectURL);
return;
}
if (response.action === "fulfill") {
if (response.status === -1)
return;
await route.fulfill({
status: response.status,
headers: Object.fromEntries(response.headers.map((h) => [h.name, h.value])),
body: response.body
});
return;
}
if (response.action === "error")
route._platform.log("api", "HAR: " + response.message);
if (this._notFoundAction === "abort") {
await route.abort();
return;
}
await route.fallback();
}
async addContextRoute(context) {
await context.route(this._options.urlMatch || "**/*", (route) => this._handle(route));
}
async addPageRoute(page) {
await page.route(this._options.urlMatch || "**/*", (route) => this._handle(route));
}
async [Symbol.asyncDispose]() {
await this.dispose();
}
dispose() {
this._localUtils.harClose({ harId: this._harId }).catch(() => {
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
HarRouter
});

84
node_modules/playwright-core/lib/client/input.js generated vendored Normal file
View File

@@ -0,0 +1,84 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var input_exports = {};
__export(input_exports, {
Keyboard: () => Keyboard,
Mouse: () => Mouse,
Touchscreen: () => Touchscreen
});
module.exports = __toCommonJS(input_exports);
class Keyboard {
constructor(page) {
this._page = page;
}
async down(key) {
await this._page._channel.keyboardDown({ key });
}
async up(key) {
await this._page._channel.keyboardUp({ key });
}
async insertText(text) {
await this._page._channel.keyboardInsertText({ text });
}
async type(text, options = {}) {
await this._page._channel.keyboardType({ text, ...options });
}
async press(key, options = {}) {
await this._page._channel.keyboardPress({ key, ...options });
}
}
class Mouse {
constructor(page) {
this._page = page;
}
async move(x, y, options = {}) {
await this._page._channel.mouseMove({ x, y, ...options });
}
async down(options = {}) {
await this._page._channel.mouseDown({ ...options });
}
async up(options = {}) {
await this._page._channel.mouseUp(options);
}
async click(x, y, options = {}) {
await this._page._channel.mouseClick({ x, y, ...options });
}
async dblclick(x, y, options = {}) {
await this._page._wrapApiCall(async () => {
await this.click(x, y, { ...options, clickCount: 2 });
}, { title: "Double click" });
}
async wheel(deltaX, deltaY) {
await this._page._channel.mouseWheel({ deltaX, deltaY });
}
}
class Touchscreen {
constructor(page) {
this._page = page;
}
async tap(x, y) {
await this._page._channel.touchscreenTap({ x, y });
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Keyboard,
Mouse,
Touchscreen
});

109
node_modules/playwright-core/lib/client/jsHandle.js generated vendored Normal file
View File

@@ -0,0 +1,109 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var jsHandle_exports = {};
__export(jsHandle_exports, {
JSHandle: () => JSHandle,
assertMaxArguments: () => assertMaxArguments,
parseResult: () => parseResult,
serializeArgument: () => serializeArgument
});
module.exports = __toCommonJS(jsHandle_exports);
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_serializers = require("../protocol/serializers");
class JSHandle extends import_channelOwner.ChannelOwner {
static from(handle) {
return handle._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._preview = this._initializer.preview;
this._channel.on("previewUpdated", ({ preview }) => this._preview = preview);
}
async evaluate(pageFunction, arg) {
const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) });
return parseResult(result.value);
}
async _evaluateFunction(functionDeclaration) {
const result = await this._channel.evaluateExpression({ expression: functionDeclaration, isFunction: true, arg: serializeArgument(void 0) });
return parseResult(result.value);
}
async evaluateHandle(pageFunction, arg) {
const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: serializeArgument(arg) });
return JSHandle.from(result.handle);
}
async getProperty(propertyName) {
const result = await this._channel.getProperty({ name: propertyName });
return JSHandle.from(result.handle);
}
async getProperties() {
const map = /* @__PURE__ */ new Map();
for (const { name, value } of (await this._channel.getPropertyList()).properties)
map.set(name, JSHandle.from(value));
return map;
}
async jsonValue() {
return parseResult((await this._channel.jsonValue()).value);
}
asElement() {
return null;
}
async [Symbol.asyncDispose]() {
await this.dispose();
}
async dispose() {
try {
await this._channel.dispose();
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e))
return;
throw e;
}
}
toString() {
return this._preview;
}
}
function serializeArgument(arg) {
const handles = [];
const pushHandle = (channel) => {
handles.push(channel);
return handles.length - 1;
};
const value = (0, import_serializers.serializeValue)(arg, (value2) => {
if (value2 instanceof JSHandle)
return { h: pushHandle(value2._channel) };
return { fallThrough: value2 };
});
return { value, handles };
}
function parseResult(value) {
return (0, import_serializers.parseSerializedValue)(value, void 0);
}
function assertMaxArguments(count, max) {
if (count > max)
throw new Error("Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object.");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
JSHandle,
assertMaxArguments,
parseResult,
serializeArgument
});

39
node_modules/playwright-core/lib/client/jsonPipe.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var jsonPipe_exports = {};
__export(jsonPipe_exports, {
JsonPipe: () => JsonPipe
});
module.exports = __toCommonJS(jsonPipe_exports);
var import_channelOwner = require("./channelOwner");
class JsonPipe extends import_channelOwner.ChannelOwner {
static from(jsonPipe) {
return jsonPipe._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
}
channel() {
return this._channel;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
JsonPipe
});

60
node_modules/playwright-core/lib/client/localUtils.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var localUtils_exports = {};
__export(localUtils_exports, {
LocalUtils: () => LocalUtils
});
module.exports = __toCommonJS(localUtils_exports);
var import_channelOwner = require("./channelOwner");
class LocalUtils extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this.devices = {};
for (const { name, descriptor } of initializer.deviceDescriptors)
this.devices[name] = descriptor;
}
async zip(params) {
return await this._channel.zip(params);
}
async harOpen(params) {
return await this._channel.harOpen(params);
}
async harLookup(params) {
return await this._channel.harLookup(params);
}
async harClose(params) {
return await this._channel.harClose(params);
}
async harUnzip(params) {
return await this._channel.harUnzip(params);
}
async tracingStarted(params) {
return await this._channel.tracingStarted(params);
}
async traceDiscarded(params) {
return await this._channel.traceDiscarded(params);
}
async addStackToTracingNoReply(params) {
return await this._channel.addStackToTracingNoReply(params);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
LocalUtils
});

366
node_modules/playwright-core/lib/client/locator.js generated vendored Normal file
View File

@@ -0,0 +1,366 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var locator_exports = {};
__export(locator_exports, {
FrameLocator: () => FrameLocator,
Locator: () => Locator,
setTestIdAttribute: () => setTestIdAttribute,
testIdAttributeName: () => testIdAttributeName
});
module.exports = __toCommonJS(locator_exports);
var import_elementHandle = require("./elementHandle");
var import_locatorGenerators = require("../utils/isomorphic/locatorGenerators");
var import_locatorUtils = require("../utils/isomorphic/locatorUtils");
var import_stringUtils = require("../utils/isomorphic/stringUtils");
var import_rtti = require("../utils/isomorphic/rtti");
var import_time = require("../utils/isomorphic/time");
class Locator {
constructor(frame, selector, options) {
this._frame = frame;
this._selector = selector;
if (options?.hasText)
this._selector += ` >> internal:has-text=${(0, import_stringUtils.escapeForTextSelector)(options.hasText, false)}`;
if (options?.hasNotText)
this._selector += ` >> internal:has-not-text=${(0, import_stringUtils.escapeForTextSelector)(options.hasNotText, false)}`;
if (options?.has) {
const locator = options.has;
if (locator._frame !== frame)
throw new Error(`Inner "has" locator must belong to the same frame.`);
this._selector += ` >> internal:has=` + JSON.stringify(locator._selector);
}
if (options?.hasNot) {
const locator = options.hasNot;
if (locator._frame !== frame)
throw new Error(`Inner "hasNot" locator must belong to the same frame.`);
this._selector += ` >> internal:has-not=` + JSON.stringify(locator._selector);
}
if (options?.visible !== void 0)
this._selector += ` >> visible=${options.visible ? "true" : "false"}`;
if (this._frame._platform.inspectCustom)
this[this._frame._platform.inspectCustom] = () => this._inspect();
}
async _withElement(task, options) {
const timeout = this._frame._timeout({ timeout: options.timeout });
const deadline = timeout ? (0, import_time.monotonicTime)() + timeout : 0;
return await this._frame._wrapApiCall(async () => {
const result = await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, state: "attached", timeout });
const handle = import_elementHandle.ElementHandle.fromNullable(result.element);
if (!handle)
throw new Error(`Could not resolve ${this._selector} to DOM Element`);
try {
return await task(handle, deadline ? deadline - (0, import_time.monotonicTime)() : 0);
} finally {
await handle.dispose();
}
}, { title: options.title, internal: options.internal });
}
_equals(locator) {
return this._frame === locator._frame && this._selector === locator._selector;
}
page() {
return this._frame.page();
}
async boundingBox(options) {
return await this._withElement((h) => h.boundingBox(), { title: "Bounding box", timeout: options?.timeout });
}
async check(options = {}) {
return await this._frame.check(this._selector, { strict: true, ...options });
}
async click(options = {}) {
return await this._frame.click(this._selector, { strict: true, ...options });
}
async dblclick(options = {}) {
await this._frame.dblclick(this._selector, { strict: true, ...options });
}
async dispatchEvent(type, eventInit = {}, options) {
return await this._frame.dispatchEvent(this._selector, type, eventInit, { strict: true, ...options });
}
async dragTo(target, options = {}) {
return await this._frame.dragAndDrop(this._selector, target._selector, {
strict: true,
...options
});
}
async evaluate(pageFunction, arg, options) {
return await this._withElement((h) => h.evaluate(pageFunction, arg), { title: "Evaluate", timeout: options?.timeout });
}
async _evaluateFunction(functionDeclaration, options) {
return await this._withElement((h) => h._evaluateFunction(functionDeclaration), { title: "Evaluate", timeout: options?.timeout });
}
async evaluateAll(pageFunction, arg) {
return await this._frame.$$eval(this._selector, pageFunction, arg);
}
async evaluateHandle(pageFunction, arg, options) {
return await this._withElement((h) => h.evaluateHandle(pageFunction, arg), { title: "Evaluate", timeout: options?.timeout });
}
async fill(value, options = {}) {
return await this._frame.fill(this._selector, value, { strict: true, ...options });
}
async clear(options = {}) {
await this._frame._wrapApiCall(() => this.fill("", options), { title: "Clear" });
}
async _highlight() {
return await this._frame._highlight(this._selector);
}
async highlight() {
return await this._frame._highlight(this._selector);
}
locator(selectorOrLocator, options) {
if ((0, import_rtti.isString)(selectorOrLocator))
return new Locator(this._frame, this._selector + " >> " + selectorOrLocator, options);
if (selectorOrLocator._frame !== this._frame)
throw new Error(`Locators must belong to the same frame.`);
return new Locator(this._frame, this._selector + " >> internal:chain=" + JSON.stringify(selectorOrLocator._selector), options);
}
getByTestId(testId) {
return this.locator((0, import_locatorUtils.getByTestIdSelector)(testIdAttributeName(), testId));
}
getByAltText(text, options) {
return this.locator((0, import_locatorUtils.getByAltTextSelector)(text, options));
}
getByLabel(text, options) {
return this.locator((0, import_locatorUtils.getByLabelSelector)(text, options));
}
getByPlaceholder(text, options) {
return this.locator((0, import_locatorUtils.getByPlaceholderSelector)(text, options));
}
getByText(text, options) {
return this.locator((0, import_locatorUtils.getByTextSelector)(text, options));
}
getByTitle(text, options) {
return this.locator((0, import_locatorUtils.getByTitleSelector)(text, options));
}
getByRole(role, options = {}) {
return this.locator((0, import_locatorUtils.getByRoleSelector)(role, options));
}
frameLocator(selector) {
return new FrameLocator(this._frame, this._selector + " >> " + selector);
}
filter(options) {
return new Locator(this._frame, this._selector, options);
}
async elementHandle(options) {
return await this._frame.waitForSelector(this._selector, { strict: true, state: "attached", ...options });
}
async elementHandles() {
return await this._frame.$$(this._selector);
}
contentFrame() {
return new FrameLocator(this._frame, this._selector);
}
describe(description) {
return new Locator(this._frame, this._selector + " >> internal:describe=" + JSON.stringify(description));
}
first() {
return new Locator(this._frame, this._selector + " >> nth=0");
}
last() {
return new Locator(this._frame, this._selector + ` >> nth=-1`);
}
nth(index) {
return new Locator(this._frame, this._selector + ` >> nth=${index}`);
}
and(locator) {
if (locator._frame !== this._frame)
throw new Error(`Locators must belong to the same frame.`);
return new Locator(this._frame, this._selector + ` >> internal:and=` + JSON.stringify(locator._selector));
}
or(locator) {
if (locator._frame !== this._frame)
throw new Error(`Locators must belong to the same frame.`);
return new Locator(this._frame, this._selector + ` >> internal:or=` + JSON.stringify(locator._selector));
}
async focus(options) {
return await this._frame.focus(this._selector, { strict: true, ...options });
}
async blur(options) {
await this._frame._channel.blur({ selector: this._selector, strict: true, ...options, timeout: this._frame._timeout(options) });
}
// options are only here for testing
async count(_options) {
return await this._frame._queryCount(this._selector, _options);
}
async _resolveSelector() {
return await this._frame._channel.resolveSelector({ selector: this._selector });
}
async getAttribute(name, options) {
return await this._frame.getAttribute(this._selector, name, { strict: true, ...options });
}
async hover(options = {}) {
return await this._frame.hover(this._selector, { strict: true, ...options });
}
async innerHTML(options) {
return await this._frame.innerHTML(this._selector, { strict: true, ...options });
}
async innerText(options) {
return await this._frame.innerText(this._selector, { strict: true, ...options });
}
async inputValue(options) {
return await this._frame.inputValue(this._selector, { strict: true, ...options });
}
async isChecked(options) {
return await this._frame.isChecked(this._selector, { strict: true, ...options });
}
async isDisabled(options) {
return await this._frame.isDisabled(this._selector, { strict: true, ...options });
}
async isEditable(options) {
return await this._frame.isEditable(this._selector, { strict: true, ...options });
}
async isEnabled(options) {
return await this._frame.isEnabled(this._selector, { strict: true, ...options });
}
async isHidden(options) {
return await this._frame.isHidden(this._selector, { strict: true, ...options });
}
async isVisible(options) {
return await this._frame.isVisible(this._selector, { strict: true, ...options });
}
async press(key, options = {}) {
return await this._frame.press(this._selector, key, { strict: true, ...options });
}
async screenshot(options = {}) {
const mask = options.mask;
return await this._withElement((h, timeout) => h.screenshot({ ...options, mask, timeout }), { title: "Screenshot", timeout: options.timeout });
}
async ariaSnapshot(options) {
const result = await this._frame._channel.ariaSnapshot({ ...options, selector: this._selector, timeout: this._frame._timeout(options) });
return result.snapshot;
}
async scrollIntoViewIfNeeded(options = {}) {
return await this._withElement((h, timeout) => h.scrollIntoViewIfNeeded({ ...options, timeout }), { title: "Scroll into view", timeout: options.timeout });
}
async selectOption(values, options = {}) {
return await this._frame.selectOption(this._selector, values, { strict: true, ...options });
}
async selectText(options = {}) {
return await this._withElement((h, timeout) => h.selectText({ ...options, timeout }), { title: "Select text", timeout: options.timeout });
}
async setChecked(checked, options) {
if (checked)
await this.check(options);
else
await this.uncheck(options);
}
async setInputFiles(files, options = {}) {
return await this._frame.setInputFiles(this._selector, files, { strict: true, ...options });
}
async tap(options = {}) {
return await this._frame.tap(this._selector, { strict: true, ...options });
}
async textContent(options) {
return await this._frame.textContent(this._selector, { strict: true, ...options });
}
async type(text, options = {}) {
return await this._frame.type(this._selector, text, { strict: true, ...options });
}
async pressSequentially(text, options = {}) {
return await this.type(text, options);
}
async uncheck(options = {}) {
return await this._frame.uncheck(this._selector, { strict: true, ...options });
}
async all() {
return new Array(await this.count()).fill(0).map((e, i) => this.nth(i));
}
async allInnerTexts() {
return await this._frame.$$eval(this._selector, (ee) => ee.map((e) => e.innerText));
}
async allTextContents() {
return await this._frame.$$eval(this._selector, (ee) => ee.map((e) => e.textContent || ""));
}
async waitFor(options) {
await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, omitReturnValue: true, ...options, timeout: this._frame._timeout(options) });
}
async _expect(expression, options) {
return this._frame._expect(expression, {
...options,
selector: this._selector
});
}
_inspect() {
return this.toString();
}
toString() {
return (0, import_locatorGenerators.asLocator)("javascript", this._selector);
}
}
class FrameLocator {
constructor(frame, selector) {
this._frame = frame;
this._frameSelector = selector;
}
locator(selectorOrLocator, options) {
if ((0, import_rtti.isString)(selectorOrLocator))
return new Locator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator, options);
if (selectorOrLocator._frame !== this._frame)
throw new Error(`Locators must belong to the same frame.`);
return new Locator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selectorOrLocator._selector, options);
}
getByTestId(testId) {
return this.locator((0, import_locatorUtils.getByTestIdSelector)(testIdAttributeName(), testId));
}
getByAltText(text, options) {
return this.locator((0, import_locatorUtils.getByAltTextSelector)(text, options));
}
getByLabel(text, options) {
return this.locator((0, import_locatorUtils.getByLabelSelector)(text, options));
}
getByPlaceholder(text, options) {
return this.locator((0, import_locatorUtils.getByPlaceholderSelector)(text, options));
}
getByText(text, options) {
return this.locator((0, import_locatorUtils.getByTextSelector)(text, options));
}
getByTitle(text, options) {
return this.locator((0, import_locatorUtils.getByTitleSelector)(text, options));
}
getByRole(role, options = {}) {
return this.locator((0, import_locatorUtils.getByRoleSelector)(role, options));
}
owner() {
return new Locator(this._frame, this._frameSelector);
}
frameLocator(selector) {
return new FrameLocator(this._frame, this._frameSelector + " >> internal:control=enter-frame >> " + selector);
}
first() {
return new FrameLocator(this._frame, this._frameSelector + " >> nth=0");
}
last() {
return new FrameLocator(this._frame, this._frameSelector + ` >> nth=-1`);
}
nth(index) {
return new FrameLocator(this._frame, this._frameSelector + ` >> nth=${index}`);
}
}
let _testIdAttributeName = "data-testid";
function testIdAttributeName() {
return _testIdAttributeName;
}
function setTestIdAttribute(attributeName) {
_testIdAttributeName = attributeName;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FrameLocator,
Locator,
setTestIdAttribute,
testIdAttributeName
});

744
node_modules/playwright-core/lib/client/network.js generated vendored Normal file
View File

@@ -0,0 +1,744 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var network_exports = {};
__export(network_exports, {
RawHeaders: () => RawHeaders,
Request: () => Request,
Response: () => Response,
Route: () => Route,
RouteHandler: () => RouteHandler,
WebSocket: () => WebSocket,
WebSocketRoute: () => WebSocketRoute,
WebSocketRouteHandler: () => WebSocketRouteHandler,
validateHeaders: () => validateHeaders
});
module.exports = __toCommonJS(network_exports);
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_events = require("./events");
var import_fetch = require("./fetch");
var import_frame = require("./frame");
var import_waiter = require("./waiter");
var import_worker = require("./worker");
var import_assert = require("../utils/isomorphic/assert");
var import_headers = require("../utils/isomorphic/headers");
var import_urlMatch = require("../utils/isomorphic/urlMatch");
var import_manualPromise = require("../utils/isomorphic/manualPromise");
var import_multimap = require("../utils/isomorphic/multimap");
var import_rtti = require("../utils/isomorphic/rtti");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
var import_mimeType = require("../utils/isomorphic/mimeType");
class Request extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._redirectedFrom = null;
this._redirectedTo = null;
this._failureText = null;
this._fallbackOverrides = {};
this._redirectedFrom = Request.fromNullable(initializer.redirectedFrom);
if (this._redirectedFrom)
this._redirectedFrom._redirectedTo = this;
this._provisionalHeaders = new RawHeaders(initializer.headers);
this._timing = {
startTime: 0,
domainLookupStart: -1,
domainLookupEnd: -1,
connectStart: -1,
secureConnectionStart: -1,
connectEnd: -1,
requestStart: -1,
responseStart: -1,
responseEnd: -1
};
}
static from(request) {
return request._object;
}
static fromNullable(request) {
return request ? Request.from(request) : null;
}
url() {
return this._fallbackOverrides.url || this._initializer.url;
}
resourceType() {
return this._initializer.resourceType;
}
method() {
return this._fallbackOverrides.method || this._initializer.method;
}
postData() {
return (this._fallbackOverrides.postDataBuffer || this._initializer.postData)?.toString("utf-8") || null;
}
postDataBuffer() {
return this._fallbackOverrides.postDataBuffer || this._initializer.postData || null;
}
postDataJSON() {
const postData = this.postData();
if (!postData)
return null;
const contentType = this.headers()["content-type"];
if (contentType?.includes("application/x-www-form-urlencoded")) {
const entries = {};
const parsed = new URLSearchParams(postData);
for (const [k, v] of parsed.entries())
entries[k] = v;
return entries;
}
try {
return JSON.parse(postData);
} catch (e) {
throw new Error("POST data is not a valid JSON object: " + postData);
}
}
/**
* @deprecated
*/
headers() {
if (this._fallbackOverrides.headers)
return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers).headers();
return this._provisionalHeaders.headers();
}
async _actualHeaders() {
if (this._fallbackOverrides.headers)
return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers);
if (!this._actualHeadersPromise) {
this._actualHeadersPromise = this._wrapApiCall(async () => {
return new RawHeaders((await this._channel.rawRequestHeaders()).headers);
}, { internal: true });
}
return await this._actualHeadersPromise;
}
async allHeaders() {
return (await this._actualHeaders()).headers();
}
async headersArray() {
return (await this._actualHeaders()).headersArray();
}
async headerValue(name) {
return (await this._actualHeaders()).get(name);
}
async response() {
return Response.fromNullable((await this._channel.response()).response);
}
async _internalResponse() {
return Response.fromNullable((await this._channel.response()).response);
}
frame() {
if (!this._initializer.frame) {
(0, import_assert.assert)(this.serviceWorker());
throw new Error("Service Worker requests do not have an associated frame.");
}
const frame = import_frame.Frame.from(this._initializer.frame);
if (!frame._page) {
throw new Error([
"Frame for this navigation request is not available, because the request",
"was issued before the frame is created. You can check whether the request",
"is a navigation request by calling isNavigationRequest() method."
].join("\n"));
}
return frame;
}
_safePage() {
return import_frame.Frame.fromNullable(this._initializer.frame)?._page || null;
}
serviceWorker() {
return this._initializer.serviceWorker ? import_worker.Worker.from(this._initializer.serviceWorker) : null;
}
isNavigationRequest() {
return this._initializer.isNavigationRequest;
}
redirectedFrom() {
return this._redirectedFrom;
}
redirectedTo() {
return this._redirectedTo;
}
failure() {
if (this._failureText === null)
return null;
return {
errorText: this._failureText
};
}
timing() {
return this._timing;
}
async sizes() {
const response = await this.response();
if (!response)
throw new Error("Unable to fetch sizes for failed request");
return (await response._channel.sizes()).sizes;
}
_setResponseEndTiming(responseEndTiming) {
this._timing.responseEnd = responseEndTiming;
if (this._timing.responseStart === -1)
this._timing.responseStart = responseEndTiming;
}
_finalRequest() {
return this._redirectedTo ? this._redirectedTo._finalRequest() : this;
}
_applyFallbackOverrides(overrides) {
if (overrides.url)
this._fallbackOverrides.url = overrides.url;
if (overrides.method)
this._fallbackOverrides.method = overrides.method;
if (overrides.headers)
this._fallbackOverrides.headers = overrides.headers;
if ((0, import_rtti.isString)(overrides.postData))
this._fallbackOverrides.postDataBuffer = Buffer.from(overrides.postData, "utf-8");
else if (overrides.postData instanceof Buffer)
this._fallbackOverrides.postDataBuffer = overrides.postData;
else if (overrides.postData)
this._fallbackOverrides.postDataBuffer = Buffer.from(JSON.stringify(overrides.postData), "utf-8");
}
_fallbackOverridesForContinue() {
return this._fallbackOverrides;
}
_targetClosedScope() {
return this.serviceWorker()?._closedScope || this._safePage()?._closedOrCrashedScope || new import_manualPromise.LongStandingScope();
}
}
class Route extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._handlingPromise = null;
this._didThrow = false;
}
static from(route) {
return route._object;
}
request() {
return Request.from(this._initializer.request);
}
async _raceWithTargetClose(promise) {
return await this.request()._targetClosedScope().safeRace(promise);
}
async _startHandling() {
this._handlingPromise = new import_manualPromise.ManualPromise();
return await this._handlingPromise;
}
async fallback(options = {}) {
this._checkNotHandled();
this.request()._applyFallbackOverrides(options);
this._reportHandled(false);
}
async abort(errorCode) {
await this._handleRoute(async () => {
await this._raceWithTargetClose(this._channel.abort({ errorCode }));
});
}
async _redirectNavigationRequest(url) {
await this._handleRoute(async () => {
await this._raceWithTargetClose(this._channel.redirectNavigationRequest({ url }));
});
}
async fetch(options = {}) {
return await this._wrapApiCall(async () => {
return await this._context.request._innerFetch({ request: this.request(), data: options.postData, ...options });
});
}
async fulfill(options = {}) {
await this._handleRoute(async () => {
await this._innerFulfill(options);
});
}
async _handleRoute(callback) {
this._checkNotHandled();
try {
await callback();
this._reportHandled(true);
} catch (e) {
this._didThrow = true;
throw e;
}
}
async _innerFulfill(options = {}) {
let fetchResponseUid;
let { status: statusOption, headers: headersOption, body } = options;
if (options.json !== void 0) {
(0, import_assert.assert)(options.body === void 0, "Can specify either body or json parameters");
body = JSON.stringify(options.json);
}
if (options.response instanceof import_fetch.APIResponse) {
statusOption ??= options.response.status();
headersOption ??= options.response.headers();
if (body === void 0 && options.path === void 0) {
if (options.response._request._connection === this._connection)
fetchResponseUid = options.response._fetchUid();
else
body = await options.response.body();
}
}
let isBase64 = false;
let length = 0;
if (options.path) {
const buffer = await this._platform.fs().promises.readFile(options.path);
body = buffer.toString("base64");
isBase64 = true;
length = buffer.length;
} else if ((0, import_rtti.isString)(body)) {
isBase64 = false;
length = Buffer.byteLength(body);
} else if (body) {
length = body.length;
body = body.toString("base64");
isBase64 = true;
}
const headers = {};
for (const header of Object.keys(headersOption || {}))
headers[header.toLowerCase()] = String(headersOption[header]);
if (options.contentType)
headers["content-type"] = String(options.contentType);
else if (options.json)
headers["content-type"] = "application/json";
else if (options.path)
headers["content-type"] = (0, import_mimeType.getMimeTypeForPath)(options.path) || "application/octet-stream";
if (length && !("content-length" in headers))
headers["content-length"] = String(length);
await this._raceWithTargetClose(this._channel.fulfill({
status: statusOption || 200,
headers: (0, import_headers.headersObjectToArray)(headers),
body,
isBase64,
fetchResponseUid
}));
}
async continue(options = {}) {
await this._handleRoute(async () => {
this.request()._applyFallbackOverrides(options);
await this._innerContinue(
false
/* isFallback */
);
});
}
_checkNotHandled() {
if (!this._handlingPromise)
throw new Error("Route is already handled!");
}
_reportHandled(done) {
const chain = this._handlingPromise;
this._handlingPromise = null;
chain.resolve(done);
}
async _innerContinue(isFallback) {
const options = this.request()._fallbackOverridesForContinue();
return await this._raceWithTargetClose(this._channel.continue({
url: options.url,
method: options.method,
headers: options.headers ? (0, import_headers.headersObjectToArray)(options.headers) : void 0,
postData: options.postDataBuffer,
isFallback
}));
}
}
class WebSocketRoute extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._connected = false;
this._server = {
onMessage: (handler) => {
this._onServerMessage = handler;
},
onClose: (handler) => {
this._onServerClose = handler;
},
connectToServer: () => {
throw new Error(`connectToServer must be called on the page-side WebSocketRoute`);
},
url: () => {
return this._initializer.url;
},
close: async (options = {}) => {
await this._channel.closeServer({ ...options, wasClean: true }).catch(() => {
});
},
send: (message) => {
if ((0, import_rtti.isString)(message))
this._channel.sendToServer({ message, isBase64: false }).catch(() => {
});
else
this._channel.sendToServer({ message: message.toString("base64"), isBase64: true }).catch(() => {
});
},
async [Symbol.asyncDispose]() {
await this.close();
}
};
this._channel.on("messageFromPage", ({ message, isBase64 }) => {
if (this._onPageMessage)
this._onPageMessage(isBase64 ? Buffer.from(message, "base64") : message);
else if (this._connected)
this._channel.sendToServer({ message, isBase64 }).catch(() => {
});
});
this._channel.on("messageFromServer", ({ message, isBase64 }) => {
if (this._onServerMessage)
this._onServerMessage(isBase64 ? Buffer.from(message, "base64") : message);
else
this._channel.sendToPage({ message, isBase64 }).catch(() => {
});
});
this._channel.on("closePage", ({ code, reason, wasClean }) => {
if (this._onPageClose)
this._onPageClose(code, reason);
else
this._channel.closeServer({ code, reason, wasClean }).catch(() => {
});
});
this._channel.on("closeServer", ({ code, reason, wasClean }) => {
if (this._onServerClose)
this._onServerClose(code, reason);
else
this._channel.closePage({ code, reason, wasClean }).catch(() => {
});
});
}
static from(route) {
return route._object;
}
url() {
return this._initializer.url;
}
async close(options = {}) {
await this._channel.closePage({ ...options, wasClean: true }).catch(() => {
});
}
connectToServer() {
if (this._connected)
throw new Error("Already connected to the server");
this._connected = true;
this._channel.connect().catch(() => {
});
return this._server;
}
send(message) {
if ((0, import_rtti.isString)(message))
this._channel.sendToPage({ message, isBase64: false }).catch(() => {
});
else
this._channel.sendToPage({ message: message.toString("base64"), isBase64: true }).catch(() => {
});
}
onMessage(handler) {
this._onPageMessage = handler;
}
onClose(handler) {
this._onPageClose = handler;
}
async [Symbol.asyncDispose]() {
await this.close();
}
async _afterHandle() {
if (this._connected)
return;
await this._channel.ensureOpened().catch(() => {
});
}
}
class WebSocketRouteHandler {
constructor(baseURL, url, handler) {
this._baseURL = baseURL;
this.url = url;
this.handler = handler;
}
static prepareInterceptionPatterns(handlers) {
const patterns = [];
let all = false;
for (const handler of handlers) {
if ((0, import_rtti.isString)(handler.url))
patterns.push({ glob: handler.url });
else if ((0, import_rtti.isRegExp)(handler.url))
patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags });
else
all = true;
}
if (all)
return [{ glob: "**/*" }];
return patterns;
}
matches(wsURL) {
return (0, import_urlMatch.urlMatches)(this._baseURL, wsURL, this.url, true);
}
async handle(webSocketRoute) {
const handler = this.handler;
await handler(webSocketRoute);
await webSocketRoute._afterHandle();
}
}
class Response extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._finishedPromise = new import_manualPromise.ManualPromise();
this._provisionalHeaders = new RawHeaders(initializer.headers);
this._request = Request.from(this._initializer.request);
Object.assign(this._request._timing, this._initializer.timing);
}
static from(response) {
return response._object;
}
static fromNullable(response) {
return response ? Response.from(response) : null;
}
url() {
return this._initializer.url;
}
ok() {
return this._initializer.status === 0 || this._initializer.status >= 200 && this._initializer.status <= 299;
}
status() {
return this._initializer.status;
}
statusText() {
return this._initializer.statusText;
}
fromServiceWorker() {
return this._initializer.fromServiceWorker;
}
/**
* @deprecated
*/
headers() {
return this._provisionalHeaders.headers();
}
async _actualHeaders() {
if (!this._actualHeadersPromise) {
this._actualHeadersPromise = (async () => {
return new RawHeaders((await this._channel.rawResponseHeaders()).headers);
})();
}
return await this._actualHeadersPromise;
}
async allHeaders() {
return (await this._actualHeaders()).headers();
}
async headersArray() {
return (await this._actualHeaders()).headersArray().slice();
}
async headerValue(name) {
return (await this._actualHeaders()).get(name);
}
async headerValues(name) {
return (await this._actualHeaders()).getAll(name);
}
async finished() {
return await this.request()._targetClosedScope().race(this._finishedPromise);
}
async body() {
return (await this._channel.body()).binary;
}
async text() {
const content = await this.body();
return content.toString("utf8");
}
async json() {
const content = await this.text();
return JSON.parse(content);
}
request() {
return this._request;
}
frame() {
return this._request.frame();
}
async serverAddr() {
return (await this._channel.serverAddr()).value || null;
}
async securityDetails() {
return (await this._channel.securityDetails()).value || null;
}
}
class WebSocket extends import_channelOwner.ChannelOwner {
static from(webSocket) {
return webSocket._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._isClosed = false;
this._page = parent;
this._channel.on("frameSent", (event) => {
if (event.opcode === 1)
this.emit(import_events.Events.WebSocket.FrameSent, { payload: event.data });
else if (event.opcode === 2)
this.emit(import_events.Events.WebSocket.FrameSent, { payload: Buffer.from(event.data, "base64") });
});
this._channel.on("frameReceived", (event) => {
if (event.opcode === 1)
this.emit(import_events.Events.WebSocket.FrameReceived, { payload: event.data });
else if (event.opcode === 2)
this.emit(import_events.Events.WebSocket.FrameReceived, { payload: Buffer.from(event.data, "base64") });
});
this._channel.on("socketError", ({ error }) => this.emit(import_events.Events.WebSocket.Error, error));
this._channel.on("close", () => {
this._isClosed = true;
this.emit(import_events.Events.WebSocket.Close, this);
});
}
url() {
return this._initializer.url;
}
isClosed() {
return this._isClosed;
}
async waitForEvent(event, optionsOrPredicate = {}) {
return await this._wrapApiCall(async () => {
const timeout = this._page._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
const waiter = import_waiter.Waiter.createForEvent(this, event);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
if (event !== import_events.Events.WebSocket.Error)
waiter.rejectOnEvent(this, import_events.Events.WebSocket.Error, new Error("Socket error"));
if (event !== import_events.Events.WebSocket.Close)
waiter.rejectOnEvent(this, import_events.Events.WebSocket.Close, new Error("Socket closed"));
waiter.rejectOnEvent(this._page, import_events.Events.Page.Close, () => this._page._closeErrorWithReason());
const result = await waiter.waitForEvent(this, event, predicate);
waiter.dispose();
return result;
});
}
}
function validateHeaders(headers) {
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Object.is(value, void 0) && !(0, import_rtti.isString)(value))
throw new Error(`Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
}
}
class RouteHandler {
constructor(platform, baseURL, url, handler, times = Number.MAX_SAFE_INTEGER) {
this.handledCount = 0;
this._ignoreException = false;
this._activeInvocations = /* @__PURE__ */ new Set();
this._baseURL = baseURL;
this._times = times;
this.url = url;
this.handler = handler;
this._savedZone = platform.zones.current().pop();
}
static prepareInterceptionPatterns(handlers) {
const patterns = [];
let all = false;
for (const handler of handlers) {
if ((0, import_rtti.isString)(handler.url))
patterns.push({ glob: handler.url });
else if ((0, import_rtti.isRegExp)(handler.url))
patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags });
else
all = true;
}
if (all)
return [{ glob: "**/*" }];
return patterns;
}
matches(requestURL) {
return (0, import_urlMatch.urlMatches)(this._baseURL, requestURL, this.url);
}
async handle(route) {
return await this._savedZone.run(async () => this._handleImpl(route));
}
async _handleImpl(route) {
const handlerInvocation = { complete: new import_manualPromise.ManualPromise(), route };
this._activeInvocations.add(handlerInvocation);
try {
return await this._handleInternal(route);
} catch (e) {
if (this._ignoreException)
return false;
if ((0, import_errors.isTargetClosedError)(e)) {
(0, import_stackTrace.rewriteErrorMessage)(e, `"${e.message}" while running route callback.
Consider awaiting \`await page.unrouteAll({ behavior: 'ignoreErrors' })\`
before the end of the test to ignore remaining routes in flight.`);
}
throw e;
} finally {
handlerInvocation.complete.resolve();
this._activeInvocations.delete(handlerInvocation);
}
}
async stop(behavior) {
if (behavior === "ignoreErrors") {
this._ignoreException = true;
} else {
const promises = [];
for (const activation of this._activeInvocations) {
if (!activation.route._didThrow)
promises.push(activation.complete);
}
await Promise.all(promises);
}
}
async _handleInternal(route) {
++this.handledCount;
const handledPromise = route._startHandling();
const handler = this.handler;
const [handled] = await Promise.all([
handledPromise,
handler(route, route.request())
]);
return handled;
}
willExpire() {
return this.handledCount + 1 >= this._times;
}
}
class RawHeaders {
constructor(headers) {
this._headersMap = new import_multimap.MultiMap();
this._headersArray = headers;
for (const header of headers)
this._headersMap.set(header.name.toLowerCase(), header.value);
}
static _fromHeadersObjectLossy(headers) {
const headersArray = Object.entries(headers).map(([name, value]) => ({
name,
value
})).filter((header) => header.value !== void 0);
return new RawHeaders(headersArray);
}
get(name) {
const values = this.getAll(name);
if (!values || !values.length)
return null;
return values.join(name.toLowerCase() === "set-cookie" ? "\n" : ", ");
}
getAll(name) {
return [...this._headersMap.get(name.toLowerCase())];
}
headers() {
const result = {};
for (const name of this._headersMap.keys())
result[name] = this.get(name);
return result;
}
headersArray() {
return this._headersArray;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RawHeaders,
Request,
Response,
Route,
RouteHandler,
WebSocket,
WebSocketRoute,
WebSocketRouteHandler,
validateHeaders
});

709
node_modules/playwright-core/lib/client/page.js generated vendored Normal file
View File

@@ -0,0 +1,709 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var page_exports = {};
__export(page_exports, {
BindingCall: () => BindingCall,
Page: () => Page
});
module.exports = __toCommonJS(page_exports);
var import_accessibility = require("./accessibility");
var import_artifact = require("./artifact");
var import_channelOwner = require("./channelOwner");
var import_clientHelper = require("./clientHelper");
var import_coverage = require("./coverage");
var import_download = require("./download");
var import_elementHandle = require("./elementHandle");
var import_errors = require("./errors");
var import_events = require("./events");
var import_fileChooser = require("./fileChooser");
var import_frame = require("./frame");
var import_harRouter = require("./harRouter");
var import_input = require("./input");
var import_jsHandle = require("./jsHandle");
var import_network = require("./network");
var import_video = require("./video");
var import_waiter = require("./waiter");
var import_worker = require("./worker");
var import_timeoutSettings = require("./timeoutSettings");
var import_assert = require("../utils/isomorphic/assert");
var import_fileUtils = require("./fileUtils");
var import_headers = require("../utils/isomorphic/headers");
var import_stringUtils = require("../utils/isomorphic/stringUtils");
var import_urlMatch = require("../utils/isomorphic/urlMatch");
var import_manualPromise = require("../utils/isomorphic/manualPromise");
var import_rtti = require("../utils/isomorphic/rtti");
class Page extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._frames = /* @__PURE__ */ new Set();
this._workers = /* @__PURE__ */ new Set();
this._closed = false;
this._closedOrCrashedScope = new import_manualPromise.LongStandingScope();
this._routes = [];
this._webSocketRoutes = [];
this._bindings = /* @__PURE__ */ new Map();
this._video = null;
this._closeWasCalled = false;
this._harRouters = [];
this._locatorHandlers = /* @__PURE__ */ new Map();
this._browserContext = parent;
this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform, this._browserContext._timeoutSettings);
this.accessibility = new import_accessibility.Accessibility(this._channel);
this.keyboard = new import_input.Keyboard(this);
this.mouse = new import_input.Mouse(this);
this.request = this._browserContext.request;
this.touchscreen = new import_input.Touchscreen(this);
this.clock = this._browserContext.clock;
this._mainFrame = import_frame.Frame.from(initializer.mainFrame);
this._mainFrame._page = this;
this._frames.add(this._mainFrame);
this._viewportSize = initializer.viewportSize;
this._closed = initializer.isClosed;
this._opener = Page.fromNullable(initializer.opener);
this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding)));
this._channel.on("close", () => this._onClose());
this._channel.on("crash", () => this._onCrash());
this._channel.on("download", ({ url, suggestedFilename, artifact }) => {
const artifactObject = import_artifact.Artifact.from(artifact);
this.emit(import_events.Events.Page.Download, new import_download.Download(this, url, suggestedFilename, artifactObject));
});
this._channel.on("fileChooser", ({ element, isMultiple }) => this.emit(import_events.Events.Page.FileChooser, new import_fileChooser.FileChooser(this, import_elementHandle.ElementHandle.from(element), isMultiple)));
this._channel.on("frameAttached", ({ frame }) => this._onFrameAttached(import_frame.Frame.from(frame)));
this._channel.on("frameDetached", ({ frame }) => this._onFrameDetached(import_frame.Frame.from(frame)));
this._channel.on("locatorHandlerTriggered", ({ uid }) => this._onLocatorHandlerTriggered(uid));
this._channel.on("route", ({ route }) => this._onRoute(import_network.Route.from(route)));
this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(import_network.WebSocketRoute.from(webSocketRoute)));
this._channel.on("video", ({ artifact }) => {
const artifactObject = import_artifact.Artifact.from(artifact);
this._forceVideo()._artifactReady(artifactObject);
});
this._channel.on("viewportSizeChanged", ({ viewportSize }) => this._viewportSize = viewportSize);
this._channel.on("webSocket", ({ webSocket }) => this.emit(import_events.Events.Page.WebSocket, import_network.WebSocket.from(webSocket)));
this._channel.on("worker", ({ worker }) => this._onWorker(import_worker.Worker.from(worker)));
this.coverage = new import_coverage.Coverage(this._channel);
this.once(import_events.Events.Page.Close, () => this._closedOrCrashedScope.close(this._closeErrorWithReason()));
this.once(import_events.Events.Page.Crash, () => this._closedOrCrashedScope.close(new import_errors.TargetClosedError()));
this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([
[import_events.Events.Page.Console, "console"],
[import_events.Events.Page.Dialog, "dialog"],
[import_events.Events.Page.Request, "request"],
[import_events.Events.Page.Response, "response"],
[import_events.Events.Page.RequestFinished, "requestFinished"],
[import_events.Events.Page.RequestFailed, "requestFailed"],
[import_events.Events.Page.FileChooser, "fileChooser"]
]));
}
static from(page) {
return page._object;
}
static fromNullable(page) {
return page ? Page.from(page) : null;
}
_onFrameAttached(frame) {
frame._page = this;
this._frames.add(frame);
if (frame._parentFrame)
frame._parentFrame._childFrames.add(frame);
this.emit(import_events.Events.Page.FrameAttached, frame);
}
_onFrameDetached(frame) {
this._frames.delete(frame);
frame._detached = true;
if (frame._parentFrame)
frame._parentFrame._childFrames.delete(frame);
this.emit(import_events.Events.Page.FrameDetached, frame);
}
async _onRoute(route) {
route._context = this.context();
const routeHandlers = this._routes.slice();
for (const routeHandler of routeHandlers) {
if (this._closeWasCalled || this._browserContext._closingStatus !== "none")
return;
if (!routeHandler.matches(route.request().url()))
continue;
const index = this._routes.indexOf(routeHandler);
if (index === -1)
continue;
if (routeHandler.willExpire())
this._routes.splice(index, 1);
const handled = await routeHandler.handle(route);
if (!this._routes.length)
this._updateInterceptionPatterns({ internal: true }).catch(() => {
});
if (handled)
return;
}
await this._browserContext._onRoute(route);
}
async _onWebSocketRoute(webSocketRoute) {
const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url()));
if (routeHandler)
await routeHandler.handle(webSocketRoute);
else
await this._browserContext._onWebSocketRoute(webSocketRoute);
}
async _onBinding(bindingCall) {
const func = this._bindings.get(bindingCall._initializer.name);
if (func) {
await bindingCall.call(func);
return;
}
await this._browserContext._onBinding(bindingCall);
}
_onWorker(worker) {
this._workers.add(worker);
worker._page = this;
this.emit(import_events.Events.Page.Worker, worker);
}
_onClose() {
this._closed = true;
this._browserContext._pages.delete(this);
this._browserContext._backgroundPages.delete(this);
this._disposeHarRouters();
this.emit(import_events.Events.Page.Close, this);
}
_onCrash() {
this.emit(import_events.Events.Page.Crash, this);
}
context() {
return this._browserContext;
}
async opener() {
if (!this._opener || this._opener.isClosed())
return null;
return this._opener;
}
mainFrame() {
return this._mainFrame;
}
frame(frameSelector) {
const name = (0, import_rtti.isString)(frameSelector) ? frameSelector : frameSelector.name;
const url = (0, import_rtti.isObject)(frameSelector) ? frameSelector.url : void 0;
(0, import_assert.assert)(name || url, "Either name or url matcher should be specified");
return this.frames().find((f) => {
if (name)
return f.name() === name;
return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, f.url(), url);
}) || null;
}
frames() {
return [...this._frames];
}
setDefaultNavigationTimeout(timeout) {
this._timeoutSettings.setDefaultNavigationTimeout(timeout);
}
setDefaultTimeout(timeout) {
this._timeoutSettings.setDefaultTimeout(timeout);
}
_forceVideo() {
if (!this._video)
this._video = new import_video.Video(this, this._connection);
return this._video;
}
video() {
if (!this._browserContext._options.recordVideo)
return null;
return this._forceVideo();
}
async $(selector, options) {
return await this._mainFrame.$(selector, options);
}
async waitForSelector(selector, options) {
return await this._mainFrame.waitForSelector(selector, options);
}
async dispatchEvent(selector, type, eventInit, options) {
return await this._mainFrame.dispatchEvent(selector, type, eventInit, options);
}
async evaluateHandle(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
return await this._mainFrame.evaluateHandle(pageFunction, arg);
}
async $eval(selector, pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
return await this._mainFrame.$eval(selector, pageFunction, arg);
}
async $$eval(selector, pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
return await this._mainFrame.$$eval(selector, pageFunction, arg);
}
async $$(selector) {
return await this._mainFrame.$$(selector);
}
async addScriptTag(options = {}) {
return await this._mainFrame.addScriptTag(options);
}
async addStyleTag(options = {}) {
return await this._mainFrame.addStyleTag(options);
}
async exposeFunction(name, callback) {
await this._channel.exposeBinding({ name });
const binding = (source, ...args) => callback(...args);
this._bindings.set(name, binding);
}
async exposeBinding(name, callback, options = {}) {
await this._channel.exposeBinding({ name, needsHandle: options.handle });
this._bindings.set(name, callback);
}
async setExtraHTTPHeaders(headers) {
(0, import_network.validateHeaders)(headers);
await this._channel.setExtraHTTPHeaders({ headers: (0, import_headers.headersObjectToArray)(headers) });
}
url() {
return this._mainFrame.url();
}
async content() {
return await this._mainFrame.content();
}
async setContent(html, options) {
return await this._mainFrame.setContent(html, options);
}
async goto(url, options) {
return await this._mainFrame.goto(url, options);
}
async reload(options = {}) {
const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
return import_network.Response.fromNullable((await this._channel.reload({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
}
async addLocatorHandler(locator, handler, options = {}) {
if (locator._frame !== this._mainFrame)
throw new Error(`Locator must belong to the main frame of this page`);
if (options.times === 0)
return;
const { uid } = await this._channel.registerLocatorHandler({ selector: locator._selector, noWaitAfter: options.noWaitAfter });
this._locatorHandlers.set(uid, { locator, handler, times: options.times });
}
async _onLocatorHandlerTriggered(uid) {
let remove = false;
try {
const handler = this._locatorHandlers.get(uid);
if (handler && handler.times !== 0) {
if (handler.times !== void 0)
handler.times--;
await handler.handler(handler.locator);
}
remove = handler?.times === 0;
} finally {
if (remove)
this._locatorHandlers.delete(uid);
this._channel.resolveLocatorHandlerNoReply({ uid, remove }).catch(() => {
});
}
}
async removeLocatorHandler(locator) {
for (const [uid, data] of this._locatorHandlers) {
if (data.locator._equals(locator)) {
this._locatorHandlers.delete(uid);
await this._channel.unregisterLocatorHandler({ uid }).catch(() => {
});
}
}
}
async waitForLoadState(state, options) {
return await this._mainFrame.waitForLoadState(state, options);
}
async waitForNavigation(options) {
return await this._mainFrame.waitForNavigation(options);
}
async waitForURL(url, options) {
return await this._mainFrame.waitForURL(url, options);
}
async waitForRequest(urlOrPredicate, options = {}) {
const predicate = async (request) => {
if ((0, import_rtti.isString)(urlOrPredicate) || (0, import_rtti.isRegExp)(urlOrPredicate))
return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);
return await urlOrPredicate(request);
};
const trimmedUrl = trimUrl(urlOrPredicate);
const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : void 0;
return await this._waitForEvent(import_events.Events.Page.Request, { predicate, timeout: options.timeout }, logLine);
}
async waitForResponse(urlOrPredicate, options = {}) {
const predicate = async (response) => {
if ((0, import_rtti.isString)(urlOrPredicate) || (0, import_rtti.isRegExp)(urlOrPredicate))
return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);
return await urlOrPredicate(response);
};
const trimmedUrl = trimUrl(urlOrPredicate);
const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : void 0;
return await this._waitForEvent(import_events.Events.Page.Response, { predicate, timeout: options.timeout }, logLine);
}
async waitForEvent(event, optionsOrPredicate = {}) {
return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);
}
_closeErrorWithReason() {
return new import_errors.TargetClosedError(this._closeReason || this._browserContext._effectiveCloseReason());
}
async _waitForEvent(event, optionsOrPredicate, logLine) {
return await this._wrapApiCall(async () => {
const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
const waiter = import_waiter.Waiter.createForEvent(this, event);
if (logLine)
waiter.log(logLine);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
if (event !== import_events.Events.Page.Crash)
waiter.rejectOnEvent(this, import_events.Events.Page.Crash, new Error("Page crashed"));
if (event !== import_events.Events.Page.Close)
waiter.rejectOnEvent(this, import_events.Events.Page.Close, () => this._closeErrorWithReason());
const result = await waiter.waitForEvent(this, event, predicate);
waiter.dispose();
return result;
});
}
async goBack(options = {}) {
const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
return import_network.Response.fromNullable((await this._channel.goBack({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
}
async goForward(options = {}) {
const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
return import_network.Response.fromNullable((await this._channel.goForward({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
}
async requestGC() {
await this._channel.requestGC();
}
async emulateMedia(options = {}) {
await this._channel.emulateMedia({
media: options.media === null ? "no-override" : options.media,
colorScheme: options.colorScheme === null ? "no-override" : options.colorScheme,
reducedMotion: options.reducedMotion === null ? "no-override" : options.reducedMotion,
forcedColors: options.forcedColors === null ? "no-override" : options.forcedColors,
contrast: options.contrast === null ? "no-override" : options.contrast
});
}
async setViewportSize(viewportSize) {
this._viewportSize = viewportSize;
await this._channel.setViewportSize({ viewportSize });
}
viewportSize() {
return this._viewportSize || null;
}
async evaluate(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
return await this._mainFrame.evaluate(pageFunction, arg);
}
async _evaluateFunction(functionDeclaration) {
return this._mainFrame._evaluateFunction(functionDeclaration);
}
async addInitScript(script, arg) {
const source = await (0, import_clientHelper.evaluationScript)(this._platform, script, arg);
await this._channel.addInitScript({ source });
}
async route(url, handler, options = {}) {
this._routes.unshift(new import_network.RouteHandler(this._platform, this._browserContext._options.baseURL, url, handler, options.times));
await this._updateInterceptionPatterns({ title: "Route requests" });
}
async routeFromHAR(har, options = {}) {
const localUtils = this._connection.localUtils();
if (!localUtils)
throw new Error("Route from har is not supported in thin clients");
if (options.update) {
await this._browserContext._recordIntoHAR(har, this, options);
return;
}
const harRouter = await import_harRouter.HarRouter.create(localUtils, har, options.notFound || "abort", { urlMatch: options.url });
this._harRouters.push(harRouter);
await harRouter.addPageRoute(this);
}
async routeWebSocket(url, handler) {
this._webSocketRoutes.unshift(new import_network.WebSocketRouteHandler(this._browserContext._options.baseURL, url, handler));
await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" });
}
_disposeHarRouters() {
this._harRouters.forEach((router) => router.dispose());
this._harRouters = [];
}
async unrouteAll(options) {
await this._unrouteInternal(this._routes, [], options?.behavior);
this._disposeHarRouters();
}
async unroute(url, handler) {
const removed = [];
const remaining = [];
for (const route of this._routes) {
if ((0, import_urlMatch.urlMatchesEqual)(route.url, url) && (!handler || route.handler === handler))
removed.push(route);
else
remaining.push(route);
}
await this._unrouteInternal(removed, remaining, "default");
}
async _unrouteInternal(removed, remaining, behavior) {
this._routes = remaining;
if (behavior && behavior !== "default") {
const promises = removed.map((routeHandler) => routeHandler.stop(behavior));
await Promise.all(promises);
}
await this._updateInterceptionPatterns({ title: "Unroute requests" });
}
async _updateInterceptionPatterns(options) {
const patterns = import_network.RouteHandler.prepareInterceptionPatterns(this._routes);
await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }), options);
}
async _updateWebSocketInterceptionPatterns(options) {
const patterns = import_network.WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);
await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }), options);
}
async screenshot(options = {}) {
const mask = options.mask;
const copy = { ...options, mask: void 0, timeout: this._timeoutSettings.timeout(options) };
if (!copy.type)
copy.type = (0, import_elementHandle.determineScreenshotType)(options);
if (mask) {
copy.mask = mask.map((locator) => ({
frame: locator._frame._channel,
selector: locator._selector
}));
}
const result = await this._channel.screenshot(copy);
if (options.path) {
await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
await this._platform.fs().promises.writeFile(options.path, result.binary);
}
return result.binary;
}
async _expectScreenshot(options) {
const mask = options?.mask ? options?.mask.map((locator2) => ({
frame: locator2._frame._channel,
selector: locator2._selector
})) : void 0;
const locator = options.locator ? {
frame: options.locator._frame._channel,
selector: options.locator._selector
} : void 0;
return await this._channel.expectScreenshot({
...options,
isNot: !!options.isNot,
locator,
mask
});
}
async title() {
return await this._mainFrame.title();
}
async bringToFront() {
await this._channel.bringToFront();
}
async [Symbol.asyncDispose]() {
await this.close();
}
async close(options = {}) {
this._closeReason = options.reason;
this._closeWasCalled = true;
try {
if (this._ownedContext)
await this._ownedContext.close();
else
await this._channel.close(options);
} catch (e) {
if ((0, import_errors.isTargetClosedError)(e) && !options.runBeforeUnload)
return;
throw e;
}
}
isClosed() {
return this._closed;
}
async click(selector, options) {
return await this._mainFrame.click(selector, options);
}
async dragAndDrop(source, target, options) {
return await this._mainFrame.dragAndDrop(source, target, options);
}
async dblclick(selector, options) {
await this._mainFrame.dblclick(selector, options);
}
async tap(selector, options) {
return await this._mainFrame.tap(selector, options);
}
async fill(selector, value, options) {
return await this._mainFrame.fill(selector, value, options);
}
locator(selector, options) {
return this.mainFrame().locator(selector, options);
}
getByTestId(testId) {
return this.mainFrame().getByTestId(testId);
}
getByAltText(text, options) {
return this.mainFrame().getByAltText(text, options);
}
getByLabel(text, options) {
return this.mainFrame().getByLabel(text, options);
}
getByPlaceholder(text, options) {
return this.mainFrame().getByPlaceholder(text, options);
}
getByText(text, options) {
return this.mainFrame().getByText(text, options);
}
getByTitle(text, options) {
return this.mainFrame().getByTitle(text, options);
}
getByRole(role, options = {}) {
return this.mainFrame().getByRole(role, options);
}
frameLocator(selector) {
return this.mainFrame().frameLocator(selector);
}
async focus(selector, options) {
return await this._mainFrame.focus(selector, options);
}
async textContent(selector, options) {
return await this._mainFrame.textContent(selector, options);
}
async innerText(selector, options) {
return await this._mainFrame.innerText(selector, options);
}
async innerHTML(selector, options) {
return await this._mainFrame.innerHTML(selector, options);
}
async getAttribute(selector, name, options) {
return await this._mainFrame.getAttribute(selector, name, options);
}
async inputValue(selector, options) {
return await this._mainFrame.inputValue(selector, options);
}
async isChecked(selector, options) {
return await this._mainFrame.isChecked(selector, options);
}
async isDisabled(selector, options) {
return await this._mainFrame.isDisabled(selector, options);
}
async isEditable(selector, options) {
return await this._mainFrame.isEditable(selector, options);
}
async isEnabled(selector, options) {
return await this._mainFrame.isEnabled(selector, options);
}
async isHidden(selector, options) {
return await this._mainFrame.isHidden(selector, options);
}
async isVisible(selector, options) {
return await this._mainFrame.isVisible(selector, options);
}
async hover(selector, options) {
return await this._mainFrame.hover(selector, options);
}
async selectOption(selector, values, options) {
return await this._mainFrame.selectOption(selector, values, options);
}
async setInputFiles(selector, files, options) {
return await this._mainFrame.setInputFiles(selector, files, options);
}
async type(selector, text, options) {
return await this._mainFrame.type(selector, text, options);
}
async press(selector, key, options) {
return await this._mainFrame.press(selector, key, options);
}
async check(selector, options) {
return await this._mainFrame.check(selector, options);
}
async uncheck(selector, options) {
return await this._mainFrame.uncheck(selector, options);
}
async setChecked(selector, checked, options) {
return await this._mainFrame.setChecked(selector, checked, options);
}
async waitForTimeout(timeout) {
return await this._mainFrame.waitForTimeout(timeout);
}
async waitForFunction(pageFunction, arg, options) {
return await this._mainFrame.waitForFunction(pageFunction, arg, options);
}
workers() {
return [...this._workers];
}
async pause(_options) {
if (this._platform.isJSDebuggerAttached())
return;
const defaultNavigationTimeout = this._browserContext._timeoutSettings.defaultNavigationTimeout();
const defaultTimeout = this._browserContext._timeoutSettings.defaultTimeout();
this._browserContext.setDefaultNavigationTimeout(0);
this._browserContext.setDefaultTimeout(0);
this._instrumentation?.onWillPause({ keepTestTimeout: !!_options?.__testHookKeepTestTimeout });
await this._closedOrCrashedScope.safeRace(this.context()._channel.pause());
this._browserContext.setDefaultNavigationTimeout(defaultNavigationTimeout);
this._browserContext.setDefaultTimeout(defaultTimeout);
}
async pdf(options = {}) {
const transportOptions = { ...options };
if (transportOptions.margin)
transportOptions.margin = { ...transportOptions.margin };
if (typeof options.width === "number")
transportOptions.width = options.width + "px";
if (typeof options.height === "number")
transportOptions.height = options.height + "px";
for (const margin of ["top", "right", "bottom", "left"]) {
const index = margin;
if (options.margin && typeof options.margin[index] === "number")
transportOptions.margin[index] = transportOptions.margin[index] + "px";
}
const result = await this._channel.pdf(transportOptions);
if (options.path) {
const platform = this._platform;
await platform.fs().promises.mkdir(platform.path().dirname(options.path), { recursive: true });
await platform.fs().promises.writeFile(options.path, result.pdf);
}
return result.pdf;
}
async _snapshotForAI(options = {}) {
const result = await this._channel.snapshotForAI({ timeout: this._timeoutSettings.timeout(options) });
return result.snapshot;
}
}
class BindingCall extends import_channelOwner.ChannelOwner {
static from(channel) {
return channel._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
}
async call(func) {
try {
const frame = import_frame.Frame.from(this._initializer.frame);
const source = {
context: frame._page.context(),
page: frame._page,
frame
};
let result;
if (this._initializer.handle)
result = await func(source, import_jsHandle.JSHandle.from(this._initializer.handle));
else
result = await func(source, ...this._initializer.args.map(import_jsHandle.parseResult));
this._channel.resolve({ result: (0, import_jsHandle.serializeArgument)(result) }).catch(() => {
});
} catch (e) {
this._channel.reject({ error: (0, import_errors.serializeError)(e) }).catch(() => {
});
}
}
}
function trimUrl(param) {
if ((0, import_rtti.isRegExp)(param))
return `/${(0, import_stringUtils.trimStringWithEllipsis)(param.source, 50)}/${param.flags}`;
if ((0, import_rtti.isString)(param))
return `"${(0, import_stringUtils.trimStringWithEllipsis)(param, 50)}"`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BindingCall,
Page
});

74
node_modules/playwright-core/lib/client/platform.js generated vendored Normal file
View File

@@ -0,0 +1,74 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var platform_exports = {};
__export(platform_exports, {
emptyPlatform: () => emptyPlatform
});
module.exports = __toCommonJS(platform_exports);
var import_colors = require("../utils/isomorphic/colors");
const noopZone = {
push: () => noopZone,
pop: () => noopZone,
run: (func) => func(),
data: () => void 0
};
const emptyPlatform = {
name: "empty",
boxedStackPrefixes: () => [],
calculateSha1: async () => {
throw new Error("Not implemented");
},
colors: import_colors.webColors,
createGuid: () => {
throw new Error("Not implemented");
},
defaultMaxListeners: () => 10,
env: {},
fs: () => {
throw new Error("Not implemented");
},
inspectCustom: void 0,
isDebugMode: () => false,
isJSDebuggerAttached: () => false,
isLogEnabled(name) {
return false;
},
isUnderTest: () => false,
log(name, message) {
},
path: () => {
throw new Error("Function not implemented.");
},
pathSeparator: "/",
showInternalStackFrames: () => false,
streamFile(path, writable) {
throw new Error("Streams are not available");
},
streamReadable: (channel) => {
throw new Error("Streams are not available");
},
streamWritable: (channel) => {
throw new Error("Streams are not available");
},
zones: { empty: noopZone, current: () => noopZone }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
emptyPlatform
});

75
node_modules/playwright-core/lib/client/playwright.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var playwright_exports = {};
__export(playwright_exports, {
Playwright: () => Playwright
});
module.exports = __toCommonJS(playwright_exports);
var import_android = require("./android");
var import_browser = require("./browser");
var import_browserType = require("./browserType");
var import_channelOwner = require("./channelOwner");
var import_electron = require("./electron");
var import_errors = require("./errors");
var import_fetch = require("./fetch");
var import_selectors = require("./selectors");
class Playwright extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this.request = new import_fetch.APIRequest(this);
this.chromium = import_browserType.BrowserType.from(initializer.chromium);
this.chromium._playwright = this;
this.firefox = import_browserType.BrowserType.from(initializer.firefox);
this.firefox._playwright = this;
this.webkit = import_browserType.BrowserType.from(initializer.webkit);
this.webkit._playwright = this;
this._android = import_android.Android.from(initializer.android);
this._android._playwright = this;
this._electron = import_electron.Electron.from(initializer.electron);
this._electron._playwright = this;
this._bidiChromium = import_browserType.BrowserType.from(initializer._bidiChromium);
this._bidiChromium._playwright = this;
this._bidiFirefox = import_browserType.BrowserType.from(initializer._bidiFirefox);
this._bidiFirefox._playwright = this;
this.devices = this._connection.localUtils()?.devices ?? {};
this.selectors = new import_selectors.Selectors(this._connection._platform);
this.errors = { TimeoutError: import_errors.TimeoutError };
}
static from(channel) {
return channel._object;
}
_browserTypes() {
return [this.chromium, this.firefox, this.webkit, this._bidiChromium, this._bidiFirefox];
}
_preLaunchedBrowser() {
const browser = import_browser.Browser.from(this._initializer.preLaunchedBrowser);
browser._connectToBrowserType(this[browser._name], {}, void 0);
return browser;
}
_allContexts() {
return this._browserTypes().flatMap((type) => [...type._contexts]);
}
_allPages() {
return this._allContexts().flatMap((context) => context.pages());
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Playwright
});

55
node_modules/playwright-core/lib/client/selectors.js generated vendored Normal file
View File

@@ -0,0 +1,55 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var selectors_exports = {};
__export(selectors_exports, {
Selectors: () => Selectors
});
module.exports = __toCommonJS(selectors_exports);
var import_clientHelper = require("./clientHelper");
var import_locator = require("./locator");
class Selectors {
constructor(platform) {
this._selectorEngines = [];
this._contextsForSelectors = /* @__PURE__ */ new Set();
this._platform = platform;
}
async register(name, script, options = {}) {
if (this._selectorEngines.some((engine) => engine.name === name))
throw new Error(`selectors.register: "${name}" selector engine has been already registered`);
const source = await (0, import_clientHelper.evaluationScript)(this._platform, script, void 0, false);
const selectorEngine = { ...options, name, source };
for (const context of this._contextsForSelectors)
await context._channel.registerSelectorEngine({ selectorEngine });
this._selectorEngines.push(selectorEngine);
}
setTestIdAttribute(attributeName) {
this._testIdAttributeName = attributeName;
(0, import_locator.setTestIdAttribute)(attributeName);
for (const context of this._contextsForSelectors)
context._channel.setTestIdAttributeName({ testIdAttributeName: attributeName }).catch(() => {
});
}
_withSelectorOptions(options) {
return { ...options, selectorEngines: this._selectorEngines, testIdAttributeName: this._testIdAttributeName };
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Selectors
});

39
node_modules/playwright-core/lib/client/stream.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var stream_exports = {};
__export(stream_exports, {
Stream: () => Stream
});
module.exports = __toCommonJS(stream_exports);
var import_channelOwner = require("./channelOwner");
class Stream extends import_channelOwner.ChannelOwner {
static from(Stream2) {
return Stream2._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
}
stream() {
return this._platform.streamReadable(this._channel);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Stream
});

View File

@@ -0,0 +1,79 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var timeoutSettings_exports = {};
__export(timeoutSettings_exports, {
TimeoutSettings: () => TimeoutSettings
});
module.exports = __toCommonJS(timeoutSettings_exports);
var import_time = require("../utils/isomorphic/time");
class TimeoutSettings {
constructor(platform, parent) {
this._parent = parent;
this._platform = platform;
}
setDefaultTimeout(timeout) {
this._defaultTimeout = timeout;
}
setDefaultNavigationTimeout(timeout) {
this._defaultNavigationTimeout = timeout;
}
defaultNavigationTimeout() {
return this._defaultNavigationTimeout;
}
defaultTimeout() {
return this._defaultTimeout;
}
navigationTimeout(options) {
if (typeof options.timeout === "number")
return options.timeout;
if (this._defaultNavigationTimeout !== void 0)
return this._defaultNavigationTimeout;
if (this._platform.isDebugMode())
return 0;
if (this._defaultTimeout !== void 0)
return this._defaultTimeout;
if (this._parent)
return this._parent.navigationTimeout(options);
return import_time.DEFAULT_PLAYWRIGHT_TIMEOUT;
}
timeout(options) {
if (typeof options.timeout === "number")
return options.timeout;
if (this._platform.isDebugMode())
return 0;
if (this._defaultTimeout !== void 0)
return this._defaultTimeout;
if (this._parent)
return this._parent.timeout(options);
return import_time.DEFAULT_PLAYWRIGHT_TIMEOUT;
}
launchTimeout(options) {
if (typeof options.timeout === "number")
return options.timeout;
if (this._platform.isDebugMode())
return 0;
if (this._parent)
return this._parent.launchTimeout(options);
return import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TimeoutSettings
});

117
node_modules/playwright-core/lib/client/tracing.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tracing_exports = {};
__export(tracing_exports, {
Tracing: () => Tracing
});
module.exports = __toCommonJS(tracing_exports);
var import_artifact = require("./artifact");
var import_channelOwner = require("./channelOwner");
class Tracing extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._includeSources = false;
this._isTracing = false;
}
static from(channel) {
return channel._object;
}
async start(options = {}) {
await this._wrapApiCall(async () => {
this._includeSources = !!options.sources;
await this._channel.tracingStart({
name: options.name,
snapshots: options.snapshots,
screenshots: options.screenshots,
live: options._live
});
const { traceName } = await this._channel.tracingStartChunk({ name: options.name, title: options.title });
await this._startCollectingStacks(traceName);
});
}
async startChunk(options = {}) {
await this._wrapApiCall(async () => {
const { traceName } = await this._channel.tracingStartChunk(options);
await this._startCollectingStacks(traceName);
});
}
async group(name, options = {}) {
await this._channel.tracingGroup({ name, location: options.location });
}
async groupEnd() {
await this._channel.tracingGroupEnd();
}
async _startCollectingStacks(traceName) {
if (!this._isTracing) {
this._isTracing = true;
this._connection.setIsTracing(true);
}
const result = await this._connection.localUtils()?.tracingStarted({ tracesDir: this._tracesDir, traceName });
this._stacksId = result?.stacksId;
}
async stopChunk(options = {}) {
await this._wrapApiCall(async () => {
await this._doStopChunk(options.path);
});
}
async stop(options = {}) {
await this._wrapApiCall(async () => {
await this._doStopChunk(options.path);
await this._channel.tracingStop();
});
}
async _doStopChunk(filePath) {
this._resetStackCounter();
if (!filePath) {
await this._channel.tracingStopChunk({ mode: "discard" });
if (this._stacksId)
await this._connection.localUtils().traceDiscarded({ stacksId: this._stacksId });
return;
}
const localUtils = this._connection.localUtils();
if (!localUtils)
throw new Error("Cannot save trace in thin clients");
const isLocal = !this._connection.isRemote();
if (isLocal) {
const result2 = await this._channel.tracingStopChunk({ mode: "entries" });
await localUtils.zip({ zipFile: filePath, entries: result2.entries, mode: "write", stacksId: this._stacksId, includeSources: this._includeSources });
return;
}
const result = await this._channel.tracingStopChunk({ mode: "archive" });
if (!result.artifact) {
if (this._stacksId)
await localUtils.traceDiscarded({ stacksId: this._stacksId });
return;
}
const artifact = import_artifact.Artifact.from(result.artifact);
await artifact.saveAs(filePath);
await artifact.delete();
await localUtils.zip({ zipFile: filePath, entries: [], mode: "append", stacksId: this._stacksId, includeSources: this._includeSources });
}
_resetStackCounter() {
if (this._isTracing) {
this._isTracing = false;
this._connection.setIsTracing(false);
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Tracing
});

28
node_modules/playwright-core/lib/client/types.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var types_exports = {};
__export(types_exports, {
kLifecycleEvents: () => kLifecycleEvents
});
module.exports = __toCommonJS(types_exports);
const kLifecycleEvents = /* @__PURE__ */ new Set(["load", "domcontentloaded", "networkidle", "commit"]);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
kLifecycleEvents
});

59
node_modules/playwright-core/lib/client/video.js generated vendored Normal file
View File

@@ -0,0 +1,59 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var video_exports = {};
__export(video_exports, {
Video: () => Video
});
module.exports = __toCommonJS(video_exports);
var import_manualPromise = require("../utils/isomorphic/manualPromise");
class Video {
constructor(page, connection) {
this._artifact = null;
this._artifactReadyPromise = new import_manualPromise.ManualPromise();
this._isRemote = false;
this._isRemote = connection.isRemote();
this._artifact = page._closedOrCrashedScope.safeRace(this._artifactReadyPromise);
}
_artifactReady(artifact) {
this._artifactReadyPromise.resolve(artifact);
}
async path() {
if (this._isRemote)
throw new Error(`Path is not available when connecting remotely. Use saveAs() to save a local copy.`);
const artifact = await this._artifact;
if (!artifact)
throw new Error("Page did not produce any video frames");
return artifact._initializer.absolutePath;
}
async saveAs(path) {
const artifact = await this._artifact;
if (!artifact)
throw new Error("Page did not produce any video frames");
return await artifact.saveAs(path);
}
async delete() {
const artifact = await this._artifact;
if (artifact)
await artifact.delete();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Video
});

142
node_modules/playwright-core/lib/client/waiter.js generated vendored Normal file
View File

@@ -0,0 +1,142 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var waiter_exports = {};
__export(waiter_exports, {
Waiter: () => Waiter
});
module.exports = __toCommonJS(waiter_exports);
var import_errors = require("./errors");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
class Waiter {
constructor(channelOwner, event) {
this._failures = [];
this._logs = [];
this._waitId = channelOwner._platform.createGuid();
this._channelOwner = channelOwner;
this._savedZone = channelOwner._platform.zones.current().pop();
this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "before", event } }).catch(() => {
});
this._dispose = [
() => this._channelOwner._wrapApiCall(async () => {
await this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "after", error: this._error } });
}, { internal: true }).catch(() => {
})
];
}
static createForEvent(channelOwner, event) {
return new Waiter(channelOwner, event);
}
async waitForEvent(emitter, event, predicate) {
const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate);
return await this.waitForPromise(promise, dispose);
}
rejectOnEvent(emitter, event, error, predicate) {
const { promise, dispose } = waitForEvent(emitter, event, this._savedZone, predicate);
this._rejectOn(promise.then(() => {
throw typeof error === "function" ? error() : error;
}), dispose);
}
rejectOnTimeout(timeout, message) {
if (!timeout)
return;
const { promise, dispose } = waitForTimeout(timeout);
this._rejectOn(promise.then(() => {
throw new import_errors.TimeoutError(message);
}), dispose);
}
rejectImmediately(error) {
this._immediateError = error;
}
dispose() {
for (const dispose of this._dispose)
dispose();
}
async waitForPromise(promise, dispose) {
try {
if (this._immediateError)
throw this._immediateError;
const result = await Promise.race([promise, ...this._failures]);
if (dispose)
dispose();
return result;
} catch (e) {
if (dispose)
dispose();
this._error = e.message;
this.dispose();
(0, import_stackTrace.rewriteErrorMessage)(e, e.message + formatLogRecording(this._logs));
throw e;
}
}
log(s) {
this._logs.push(s);
this._channelOwner._wrapApiCall(async () => {
await this._channelOwner._channel.waitForEventInfo({ info: { waitId: this._waitId, phase: "log", message: s } });
}, { internal: true }).catch(() => {
});
}
_rejectOn(promise, dispose) {
this._failures.push(promise);
if (dispose)
this._dispose.push(dispose);
}
}
function waitForEvent(emitter, event, savedZone, predicate) {
let listener;
const promise = new Promise((resolve, reject) => {
listener = async (eventArg) => {
await savedZone.run(async () => {
try {
if (predicate && !await predicate(eventArg))
return;
emitter.removeListener(event, listener);
resolve(eventArg);
} catch (e) {
emitter.removeListener(event, listener);
reject(e);
}
});
};
emitter.addListener(event, listener);
});
const dispose = () => emitter.removeListener(event, listener);
return { promise, dispose };
}
function waitForTimeout(timeout) {
let timeoutId;
const promise = new Promise((resolve) => timeoutId = setTimeout(resolve, timeout));
const dispose = () => clearTimeout(timeoutId);
return { promise, dispose };
}
function formatLogRecording(log) {
if (!log.length)
return "";
const header = ` logs `;
const headerLength = 60;
const leftLength = (headerLength - header.length) / 2;
const rightLength = headerLength - header.length - leftLength;
return `
${"=".repeat(leftLength)}${header}${"=".repeat(rightLength)}
${log.join("\n")}
${"=".repeat(headerLength)}`;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Waiter
});

39
node_modules/playwright-core/lib/client/webError.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var webError_exports = {};
__export(webError_exports, {
WebError: () => WebError
});
module.exports = __toCommonJS(webError_exports);
class WebError {
constructor(page, error) {
this._page = page;
this._error = error;
}
page() {
return this._page;
}
error() {
return this._error;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WebError
});

93
node_modules/playwright-core/lib/client/webSocket.js generated vendored Normal file
View File

@@ -0,0 +1,93 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var webSocket_exports = {};
__export(webSocket_exports, {
connectOverWebSocket: () => connectOverWebSocket
});
module.exports = __toCommonJS(webSocket_exports);
var import_connection = require("./connection");
async function connectOverWebSocket(parentConnection, params) {
const localUtils = parentConnection.localUtils();
const transport = localUtils ? new JsonPipeTransport(localUtils) : new WebSocketTransport();
const connectHeaders = await transport.connect(params);
const connection = new import_connection.Connection(parentConnection._platform, localUtils, parentConnection._instrumentation, connectHeaders);
connection.markAsRemote();
connection.on("close", () => transport.close());
let closeError;
const onTransportClosed = (reason) => {
connection.close(reason || closeError);
};
transport.onClose((reason) => onTransportClosed(reason));
connection.onmessage = (message) => transport.send(message).catch(() => onTransportClosed());
transport.onMessage((message) => {
try {
connection.dispatch(message);
} catch (e) {
closeError = String(e);
transport.close().catch(() => {
});
}
});
return connection;
}
class JsonPipeTransport {
constructor(owner) {
this._owner = owner;
}
async connect(params) {
const { pipe, headers: connectHeaders } = await this._owner._channel.connect(params);
this._pipe = pipe;
return connectHeaders;
}
async send(message) {
await this._pipe.send({ message });
}
onMessage(callback) {
this._pipe.on("message", ({ message }) => callback(message));
}
onClose(callback) {
this._pipe.on("closed", ({ reason }) => callback(reason));
}
async close() {
await this._pipe.close().catch(() => {
});
}
}
class WebSocketTransport {
async connect(params) {
this._ws = new window.WebSocket(params.wsEndpoint);
return [];
}
async send(message) {
this._ws.send(JSON.stringify(message));
}
onMessage(callback) {
this._ws.addEventListener("message", (event) => callback(JSON.parse(event.data)));
}
onClose(callback) {
this._ws.addEventListener("close", () => callback());
}
async close() {
this._ws.close();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
connectOverWebSocket
});

63
node_modules/playwright-core/lib/client/worker.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var worker_exports = {};
__export(worker_exports, {
Worker: () => Worker
});
module.exports = __toCommonJS(worker_exports);
var import_channelOwner = require("./channelOwner");
var import_errors = require("./errors");
var import_events = require("./events");
var import_jsHandle = require("./jsHandle");
var import_manualPromise = require("../utils/isomorphic/manualPromise");
class Worker extends import_channelOwner.ChannelOwner {
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
// Set for service workers.
this._closedScope = new import_manualPromise.LongStandingScope();
this._channel.on("close", () => {
if (this._page)
this._page._workers.delete(this);
if (this._context)
this._context._serviceWorkers.delete(this);
this.emit(import_events.Events.Worker.Close, this);
});
this.once(import_events.Events.Worker.Close, () => this._closedScope.close(this._page?._closeErrorWithReason() || new import_errors.TargetClosedError()));
}
static from(worker) {
return worker._object;
}
url() {
return this._initializer.url;
}
async evaluate(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return (0, import_jsHandle.parseResult)(result.value);
}
async evaluateHandle(pageFunction, arg) {
(0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === "function", arg: (0, import_jsHandle.serializeArgument)(arg) });
return import_jsHandle.JSHandle.from(result.handle);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Worker
});

View File

@@ -0,0 +1,39 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var writableStream_exports = {};
__export(writableStream_exports, {
WritableStream: () => WritableStream
});
module.exports = __toCommonJS(writableStream_exports);
var import_channelOwner = require("./channelOwner");
class WritableStream extends import_channelOwner.ChannelOwner {
static from(Stream) {
return Stream._object;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
}
stream() {
return this._platform.streamWritable(this._channel);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
WritableStream
});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,336 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var webSocketMockSource_exports = {};
__export(webSocketMockSource_exports, {
source: () => source
});
module.exports = __toCommonJS(webSocketMockSource_exports);
const source = `
var __commonJS = obj => {
let required = false;
let result;
return function __require() {
if (!required) {
required = true;
let fn;
for (const name in obj) { fn = obj[name]; break; }
const module = { exports: {} };
fn(module.exports, module);
result = module.exports;
}
return result;
}
};
var __export = (target, all) => {for (var name in all) target[name] = all[name];};
var __toESM = mod => ({ ...mod, 'default': mod });
var __toCommonJS = mod => ({ ...mod, __esModule: true });
// packages/injected/src/webSocketMock.ts
var webSocketMock_exports = {};
__export(webSocketMock_exports, {
inject: () => inject
});
module.exports = __toCommonJS(webSocketMock_exports);
function inject(globalThis) {
if (globalThis.__pwWebSocketDispatch)
return;
function generateId() {
const bytes = new Uint8Array(32);
globalThis.crypto.getRandomValues(bytes);
const hex = "0123456789abcdef";
return [...bytes].map((value) => {
const high = Math.floor(value / 16);
const low = value % 16;
return hex[high] + hex[low];
}).join("");
}
function bufferToData(b) {
let s = "";
for (let i = 0; i < b.length; i++)
s += String.fromCharCode(b[i]);
return { data: globalThis.btoa(s), isBase64: true };
}
function stringToBuffer(s) {
s = globalThis.atob(s);
const b = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++)
b[i] = s.charCodeAt(i);
return b.buffer;
}
function messageToData(message, cb) {
if (message instanceof globalThis.Blob)
return message.arrayBuffer().then((buffer) => cb(bufferToData(new Uint8Array(buffer))));
if (typeof message === "string")
return cb({ data: message, isBase64: false });
if (ArrayBuffer.isView(message))
return cb(bufferToData(new Uint8Array(message.buffer, message.byteOffset, message.byteLength)));
return cb(bufferToData(new Uint8Array(message)));
}
function dataToMessage(data, binaryType) {
if (!data.isBase64)
return data.data;
const buffer = stringToBuffer(data.data);
return binaryType === "arraybuffer" ? buffer : new Blob([buffer]);
}
const binding = globalThis.__pwWebSocketBinding;
const NativeWebSocket = globalThis.WebSocket;
const idToWebSocket = /* @__PURE__ */ new Map();
globalThis.__pwWebSocketDispatch = (request) => {
const ws = idToWebSocket.get(request.id);
if (!ws)
return;
if (request.type === "connect")
ws._apiConnect();
if (request.type === "passthrough")
ws._apiPassThrough();
if (request.type === "ensureOpened")
ws._apiEnsureOpened();
if (request.type === "sendToPage")
ws._apiSendToPage(dataToMessage(request.data, ws.binaryType));
if (request.type === "closePage")
ws._apiClosePage(request.code, request.reason, request.wasClean);
if (request.type === "sendToServer")
ws._apiSendToServer(dataToMessage(request.data, ws.binaryType));
if (request.type === "closeServer")
ws._apiCloseServer(request.code, request.reason, request.wasClean);
};
const _WebSocketMock = class _WebSocketMock extends EventTarget {
constructor(url, protocols) {
var _a, _b;
super();
// WebSocket.CLOSED
this.CONNECTING = 0;
// WebSocket.CONNECTING
this.OPEN = 1;
// WebSocket.OPEN
this.CLOSING = 2;
// WebSocket.CLOSING
this.CLOSED = 3;
// WebSocket.CLOSED
this._oncloseListener = null;
this._onerrorListener = null;
this._onmessageListener = null;
this._onopenListener = null;
this.bufferedAmount = 0;
this.extensions = "";
this.protocol = "";
this.readyState = 0;
this._origin = "";
this._passthrough = false;
this._wsBufferedMessages = [];
this._binaryType = "blob";
this.url = new URL(url, globalThis.window.document.baseURI).href.replace(/^http/, "ws");
this._origin = (_b = (_a = URL.parse(this.url)) == null ? void 0 : _a.origin) != null ? _b : "";
this._protocols = protocols;
this._id = generateId();
idToWebSocket.set(this._id, this);
binding({ type: "onCreate", id: this._id, url: this.url });
}
// --- native WebSocket implementation ---
get binaryType() {
return this._binaryType;
}
set binaryType(type) {
this._binaryType = type;
if (this._ws)
this._ws.binaryType = type;
}
get onclose() {
return this._oncloseListener;
}
set onclose(listener) {
if (this._oncloseListener)
this.removeEventListener("close", this._oncloseListener);
this._oncloseListener = listener;
if (this._oncloseListener)
this.addEventListener("close", this._oncloseListener);
}
get onerror() {
return this._onerrorListener;
}
set onerror(listener) {
if (this._onerrorListener)
this.removeEventListener("error", this._onerrorListener);
this._onerrorListener = listener;
if (this._onerrorListener)
this.addEventListener("error", this._onerrorListener);
}
get onopen() {
return this._onopenListener;
}
set onopen(listener) {
if (this._onopenListener)
this.removeEventListener("open", this._onopenListener);
this._onopenListener = listener;
if (this._onopenListener)
this.addEventListener("open", this._onopenListener);
}
get onmessage() {
return this._onmessageListener;
}
set onmessage(listener) {
if (this._onmessageListener)
this.removeEventListener("message", this._onmessageListener);
this._onmessageListener = listener;
if (this._onmessageListener)
this.addEventListener("message", this._onmessageListener);
}
send(message) {
if (this.readyState === _WebSocketMock.CONNECTING)
throw new DOMException(\`Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.\`);
if (this.readyState !== _WebSocketMock.OPEN)
throw new DOMException(\`WebSocket is already in CLOSING or CLOSED state.\`);
if (this._passthrough) {
if (this._ws)
this._apiSendToServer(message);
} else {
messageToData(message, (data) => binding({ type: "onMessageFromPage", id: this._id, data }));
}
}
close(code, reason) {
if (code !== void 0 && code !== 1e3 && (code < 3e3 || code > 4999))
throw new DOMException(\`Failed to execute 'close' on 'WebSocket': The close code must be either 1000, or between 3000 and 4999. \${code} is neither.\`);
if (this.readyState === _WebSocketMock.OPEN || this.readyState === _WebSocketMock.CONNECTING)
this.readyState = _WebSocketMock.CLOSING;
if (this._passthrough)
this._apiCloseServer(code, reason, true);
else
binding({ type: "onClosePage", id: this._id, code, reason, wasClean: true });
}
// --- methods called from the routing API ---
_apiEnsureOpened() {
if (!this._ws)
this._ensureOpened();
}
_apiSendToPage(message) {
this._ensureOpened();
if (this.readyState !== _WebSocketMock.OPEN)
throw new DOMException(\`WebSocket is already in CLOSING or CLOSED state.\`);
this.dispatchEvent(new MessageEvent("message", { data: message, origin: this._origin, cancelable: true }));
}
_apiSendToServer(message) {
if (!this._ws)
throw new Error("Cannot send a message before connecting to the server");
if (this._ws.readyState === _WebSocketMock.CONNECTING)
this._wsBufferedMessages.push(message);
else
this._ws.send(message);
}
_apiConnect() {
if (this._ws)
throw new Error("Can only connect to the server once");
this._ws = new NativeWebSocket(this.url, this._protocols);
this._ws.binaryType = this._binaryType;
this._ws.onopen = () => {
for (const message of this._wsBufferedMessages)
this._ws.send(message);
this._wsBufferedMessages = [];
this._ensureOpened();
};
this._ws.onclose = (event) => {
this._onWSClose(event.code, event.reason, event.wasClean);
};
this._ws.onmessage = (event) => {
if (this._passthrough)
this._apiSendToPage(event.data);
else
messageToData(event.data, (data) => binding({ type: "onMessageFromServer", id: this._id, data }));
};
this._ws.onerror = () => {
const event = new Event("error", { cancelable: true });
this.dispatchEvent(event);
};
}
// This method connects to the server, and passes all messages through,
// as if WebSocketMock was not engaged.
_apiPassThrough() {
this._passthrough = true;
this._apiConnect();
}
_apiCloseServer(code, reason, wasClean) {
if (!this._ws) {
this._onWSClose(code, reason, wasClean);
return;
}
if (this._ws.readyState === _WebSocketMock.CONNECTING || this._ws.readyState === _WebSocketMock.OPEN)
this._ws.close(code, reason);
}
_apiClosePage(code, reason, wasClean) {
if (this.readyState === _WebSocketMock.CLOSED)
return;
this.readyState = _WebSocketMock.CLOSED;
this.dispatchEvent(new CloseEvent("close", { code, reason, wasClean, cancelable: true }));
this._maybeCleanup();
if (this._passthrough)
this._apiCloseServer(code, reason, wasClean);
else
binding({ type: "onClosePage", id: this._id, code, reason, wasClean });
}
// --- internals ---
_ensureOpened() {
var _a;
if (this.readyState !== _WebSocketMock.CONNECTING)
return;
this.extensions = ((_a = this._ws) == null ? void 0 : _a.extensions) || "";
if (this._ws)
this.protocol = this._ws.protocol;
else if (Array.isArray(this._protocols))
this.protocol = this._protocols[0] || "";
else
this.protocol = this._protocols || "";
this.readyState = _WebSocketMock.OPEN;
this.dispatchEvent(new Event("open", { cancelable: true }));
}
_onWSClose(code, reason, wasClean) {
if (this._passthrough)
this._apiClosePage(code, reason, wasClean);
else
binding({ type: "onCloseServer", id: this._id, code, reason, wasClean });
if (this._ws) {
this._ws.onopen = null;
this._ws.onclose = null;
this._ws.onmessage = null;
this._ws.onerror = null;
this._ws = void 0;
this._wsBufferedMessages = [];
}
this._maybeCleanup();
}
_maybeCleanup() {
if (this.readyState === _WebSocketMock.CLOSED && !this._ws)
idToWebSocket.delete(this._id);
}
};
_WebSocketMock.CONNECTING = 0;
// WebSocket.CONNECTING
_WebSocketMock.OPEN = 1;
// WebSocket.OPEN
_WebSocketMock.CLOSING = 2;
// WebSocket.CLOSING
_WebSocketMock.CLOSED = 3;
let WebSocketMock = _WebSocketMock;
globalThis.WebSocket = class WebSocket extends WebSocketMock {
};
}
`;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
source
});

62
node_modules/playwright-core/lib/inProcessFactory.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var inProcessFactory_exports = {};
__export(inProcessFactory_exports, {
createInProcessPlaywright: () => createInProcessPlaywright
});
module.exports = __toCommonJS(inProcessFactory_exports);
var import_androidServerImpl = require("./androidServerImpl");
var import_browserServerImpl = require("./browserServerImpl");
var import_server = require("./server");
var import_nodePlatform = require("./server/utils/nodePlatform");
var import_connection = require("./client/connection");
function createInProcessPlaywright() {
const playwright = (0, import_server.createPlaywright)({ sdkLanguage: process.env.PW_LANG_NAME || "javascript" });
const clientConnection = new import_connection.Connection(import_nodePlatform.nodePlatform);
clientConnection.useRawBuffers();
const dispatcherConnection = new import_server.DispatcherConnection(
true
/* local */
);
dispatcherConnection.onmessage = (message) => clientConnection.dispatch(message);
clientConnection.onmessage = (message) => dispatcherConnection.dispatch(message);
const rootScope = new import_server.RootDispatcher(dispatcherConnection);
new import_server.PlaywrightDispatcher(rootScope, playwright);
const playwrightAPI = clientConnection.getObjectWithKnownName("Playwright");
playwrightAPI.chromium._serverLauncher = new import_browserServerImpl.BrowserServerLauncherImpl("chromium");
playwrightAPI.firefox._serverLauncher = new import_browserServerImpl.BrowserServerLauncherImpl("firefox");
playwrightAPI.webkit._serverLauncher = new import_browserServerImpl.BrowserServerLauncherImpl("webkit");
playwrightAPI._android._serverLauncher = new import_androidServerImpl.AndroidServerLauncherImpl();
playwrightAPI._bidiChromium._serverLauncher = new import_browserServerImpl.BrowserServerLauncherImpl("_bidiChromium");
playwrightAPI._bidiFirefox._serverLauncher = new import_browserServerImpl.BrowserServerLauncherImpl("_bidiFirefox");
dispatcherConnection.onmessage = (message) => setImmediate(() => clientConnection.dispatch(message));
clientConnection.onmessage = (message) => setImmediate(() => dispatcherConnection.dispatch(message));
clientConnection.toImpl = (x) => {
if (x instanceof import_connection.Connection)
return x === clientConnection ? dispatcherConnection : void 0;
if (!x)
return dispatcherConnection._dispatcherByGuid.get("");
return dispatcherConnection._dispatcherByGuid.get(x._guid)._object;
};
return playwrightAPI;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createInProcessPlaywright
});

3
node_modules/playwright-core/lib/inprocess.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
"use strict";
var import_inProcessFactory = require("./inProcessFactory");
module.exports = (0, import_inProcessFactory.createInProcessPlaywright)();

76
node_modules/playwright-core/lib/outofprocess.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var outofprocess_exports = {};
__export(outofprocess_exports, {
start: () => start
});
module.exports = __toCommonJS(outofprocess_exports);
var childProcess = __toESM(require("child_process"));
var import_path = __toESM(require("path"));
var import_connection = require("./client/connection");
var import_pipeTransport = require("./server/utils/pipeTransport");
var import_manualPromise = require("./utils/isomorphic/manualPromise");
var import_nodePlatform = require("./server/utils/nodePlatform");
async function start(env = {}) {
const client = new PlaywrightClient(env);
const playwright = await client._playwright;
playwright.driverProcess = client._driverProcess;
return { playwright, stop: () => client.stop() };
}
class PlaywrightClient {
constructor(env) {
this._closePromise = new import_manualPromise.ManualPromise();
this._driverProcess = childProcess.fork(import_path.default.join(__dirname, "..", "cli.js"), ["run-driver"], {
stdio: "pipe",
detached: true,
env: {
...process.env,
...env
}
});
this._driverProcess.unref();
this._driverProcess.stderr.on("data", (data) => process.stderr.write(data));
const connection = new import_connection.Connection(import_nodePlatform.nodePlatform);
const transport = new import_pipeTransport.PipeTransport(this._driverProcess.stdin, this._driverProcess.stdout);
connection.onmessage = (message) => transport.send(JSON.stringify(message));
transport.onmessage = (message) => connection.dispatch(JSON.parse(message));
transport.onclose = () => this._closePromise.resolve();
this._playwright = connection.initializePlaywright();
}
async stop() {
this._driverProcess.stdin.destroy();
this._driverProcess.stdout.destroy();
this._driverProcess.stderr.destroy();
await this._closePromise;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
start
});

View File

@@ -0,0 +1,192 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var serializers_exports = {};
__export(serializers_exports, {
parseSerializedValue: () => parseSerializedValue,
serializeValue: () => serializeValue
});
module.exports = __toCommonJS(serializers_exports);
function parseSerializedValue(value, handles) {
return innerParseSerializedValue(value, handles, /* @__PURE__ */ new Map(), []);
}
function innerParseSerializedValue(value, handles, refs, accessChain) {
if (value.ref !== void 0)
return refs.get(value.ref);
if (value.n !== void 0)
return value.n;
if (value.s !== void 0)
return value.s;
if (value.b !== void 0)
return value.b;
if (value.v !== void 0) {
if (value.v === "undefined")
return void 0;
if (value.v === "null")
return null;
if (value.v === "NaN")
return NaN;
if (value.v === "Infinity")
return Infinity;
if (value.v === "-Infinity")
return -Infinity;
if (value.v === "-0")
return -0;
}
if (value.d !== void 0)
return new Date(value.d);
if (value.u !== void 0)
return new URL(value.u);
if (value.bi !== void 0)
return BigInt(value.bi);
if (value.e !== void 0) {
const error = new Error(value.e.m);
error.name = value.e.n;
error.stack = value.e.s;
return error;
}
if (value.r !== void 0)
return new RegExp(value.r.p, value.r.f);
if (value.ta !== void 0) {
const ctor = typedArrayKindToConstructor[value.ta.k];
return new ctor(value.ta.b.buffer, value.ta.b.byteOffset, value.ta.b.length / ctor.BYTES_PER_ELEMENT);
}
if (value.a !== void 0) {
const result = [];
refs.set(value.id, result);
for (let i = 0; i < value.a.length; i++)
result.push(innerParseSerializedValue(value.a[i], handles, refs, [...accessChain, i]));
return result;
}
if (value.o !== void 0) {
const result = {};
refs.set(value.id, result);
for (const { k, v } of value.o)
result[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]);
return result;
}
if (value.h !== void 0) {
if (handles === void 0)
throw new Error("Unexpected handle");
return handles[value.h];
}
throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`);
}
function serializeValue(value, handleSerializer) {
return innerSerializeValue(value, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []);
}
function innerSerializeValue(value, handleSerializer, visitorInfo, accessChain) {
const handle = handleSerializer(value);
if ("fallThrough" in handle)
value = handle.fallThrough;
else
return handle;
if (typeof value === "symbol")
return { v: "undefined" };
if (Object.is(value, void 0))
return { v: "undefined" };
if (Object.is(value, null))
return { v: "null" };
if (Object.is(value, NaN))
return { v: "NaN" };
if (Object.is(value, Infinity))
return { v: "Infinity" };
if (Object.is(value, -Infinity))
return { v: "-Infinity" };
if (Object.is(value, -0))
return { v: "-0" };
if (typeof value === "boolean")
return { b: value };
if (typeof value === "number")
return { n: value };
if (typeof value === "string")
return { s: value };
if (typeof value === "bigint")
return { bi: value.toString() };
if (isError(value))
return { e: { n: value.name, m: value.message, s: value.stack || "" } };
if (isDate(value))
return { d: value.toJSON() };
if (isURL(value))
return { u: value.toJSON() };
if (isRegExp(value))
return { r: { p: value.source, f: value.flags } };
const typedArrayKind = constructorToTypedArrayKind.get(value.constructor);
if (typedArrayKind)
return { ta: { b: Buffer.from(value.buffer, value.byteOffset, value.byteLength), k: typedArrayKind } };
const id = visitorInfo.visited.get(value);
if (id)
return { ref: id };
if (Array.isArray(value)) {
const a = [];
const id2 = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id2);
for (let i = 0; i < value.length; ++i)
a.push(innerSerializeValue(value[i], handleSerializer, visitorInfo, [...accessChain, i]));
return { a, id: id2 };
}
if (typeof value === "object") {
const o = [];
const id2 = ++visitorInfo.lastId;
visitorInfo.visited.set(value, id2);
for (const name of Object.keys(value))
o.push({ k: name, v: innerSerializeValue(value[name], handleSerializer, visitorInfo, [...accessChain, name]) });
return { o, id: id2 };
}
throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value}`);
}
function accessChainToDisplayString(accessChain) {
const chainString = accessChain.map((accessor, i) => {
if (typeof accessor === "string")
return i ? `.${accessor}` : accessor;
return `[${accessor}]`;
}).join("");
return chainString.length > 0 ? ` at position "${chainString}"` : "";
}
function isRegExp(obj) {
return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";
}
function isDate(obj) {
return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";
}
function isURL(obj) {
return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";
}
function isError(obj) {
const proto = obj ? Object.getPrototypeOf(obj) : null;
return obj instanceof Error || proto?.name === "Error" || proto && isError(proto);
}
const typedArrayKindToConstructor = {
i8: Int8Array,
ui8: Uint8Array,
ui8c: Uint8ClampedArray,
i16: Int16Array,
ui16: Uint16Array,
i32: Int32Array,
ui32: Uint32Array,
f32: Float32Array,
f64: Float64Array,
bi64: BigInt64Array,
bui64: BigUint64Array
};
const constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k]));
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
parseSerializedValue,
serializeValue
});

2901
node_modules/playwright-core/lib/protocol/validator.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,193 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var validatorPrimitives_exports = {};
__export(validatorPrimitives_exports, {
ValidationError: () => ValidationError,
createMetadataValidator: () => createMetadataValidator,
findValidator: () => findValidator,
maybeFindValidator: () => maybeFindValidator,
scheme: () => scheme,
tAny: () => tAny,
tArray: () => tArray,
tBinary: () => tBinary,
tBoolean: () => tBoolean,
tChannel: () => tChannel,
tEnum: () => tEnum,
tFloat: () => tFloat,
tInt: () => tInt,
tObject: () => tObject,
tOptional: () => tOptional,
tString: () => tString,
tType: () => tType,
tUndefined: () => tUndefined
});
module.exports = __toCommonJS(validatorPrimitives_exports);
class ValidationError extends Error {
}
const scheme = {};
function findValidator(type, method, kind) {
const validator = maybeFindValidator(type, method, kind);
if (!validator)
throw new ValidationError(`Unknown scheme for ${kind}: ${type}.${method}`);
return validator;
}
function maybeFindValidator(type, method, kind) {
const schemeName = type + (kind === "Initializer" ? "" : method[0].toUpperCase() + method.substring(1)) + kind;
return scheme[schemeName];
}
function createMetadataValidator() {
return tOptional(scheme["Metadata"]);
}
const tFloat = (arg, path, context) => {
if (arg instanceof Number)
return arg.valueOf();
if (typeof arg === "number")
return arg;
throw new ValidationError(`${path}: expected float, got ${typeof arg}`);
};
const tInt = (arg, path, context) => {
let value;
if (arg instanceof Number)
value = arg.valueOf();
else if (typeof arg === "number")
value = arg;
else
throw new ValidationError(`${path}: expected integer, got ${typeof arg}`);
if (!Number.isInteger(value))
throw new ValidationError(`${path}: expected integer, got float ${value}`);
return value;
};
const tBoolean = (arg, path, context) => {
if (arg instanceof Boolean)
return arg.valueOf();
if (typeof arg === "boolean")
return arg;
throw new ValidationError(`${path}: expected boolean, got ${typeof arg}`);
};
const tString = (arg, path, context) => {
if (arg instanceof String)
return arg.valueOf();
if (typeof arg === "string")
return arg;
throw new ValidationError(`${path}: expected string, got ${typeof arg}`);
};
const tBinary = (arg, path, context) => {
if (context.binary === "fromBase64") {
if (arg instanceof String)
return Buffer.from(arg.valueOf(), "base64");
if (typeof arg === "string")
return Buffer.from(arg, "base64");
throw new ValidationError(`${path}: expected base64-encoded buffer, got ${typeof arg}`);
}
if (context.binary === "toBase64") {
if (!(arg instanceof Buffer))
throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);
return arg.toString("base64");
}
if (context.binary === "buffer") {
if (!(arg instanceof Buffer))
throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);
return arg;
}
throw new ValidationError(`Unsupported binary behavior "${context.binary}"`);
};
const tUndefined = (arg, path, context) => {
if (Object.is(arg, void 0))
return arg;
throw new ValidationError(`${path}: expected undefined, got ${typeof arg}`);
};
const tAny = (arg, path, context) => {
return arg;
};
const tOptional = (v) => {
return (arg, path, context) => {
if (Object.is(arg, void 0))
return arg;
return v(arg, path, context);
};
};
const tArray = (v) => {
return (arg, path, context) => {
if (!Array.isArray(arg))
throw new ValidationError(`${path}: expected array, got ${typeof arg}`);
return arg.map((x, index) => v(x, path + "[" + index + "]", context));
};
};
const tObject = (s) => {
return (arg, path, context) => {
if (Object.is(arg, null))
throw new ValidationError(`${path}: expected object, got null`);
if (typeof arg !== "object")
throw new ValidationError(`${path}: expected object, got ${typeof arg}`);
const result = {};
for (const [key, v] of Object.entries(s)) {
const value = v(arg[key], path ? path + "." + key : key, context);
if (!Object.is(value, void 0))
result[key] = value;
}
if (context.isUnderTest()) {
for (const [key, value] of Object.entries(arg)) {
if (key.startsWith("__testHook"))
result[key] = value;
}
}
return result;
};
};
const tEnum = (e) => {
return (arg, path, context) => {
if (!e.includes(arg))
throw new ValidationError(`${path}: expected one of (${e.join("|")})`);
return arg;
};
};
const tChannel = (names) => {
return (arg, path, context) => {
return context.tChannelImpl(names, arg, path, context);
};
};
const tType = (name) => {
return (arg, path, context) => {
const v = scheme[name];
if (!v)
throw new ValidationError(path + ': unknown type "' + name + '"');
return v(arg, path, context);
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ValidationError,
createMetadataValidator,
findValidator,
maybeFindValidator,
scheme,
tAny,
tArray,
tBinary,
tBoolean,
tChannel,
tEnum,
tFloat,
tInt,
tObject,
tOptional,
tString,
tType,
tUndefined
});

View File

@@ -0,0 +1,129 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var playwrightConnection_exports = {};
__export(playwrightConnection_exports, {
PlaywrightConnection: () => PlaywrightConnection
});
module.exports = __toCommonJS(playwrightConnection_exports);
var import_server = require("../server");
var import_android = require("../server/android/android");
var import_browser = require("../server/browser");
var import_debugControllerDispatcher = require("../server/dispatchers/debugControllerDispatcher");
var import_profiler = require("../server/utils/profiler");
var import_utils = require("../utils");
var import_debugLogger = require("../server/utils/debugLogger");
class PlaywrightConnection {
constructor(semaphore, ws, controller, playwright, initialize, id) {
this._cleanups = [];
this._disconnected = false;
this._ws = ws;
this._semaphore = semaphore;
this._id = id;
this._profileName = (/* @__PURE__ */ new Date()).toISOString();
const lock = this._semaphore.acquire();
this._dispatcherConnection = new import_server.DispatcherConnection();
this._dispatcherConnection.onmessage = async (message) => {
await lock;
if (ws.readyState !== ws.CLOSING) {
const messageString = JSON.stringify(message);
if (import_debugLogger.debugLogger.isEnabled("server:channel"))
import_debugLogger.debugLogger.log("server:channel", `[${this._id}] ${(0, import_utils.monotonicTime)() * 1e3} SEND \u25BA ${messageString}`);
if (import_debugLogger.debugLogger.isEnabled("server:metadata"))
this.logServerMetadata(message, messageString, "SEND");
ws.send(messageString);
}
};
ws.on("message", async (message) => {
await lock;
const messageString = Buffer.from(message).toString();
const jsonMessage = JSON.parse(messageString);
if (import_debugLogger.debugLogger.isEnabled("server:channel"))
import_debugLogger.debugLogger.log("server:channel", `[${this._id}] ${(0, import_utils.monotonicTime)() * 1e3} \u25C0 RECV ${messageString}`);
if (import_debugLogger.debugLogger.isEnabled("server:metadata"))
this.logServerMetadata(jsonMessage, messageString, "RECV");
this._dispatcherConnection.dispatch(jsonMessage);
});
ws.on("close", () => this._onDisconnect());
ws.on("error", (error) => this._onDisconnect(error));
if (controller) {
import_debugLogger.debugLogger.log("server", `[${this._id}] engaged reuse controller mode`);
this._root = new import_debugControllerDispatcher.DebugControllerDispatcher(this._dispatcherConnection, playwright.debugController);
return;
}
this._root = new import_server.RootDispatcher(this._dispatcherConnection, async (scope, params) => {
await (0, import_profiler.startProfiling)();
const options = await initialize();
if (options.preLaunchedBrowser) {
const browser = options.preLaunchedBrowser;
browser.options.sdkLanguage = params.sdkLanguage;
browser.on(import_browser.Browser.Events.Disconnected, () => {
this.close({ code: 1001, reason: "Browser closed" });
});
}
if (options.preLaunchedAndroidDevice) {
const androidDevice = options.preLaunchedAndroidDevice;
androidDevice.on(import_android.AndroidDevice.Events.Close, () => {
this.close({ code: 1001, reason: "Android device disconnected" });
});
}
if (options.dispose)
this._cleanups.push(options.dispose);
const dispatcher = new import_server.PlaywrightDispatcher(scope, playwright, options);
this._cleanups.push(() => dispatcher.cleanup());
return dispatcher;
});
}
async _onDisconnect(error) {
this._disconnected = true;
import_debugLogger.debugLogger.log("server", `[${this._id}] disconnected. error: ${error}`);
await this._root.stopPendingOperations(new Error("Disconnected")).catch(() => {
});
this._root._dispose();
import_debugLogger.debugLogger.log("server", `[${this._id}] starting cleanup`);
for (const cleanup of this._cleanups)
await cleanup().catch(() => {
});
await (0, import_profiler.stopProfiling)(this._profileName);
this._semaphore.release();
import_debugLogger.debugLogger.log("server", `[${this._id}] finished cleanup`);
}
logServerMetadata(message, messageString, direction) {
const serverLogMetadata = {
wallTime: Date.now(),
id: message.id,
guid: message.guid,
method: message.method,
payloadSizeInBytes: Buffer.byteLength(messageString, "utf-8")
};
import_debugLogger.debugLogger.log("server:metadata", (direction === "SEND" ? "SEND \u25BA " : "\u25C0 RECV ") + JSON.stringify(serverLogMetadata));
}
async close(reason) {
if (this._disconnected)
return;
import_debugLogger.debugLogger.log("server", `[${this._id}] force closing connection: ${reason?.reason || ""} (${reason?.code || 0})`);
try {
this._ws.close(reason?.code, reason?.reason);
} catch (e) {
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PlaywrightConnection
});

View File

@@ -0,0 +1,337 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var playwrightServer_exports = {};
__export(playwrightServer_exports, {
PlaywrightServer: () => PlaywrightServer
});
module.exports = __toCommonJS(playwrightServer_exports);
var import_playwrightConnection = require("./playwrightConnection");
var import_playwright = require("../server/playwright");
var import_semaphore = require("../utils/isomorphic/semaphore");
var import_time = require("../utils/isomorphic/time");
var import_wsServer = require("../server/utils/wsServer");
var import_ascii = require("../server/utils/ascii");
var import_userAgent = require("../server/utils/userAgent");
var import_utils = require("../utils");
var import_socksProxy = require("../server/utils/socksProxy");
var import_browser = require("../server/browser");
var import_progress = require("../server/progress");
class PlaywrightServer {
constructor(options) {
this._dontReuseBrowsers = /* @__PURE__ */ new Set();
this._options = options;
if (options.preLaunchedBrowser) {
this._playwright = options.preLaunchedBrowser.attribution.playwright;
this._dontReuse(options.preLaunchedBrowser);
}
if (options.preLaunchedAndroidDevice)
this._playwright = options.preLaunchedAndroidDevice._android.attribution.playwright;
this._playwright ??= (0, import_playwright.createPlaywright)({ sdkLanguage: "javascript", isServer: true });
const browserSemaphore = new import_semaphore.Semaphore(this._options.maxConnections);
const controllerSemaphore = new import_semaphore.Semaphore(1);
const reuseBrowserSemaphore = new import_semaphore.Semaphore(1);
this._wsServer = new import_wsServer.WSServer({
onRequest: (request, response) => {
if (request.method === "GET" && request.url === "/json") {
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify({
wsEndpointPath: this._options.path
}));
return;
}
response.end("Running");
},
onUpgrade: (request, socket) => {
const uaError = userAgentVersionMatchesErrorMessage(request.headers["user-agent"] || "");
if (uaError)
return { error: `HTTP/${request.httpVersion} 428 Precondition Required\r
\r
${uaError}` };
},
onHeaders: (headers) => {
if (process.env.PWTEST_SERVER_WS_HEADERS)
headers.push(process.env.PWTEST_SERVER_WS_HEADERS);
},
onConnection: (request, url, ws, id) => {
const browserHeader = request.headers["x-playwright-browser"];
const browserName = url.searchParams.get("browser") || (Array.isArray(browserHeader) ? browserHeader[0] : browserHeader) || null;
const proxyHeader = request.headers["x-playwright-proxy"];
const proxyValue = url.searchParams.get("proxy") || (Array.isArray(proxyHeader) ? proxyHeader[0] : proxyHeader);
const launchOptionsHeader = request.headers["x-playwright-launch-options"] || "";
const launchOptionsHeaderValue = Array.isArray(launchOptionsHeader) ? launchOptionsHeader[0] : launchOptionsHeader;
const launchOptionsParam = url.searchParams.get("launch-options");
let launchOptions = { timeout: import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT };
try {
launchOptions = JSON.parse(launchOptionsParam || launchOptionsHeaderValue);
if (!launchOptions.timeout)
launchOptions.timeout = import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT;
} catch (e) {
}
const isExtension = this._options.mode === "extension";
const allowFSPaths = isExtension;
launchOptions = filterLaunchOptions(launchOptions, allowFSPaths);
if (url.searchParams.has("debug-controller")) {
if (!(this._options.debugController || isExtension))
throw new Error("Debug controller is not enabled");
return new import_playwrightConnection.PlaywrightConnection(
controllerSemaphore,
ws,
true,
this._playwright,
async () => {
throw new Error("shouldnt be used");
},
id
);
}
if (isExtension) {
const connectFilter = url.searchParams.get("connect");
if (connectFilter) {
if (connectFilter !== "first")
throw new Error(`Unknown connect filter: ${connectFilter}`);
return new import_playwrightConnection.PlaywrightConnection(
browserSemaphore,
ws,
false,
this._playwright,
() => this._initConnectMode(id, connectFilter, browserName, launchOptions),
id
);
}
return new import_playwrightConnection.PlaywrightConnection(
reuseBrowserSemaphore,
ws,
false,
this._playwright,
() => this._initReuseBrowsersMode(browserName, launchOptions, id),
id
);
}
if (this._options.mode === "launchServer" || this._options.mode === "launchServerShared") {
if (this._options.preLaunchedBrowser) {
return new import_playwrightConnection.PlaywrightConnection(
browserSemaphore,
ws,
false,
this._playwright,
() => this._initPreLaunchedBrowserMode(id),
id
);
}
return new import_playwrightConnection.PlaywrightConnection(
browserSemaphore,
ws,
false,
this._playwright,
() => this._initPreLaunchedAndroidMode(id),
id
);
}
return new import_playwrightConnection.PlaywrightConnection(
browserSemaphore,
ws,
false,
this._playwright,
() => this._initLaunchBrowserMode(browserName, proxyValue, launchOptions, id),
id
);
}
});
}
async _initReuseBrowsersMode(browserName, launchOptions, id) {
import_utils.debugLogger.log("server", `[${id}] engaged reuse browsers mode for ${browserName}`);
const requestedOptions = launchOptionsHash(launchOptions);
let browser = this._playwright.allBrowsers().find((b) => {
if (b.options.name !== browserName)
return false;
if (this._dontReuseBrowsers.has(b))
return false;
const existingOptions = launchOptionsHash({ ...b.options.originalLaunchOptions, timeout: import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT });
return existingOptions === requestedOptions;
});
for (const b of this._playwright.allBrowsers()) {
if (b === browser)
continue;
if (this._dontReuseBrowsers.has(b))
continue;
if (b.options.name === browserName && b.options.channel === launchOptions.channel)
await b.close({ reason: "Connection terminated" });
}
if (!browser) {
const browserType = this._playwright[browserName || "chromium"];
const controller = new import_progress.ProgressController();
browser = await controller.run((progress) => browserType.launch(progress, {
...launchOptions,
headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS
}), launchOptions.timeout);
}
return {
preLaunchedBrowser: browser,
denyLaunch: true,
dispose: async () => {
for (const context of browser.contexts()) {
if (!context.pages().length)
await context.close({ reason: "Connection terminated" });
}
}
};
}
async _initConnectMode(id, filter, browserName, launchOptions) {
browserName ??= "chromium";
import_utils.debugLogger.log("server", `[${id}] engaged connect mode`);
let browser = this._playwright.allBrowsers().find((b) => b.options.name === browserName);
if (!browser) {
const browserType = this._playwright[browserName];
const controller = new import_progress.ProgressController();
browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
this._dontReuse(browser);
}
return {
preLaunchedBrowser: browser,
denyLaunch: true,
sharedBrowser: true
};
}
async _initPreLaunchedBrowserMode(id) {
import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (browser) mode`);
const browser = this._options.preLaunchedBrowser;
for (const b of this._playwright.allBrowsers()) {
if (b !== browser)
await b.close({ reason: "Connection terminated" });
}
return {
preLaunchedBrowser: browser,
socksProxy: this._options.preLaunchedSocksProxy,
sharedBrowser: this._options.mode === "launchServerShared",
denyLaunch: true
};
}
async _initPreLaunchedAndroidMode(id) {
import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (Android) mode`);
const androidDevice = this._options.preLaunchedAndroidDevice;
return {
preLaunchedAndroidDevice: androidDevice,
denyLaunch: true
};
}
async _initLaunchBrowserMode(browserName, proxyValue, launchOptions, id) {
import_utils.debugLogger.log("server", `[${id}] engaged launch mode for "${browserName}"`);
let socksProxy;
if (proxyValue) {
socksProxy = new import_socksProxy.SocksProxy();
socksProxy.setPattern(proxyValue);
launchOptions.socksProxyPort = await socksProxy.listen(0);
import_utils.debugLogger.log("server", `[${id}] started socks proxy on port ${launchOptions.socksProxyPort}`);
} else {
launchOptions.socksProxyPort = void 0;
}
const browserType = this._playwright[browserName];
const controller = new import_progress.ProgressController();
const browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
this._dontReuseBrowsers.add(browser);
return {
preLaunchedBrowser: browser,
socksProxy,
denyLaunch: true,
dispose: async () => {
await browser.close({ reason: "Connection terminated" });
socksProxy?.close();
}
};
}
_dontReuse(browser) {
this._dontReuseBrowsers.add(browser);
browser.on(import_browser.Browser.Events.Disconnected, () => {
this._dontReuseBrowsers.delete(browser);
});
}
async listen(port = 0, hostname) {
return this._wsServer.listen(port, hostname, this._options.path);
}
async close() {
await this._wsServer.close();
}
}
function userAgentVersionMatchesErrorMessage(userAgent) {
const match = userAgent.match(/^Playwright\/(\d+\.\d+\.\d+)/);
if (!match) {
return;
}
const received = match[1].split(".").slice(0, 2).join(".");
const expected = (0, import_userAgent.getPlaywrightVersion)(true);
if (received !== expected) {
return (0, import_ascii.wrapInASCIIBox)([
`Playwright version mismatch:`,
` - server version: v${expected}`,
` - client version: v${received}`,
``,
`If you are using VSCode extension, restart VSCode.`,
``,
`If you are connecting to a remote service,`,
`keep your local Playwright version in sync`,
`with the remote service version.`,
``,
`<3 Playwright Team`
].join("\n"), 1);
}
}
function launchOptionsHash(options) {
const copy = { ...options };
for (const k of Object.keys(copy)) {
const key = k;
if (copy[key] === defaultLaunchOptions[key])
delete copy[key];
}
for (const key of optionsThatAllowBrowserReuse)
delete copy[key];
return JSON.stringify(copy);
}
function filterLaunchOptions(options, allowFSPaths) {
return {
channel: options.channel,
args: options.args,
ignoreAllDefaultArgs: options.ignoreAllDefaultArgs,
ignoreDefaultArgs: options.ignoreDefaultArgs,
timeout: options.timeout,
headless: options.headless,
proxy: options.proxy,
chromiumSandbox: options.chromiumSandbox,
firefoxUserPrefs: options.firefoxUserPrefs,
slowMo: options.slowMo,
executablePath: (0, import_utils.isUnderTest)() || allowFSPaths ? options.executablePath : void 0,
downloadsPath: allowFSPaths ? options.downloadsPath : void 0
};
}
const defaultLaunchOptions = {
ignoreAllDefaultArgs: false,
handleSIGINT: false,
handleSIGTERM: false,
handleSIGHUP: false,
headless: true,
devtools: false
};
const optionsThatAllowBrowserReuse = [
"headless",
"timeout",
"tracesDir"
];
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PlaywrightServer
});

View File

@@ -0,0 +1,69 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var accessibility_exports = {};
__export(accessibility_exports, {
Accessibility: () => Accessibility
});
module.exports = __toCommonJS(accessibility_exports);
class Accessibility {
constructor(getAXTree) {
this._getAXTree = getAXTree;
}
async snapshot(options = {}) {
const {
interestingOnly = true,
root = null
} = options;
const { tree, needle } = await this._getAXTree(root || void 0);
if (!interestingOnly) {
if (root)
return needle && serializeTree(needle)[0];
return serializeTree(tree)[0];
}
const interestingNodes = /* @__PURE__ */ new Set();
collectInterestingNodes(interestingNodes, tree, false);
if (root && (!needle || !interestingNodes.has(needle)))
return null;
return serializeTree(needle || tree, interestingNodes)[0];
}
}
function collectInterestingNodes(collection, node, insideControl) {
if (node.isInteresting(insideControl))
collection.add(node);
if (node.isLeafNode())
return;
insideControl = insideControl || node.isControl();
for (const child of node.children())
collectInterestingNodes(collection, child, insideControl);
}
function serializeTree(node, whitelistedNodes) {
const children = [];
for (const child of node.children())
children.push(...serializeTree(child, whitelistedNodes));
if (whitelistedNodes && !whitelistedNodes.has(node))
return children;
const serializedNode = node.serialize();
if (children.length)
serializedNode.children = children;
return [serializedNode];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Accessibility
});

View File

@@ -0,0 +1,465 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var android_exports = {};
__export(android_exports, {
Android: () => Android,
AndroidDevice: () => AndroidDevice
});
module.exports = __toCommonJS(android_exports);
var import_events = require("events");
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var import_pipeTransport = require("../utils/pipeTransport");
var import_crypto = require("../utils/crypto");
var import_debug = require("../utils/debug");
var import_env = require("../utils/env");
var import_task = require("../utils/task");
var import_debugLogger = require("../utils/debugLogger");
var import_utilsBundle = require("../../utilsBundle");
var import_utilsBundle2 = require("../../utilsBundle");
var import_browserContext = require("../browserContext");
var import_chromiumSwitches = require("../chromium/chromiumSwitches");
var import_crBrowser = require("../chromium/crBrowser");
var import_fileUtils = require("../utils/fileUtils");
var import_helper = require("../helper");
var import_instrumentation = require("../instrumentation");
var import_processLauncher = require("../utils/processLauncher");
var import_progress = require("../progress");
var import_registry = require("../registry");
const ARTIFACTS_FOLDER = import_path.default.join(import_os.default.tmpdir(), "playwright-artifacts-");
class Android extends import_instrumentation.SdkObject {
constructor(parent, backend) {
super(parent, "android");
this._devices = /* @__PURE__ */ new Map();
this._backend = backend;
}
async devices(progress, options) {
const devices = (await progress.race(this._backend.devices(options))).filter((d) => d.status === "device");
const newSerials = /* @__PURE__ */ new Set();
for (const d of devices) {
newSerials.add(d.serial);
if (this._devices.has(d.serial))
continue;
await progress.race(AndroidDevice.create(this, d, options).then((device) => this._devices.set(d.serial, device)));
}
for (const d of this._devices.keys()) {
if (!newSerials.has(d))
this._devices.delete(d);
}
return [...this._devices.values()];
}
_deviceClosed(device) {
this._devices.delete(device.serial);
}
}
class AndroidDevice extends import_instrumentation.SdkObject {
constructor(android, backend, model, options) {
super(android, "android-device");
this._lastId = 0;
this._callbacks = /* @__PURE__ */ new Map();
this._webViews = /* @__PURE__ */ new Map();
this._browserConnections = /* @__PURE__ */ new Set();
this._isClosed = false;
this._android = android;
this._backend = backend;
this.model = model;
this.serial = backend.serial;
this._options = options;
this.logName = "browser";
}
static {
this.Events = {
WebViewAdded: "webViewAdded",
WebViewRemoved: "webViewRemoved",
Close: "close"
};
}
static async create(android, backend, options) {
await backend.init();
const model = await backend.runCommand("shell:getprop ro.product.model");
const device = new AndroidDevice(android, backend, model.toString().trim(), options);
await device._init();
return device;
}
async _init() {
await this._refreshWebViews();
const poll = () => {
this._pollingWebViews = setTimeout(() => this._refreshWebViews().then(poll).catch(() => {
this.close().catch(() => {
});
}), 500);
};
poll();
}
async shell(command) {
const result = await this._backend.runCommand(`shell:${command}`);
await this._refreshWebViews();
return result;
}
async open(progress, command) {
return await this._open(progress, command);
}
async screenshot() {
return await this._backend.runCommand(`shell:screencap -p`);
}
async _driver() {
if (this._isClosed)
return;
if (!this._driverPromise) {
const controller = new import_progress.ProgressController();
this._driverPromise = controller.run((progress) => this._installDriver(progress));
}
return this._driverPromise;
}
async _installDriver(progress) {
(0, import_utilsBundle.debug)("pw:android")("Stopping the old driver");
await progress.race(this.shell(`am force-stop com.microsoft.playwright.androiddriver`));
if (!this._options.omitDriverInstall) {
(0, import_utilsBundle.debug)("pw:android")("Uninstalling the old driver");
await progress.race(this.shell(`cmd package uninstall com.microsoft.playwright.androiddriver`));
await progress.race(this.shell(`cmd package uninstall com.microsoft.playwright.androiddriver.test`));
(0, import_utilsBundle.debug)("pw:android")("Installing the new driver");
const executable = import_registry.registry.findExecutable("android");
const packageManagerCommand = (0, import_env.getPackageManagerExecCommand)();
for (const file of ["android-driver.apk", "android-driver-target.apk"]) {
const fullName = import_path.default.join(executable.directory, file);
if (!import_fs.default.existsSync(fullName))
throw new Error(`Please install Android driver apk using '${packageManagerCommand} playwright install android'`);
await this.installApk(progress, await progress.race(import_fs.default.promises.readFile(fullName)));
}
} else {
(0, import_utilsBundle.debug)("pw:android")("Skipping the driver installation");
}
(0, import_utilsBundle.debug)("pw:android")("Starting the new driver");
this.shell("am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner").catch((e) => (0, import_utilsBundle.debug)("pw:android")(e));
const socket = await this._waitForLocalAbstract(progress, "playwright_android_driver_socket");
const transport = new import_pipeTransport.PipeTransport(socket, socket, socket, "be");
transport.onmessage = (message) => {
const response = JSON.parse(message);
const { id, result, error } = response;
const callback = this._callbacks.get(id);
if (!callback)
return;
if (error)
callback.reject(new Error(error));
else
callback.fulfill(result);
this._callbacks.delete(id);
};
return transport;
}
async _waitForLocalAbstract(progress, socketName) {
let socket;
(0, import_utilsBundle.debug)("pw:android")(`Polling the socket localabstract:${socketName}`);
while (!socket) {
try {
socket = await this._open(progress, `localabstract:${socketName}`);
} catch (e) {
if ((0, import_progress.isAbortError)(e))
throw e;
await progress.wait(250);
}
}
(0, import_utilsBundle.debug)("pw:android")(`Connected to localabstract:${socketName}`);
return socket;
}
async send(method, params = {}) {
params = {
...params,
// Patch the timeout in, just in case it's missing in one of the commands.
timeout: params.timeout || 0
};
if (params.androidSelector) {
params.selector = params.androidSelector;
delete params.androidSelector;
}
const driver = await this._driver();
if (!driver)
throw new Error("Device is closed");
const id = ++this._lastId;
const result = new Promise((fulfill, reject) => this._callbacks.set(id, { fulfill, reject }));
driver.send(JSON.stringify({ id, method, params }));
return result;
}
async close() {
if (this._isClosed)
return;
this._isClosed = true;
if (this._pollingWebViews)
clearTimeout(this._pollingWebViews);
for (const connection of this._browserConnections)
await connection.close();
if (this._driverPromise) {
const driver = await this._driver();
driver?.close();
}
await this._backend.close();
this._android._deviceClosed(this);
this.emit(AndroidDevice.Events.Close);
}
async launchBrowser(progress, pkg = "com.android.chrome", options) {
(0, import_utilsBundle.debug)("pw:android")("Force-stopping", pkg);
await this._backend.runCommand(`shell:am force-stop ${pkg}`);
const socketName = (0, import_debug.isUnderTest)() ? "webview_devtools_remote_playwright_test" : "playwright_" + (0, import_crypto.createGuid)() + "_devtools_remote";
const commandLine = this._defaultArgs(options, socketName).join(" ");
(0, import_utilsBundle.debug)("pw:android")("Starting", pkg, commandLine);
await progress.race(this._backend.runCommand(`shell:echo "${Buffer.from(commandLine).toString("base64")}" | base64 -d > /data/local/tmp/chrome-command-line`));
await progress.race(this._backend.runCommand(`shell:am start -a android.intent.action.VIEW -d about:blank ${pkg}`));
const browserContext = await this._connectToBrowser(progress, socketName, options);
try {
await progress.race(this._backend.runCommand(`shell:rm /data/local/tmp/chrome-command-line`));
return browserContext;
} catch (error) {
await browserContext.close({ reason: "Failed to launch" }).catch(() => {
});
throw error;
}
}
_defaultArgs(options, socketName) {
const chromeArguments = [
"_",
"--disable-fre",
"--no-default-browser-check",
`--remote-debugging-socket-name=${socketName}`,
...(0, import_chromiumSwitches.chromiumSwitches)(),
...this._innerDefaultArgs(options)
];
return chromeArguments;
}
_innerDefaultArgs(options) {
const { args = [], proxy } = options;
const chromeArguments = [];
if (proxy) {
chromeArguments.push(`--proxy-server=${proxy.server}`);
const proxyBypassRules = [];
if (proxy.bypass)
proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t));
if (!process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>"))
proxyBypassRules.push("<-loopback>");
if (proxyBypassRules.length > 0)
chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`);
}
chromeArguments.push(...args);
return chromeArguments;
}
async connectToWebView(progress, socketName) {
const webView = this._webViews.get(socketName);
if (!webView)
throw new Error("WebView has been closed");
return await this._connectToBrowser(progress, socketName);
}
async _connectToBrowser(progress, socketName, options = {}) {
const socket = await this._waitForLocalAbstract(progress, socketName);
try {
const androidBrowser = new AndroidBrowser(this, socket);
await progress.race(androidBrowser._init());
this._browserConnections.add(androidBrowser);
const artifactsDir = await progress.race(import_fs.default.promises.mkdtemp(ARTIFACTS_FOLDER));
const cleanupArtifactsDir = async () => {
const errors = (await (0, import_fileUtils.removeFolders)([artifactsDir])).filter(Boolean);
for (let i = 0; i < (errors || []).length; ++i)
(0, import_utilsBundle.debug)("pw:android")(`exception while removing ${artifactsDir}: ${errors[i]}`);
};
import_processLauncher.gracefullyCloseSet.add(cleanupArtifactsDir);
socket.on("close", async () => {
import_processLauncher.gracefullyCloseSet.delete(cleanupArtifactsDir);
cleanupArtifactsDir().catch((e) => (0, import_utilsBundle.debug)("pw:android")(`could not cleanup artifacts dir: ${e}`));
});
const browserOptions = {
name: "clank",
isChromium: true,
slowMo: 0,
persistent: { ...options, noDefaultViewport: true },
artifactsDir,
downloadsPath: artifactsDir,
tracesDir: artifactsDir,
browserProcess: new ClankBrowserProcess(androidBrowser),
proxy: options.proxy,
protocolLogger: import_helper.helper.debugProtocolLogger(),
browserLogsCollector: new import_debugLogger.RecentLogsCollector(),
originalLaunchOptions: {}
};
(0, import_browserContext.validateBrowserContextOptions)(options, browserOptions);
const browser = await progress.race(import_crBrowser.CRBrowser.connect(this.attribution.playwright, androidBrowser, browserOptions));
const defaultContext = browser._defaultContext;
await defaultContext._loadDefaultContextAsIs(progress);
return defaultContext;
} catch (error) {
socket.close();
throw error;
}
}
_open(progress, command) {
return (0, import_progress.raceUncancellableOperationWithCleanup)(progress, () => this._backend.open(command), (socket) => socket.close());
}
webViews() {
return [...this._webViews.values()];
}
async installApk(progress, content, options) {
const args = options && options.args ? options.args : ["-r", "-t", "-S"];
(0, import_utilsBundle.debug)("pw:android")("Opening install socket");
const installSocket = await this._open(progress, `shell:cmd package install ${args.join(" ")} ${content.length}`);
(0, import_utilsBundle.debug)("pw:android")("Writing driver bytes: " + content.length);
await progress.race(installSocket.write(content));
const success = await progress.race(new Promise((f) => installSocket.on("data", f)));
(0, import_utilsBundle.debug)("pw:android")("Written driver bytes: " + success);
installSocket.close();
}
async push(progress, content, path2, mode = 420) {
const socket = await this._open(progress, `sync:`);
const sendHeader = async (command, length) => {
const buffer = Buffer.alloc(command.length + 4);
buffer.write(command, 0);
buffer.writeUInt32LE(length, command.length);
await progress.race(socket.write(buffer));
};
const send = async (command, data) => {
await sendHeader(command, data.length);
await progress.race(socket.write(data));
};
await send("SEND", Buffer.from(`${path2},${mode}`));
const maxChunk = 65535;
for (let i = 0; i < content.length; i += maxChunk)
await send("DATA", content.slice(i, i + maxChunk));
await sendHeader("DONE", Date.now() / 1e3 | 0);
const result = await progress.race(new Promise((f) => socket.once("data", f)));
const code = result.slice(0, 4).toString();
if (code !== "OKAY")
throw new Error("Could not push: " + code);
socket.close();
}
async _refreshWebViews() {
const sockets = (await this._backend.runCommand(`shell:cat /proc/net/unix | grep webview_devtools_remote`)).toString().split("\n");
if (this._isClosed)
return;
const socketNames = /* @__PURE__ */ new Set();
for (const line of sockets) {
const matchSocketName = line.match(/[^@]+@(.*?webview_devtools_remote_?.*)/);
if (!matchSocketName)
continue;
const socketName = matchSocketName[1];
socketNames.add(socketName);
if (this._webViews.has(socketName))
continue;
const match = line.match(/[^@]+@.*?webview_devtools_remote_?(\d*)/);
let pid = -1;
if (match && match[1])
pid = +match[1];
const pkg = await this._extractPkg(pid);
if (this._isClosed)
return;
const webView = { pid, pkg, socketName };
this._webViews.set(socketName, webView);
this.emit(AndroidDevice.Events.WebViewAdded, webView);
}
for (const p of this._webViews.keys()) {
if (!socketNames.has(p)) {
this._webViews.delete(p);
this.emit(AndroidDevice.Events.WebViewRemoved, p);
}
}
}
async _extractPkg(pid) {
let pkg = "";
if (pid === -1)
return pkg;
const procs = (await this._backend.runCommand(`shell:ps -A | grep ${pid}`)).toString().split("\n");
for (const proc of procs) {
const match = proc.match(/[^\s]+\s+(\d+).*$/);
if (!match)
continue;
pkg = proc.substring(proc.lastIndexOf(" ") + 1);
}
return pkg;
}
}
class AndroidBrowser extends import_events.EventEmitter {
constructor(device, socket) {
super();
this._waitForNextTask = (0, import_task.makeWaitForNextTask)();
this.setMaxListeners(0);
this.device = device;
this._socket = socket;
this._socket.on("close", () => {
this._waitForNextTask(() => {
if (this.onclose)
this.onclose();
});
});
this._receiver = new import_utilsBundle2.wsReceiver();
this._receiver.on("message", (message) => {
this._waitForNextTask(() => {
if (this.onmessage)
this.onmessage(JSON.parse(message));
});
});
}
async _init() {
await this._socket.write(Buffer.from(`GET /devtools/browser HTTP/1.1\r
Upgrade: WebSocket\r
Connection: Upgrade\r
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r
Sec-WebSocket-Version: 13\r
\r
`));
await new Promise((f) => this._socket.once("data", f));
this._socket.on("data", (data) => this._receiver._write(data, "binary", () => {
}));
}
async send(s) {
await this._socket.write(encodeWebFrame(JSON.stringify(s)));
}
async close() {
this._socket.close();
}
}
function encodeWebFrame(data) {
return import_utilsBundle2.wsSender.frame(Buffer.from(data), {
opcode: 1,
mask: true,
fin: true,
readOnly: true
})[0];
}
class ClankBrowserProcess {
constructor(browser) {
this._browser = browser;
}
async kill() {
}
async close() {
await this._browser.close();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Android,
AndroidDevice
});

View File

@@ -0,0 +1,177 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var backendAdb_exports = {};
__export(backendAdb_exports, {
AdbBackend: () => AdbBackend
});
module.exports = __toCommonJS(backendAdb_exports);
var import_events = require("events");
var import_net = __toESM(require("net"));
var import_assert = require("../../utils/isomorphic/assert");
var import_utilsBundle = require("../../utilsBundle");
class AdbBackend {
async devices(options = {}) {
const result = await runCommand("host:devices", options.host, options.port);
const lines = result.toString().trim().split("\n");
return lines.map((line) => {
const [serial, status] = line.trim().split(" ");
return new AdbDevice(serial, status, options.host, options.port);
});
}
}
class AdbDevice {
constructor(serial, status, host, port) {
this._closed = false;
this.serial = serial;
this.status = status;
this.host = host;
this.port = port;
}
async init() {
}
async close() {
this._closed = true;
}
runCommand(command) {
if (this._closed)
throw new Error("Device is closed");
return runCommand(command, this.host, this.port, this.serial);
}
async open(command) {
if (this._closed)
throw new Error("Device is closed");
const result = await open(command, this.host, this.port, this.serial);
result.becomeSocket();
return result;
}
}
async function runCommand(command, host = "127.0.0.1", port = 5037, serial) {
(0, import_utilsBundle.debug)("pw:adb:runCommand")(command, serial);
const socket = new BufferedSocketWrapper(command, import_net.default.createConnection({ host, port }));
try {
if (serial) {
await socket.write(encodeMessage(`host:transport:${serial}`));
const status2 = await socket.read(4);
(0, import_assert.assert)(status2.toString() === "OKAY", status2.toString());
}
await socket.write(encodeMessage(command));
const status = await socket.read(4);
(0, import_assert.assert)(status.toString() === "OKAY", status.toString());
let commandOutput;
if (!command.startsWith("shell:")) {
const remainingLength = parseInt((await socket.read(4)).toString(), 16);
commandOutput = await socket.read(remainingLength);
} else {
commandOutput = await socket.readAll();
}
return commandOutput;
} finally {
socket.close();
}
}
async function open(command, host = "127.0.0.1", port = 5037, serial) {
const socket = new BufferedSocketWrapper(command, import_net.default.createConnection({ host, port }));
if (serial) {
await socket.write(encodeMessage(`host:transport:${serial}`));
const status2 = await socket.read(4);
(0, import_assert.assert)(status2.toString() === "OKAY", status2.toString());
}
await socket.write(encodeMessage(command));
const status = await socket.read(4);
(0, import_assert.assert)(status.toString() === "OKAY", status.toString());
return socket;
}
function encodeMessage(message) {
let lenHex = message.length.toString(16);
lenHex = "0".repeat(4 - lenHex.length) + lenHex;
return Buffer.from(lenHex + message);
}
class BufferedSocketWrapper extends import_events.EventEmitter {
constructor(command, socket) {
super();
this._buffer = Buffer.from([]);
this._isSocket = false;
this._isClosed = false;
this._command = command;
this._socket = socket;
this._connectPromise = new Promise((f) => this._socket.on("connect", f));
this._socket.on("data", (data) => {
(0, import_utilsBundle.debug)("pw:adb:data")(data.toString());
if (this._isSocket) {
this.emit("data", data);
return;
}
this._buffer = Buffer.concat([this._buffer, data]);
if (this._notifyReader)
this._notifyReader();
});
this._socket.on("close", () => {
this._isClosed = true;
if (this._notifyReader)
this._notifyReader();
this.close();
this.emit("close");
});
this._socket.on("error", (error) => this.emit("error", error));
}
async write(data) {
(0, import_utilsBundle.debug)("pw:adb:send")(data.toString().substring(0, 100) + "...");
await this._connectPromise;
await new Promise((f) => this._socket.write(data, f));
}
close() {
if (this._isClosed)
return;
(0, import_utilsBundle.debug)("pw:adb")("Close " + this._command);
this._socket.destroy();
}
async read(length) {
await this._connectPromise;
(0, import_assert.assert)(!this._isSocket, "Can not read by length in socket mode");
while (this._buffer.length < length)
await new Promise((f) => this._notifyReader = f);
const result = this._buffer.slice(0, length);
this._buffer = this._buffer.slice(length);
(0, import_utilsBundle.debug)("pw:adb:recv")(result.toString().substring(0, 100) + "...");
return result;
}
async readAll() {
while (!this._isClosed)
await new Promise((f) => this._notifyReader = f);
return this._buffer;
}
becomeSocket() {
(0, import_assert.assert)(!this._buffer.length);
this._isSocket = true;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AdbBackend
});

127
node_modules/playwright-core/lib/server/artifact.js generated vendored Normal file
View File

@@ -0,0 +1,127 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var artifact_exports = {};
__export(artifact_exports, {
Artifact: () => Artifact
});
module.exports = __toCommonJS(artifact_exports);
var import_fs = __toESM(require("fs"));
var import_utils = require("../utils");
var import_errors = require("./errors");
var import_instrumentation = require("./instrumentation");
var import_manualPromise = require("../utils/isomorphic/manualPromise");
class Artifact extends import_instrumentation.SdkObject {
constructor(parent, localPath, unaccessibleErrorMessage, cancelCallback) {
super(parent, "artifact");
this._finishedPromise = new import_manualPromise.ManualPromise();
this._saveCallbacks = [];
this._finished = false;
this._deleted = false;
this._localPath = localPath;
this._unaccessibleErrorMessage = unaccessibleErrorMessage;
this._cancelCallback = cancelCallback;
}
finishedPromise() {
return this._finishedPromise;
}
localPath() {
return this._localPath;
}
async localPathAfterFinished() {
if (this._unaccessibleErrorMessage)
throw new Error(this._unaccessibleErrorMessage);
await this._finishedPromise;
if (this._failureError)
throw this._failureError;
return this._localPath;
}
saveAs(saveCallback) {
if (this._unaccessibleErrorMessage)
throw new Error(this._unaccessibleErrorMessage);
if (this._deleted)
throw new Error(`File already deleted. Save before deleting.`);
if (this._failureError)
throw this._failureError;
if (this._finished) {
saveCallback(this._localPath).catch(() => {
});
return;
}
this._saveCallbacks.push(saveCallback);
}
async failureError() {
if (this._unaccessibleErrorMessage)
return this._unaccessibleErrorMessage;
await this._finishedPromise;
return this._failureError?.message || null;
}
async cancel() {
(0, import_utils.assert)(this._cancelCallback !== void 0);
return this._cancelCallback();
}
async delete() {
if (this._unaccessibleErrorMessage)
return;
const fileName = await this.localPathAfterFinished();
if (this._deleted)
return;
this._deleted = true;
if (fileName)
await import_fs.default.promises.unlink(fileName).catch((e) => {
});
}
async deleteOnContextClose() {
if (this._deleted)
return;
this._deleted = true;
if (!this._unaccessibleErrorMessage)
await import_fs.default.promises.unlink(this._localPath).catch((e) => {
});
await this.reportFinished(new import_errors.TargetClosedError());
}
async reportFinished(error) {
if (this._finished)
return;
this._finished = true;
this._failureError = error;
if (error) {
for (const callback of this._saveCallbacks)
await callback("", error);
} else {
for (const callback of this._saveCallbacks)
await callback(this._localPath);
}
this._saveCallbacks = [];
this._finishedPromise.resolve();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Artifact
});

View File

@@ -0,0 +1,446 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiBrowser_exports = {};
__export(bidiBrowser_exports, {
BidiBrowser: () => BidiBrowser,
BidiBrowserContext: () => BidiBrowserContext,
Network: () => Network
});
module.exports = __toCommonJS(bidiBrowser_exports);
var import_eventsHelper = require("../utils/eventsHelper");
var import_browser = require("../browser");
var import_browserContext = require("../browserContext");
var network = __toESM(require("../network"));
var import_bidiConnection = require("./bidiConnection");
var import_bidiNetworkManager = require("./bidiNetworkManager");
var import_bidiPage = require("./bidiPage");
var import_page = require("../page");
var bidi = __toESM(require("./third_party/bidiProtocol"));
class BidiBrowser extends import_browser.Browser {
constructor(parent, transport, options) {
super(parent, options);
this._contexts = /* @__PURE__ */ new Map();
this._bidiPages = /* @__PURE__ */ new Map();
this._connection = new import_bidiConnection.BidiConnection(transport, this._onDisconnect.bind(this), options.protocolLogger, options.browserLogsCollector);
this._browserSession = this._connection.browserSession;
this._eventListeners = [
import_eventsHelper.eventsHelper.addEventListener(this._browserSession, "browsingContext.contextCreated", this._onBrowsingContextCreated.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(this._browserSession, "script.realmDestroyed", this._onScriptRealmDestroyed.bind(this))
];
}
static async connect(parent, transport, options) {
const browser = new BidiBrowser(parent, transport, options);
if (options.__testHookOnConnectToBrowser)
await options.__testHookOnConnectToBrowser();
browser._bidiSessionInfo = await browser._browserSession.send("session.new", {
capabilities: {
alwaysMatch: {
acceptInsecureCerts: options.persistent?.internalIgnoreHTTPSErrors || options.persistent?.ignoreHTTPSErrors,
proxy: getProxyConfiguration(options.originalLaunchOptions.proxyOverride ?? options.proxy),
unhandledPromptBehavior: {
default: bidi.Session.UserPromptHandlerType.Ignore
},
webSocketUrl: true
}
}
});
await browser._browserSession.send("session.subscribe", {
events: [
"browsingContext",
"network",
"log",
"script"
]
});
if (options.persistent) {
const context = new BidiBrowserContext(browser, void 0, options.persistent);
browser._defaultContext = context;
await context._initialize();
const page = await browser._defaultContext.doCreateNewPage();
await page.waitForInitializedOrError();
}
return browser;
}
_onDisconnect() {
this._didClose();
}
async doCreateNewContext(options) {
const proxy = options.proxyOverride || options.proxy;
const { userContext } = await this._browserSession.send("browser.createUserContext", {
acceptInsecureCerts: options.internalIgnoreHTTPSErrors || options.ignoreHTTPSErrors,
proxy: getProxyConfiguration(proxy)
});
const context = new BidiBrowserContext(this, userContext, options);
await context._initialize();
this._contexts.set(userContext, context);
return context;
}
contexts() {
return Array.from(this._contexts.values());
}
version() {
return this._bidiSessionInfo.capabilities.browserVersion;
}
userAgent() {
return this._bidiSessionInfo.capabilities.userAgent;
}
isConnected() {
return !this._connection.isClosed();
}
_onBrowsingContextCreated(event) {
if (event.parent) {
const parentFrameId = event.parent;
for (const page2 of this._bidiPages.values()) {
const parentFrame = page2._page.frameManager.frame(parentFrameId);
if (!parentFrame)
continue;
page2._session.addFrameBrowsingContext(event.context);
page2._page.frameManager.frameAttached(event.context, parentFrameId);
const frame = page2._page.frameManager.frame(event.context);
if (frame)
frame._url = event.url;
return;
}
return;
}
let context = this._contexts.get(event.userContext);
if (!context)
context = this._defaultContext;
if (!context)
return;
const session = this._connection.createMainFrameBrowsingContextSession(event.context);
const opener = event.originalOpener && this._bidiPages.get(event.originalOpener);
const page = new import_bidiPage.BidiPage(context, session, opener || null);
page._page.mainFrame()._url = event.url;
this._bidiPages.set(event.context, page);
}
_onBrowsingContextDestroyed(event) {
if (event.parent) {
this._browserSession.removeFrameBrowsingContext(event.context);
const parentFrameId = event.parent;
for (const page of this._bidiPages.values()) {
const parentFrame = page._page.frameManager.frame(parentFrameId);
if (!parentFrame)
continue;
page._page.frameManager.frameDetached(event.context);
return;
}
return;
}
const bidiPage = this._bidiPages.get(event.context);
if (!bidiPage)
return;
bidiPage.didClose();
this._bidiPages.delete(event.context);
}
_onScriptRealmDestroyed(event) {
for (const page of this._bidiPages.values()) {
if (page._onRealmDestroyed(event))
return;
}
}
}
class BidiBrowserContext extends import_browserContext.BrowserContext {
constructor(browser, browserContextId, options) {
super(browser, options, browserContextId);
this._originToPermissions = /* @__PURE__ */ new Map();
this._initScriptIds = /* @__PURE__ */ new Map();
this._authenticateProxyViaHeader();
}
_bidiPages() {
return [...this._browser._bidiPages.values()].filter((bidiPage) => bidiPage._browserContext === this);
}
async _initialize() {
const promises = [
super._initialize()
];
promises.push(this.doUpdateDefaultViewport());
if (this._options.geolocation)
promises.push(this.setGeolocation(this._options.geolocation));
if (this._options.locale) {
promises.push(this._browser._browserSession.send("emulation.setLocaleOverride", {
locale: this._options.locale,
userContexts: [this._userContextId()]
}));
}
await Promise.all(promises);
}
possiblyUninitializedPages() {
return this._bidiPages().map((bidiPage) => bidiPage._page);
}
async doCreateNewPage() {
const { context } = await this._browser._browserSession.send("browsingContext.create", {
type: bidi.BrowsingContext.CreateType.Window,
userContext: this._browserContextId
});
return this._browser._bidiPages.get(context)._page;
}
async doGetCookies(urls) {
const { cookies } = await this._browser._browserSession.send(
"storage.getCookies",
{ partition: { type: "storageKey", userContext: this._browserContextId } }
);
return network.filterCookies(cookies.map((c) => {
const copy = {
name: c.name,
value: (0, import_bidiNetworkManager.bidiBytesValueToString)(c.value),
domain: c.domain,
path: c.path,
httpOnly: c.httpOnly,
secure: c.secure,
expires: c.expiry ?? -1,
sameSite: c.sameSite ? fromBidiSameSite(c.sameSite) : "None"
};
return copy;
}), urls);
}
async addCookies(cookies) {
cookies = network.rewriteCookies(cookies);
const promises = cookies.map((c) => {
const cookie = {
name: c.name,
value: { type: "string", value: c.value },
domain: c.domain,
path: c.path,
httpOnly: c.httpOnly,
secure: c.secure,
sameSite: c.sameSite && toBidiSameSite(c.sameSite),
expiry: c.expires === -1 || c.expires === void 0 ? void 0 : Math.round(c.expires)
};
return this._browser._browserSession.send(
"storage.setCookie",
{ cookie, partition: { type: "storageKey", userContext: this._browserContextId } }
);
});
await Promise.all(promises);
}
async doClearCookies() {
await this._browser._browserSession.send(
"storage.deleteCookies",
{ partition: { type: "storageKey", userContext: this._browserContextId } }
);
}
async doGrantPermissions(origin, permissions) {
const currentPermissions = this._originToPermissions.get(origin) || [];
const toGrant = permissions.filter((permission) => !currentPermissions.includes(permission));
this._originToPermissions.set(origin, [...currentPermissions, ...toGrant]);
await Promise.all(toGrant.map((permission) => this._setPermission(origin, permission, bidi.Permissions.PermissionState.Granted)));
}
async doClearPermissions() {
const currentPermissions = [...this._originToPermissions.entries()];
this._originToPermissions = /* @__PURE__ */ new Map();
await Promise.all(currentPermissions.map(([origin, permissions]) => permissions.map(
(p) => this._setPermission(origin, p, bidi.Permissions.PermissionState.Prompt)
)));
}
async _setPermission(origin, permission, state) {
await this._browser._browserSession.send("permissions.setPermission", {
descriptor: {
name: permission
},
state,
origin,
userContext: this._userContextId()
});
}
async setGeolocation(geolocation) {
(0, import_browserContext.verifyGeolocation)(geolocation);
this._options.geolocation = geolocation;
await this._browser._browserSession.send("emulation.setGeolocationOverride", {
coordinates: geolocation ? {
latitude: geolocation.latitude,
longitude: geolocation.longitude,
accuracy: geolocation.accuracy
} : null,
userContexts: [this._userContextId()]
});
}
async doUpdateExtraHTTPHeaders() {
}
async setUserAgent(userAgent) {
}
async doUpdateOffline() {
}
async doSetHTTPCredentials(httpCredentials) {
this._options.httpCredentials = httpCredentials;
for (const page of this.pages())
await page.delegate.updateHttpCredentials();
}
async doAddInitScript(initScript) {
const { script } = await this._browser._browserSession.send("script.addPreloadScript", {
// TODO: remove function call from the source.
functionDeclaration: `() => { return ${initScript.source} }`,
userContexts: [this._userContextId()]
});
this._initScriptIds.set(initScript, script);
}
async doRemoveInitScripts(initScripts) {
const ids = [];
for (const script of initScripts) {
const id = this._initScriptIds.get(script);
if (id)
ids.push(id);
this._initScriptIds.delete(script);
}
await Promise.all(ids.map((script) => this._browser._browserSession.send("script.removePreloadScript", { script })));
}
async doUpdateRequestInterception() {
}
async doUpdateDefaultViewport() {
if (!this._options.viewport)
return;
await this._browser._browserSession.send("browsingContext.setViewport", {
viewport: {
width: this._options.viewport.width,
height: this._options.viewport.height
},
devicePixelRatio: this._options.deviceScaleFactor || 1,
userContexts: [this._userContextId()]
});
}
async doUpdateDefaultEmulatedMedia() {
}
async doExposePlaywrightBinding() {
const args = [{
type: "channel",
value: {
channel: import_bidiPage.kPlaywrightBindingChannel,
ownership: bidi.Script.ResultOwnership.Root
}
}];
const functionDeclaration = `function addMainBinding(callback) { globalThis['${import_page.PageBinding.kBindingName}'] = callback; }`;
const promises = [];
promises.push(this._browser._browserSession.send("script.addPreloadScript", {
functionDeclaration,
arguments: args,
userContexts: [this._userContextId()]
}));
promises.push(...this._bidiPages().map((page) => {
const realms = [...page._realmToContext].filter(([realm, context]) => context.world === "main").map(([realm, context]) => realm);
return Promise.all(realms.map((realm) => {
return page._session.send("script.callFunction", {
functionDeclaration,
arguments: args,
target: { realm },
awaitPromise: false,
userActivation: false
});
}));
}));
await Promise.all(promises);
}
onClosePersistent() {
}
async clearCache() {
}
async doClose(reason) {
if (!this._browserContextId) {
await this._browser.close({ reason });
return;
}
await this._browser._browserSession.send("browser.removeUserContext", {
userContext: this._browserContextId
});
this._browser._contexts.delete(this._browserContextId);
}
async cancelDownload(uuid) {
}
_userContextId() {
if (this._browserContextId)
return this._browserContextId;
return "default";
}
}
function fromBidiSameSite(sameSite) {
switch (sameSite) {
case "strict":
return "Strict";
case "lax":
return "Lax";
case "none":
return "None";
}
return "None";
}
function toBidiSameSite(sameSite) {
switch (sameSite) {
case "Strict":
return bidi.Network.SameSite.Strict;
case "Lax":
return bidi.Network.SameSite.Lax;
case "None":
return bidi.Network.SameSite.None;
}
return bidi.Network.SameSite.None;
}
function getProxyConfiguration(proxySettings) {
if (!proxySettings)
return void 0;
const proxy = {
proxyType: "manual"
};
const url = new URL(proxySettings.server);
switch (url.protocol) {
case "http:":
proxy.httpProxy = url.host;
break;
case "https:":
proxy.sslProxy = url.host;
break;
case "socks4:":
proxy.socksProxy = url.host;
proxy.socksVersion = 4;
break;
case "socks5:":
proxy.socksProxy = url.host;
proxy.socksVersion = 5;
break;
default:
throw new Error("Invalid proxy server protocol: " + proxySettings.server);
}
const bypass = proxySettings.bypass ?? process.env.PLAYWRIGHT_PROXY_BYPASS_FOR_TESTING;
if (bypass)
proxy.noProxy = bypass.split(",");
return proxy;
}
var Network;
((Network2) => {
let SameSite;
((SameSite2) => {
SameSite2["Strict"] = "strict";
SameSite2["Lax"] = "lax";
SameSite2["None"] = "none";
})(SameSite = Network2.SameSite || (Network2.SameSite = {}));
})(Network || (Network = {}));
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiBrowser,
BidiBrowserContext,
Network
});

View File

@@ -0,0 +1,153 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiChromium_exports = {};
__export(bidiChromium_exports, {
BidiChromium: () => BidiChromium
});
module.exports = __toCommonJS(bidiChromium_exports);
var import_os = __toESM(require("os"));
var import_ascii = require("../utils/ascii");
var import_browserType = require("../browserType");
var import_bidiBrowser = require("./bidiBrowser");
var import_bidiConnection = require("./bidiConnection");
var import_chromiumSwitches = require("../chromium/chromiumSwitches");
var import_chromium = require("../chromium/chromium");
class BidiChromium extends import_browserType.BrowserType {
constructor(parent) {
super(parent, "_bidiChromium");
}
async connectToTransport(transport, options, browserLogsCollector) {
const bidiTransport = await require("./bidiOverCdp").connectBidiOverCdp(transport);
transport[kBidiOverCdpWrapper] = bidiTransport;
try {
return import_bidiBrowser.BidiBrowser.connect(this.attribution.playwright, bidiTransport, options);
} catch (e) {
if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) {
throw new Error(
"Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."
);
}
throw e;
}
}
doRewriteStartupLog(error) {
if (!error.logs)
return error;
if (error.logs.includes("Missing X server"))
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);
if (!error.logs.includes("crbug.com/357670") && !error.logs.includes("No usable sandbox!") && !error.logs.includes("crbug.com/638180"))
return error;
error.logs = [
`Chromium sandboxing failed!`,
`================================`,
`To avoid the sandboxing issue, do either of the following:`,
` - (preferred): Configure your environment to support sandboxing`,
` - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`,
`================================`,
``
].join("\n");
return error;
}
amendEnvironment(env) {
return env;
}
attemptToGracefullyCloseBrowser(transport) {
const bidiTransport = transport[kBidiOverCdpWrapper];
if (bidiTransport)
transport = bidiTransport;
transport.send({ method: "browser.close", params: {}, id: import_bidiConnection.kBrowserCloseMessageId });
}
supportsPipeTransport() {
return false;
}
defaultArgs(options, isPersistent, userDataDir) {
const chromeArguments = this._innerDefaultArgs(options);
chromeArguments.push(`--user-data-dir=${userDataDir}`);
chromeArguments.push("--remote-debugging-port=0");
if (isPersistent)
chromeArguments.push("about:blank");
else
chromeArguments.push("--no-startup-window");
return chromeArguments;
}
async waitForReadyState(options, browserLogsCollector) {
return (0, import_chromium.waitForReadyState)({ ...options, cdpPort: 0 }, browserLogsCollector);
}
_innerDefaultArgs(options) {
const { args = [] } = options;
const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir"));
if (userDataDirArg)
throw this._createUserDataDirArgMisuseError("--user-data-dir");
if (args.find((arg) => arg.startsWith("--remote-debugging-pipe")))
throw new Error("Playwright manages remote debugging connection itself.");
if (args.find((arg) => !arg.startsWith("-")))
throw new Error("Arguments can not specify page to be opened");
const chromeArguments = [...(0, import_chromiumSwitches.chromiumSwitches)(options.assistantMode)];
if (import_os.default.platform() === "darwin") {
chromeArguments.push("--enable-unsafe-swiftshader");
}
if (options.devtools)
chromeArguments.push("--auto-open-devtools-for-tabs");
if (options.headless) {
chromeArguments.push("--headless");
chromeArguments.push(
"--hide-scrollbars",
"--mute-audio",
"--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"
);
}
if (options.chromiumSandbox !== true)
chromeArguments.push("--no-sandbox");
const proxy = options.proxyOverride || options.proxy;
if (proxy) {
const proxyURL = new URL(proxy.server);
const isSocks = proxyURL.protocol === "socks5:";
if (isSocks && !options.socksProxyPort) {
chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`);
}
chromeArguments.push(`--proxy-server=${proxy.server}`);
const proxyBypassRules = [];
if (options.socksProxyPort)
proxyBypassRules.push("<-loopback>");
if (proxy.bypass)
proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t));
if (!process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>"))
proxyBypassRules.push("<-loopback>");
if (proxyBypassRules.length > 0)
chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`);
}
chromeArguments.push(...args);
return chromeArguments;
}
}
const kBidiOverCdpWrapper = Symbol("kBidiConnectionWrapper");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiChromium
});

View File

@@ -0,0 +1,187 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiConnection_exports = {};
__export(bidiConnection_exports, {
BidiConnection: () => BidiConnection,
BidiSession: () => BidiSession,
kBrowserCloseMessageId: () => kBrowserCloseMessageId
});
module.exports = __toCommonJS(bidiConnection_exports);
var import_events = require("events");
var import_debugLogger = require("../utils/debugLogger");
var import_helper = require("../helper");
var import_protocolError = require("../protocolError");
const kBrowserCloseMessageId = 0;
class BidiConnection {
constructor(transport, onDisconnect, protocolLogger, browserLogsCollector) {
this._lastId = 0;
this._closed = false;
this._browsingContextToSession = /* @__PURE__ */ new Map();
this._transport = transport;
this._onDisconnect = onDisconnect;
this._protocolLogger = protocolLogger;
this._browserLogsCollector = browserLogsCollector;
this.browserSession = new BidiSession(this, "", (message) => {
this.rawSend(message);
});
this._transport.onmessage = this._dispatchMessage.bind(this);
this._transport.onclose = this._onClose.bind(this);
}
nextMessageId() {
return ++this._lastId;
}
rawSend(message) {
this._protocolLogger("send", message);
this._transport.send(message);
}
_dispatchMessage(message) {
this._protocolLogger("receive", message);
const object = message;
if (object.type === "event") {
let context;
if ("context" in object.params)
context = object.params.context;
else if (object.method === "log.entryAdded" || object.method === "script.message")
context = object.params.source?.context;
if (context) {
const session = this._browsingContextToSession.get(context);
if (session) {
session.dispatchMessage(message);
return;
}
}
} else if (message.id) {
for (const session of this._browsingContextToSession.values()) {
if (session.hasCallback(message.id)) {
session.dispatchMessage(message);
return;
}
}
}
this.browserSession.dispatchMessage(message);
}
_onClose(reason) {
this._closed = true;
this._transport.onmessage = void 0;
this._transport.onclose = void 0;
this._browserDisconnectedLogs = import_helper.helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason);
this.browserSession.dispose();
this._onDisconnect();
}
isClosed() {
return this._closed;
}
close() {
if (!this._closed)
this._transport.close();
}
createMainFrameBrowsingContextSession(bowsingContextId) {
const result = new BidiSession(this, bowsingContextId, (message) => this.rawSend(message));
this._browsingContextToSession.set(bowsingContextId, result);
return result;
}
}
class BidiSession extends import_events.EventEmitter {
constructor(connection, sessionId, rawSend) {
super();
this._disposed = false;
this._callbacks = /* @__PURE__ */ new Map();
this._crashed = false;
this._browsingContexts = /* @__PURE__ */ new Set();
this.setMaxListeners(0);
this.connection = connection;
this.sessionId = sessionId;
this._rawSend = rawSend;
this.on = super.on;
this.off = super.removeListener;
this.addListener = super.addListener;
this.removeListener = super.removeListener;
this.once = super.once;
}
addFrameBrowsingContext(context) {
this._browsingContexts.add(context);
this.connection._browsingContextToSession.set(context, this);
}
removeFrameBrowsingContext(context) {
this._browsingContexts.delete(context);
this.connection._browsingContextToSession.delete(context);
}
async send(method, params) {
if (this._crashed || this._disposed || this.connection._browserDisconnectedLogs)
throw new import_protocolError.ProtocolError(this._crashed ? "crashed" : "closed", void 0, this.connection._browserDisconnectedLogs);
const id = this.connection.nextMessageId();
const messageObj = { id, method, params };
this._rawSend(messageObj);
return new Promise((resolve, reject) => {
this._callbacks.set(id, { resolve, reject, error: new import_protocolError.ProtocolError("error", method) });
});
}
sendMayFail(method, params) {
return this.send(method, params).catch((error) => import_debugLogger.debugLogger.log("error", error));
}
markAsCrashed() {
this._crashed = true;
}
isDisposed() {
return this._disposed;
}
dispose() {
this._disposed = true;
this.connection._browsingContextToSession.delete(this.sessionId);
for (const context of this._browsingContexts)
this.connection._browsingContextToSession.delete(context);
this._browsingContexts.clear();
for (const callback of this._callbacks.values()) {
callback.error.type = this._crashed ? "crashed" : "closed";
callback.error.logs = this.connection._browserDisconnectedLogs;
callback.reject(callback.error);
}
this._callbacks.clear();
}
hasCallback(id) {
return this._callbacks.has(id);
}
dispatchMessage(message) {
const object = message;
if (object.id === kBrowserCloseMessageId)
return;
if (object.id && this._callbacks.has(object.id)) {
const callback = this._callbacks.get(object.id);
this._callbacks.delete(object.id);
if (object.type === "error") {
callback.error.setMessage(object.error + "\nMessage: " + object.message);
callback.reject(callback.error);
} else if (object.type === "success") {
callback.resolve(object.result);
} else {
callback.error.setMessage("Internal error, unexpected response type: " + JSON.stringify(object));
callback.reject(callback.error);
}
} else if (object.id) {
} else {
Promise.resolve().then(() => this.emit(object.method, object.params));
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiConnection,
BidiSession,
kBrowserCloseMessageId
});

View File

@@ -0,0 +1,221 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiExecutionContext_exports = {};
__export(bidiExecutionContext_exports, {
BidiExecutionContext: () => BidiExecutionContext,
createHandle: () => createHandle
});
module.exports = __toCommonJS(bidiExecutionContext_exports);
var import_utils = require("../../utils");
var import_utilityScriptSerializers = require("../../utils/isomorphic/utilityScriptSerializers");
var js = __toESM(require("../javascript"));
var dom = __toESM(require("../dom"));
var import_bidiDeserializer = require("./third_party/bidiDeserializer");
var bidi = __toESM(require("./third_party/bidiProtocol"));
var import_bidiSerializer = require("./third_party/bidiSerializer");
class BidiExecutionContext {
constructor(session, realmInfo) {
this._session = session;
if (realmInfo.type === "window") {
this._target = {
context: realmInfo.context,
sandbox: realmInfo.sandbox
};
} else {
this._target = {
realm: realmInfo.realm
};
}
}
async rawEvaluateJSON(expression) {
const response = await this._session.send("script.evaluate", {
expression,
target: this._target,
serializationOptions: {
maxObjectDepth: 10,
maxDomDepth: 10
},
awaitPromise: true,
userActivation: true
});
if (response.type === "success")
return import_bidiDeserializer.BidiDeserializer.deserialize(response.result);
if (response.type === "exception")
throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text + "\nFull val: " + JSON.stringify(response.exceptionDetails));
throw new js.JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response));
}
async rawEvaluateHandle(context, expression) {
const response = await this._session.send("script.evaluate", {
expression,
target: this._target,
resultOwnership: bidi.Script.ResultOwnership.Root,
// Necessary for the handle to be returned.
serializationOptions: { maxObjectDepth: 0, maxDomDepth: 0 },
awaitPromise: true,
userActivation: true
});
if (response.type === "success") {
if ("handle" in response.result)
return createHandle(context, response.result);
throw new js.JavaScriptErrorInEvaluate("Cannot get handle: " + JSON.stringify(response.result));
}
if (response.type === "exception")
throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text + "\nFull val: " + JSON.stringify(response.exceptionDetails));
throw new js.JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response));
}
async evaluateWithArguments(functionDeclaration, returnByValue, utilityScript, values, handles) {
const response = await this._session.send("script.callFunction", {
functionDeclaration,
target: this._target,
arguments: [
{ handle: utilityScript._objectId },
...values.map(import_bidiSerializer.BidiSerializer.serialize),
...handles.map((handle) => ({ handle: handle._objectId }))
],
resultOwnership: returnByValue ? void 0 : bidi.Script.ResultOwnership.Root,
// Necessary for the handle to be returned.
serializationOptions: returnByValue ? {} : { maxObjectDepth: 0, maxDomDepth: 0 },
awaitPromise: true,
userActivation: true
});
if (response.type === "exception")
throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text + "\nFull val: " + JSON.stringify(response.exceptionDetails));
if (response.type === "success") {
if (returnByValue)
return (0, import_utilityScriptSerializers.parseEvaluationResultValue)(import_bidiDeserializer.BidiDeserializer.deserialize(response.result));
return createHandle(utilityScript._context, response.result);
}
throw new js.JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response));
}
async getProperties(handle) {
const names = await handle.evaluate((object) => {
const names2 = [];
const descriptors = Object.getOwnPropertyDescriptors(object);
for (const name in descriptors) {
if (descriptors[name]?.enumerable)
names2.push(name);
}
return names2;
});
const values = await Promise.all(names.map((name) => handle.evaluateHandle((object, name2) => object[name2], name)));
const map = /* @__PURE__ */ new Map();
for (let i = 0; i < names.length; i++)
map.set(names[i], values[i]);
return map;
}
async releaseHandle(handle) {
if (!handle._objectId)
return;
await this._session.send("script.disown", {
target: this._target,
handles: [handle._objectId]
});
}
async nodeIdForElementHandle(handle) {
const shared = await this._remoteValueForReference({ handle: handle._objectId });
if (!("sharedId" in shared))
throw new Error("Element is not a node");
return {
sharedId: shared.sharedId
};
}
async remoteObjectForNodeId(context, nodeId) {
const result = await this._remoteValueForReference(nodeId, true);
if (!("handle" in result))
throw new Error("Can't get remote object for nodeId");
return createHandle(context, result);
}
async contentFrameIdForFrame(handle) {
const contentWindow = await this._rawCallFunction("e => e.contentWindow", { handle: handle._objectId });
if (contentWindow?.type === "window")
return contentWindow.value.context;
return null;
}
async frameIdForWindowHandle(handle) {
if (!handle._objectId)
throw new Error("JSHandle is not a DOM node handle");
const contentWindow = await this._remoteValueForReference({ handle: handle._objectId });
if (contentWindow.type === "window")
return contentWindow.value.context;
return null;
}
async _remoteValueForReference(reference, createHandle2) {
return await this._rawCallFunction("e => e", reference, createHandle2);
}
async _rawCallFunction(functionDeclaration, arg, createHandle2) {
const response = await this._session.send("script.callFunction", {
functionDeclaration,
target: this._target,
arguments: [arg],
// "Root" is necessary for the handle to be returned.
resultOwnership: createHandle2 ? bidi.Script.ResultOwnership.Root : bidi.Script.ResultOwnership.None,
serializationOptions: { maxObjectDepth: 0, maxDomDepth: 0 },
awaitPromise: true,
userActivation: true
});
if (response.type === "exception")
throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text + "\nFull val: " + JSON.stringify(response.exceptionDetails));
if (response.type === "success")
return response.result;
throw new js.JavaScriptErrorInEvaluate("Unexpected response type: " + JSON.stringify(response));
}
}
function renderPreview(remoteObject) {
if (remoteObject.type === "undefined")
return "undefined";
if (remoteObject.type === "null")
return "null";
if ("value" in remoteObject)
return String(remoteObject.value);
return `<${remoteObject.type}>`;
}
function remoteObjectValue(remoteObject) {
if (remoteObject.type === "undefined")
return void 0;
if (remoteObject.type === "null")
return null;
if (remoteObject.type === "number" && typeof remoteObject.value === "string")
return js.parseUnserializableValue(remoteObject.value);
if ("value" in remoteObject)
return remoteObject.value;
return void 0;
}
function createHandle(context, remoteObject) {
if (remoteObject.type === "node") {
(0, import_utils.assert)(context instanceof dom.FrameExecutionContext);
return new dom.ElementHandle(context, remoteObject.handle);
}
const objectId = "handle" in remoteObject ? remoteObject.handle : void 0;
return new js.JSHandle(context, remoteObject.type, renderPreview(remoteObject), objectId, remoteObjectValue(remoteObject));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiExecutionContext,
createHandle
});

View File

@@ -0,0 +1,115 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiFirefox_exports = {};
__export(bidiFirefox_exports, {
BidiFirefox: () => BidiFirefox
});
module.exports = __toCommonJS(bidiFirefox_exports);
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var import_ascii = require("../utils/ascii");
var import_browserType = require("../browserType");
var import_bidiBrowser = require("./bidiBrowser");
var import_bidiConnection = require("./bidiConnection");
var import_firefoxPrefs = require("./third_party/firefoxPrefs");
var import_manualPromise = require("../../utils/isomorphic/manualPromise");
class BidiFirefox extends import_browserType.BrowserType {
constructor(parent) {
super(parent, "_bidiFirefox");
}
executablePath() {
return "";
}
async connectToTransport(transport, options) {
return import_bidiBrowser.BidiBrowser.connect(this.attribution.playwright, transport, options);
}
doRewriteStartupLog(error) {
if (!error.logs)
return error;
if (error.logs.includes(`as root in a regular user's session is not supported.`))
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(`Firefox is unable to launch if the $HOME folder isn't owned by the current user.
Workaround: Set the HOME=/root environment variable${process.env.GITHUB_ACTION ? " in your GitHub Actions workflow file" : ""} when running Playwright.`, 1);
if (error.logs.includes("no DISPLAY environment variable specified"))
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);
return error;
}
amendEnvironment(env) {
if (!import_path.default.isAbsolute(import_os.default.homedir()))
throw new Error(`Cannot launch Firefox with relative home directory. Did you set ${import_os.default.platform() === "win32" ? "USERPROFILE" : "HOME"} to a relative path?`);
env = {
...env,
"MOZ_CRASHREPORTER": "1",
"MOZ_CRASHREPORTER_NO_REPORT": "1",
"MOZ_CRASHREPORTER_SHUTDOWN": "1"
};
if (import_os.default.platform() === "linux") {
return { ...env, SNAP_NAME: void 0, SNAP_INSTANCE_NAME: void 0 };
}
return env;
}
attemptToGracefullyCloseBrowser(transport) {
transport.send({ method: "browser.close", params: {}, id: import_bidiConnection.kBrowserCloseMessageId });
}
supportsPipeTransport() {
return false;
}
async prepareUserDataDir(options, userDataDir) {
await (0, import_firefoxPrefs.createProfile)({
path: userDataDir,
preferences: options.firefoxUserPrefs || {}
});
}
defaultArgs(options, isPersistent, userDataDir) {
const { args = [], headless } = options;
const userDataDirArg = args.find((arg) => arg.startsWith("-profile") || arg.startsWith("--profile"));
if (userDataDirArg)
throw this._createUserDataDirArgMisuseError("--profile");
const firefoxArguments = ["--remote-debugging-port=0"];
if (headless)
firefoxArguments.push("--headless");
else
firefoxArguments.push("--foreground");
firefoxArguments.push(`--profile`, userDataDir);
firefoxArguments.push(...args);
return firefoxArguments;
}
async waitForReadyState(options, browserLogsCollector) {
const result = new import_manualPromise.ManualPromise();
browserLogsCollector.onMessage((message) => {
const match = message.match(/WebDriver BiDi listening on (ws:\/\/.*)$/);
if (match)
result.resolve({ wsEndpoint: match[1] + "/session" });
});
return result;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiFirefox
});

View File

@@ -0,0 +1,146 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiInput_exports = {};
__export(bidiInput_exports, {
RawKeyboardImpl: () => RawKeyboardImpl,
RawMouseImpl: () => RawMouseImpl,
RawTouchscreenImpl: () => RawTouchscreenImpl
});
module.exports = __toCommonJS(bidiInput_exports);
var import_input = require("../input");
var import_bidiKeyboard = require("./third_party/bidiKeyboard");
var bidi = __toESM(require("./third_party/bidiProtocol"));
class RawKeyboardImpl {
constructor(session) {
this._session = session;
}
setSession(session) {
this._session = session;
}
async keydown(progress, modifiers, keyName, description, autoRepeat) {
keyName = (0, import_input.resolveSmartModifierString)(keyName);
const actions = [];
actions.push({ type: "keyDown", value: (0, import_bidiKeyboard.getBidiKeyValue)(keyName) });
await this._performActions(progress, actions);
}
async keyup(progress, modifiers, keyName, description) {
keyName = (0, import_input.resolveSmartModifierString)(keyName);
const actions = [];
actions.push({ type: "keyUp", value: (0, import_bidiKeyboard.getBidiKeyValue)(keyName) });
await this._performActions(progress, actions);
}
async sendText(progress, text) {
const actions = [];
for (const char of text) {
const value = (0, import_bidiKeyboard.getBidiKeyValue)(char);
actions.push({ type: "keyDown", value });
actions.push({ type: "keyUp", value });
}
await this._performActions(progress, actions);
}
async _performActions(progress, actions) {
await progress.race(this._session.send("input.performActions", {
context: this._session.sessionId,
actions: [
{
type: "key",
id: "pw_keyboard",
actions
}
]
}));
}
}
class RawMouseImpl {
constructor(session) {
this._session = session;
}
async move(progress, x, y, button, buttons, modifiers, forClick) {
await this._performActions(progress, [{ type: "pointerMove", x, y }]);
}
async down(progress, x, y, button, buttons, modifiers, clickCount) {
await this._performActions(progress, [{ type: "pointerDown", button: toBidiButton(button) }]);
}
async up(progress, x, y, button, buttons, modifiers, clickCount) {
await this._performActions(progress, [{ type: "pointerUp", button: toBidiButton(button) }]);
}
async wheel(progress, x, y, buttons, modifiers, deltaX, deltaY) {
x = Math.floor(x);
y = Math.floor(y);
await progress.race(this._session.send("input.performActions", {
context: this._session.sessionId,
actions: [
{
type: "wheel",
id: "pw_mouse_wheel",
actions: [{ type: "scroll", x, y, deltaX, deltaY }]
}
]
}));
}
async _performActions(progress, actions) {
await progress.race(this._session.send("input.performActions", {
context: this._session.sessionId,
actions: [
{
type: "pointer",
id: "pw_mouse",
parameters: {
pointerType: bidi.Input.PointerType.Mouse
},
actions
}
]
}));
}
}
class RawTouchscreenImpl {
constructor(session) {
this._session = session;
}
async tap(progress, x, y, modifiers) {
}
}
function toBidiButton(button) {
switch (button) {
case "left":
return 0;
case "right":
return 2;
case "middle":
return 1;
}
throw new Error("Unknown button: " + button);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RawKeyboardImpl,
RawMouseImpl,
RawTouchscreenImpl
});

View File

@@ -0,0 +1,317 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiNetworkManager_exports = {};
__export(bidiNetworkManager_exports, {
BidiNetworkManager: () => BidiNetworkManager,
bidiBytesValueToString: () => bidiBytesValueToString
});
module.exports = __toCommonJS(bidiNetworkManager_exports);
var import_eventsHelper = require("../utils/eventsHelper");
var import_cookieStore = require("../cookieStore");
var network = __toESM(require("../network"));
var bidi = __toESM(require("./third_party/bidiProtocol"));
class BidiNetworkManager {
constructor(bidiSession, page) {
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
this._session = bidiSession;
this._requests = /* @__PURE__ */ new Map();
this._page = page;
this._eventListeners = [
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "network.beforeRequestSent", this._onBeforeRequestSent.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "network.responseStarted", this._onResponseStarted.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "network.responseCompleted", this._onResponseCompleted.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "network.fetchError", this._onFetchError.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "network.authRequired", this._onAuthRequired.bind(this))
];
}
dispose() {
import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
}
_onBeforeRequestSent(param) {
if (param.request.url.startsWith("data:"))
return;
const redirectedFrom = param.redirectCount ? this._requests.get(param.request.request) || null : null;
const frame = redirectedFrom ? redirectedFrom.request.frame() : param.context ? this._page.frameManager.frame(param.context) : null;
if (!frame)
return;
if (redirectedFrom)
this._requests.delete(redirectedFrom._id);
let route;
if (param.intercepts) {
if (redirectedFrom) {
let params = {};
if (redirectedFrom._originalRequestRoute?._alreadyContinuedHeaders)
params = toBidiRequestHeaders(redirectedFrom._originalRequestRoute._alreadyContinuedHeaders ?? []);
this._session.sendMayFail("network.continueRequest", {
request: param.request.request,
...params
});
} else {
route = new BidiRouteImpl(this._session, param.request.request);
}
}
const request = new BidiRequest(frame, redirectedFrom, param, route);
this._requests.set(request._id, request);
this._page.frameManager.requestStarted(request.request, route);
}
_onResponseStarted(params) {
const request = this._requests.get(params.request.request);
if (!request)
return;
const getResponseBody = async () => {
throw new Error(`Response body is not available for requests in Bidi`);
};
const timings = params.request.timings;
const startTime = timings.requestTime;
function relativeToStart(time) {
if (!time)
return -1;
return time - startTime;
}
const timing = {
startTime,
requestStart: relativeToStart(timings.requestStart),
responseStart: relativeToStart(timings.responseStart),
domainLookupStart: relativeToStart(timings.dnsStart),
domainLookupEnd: relativeToStart(timings.dnsEnd),
connectStart: relativeToStart(timings.connectStart),
secureConnectionStart: relativeToStart(timings.tlsStart),
connectEnd: relativeToStart(timings.connectEnd)
};
const response = new network.Response(request.request, params.response.status, params.response.statusText, fromBidiHeaders(params.response.headers), timing, getResponseBody, false);
response._serverAddrFinished();
response._securityDetailsFinished();
response.setRawResponseHeaders(null);
response.setResponseHeadersSize(params.response.headersSize);
this._page.frameManager.requestReceivedResponse(response);
}
_onResponseCompleted(params) {
const request = this._requests.get(params.request.request);
if (!request)
return;
const response = request.request._existingResponse();
response.setTransferSize(params.response.bodySize);
response.setEncodedBodySize(params.response.bodySize);
const isRedirected = response.status() >= 300 && response.status() <= 399;
const responseEndTime = params.request.timings.responseEnd - response.timing().startTime;
if (isRedirected) {
response._requestFinished(responseEndTime);
} else {
this._requests.delete(request._id);
response._requestFinished(responseEndTime);
}
response._setHttpVersion(params.response.protocol);
this._page.frameManager.reportRequestFinished(request.request, response);
}
_onFetchError(params) {
const request = this._requests.get(params.request.request);
if (!request)
return;
this._requests.delete(request._id);
const response = request.request._existingResponse();
if (response) {
response.setTransferSize(null);
response.setEncodedBodySize(null);
response._requestFinished(-1);
}
request.request._setFailureText(params.errorText);
this._page.frameManager.requestFailed(request.request, params.errorText === "NS_BINDING_ABORTED");
}
_onAuthRequired(params) {
const isBasic = params.response.authChallenges?.some((challenge) => challenge.scheme.startsWith("Basic"));
const credentials = this._page.browserContext._options.httpCredentials;
if (isBasic && credentials) {
this._session.sendMayFail("network.continueWithAuth", {
request: params.request.request,
action: "provideCredentials",
credentials: {
type: "password",
username: credentials.username,
password: credentials.password
}
});
} else {
this._session.sendMayFail("network.continueWithAuth", {
request: params.request.request,
action: "default"
});
}
}
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async setCredentials(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception(initial) {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
if (initial && !enabled)
return;
const cachePromise = this._session.send("network.setCacheBehavior", { cacheBehavior: enabled ? "bypass" : "default" });
let interceptPromise = Promise.resolve(void 0);
if (enabled) {
interceptPromise = this._session.send("network.addIntercept", {
phases: [bidi.Network.InterceptPhase.AuthRequired, bidi.Network.InterceptPhase.BeforeRequestSent],
urlPatterns: [{ type: "pattern" }]
// urlPatterns: [{ type: 'string', pattern: '*' }],
}).then((r) => {
this._intercepId = r.intercept;
});
} else if (this._intercepId) {
interceptPromise = this._session.send("network.removeIntercept", { intercept: this._intercepId });
this._intercepId = void 0;
}
await Promise.all([cachePromise, interceptPromise]);
}
}
class BidiRequest {
constructor(frame, redirectedFrom, payload, route) {
this._id = payload.request.request;
if (redirectedFrom)
redirectedFrom._redirectedTo = this;
const postDataBuffer = null;
this.request = new network.Request(
frame._page.browserContext,
frame,
null,
redirectedFrom ? redirectedFrom.request : null,
payload.navigation ?? void 0,
payload.request.url,
"other",
payload.request.method,
postDataBuffer,
fromBidiHeaders(payload.request.headers)
);
this.request.setRawRequestHeaders(null);
this.request._setBodySize(payload.request.bodySize || 0);
this._originalRequestRoute = route ?? redirectedFrom?._originalRequestRoute;
route?._setRequest(this.request);
}
_finalRequest() {
let request = this;
while (request._redirectedTo)
request = request._redirectedTo;
return request;
}
}
class BidiRouteImpl {
constructor(session, requestId) {
this._session = session;
this._requestId = requestId;
}
_setRequest(request) {
this._request = request;
}
async continue(overrides) {
let headers = overrides.headers || this._request.headers();
if (overrides.postData && headers) {
headers = headers.map((header) => {
if (header.name.toLowerCase() === "content-length")
return { name: header.name, value: overrides.postData.byteLength.toString() };
return header;
});
}
this._alreadyContinuedHeaders = headers;
await this._session.sendMayFail("network.continueRequest", {
request: this._requestId,
url: overrides.url,
method: overrides.method,
...toBidiRequestHeaders(this._alreadyContinuedHeaders),
body: overrides.postData ? { type: "base64", value: Buffer.from(overrides.postData).toString("base64") } : void 0
});
}
async fulfill(response) {
const base64body = response.isBase64 ? response.body : Buffer.from(response.body).toString("base64");
await this._session.sendMayFail("network.provideResponse", {
request: this._requestId,
statusCode: response.status,
reasonPhrase: network.statusText(response.status),
...toBidiResponseHeaders(response.headers),
body: { type: "base64", value: base64body }
});
}
async abort(errorCode) {
await this._session.sendMayFail("network.failRequest", {
request: this._requestId
});
}
}
function fromBidiHeaders(bidiHeaders) {
const result = [];
for (const { name, value } of bidiHeaders)
result.push({ name, value: bidiBytesValueToString(value) });
return result;
}
function toBidiRequestHeaders(allHeaders) {
const bidiHeaders = toBidiHeaders(allHeaders);
return { headers: bidiHeaders };
}
function toBidiResponseHeaders(headers) {
const setCookieHeaders = headers.filter((h) => h.name.toLowerCase() === "set-cookie");
const otherHeaders = headers.filter((h) => h.name.toLowerCase() !== "set-cookie");
const rawCookies = setCookieHeaders.map((h) => (0, import_cookieStore.parseRawCookie)(h.value));
const cookies = rawCookies.filter(Boolean).map((c) => {
return {
...c,
value: { type: "string", value: c.value },
sameSite: toBidiSameSite(c.sameSite)
};
});
return { cookies, headers: toBidiHeaders(otherHeaders) };
}
function toBidiHeaders(headers) {
return headers.map(({ name, value }) => ({ name, value: { type: "string", value } }));
}
function bidiBytesValueToString(value) {
if (value.type === "string")
return value.value;
if (value.type === "base64")
return Buffer.from(value.type, "base64").toString("binary");
return "unknown value type: " + value.type;
}
function toBidiSameSite(sameSite) {
if (!sameSite)
return void 0;
if (sameSite === "Strict")
return bidi.Network.SameSite.Strict;
if (sameSite === "Lax")
return bidi.Network.SameSite.Lax;
return bidi.Network.SameSite.None;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiNetworkManager,
bidiBytesValueToString
});

View File

@@ -0,0 +1,102 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiOverCdp_exports = {};
__export(bidiOverCdp_exports, {
connectBidiOverCdp: () => connectBidiOverCdp
});
module.exports = __toCommonJS(bidiOverCdp_exports);
var bidiMapper = __toESM(require("chromium-bidi/lib/cjs/bidiMapper/BidiMapper"));
var bidiCdpConnection = __toESM(require("chromium-bidi/lib/cjs/cdp/CdpConnection"));
var import_debugLogger = require("../utils/debugLogger");
const bidiServerLogger = (prefix, ...args) => {
import_debugLogger.debugLogger.log(prefix, args);
};
async function connectBidiOverCdp(cdp) {
let server = void 0;
const bidiTransport = new BidiTransportImpl();
const bidiConnection = new BidiConnection(bidiTransport, () => server?.close());
const cdpTransportImpl = new CdpTransportImpl(cdp);
const cdpConnection = new bidiCdpConnection.MapperCdpConnection(cdpTransportImpl, bidiServerLogger);
cdp.onclose = () => bidiConnection.onclose?.();
server = await bidiMapper.BidiServer.createAndStart(
bidiTransport,
cdpConnection,
await cdpConnection.createBrowserSession(),
/* selfTargetId= */
"",
void 0,
bidiServerLogger
);
return bidiConnection;
}
class BidiTransportImpl {
setOnMessage(handler) {
this._handler = handler;
}
sendMessage(message) {
return this._bidiConnection.onmessage?.(message);
}
close() {
this._bidiConnection.onclose?.();
}
}
class BidiConnection {
constructor(bidiTransport, closeCallback) {
this._bidiTransport = bidiTransport;
this._bidiTransport._bidiConnection = this;
this._closeCallback = closeCallback;
}
send(s) {
this._bidiTransport._handler?.(s);
}
close() {
this._closeCallback();
}
}
class CdpTransportImpl {
constructor(connection) {
this._connection = connection;
this._connection.onmessage = (message) => {
this._handler?.(JSON.stringify(message));
};
}
setOnMessage(handler) {
this._handler = handler;
}
sendMessage(message) {
return this._connection.send(JSON.parse(message));
}
close() {
this._connection.close();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
connectBidiOverCdp
});

View File

@@ -0,0 +1,486 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiPage_exports = {};
__export(bidiPage_exports, {
BidiPage: () => BidiPage,
kPlaywrightBindingChannel: () => kPlaywrightBindingChannel
});
module.exports = __toCommonJS(bidiPage_exports);
var import_eventsHelper = require("../utils/eventsHelper");
var dialog = __toESM(require("../dialog"));
var dom = __toESM(require("../dom"));
var import_page = require("../page");
var import_bidiExecutionContext = require("./bidiExecutionContext");
var import_bidiInput = require("./bidiInput");
var import_bidiNetworkManager = require("./bidiNetworkManager");
var import_bidiPdf = require("./bidiPdf");
var bidi = __toESM(require("./third_party/bidiProtocol"));
const UTILITY_WORLD_NAME = "__playwright_utility_world__";
const kPlaywrightBindingChannel = "playwrightChannel";
class BidiPage {
constructor(browserContext, bidiSession, opener) {
this._sessionListeners = [];
this._initScriptIds = /* @__PURE__ */ new Map();
this._session = bidiSession;
this._opener = opener;
this.rawKeyboard = new import_bidiInput.RawKeyboardImpl(bidiSession);
this.rawMouse = new import_bidiInput.RawMouseImpl(bidiSession);
this.rawTouchscreen = new import_bidiInput.RawTouchscreenImpl(bidiSession);
this._realmToContext = /* @__PURE__ */ new Map();
this._page = new import_page.Page(this, browserContext);
this._browserContext = browserContext;
this._networkManager = new import_bidiNetworkManager.BidiNetworkManager(this._session, this._page);
this._pdf = new import_bidiPdf.BidiPDF(this._session);
this._page.on(import_page.Page.Events.FrameDetached, (frame) => this._removeContextsForFrame(frame, false));
this._sessionListeners = [
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "script.realmCreated", this._onRealmCreated.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "script.message", this._onScriptMessage.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.contextDestroyed", this._onBrowsingContextDestroyed.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.navigationStarted", this._onNavigationStarted.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.navigationCommitted", this._onNavigationCommitted.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.navigationAborted", this._onNavigationAborted.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.navigationFailed", this._onNavigationFailed.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.fragmentNavigated", this._onFragmentNavigated.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.historyUpdated", this._onHistoryUpdated.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.domContentLoaded", this._onDomContentLoaded.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.load", this._onLoad.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "browsingContext.userPromptOpened", this._onUserPromptOpened.bind(this)),
import_eventsHelper.eventsHelper.addEventListener(bidiSession, "log.entryAdded", this._onLogEntryAdded.bind(this))
];
this._initialize().then(
() => this._page.reportAsNew(this._opener?._page),
(error) => this._page.reportAsNew(this._opener?._page, error)
);
}
async _initialize() {
this._onFrameAttached(this._session.sessionId, null);
await Promise.all([
this.updateHttpCredentials(),
this.updateRequestInterception()
// If the page is created by the Playwright client's call, some initialization
// may be pending. Wait for it to complete before reporting the page as new.
]);
}
didClose() {
this._session.dispose();
import_eventsHelper.eventsHelper.removeEventListeners(this._sessionListeners);
this._page._didClose();
}
_onFrameAttached(frameId, parentFrameId) {
return this._page.frameManager.frameAttached(frameId, parentFrameId);
}
_removeContextsForFrame(frame, notifyFrame) {
for (const [contextId, context] of this._realmToContext) {
if (context.frame === frame) {
this._realmToContext.delete(contextId);
if (notifyFrame)
frame._contextDestroyed(context);
}
}
}
_onRealmCreated(realmInfo) {
if (this._realmToContext.has(realmInfo.realm))
return;
if (realmInfo.type !== "window")
return;
const frame = this._page.frameManager.frame(realmInfo.context);
if (!frame)
return;
let worldName;
if (!realmInfo.sandbox) {
worldName = "main";
this._touchUtilityWorld(realmInfo.context);
} else if (realmInfo.sandbox === UTILITY_WORLD_NAME) {
worldName = "utility";
} else {
return;
}
const delegate = new import_bidiExecutionContext.BidiExecutionContext(this._session, realmInfo);
const context = new dom.FrameExecutionContext(delegate, frame, worldName);
frame._contextCreated(worldName, context);
this._realmToContext.set(realmInfo.realm, context);
}
async _touchUtilityWorld(context) {
await this._session.sendMayFail("script.evaluate", {
expression: "1 + 1",
target: {
context,
sandbox: UTILITY_WORLD_NAME
},
serializationOptions: {
maxObjectDepth: 10,
maxDomDepth: 10
},
awaitPromise: true,
userActivation: true
});
}
_onRealmDestroyed(params) {
const context = this._realmToContext.get(params.realm);
if (!context)
return false;
this._realmToContext.delete(params.realm);
context.frame._contextDestroyed(context);
return true;
}
// TODO: route the message directly to the browser
_onBrowsingContextDestroyed(params) {
this._browserContext._browser._onBrowsingContextDestroyed(params);
}
_onNavigationStarted(params) {
const frameId = params.context;
this._page.frameManager.frameRequestedNavigation(frameId, params.navigation);
}
_onNavigationCommitted(params) {
const frameId = params.context;
this._page.frameManager.frameCommittedNewDocumentNavigation(
frameId,
params.url,
"",
params.navigation,
/* initial */
false
);
}
_onDomContentLoaded(params) {
const frameId = params.context;
this._page.frameManager.frameLifecycleEvent(frameId, "domcontentloaded");
}
_onLoad(params) {
this._page.frameManager.frameLifecycleEvent(params.context, "load");
}
_onNavigationAborted(params) {
this._page.frameManager.frameAbortedNavigation(params.context, "Navigation aborted", params.navigation || void 0);
}
_onNavigationFailed(params) {
this._page.frameManager.frameAbortedNavigation(params.context, "Navigation failed", params.navigation || void 0);
}
_onFragmentNavigated(params) {
this._page.frameManager.frameCommittedSameDocumentNavigation(params.context, params.url);
}
_onHistoryUpdated(params) {
this._page.frameManager.frameCommittedSameDocumentNavigation(params.context, params.url);
}
_onUserPromptOpened(event) {
this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
this._page,
event.type,
event.message,
async (accept, userText) => {
await this._session.send("browsingContext.handleUserPrompt", { context: event.context, accept, userText });
},
event.defaultValue
));
}
_onLogEntryAdded(params) {
if (params.type !== "console")
return;
const entry = params;
const context = this._realmToContext.get(params.source.realm);
if (!context)
return;
const callFrame = params.stackTrace?.callFrames[0];
const location = callFrame ?? { url: "", lineNumber: 1, columnNumber: 1 };
this._page.addConsoleMessage(entry.method, entry.args.map((arg) => (0, import_bidiExecutionContext.createHandle)(context, arg)), location, params.text || void 0);
}
async navigateFrame(frame, url, referrer) {
const { navigation } = await this._session.send("browsingContext.navigate", {
context: frame._id,
url
});
return { newDocumentId: navigation || void 0 };
}
async updateExtraHTTPHeaders() {
}
async updateEmulateMedia() {
}
async updateUserAgent() {
}
async bringToFront() {
await this._session.send("browsingContext.activate", {
context: this._session.sessionId
});
}
async updateEmulatedViewportSize() {
const options = this._browserContext._options;
const emulatedSize = this._page.emulatedSize();
if (!emulatedSize)
return;
const viewportSize = emulatedSize.viewport;
await this._session.send("browsingContext.setViewport", {
context: this._session.sessionId,
viewport: {
width: viewportSize.width,
height: viewportSize.height
},
devicePixelRatio: options.deviceScaleFactor || 1
});
}
async updateRequestInterception() {
await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
}
async updateOffline() {
}
async updateHttpCredentials() {
await this._networkManager.setCredentials(this._browserContext._options.httpCredentials);
}
async updateFileChooserInterception() {
}
async reload() {
await this._session.send("browsingContext.reload", {
context: this._session.sessionId,
// ignoreCache: true,
wait: bidi.BrowsingContext.ReadinessState.Interactive
});
}
async goBack() {
return await this._session.send("browsingContext.traverseHistory", {
context: this._session.sessionId,
delta: -1
}).then(() => true).catch(() => false);
}
async goForward() {
return await this._session.send("browsingContext.traverseHistory", {
context: this._session.sessionId,
delta: 1
}).then(() => true).catch(() => false);
}
async requestGC() {
throw new Error("Method not implemented.");
}
async _onScriptMessage(event) {
if (event.channel !== kPlaywrightBindingChannel)
return;
const pageOrError = await this._page.waitForInitializedOrError();
if (pageOrError instanceof Error)
return;
const context = this._realmToContext.get(event.source.realm);
if (!context)
return;
if (event.data.type !== "string")
return;
await this._page.onBindingCalled(event.data.value, context);
}
async addInitScript(initScript) {
const { script } = await this._session.send("script.addPreloadScript", {
// TODO: remove function call from the source.
functionDeclaration: `() => { return ${initScript.source} }`,
// TODO: push to iframes?
contexts: [this._session.sessionId]
});
this._initScriptIds.set(initScript, script);
}
async removeInitScripts(initScripts) {
const ids = [];
for (const script of initScripts) {
const id = this._initScriptIds.get(script);
if (id)
ids.push(id);
this._initScriptIds.delete(script);
}
await Promise.all(ids.map((script) => this._session.send("script.removePreloadScript", { script })));
}
async closePage(runBeforeUnload) {
await this._session.send("browsingContext.close", {
context: this._session.sessionId,
promptUnload: runBeforeUnload
});
}
async setBackgroundColor(color) {
}
async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
const rect = documentRect || viewportRect;
const { data } = await progress.race(this._session.send("browsingContext.captureScreenshot", {
context: this._session.sessionId,
format: {
type: `image/${format === "png" ? "png" : "jpeg"}`,
quality: quality ? quality / 100 : 0.8
},
origin: documentRect ? "document" : "viewport",
clip: {
type: "box",
...rect
}
}));
return Buffer.from(data, "base64");
}
async getContentFrame(handle) {
const executionContext = toBidiExecutionContext(handle._context);
const frameId = await executionContext.contentFrameIdForFrame(handle);
if (!frameId)
return null;
return this._page.frameManager.frame(frameId);
}
async getOwnerFrame(handle) {
const windowHandle = await handle.evaluateHandle((node) => {
const doc = node.ownerDocument ?? node;
return doc.defaultView;
});
if (!windowHandle)
return null;
const executionContext = toBidiExecutionContext(handle._context);
return executionContext.frameIdForWindowHandle(windowHandle);
}
async getBoundingBox(handle) {
const box = await handle.evaluate((element) => {
if (!(element instanceof Element))
return null;
const rect = element.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
});
if (!box)
return null;
const position = await this._framePosition(handle._frame);
if (!position)
return null;
box.x += position.x;
box.y += position.y;
return box;
}
// TODO: move to Frame.
async _framePosition(frame) {
if (frame === this._page.mainFrame())
return { x: 0, y: 0 };
const element = await frame.frameElement();
const box = await element.boundingBox();
if (!box)
return null;
const style = await element.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch((e) => "error:notconnected");
if (style === "error:notconnected" || style === "transformed")
return null;
box.x += style.left;
box.y += style.top;
return box;
}
async scrollRectIntoViewIfNeeded(handle, rect) {
return await handle.evaluateInUtility(([injected, node]) => {
node.scrollIntoView({
block: "center",
inline: "center",
behavior: "instant"
});
}, null).then(() => "done").catch((e) => {
if (e instanceof Error && e.message.includes("Node is detached from document"))
return "error:notconnected";
if (e instanceof Error && e.message.includes("Node does not have a layout object"))
return "error:notvisible";
throw e;
});
}
async setScreencastOptions(options) {
}
rafCountForStablePosition() {
return 1;
}
async getContentQuads(handle) {
const quads = await handle.evaluateInUtility(([injected, node]) => {
if (!node.isConnected)
return "error:notconnected";
const rects = node.getClientRects();
if (!rects)
return null;
return [...rects].map((rect) => [
{ x: rect.left, y: rect.top },
{ x: rect.right, y: rect.top },
{ x: rect.right, y: rect.bottom },
{ x: rect.left, y: rect.bottom }
]);
}, null);
if (!quads || quads === "error:notconnected")
return quads;
const position = await this._framePosition(handle._frame);
if (!position)
return null;
quads.forEach((quad) => quad.forEach((point) => {
point.x += position.x;
point.y += position.y;
}));
return quads;
}
async setInputFilePaths(handle, paths) {
const fromContext = toBidiExecutionContext(handle._context);
await this._session.send("input.setFiles", {
context: this._session.sessionId,
element: await fromContext.nodeIdForElementHandle(handle),
files: paths
});
}
async adoptElementHandle(handle, to) {
const fromContext = toBidiExecutionContext(handle._context);
const nodeId = await fromContext.nodeIdForElementHandle(handle);
const executionContext = toBidiExecutionContext(to);
return await executionContext.remoteObjectForNodeId(to, nodeId);
}
async getAccessibilityTree(needle) {
throw new Error("Method not implemented.");
}
async inputActionEpilogue() {
}
async resetForReuse(progress) {
}
async pdf(options) {
return this._pdf.generate(options);
}
async getFrameElement(frame) {
const parent = frame.parentFrame();
if (!parent)
throw new Error("Frame has been detached.");
const parentContext = await parent._mainContext();
const list = await parentContext.evaluateHandle(() => {
return [...document.querySelectorAll("iframe,frame")];
});
const length = await list.evaluate((list2) => list2.length);
let foundElement = null;
for (let i = 0; i < length; i++) {
const element = await list.evaluateHandle((list2, i2) => list2[i2], i);
const candidate = await element.contentFrame();
if (frame === candidate) {
foundElement = element;
break;
} else {
element.dispose();
}
}
list.dispose();
if (!foundElement)
throw new Error("Frame has been detached.");
return foundElement;
}
shouldToggleStyleSheetToSyncAnimations() {
return true;
}
}
function toBidiExecutionContext(executionContext) {
return executionContext.delegate;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiPage,
kPlaywrightBindingChannel
});

106
node_modules/playwright-core/lib/server/bidi/bidiPdf.js generated vendored Normal file
View File

@@ -0,0 +1,106 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiPdf_exports = {};
__export(bidiPdf_exports, {
BidiPDF: () => BidiPDF
});
module.exports = __toCommonJS(bidiPdf_exports);
var import_utils = require("../../utils");
const PagePaperFormats = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
};
const unitToPixels = {
"px": 1,
"in": 96,
"cm": 37.8,
"mm": 3.78
};
function convertPrintParameterToInches(text) {
if (text === void 0)
return void 0;
let unit = text.substring(text.length - 2).toLowerCase();
let valueText = "";
if (unitToPixels.hasOwnProperty(unit)) {
valueText = text.substring(0, text.length - 2);
} else {
unit = "px";
valueText = text;
}
const value = Number(valueText);
(0, import_utils.assert)(!isNaN(value), "Failed to parse parameter value: " + text);
const pixels = value * unitToPixels[unit];
return pixels / 96;
}
class BidiPDF {
constructor(session) {
this._session = session;
}
async generate(options) {
const {
scale = 1,
printBackground = false,
landscape = false,
pageRanges = "",
margin = {}
} = options;
let paperWidth = 8.5;
let paperHeight = 11;
if (options.format) {
const format = PagePaperFormats[options.format.toLowerCase()];
(0, import_utils.assert)(format, "Unknown paper format: " + options.format);
paperWidth = format.width;
paperHeight = format.height;
} else {
paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
}
const { data } = await this._session.send("browsingContext.print", {
context: this._session.sessionId,
background: printBackground,
margin: {
bottom: convertPrintParameterToInches(margin.bottom) || 0,
left: convertPrintParameterToInches(margin.left) || 0,
right: convertPrintParameterToInches(margin.right) || 0,
top: convertPrintParameterToInches(margin.top) || 0
},
orientation: landscape ? "landscape" : "portrait",
page: {
width: paperWidth,
height: paperHeight
},
pageRanges: pageRanges ? pageRanges.split(",").map((r) => r.trim()) : void 0,
scale
});
return Buffer.from(data, "base64");
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiPDF
});

View File

@@ -0,0 +1,22 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiCommands_d_exports = {};
module.exports = __toCommonJS(bidiCommands_d_exports);
/**
* @license
* Copyright 2024 Google Inc.
* Modifications copyright (c) Microsoft Corporation.
* SPDX-License-Identifier: Apache-2.0
*/

View File

@@ -0,0 +1,98 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiDeserializer_exports = {};
__export(bidiDeserializer_exports, {
BidiDeserializer: () => BidiDeserializer
});
module.exports = __toCommonJS(bidiDeserializer_exports);
/**
* @license
* Copyright 2024 Google Inc.
* Modifications copyright (c) Microsoft Corporation.
* SPDX-License-Identifier: Apache-2.0
*/
class BidiDeserializer {
static deserialize(result) {
if (!result)
return void 0;
switch (result.type) {
case "array":
return result.value?.map((value) => {
return BidiDeserializer.deserialize(value);
});
case "set":
return result.value?.reduce((acc, value) => {
return acc.add(BidiDeserializer.deserialize(value));
}, /* @__PURE__ */ new Set());
case "object":
return result.value?.reduce((acc, tuple) => {
const { key, value } = BidiDeserializer._deserializeTuple(tuple);
acc[key] = value;
return acc;
}, {});
case "map":
return result.value?.reduce((acc, tuple) => {
const { key, value } = BidiDeserializer._deserializeTuple(tuple);
return acc.set(key, value);
}, /* @__PURE__ */ new Map());
case "promise":
return {};
case "regexp":
return new RegExp(result.value.pattern, result.value.flags);
case "date":
return new Date(result.value);
case "undefined":
return void 0;
case "null":
return null;
case "number":
return BidiDeserializer._deserializeNumber(result.value);
case "bigint":
return BigInt(result.value);
case "boolean":
return Boolean(result.value);
case "string":
return result.value;
}
throw new Error(`Deserialization of type ${result.type} not supported.`);
}
static _deserializeNumber(value) {
switch (value) {
case "-0":
return -0;
case "NaN":
return NaN;
case "Infinity":
return Infinity;
case "-Infinity":
return -Infinity;
default:
return value;
}
}
static _deserializeTuple([serializedKey, serializedValue]) {
const key = typeof serializedKey === "string" ? serializedKey : BidiDeserializer.deserialize(serializedKey);
const value = BidiDeserializer.deserialize(serializedValue);
return { key, value };
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiDeserializer
});

View File

@@ -0,0 +1,256 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiKeyboard_exports = {};
__export(bidiKeyboard_exports, {
getBidiKeyValue: () => getBidiKeyValue
});
module.exports = __toCommonJS(bidiKeyboard_exports);
/**
* @license
* Copyright 2024 Google Inc.
* Modifications copyright (c) Microsoft Corporation.
* SPDX-License-Identifier: Apache-2.0
*/
const getBidiKeyValue = (keyName) => {
switch (keyName) {
case "\r":
case "\n":
keyName = "Enter";
break;
}
if ([...keyName].length === 1) {
return keyName;
}
switch (keyName) {
case "Cancel":
return "\uE001";
case "Help":
return "\uE002";
case "Backspace":
return "\uE003";
case "Tab":
return "\uE004";
case "Clear":
return "\uE005";
case "Enter":
return "\uE007";
case "Shift":
case "ShiftLeft":
return "\uE008";
case "Control":
case "ControlLeft":
return "\uE009";
case "Alt":
case "AltLeft":
return "\uE00A";
case "Pause":
return "\uE00B";
case "Escape":
return "\uE00C";
case "PageUp":
return "\uE00E";
case "PageDown":
return "\uE00F";
case "End":
return "\uE010";
case "Home":
return "\uE011";
case "ArrowLeft":
return "\uE012";
case "ArrowUp":
return "\uE013";
case "ArrowRight":
return "\uE014";
case "ArrowDown":
return "\uE015";
case "Insert":
return "\uE016";
case "Delete":
return "\uE017";
case "NumpadEqual":
return "\uE019";
case "Numpad0":
return "\uE01A";
case "Numpad1":
return "\uE01B";
case "Numpad2":
return "\uE01C";
case "Numpad3":
return "\uE01D";
case "Numpad4":
return "\uE01E";
case "Numpad5":
return "\uE01F";
case "Numpad6":
return "\uE020";
case "Numpad7":
return "\uE021";
case "Numpad8":
return "\uE022";
case "Numpad9":
return "\uE023";
case "NumpadMultiply":
return "\uE024";
case "NumpadAdd":
return "\uE025";
case "NumpadSubtract":
return "\uE027";
case "NumpadDecimal":
return "\uE028";
case "NumpadDivide":
return "\uE029";
case "F1":
return "\uE031";
case "F2":
return "\uE032";
case "F3":
return "\uE033";
case "F4":
return "\uE034";
case "F5":
return "\uE035";
case "F6":
return "\uE036";
case "F7":
return "\uE037";
case "F8":
return "\uE038";
case "F9":
return "\uE039";
case "F10":
return "\uE03A";
case "F11":
return "\uE03B";
case "F12":
return "\uE03C";
case "Meta":
case "MetaLeft":
return "\uE03D";
case "ShiftRight":
return "\uE050";
case "ControlRight":
return "\uE051";
case "AltRight":
return "\uE052";
case "MetaRight":
return "\uE053";
case "Space":
return " ";
case "Digit0":
return "0";
case "Digit1":
return "1";
case "Digit2":
return "2";
case "Digit3":
return "3";
case "Digit4":
return "4";
case "Digit5":
return "5";
case "Digit6":
return "6";
case "Digit7":
return "7";
case "Digit8":
return "8";
case "Digit9":
return "9";
case "KeyA":
return "a";
case "KeyB":
return "b";
case "KeyC":
return "c";
case "KeyD":
return "d";
case "KeyE":
return "e";
case "KeyF":
return "f";
case "KeyG":
return "g";
case "KeyH":
return "h";
case "KeyI":
return "i";
case "KeyJ":
return "j";
case "KeyK":
return "k";
case "KeyL":
return "l";
case "KeyM":
return "m";
case "KeyN":
return "n";
case "KeyO":
return "o";
case "KeyP":
return "p";
case "KeyQ":
return "q";
case "KeyR":
return "r";
case "KeyS":
return "s";
case "KeyT":
return "t";
case "KeyU":
return "u";
case "KeyV":
return "v";
case "KeyW":
return "w";
case "KeyX":
return "x";
case "KeyY":
return "y";
case "KeyZ":
return "z";
case "Semicolon":
return ";";
case "Equal":
return "=";
case "Comma":
return ",";
case "Minus":
return "-";
case "Period":
return ".";
case "Slash":
return "/";
case "Backquote":
return "`";
case "BracketLeft":
return "[";
case "Backslash":
return "\\";
case "BracketRight":
return "]";
case "Quote":
return '"';
default:
throw new Error(`Unknown key: "${keyName}"`);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getBidiKeyValue
});

View File

@@ -0,0 +1,24 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiProtocol_exports = {};
module.exports = __toCommonJS(bidiProtocol_exports);
__reExport(bidiProtocol_exports, require("./bidiProtocolCore"), module.exports);
__reExport(bidiProtocol_exports, require("./bidiProtocolPermissions"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
...require("./bidiProtocolCore"),
...require("./bidiProtocolPermissions")
});

View File

@@ -0,0 +1,179 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiProtocolCore_exports = {};
__export(bidiProtocolCore_exports, {
BrowsingContext: () => BrowsingContext,
Emulation: () => Emulation,
ErrorCode: () => ErrorCode,
Input: () => Input,
Log: () => Log,
Network: () => Network,
Script: () => Script,
Session: () => Session
});
module.exports = __toCommonJS(bidiProtocolCore_exports);
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
ErrorCode2["InvalidArgument"] = "invalid argument";
ErrorCode2["InvalidSelector"] = "invalid selector";
ErrorCode2["InvalidSessionId"] = "invalid session id";
ErrorCode2["InvalidWebExtension"] = "invalid web extension";
ErrorCode2["MoveTargetOutOfBounds"] = "move target out of bounds";
ErrorCode2["NoSuchAlert"] = "no such alert";
ErrorCode2["NoSuchNetworkCollector"] = "no such network collector";
ErrorCode2["NoSuchElement"] = "no such element";
ErrorCode2["NoSuchFrame"] = "no such frame";
ErrorCode2["NoSuchHandle"] = "no such handle";
ErrorCode2["NoSuchHistoryEntry"] = "no such history entry";
ErrorCode2["NoSuchIntercept"] = "no such intercept";
ErrorCode2["NoSuchNetworkData"] = "no such network data";
ErrorCode2["NoSuchNode"] = "no such node";
ErrorCode2["NoSuchRequest"] = "no such request";
ErrorCode2["NoSuchScript"] = "no such script";
ErrorCode2["NoSuchStoragePartition"] = "no such storage partition";
ErrorCode2["NoSuchUserContext"] = "no such user context";
ErrorCode2["NoSuchWebExtension"] = "no such web extension";
ErrorCode2["SessionNotCreated"] = "session not created";
ErrorCode2["UnableToCaptureScreen"] = "unable to capture screen";
ErrorCode2["UnableToCloseBrowser"] = "unable to close browser";
ErrorCode2["UnableToSetCookie"] = "unable to set cookie";
ErrorCode2["UnableToSetFileInput"] = "unable to set file input";
ErrorCode2["UnavailableNetworkData"] = "unavailable network data";
ErrorCode2["UnderspecifiedStoragePartition"] = "underspecified storage partition";
ErrorCode2["UnknownCommand"] = "unknown command";
ErrorCode2["UnknownError"] = "unknown error";
ErrorCode2["UnsupportedOperation"] = "unsupported operation";
return ErrorCode2;
})(ErrorCode || {});
var Session;
((Session2) => {
let UserPromptHandlerType;
((UserPromptHandlerType2) => {
UserPromptHandlerType2["Accept"] = "accept";
UserPromptHandlerType2["Dismiss"] = "dismiss";
UserPromptHandlerType2["Ignore"] = "ignore";
})(UserPromptHandlerType = Session2.UserPromptHandlerType || (Session2.UserPromptHandlerType = {}));
})(Session || (Session = {}));
var BrowsingContext;
((BrowsingContext2) => {
let ReadinessState;
((ReadinessState2) => {
ReadinessState2["None"] = "none";
ReadinessState2["Interactive"] = "interactive";
ReadinessState2["Complete"] = "complete";
})(ReadinessState = BrowsingContext2.ReadinessState || (BrowsingContext2.ReadinessState = {}));
})(BrowsingContext || (BrowsingContext = {}));
((BrowsingContext2) => {
let UserPromptType;
((UserPromptType2) => {
UserPromptType2["Alert"] = "alert";
UserPromptType2["Beforeunload"] = "beforeunload";
UserPromptType2["Confirm"] = "confirm";
UserPromptType2["Prompt"] = "prompt";
})(UserPromptType = BrowsingContext2.UserPromptType || (BrowsingContext2.UserPromptType = {}));
})(BrowsingContext || (BrowsingContext = {}));
((BrowsingContext2) => {
let CreateType;
((CreateType2) => {
CreateType2["Tab"] = "tab";
CreateType2["Window"] = "window";
})(CreateType = BrowsingContext2.CreateType || (BrowsingContext2.CreateType = {}));
})(BrowsingContext || (BrowsingContext = {}));
var Emulation;
((Emulation2) => {
let ForcedColorsModeTheme;
((ForcedColorsModeTheme2) => {
ForcedColorsModeTheme2["Light"] = "light";
ForcedColorsModeTheme2["Dark"] = "dark";
})(ForcedColorsModeTheme = Emulation2.ForcedColorsModeTheme || (Emulation2.ForcedColorsModeTheme = {}));
})(Emulation || (Emulation = {}));
((Emulation2) => {
let ScreenOrientationNatural;
((ScreenOrientationNatural2) => {
ScreenOrientationNatural2["Portrait"] = "portrait";
ScreenOrientationNatural2["Landscape"] = "landscape";
})(ScreenOrientationNatural = Emulation2.ScreenOrientationNatural || (Emulation2.ScreenOrientationNatural = {}));
})(Emulation || (Emulation = {}));
var Network;
((Network2) => {
let CollectorType;
((CollectorType2) => {
CollectorType2["Blob"] = "blob";
})(CollectorType = Network2.CollectorType || (Network2.CollectorType = {}));
})(Network || (Network = {}));
((Network2) => {
let SameSite;
((SameSite2) => {
SameSite2["Strict"] = "strict";
SameSite2["Lax"] = "lax";
SameSite2["None"] = "none";
SameSite2["Default"] = "default";
})(SameSite = Network2.SameSite || (Network2.SameSite = {}));
})(Network || (Network = {}));
((Network2) => {
let DataType;
((DataType2) => {
DataType2["Response"] = "response";
})(DataType = Network2.DataType || (Network2.DataType = {}));
})(Network || (Network = {}));
((Network2) => {
let InterceptPhase;
((InterceptPhase2) => {
InterceptPhase2["BeforeRequestSent"] = "beforeRequestSent";
InterceptPhase2["ResponseStarted"] = "responseStarted";
InterceptPhase2["AuthRequired"] = "authRequired";
})(InterceptPhase = Network2.InterceptPhase || (Network2.InterceptPhase = {}));
})(Network || (Network = {}));
var Script;
((Script2) => {
let ResultOwnership;
((ResultOwnership2) => {
ResultOwnership2["Root"] = "root";
ResultOwnership2["None"] = "none";
})(ResultOwnership = Script2.ResultOwnership || (Script2.ResultOwnership = {}));
})(Script || (Script = {}));
var Log;
((Log2) => {
let Level;
((Level2) => {
Level2["Debug"] = "debug";
Level2["Info"] = "info";
Level2["Warn"] = "warn";
Level2["Error"] = "error";
})(Level = Log2.Level || (Log2.Level = {}));
})(Log || (Log = {}));
var Input;
((Input2) => {
let PointerType;
((PointerType2) => {
PointerType2["Mouse"] = "mouse";
PointerType2["Pen"] = "pen";
PointerType2["Touch"] = "touch";
})(PointerType = Input2.PointerType || (Input2.PointerType = {}));
})(Input || (Input = {}));
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowsingContext,
Emulation,
ErrorCode,
Input,
Log,
Network,
Script,
Session
});

View File

@@ -0,0 +1,42 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiProtocolPermissions_exports = {};
__export(bidiProtocolPermissions_exports, {
Permissions: () => Permissions
});
module.exports = __toCommonJS(bidiProtocolPermissions_exports);
/**
* @license
* Copyright 2024 Google Inc.
* Modifications copyright (c) Microsoft Corporation.
* SPDX-License-Identifier: Apache-2.0
*/
var Permissions;
((Permissions2) => {
let PermissionState;
((PermissionState2) => {
PermissionState2["Granted"] = "granted";
PermissionState2["Denied"] = "denied";
PermissionState2["Prompt"] = "prompt";
})(PermissionState = Permissions2.PermissionState || (Permissions2.PermissionState = {}));
})(Permissions || (Permissions = {}));
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Permissions
});

View File

@@ -0,0 +1,148 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var bidiSerializer_exports = {};
__export(bidiSerializer_exports, {
BidiSerializer: () => BidiSerializer,
isDate: () => isDate,
isPlainObject: () => isPlainObject,
isRegExp: () => isRegExp
});
module.exports = __toCommonJS(bidiSerializer_exports);
/**
* @license
* Copyright 2024 Google Inc.
* Modifications copyright (c) Microsoft Corporation.
* SPDX-License-Identifier: Apache-2.0
*/
class UnserializableError extends Error {
}
class BidiSerializer {
static serialize(arg) {
switch (typeof arg) {
case "symbol":
case "function":
throw new UnserializableError(`Unable to serializable ${typeof arg}`);
case "object":
return BidiSerializer._serializeObject(arg);
case "undefined":
return {
type: "undefined"
};
case "number":
return BidiSerializer._serializeNumber(arg);
case "bigint":
return {
type: "bigint",
value: arg.toString()
};
case "string":
return {
type: "string",
value: arg
};
case "boolean":
return {
type: "boolean",
value: arg
};
}
}
static _serializeNumber(arg) {
let value;
if (Object.is(arg, -0)) {
value = "-0";
} else if (Object.is(arg, Infinity)) {
value = "Infinity";
} else if (Object.is(arg, -Infinity)) {
value = "-Infinity";
} else if (Object.is(arg, NaN)) {
value = "NaN";
} else {
value = arg;
}
return {
type: "number",
value
};
}
static _serializeObject(arg) {
if (arg === null) {
return {
type: "null"
};
} else if (Array.isArray(arg)) {
const parsedArray = arg.map((subArg) => {
return BidiSerializer.serialize(subArg);
});
return {
type: "array",
value: parsedArray
};
} else if (isPlainObject(arg)) {
try {
JSON.stringify(arg);
} catch (error) {
if (error instanceof TypeError && error.message.startsWith("Converting circular structure to JSON")) {
error.message += " Recursive objects are not allowed.";
}
throw error;
}
const parsedObject = [];
for (const key in arg) {
parsedObject.push([BidiSerializer.serialize(key), BidiSerializer.serialize(arg[key])]);
}
return {
type: "object",
value: parsedObject
};
} else if (isRegExp(arg)) {
return {
type: "regexp",
value: {
pattern: arg.source,
flags: arg.flags
}
};
} else if (isDate(arg)) {
return {
type: "date",
value: arg.toISOString()
};
}
throw new UnserializableError(
"Custom object serialization not possible. Use plain objects instead."
);
}
}
const isPlainObject = (obj) => {
return typeof obj === "object" && obj?.constructor === Object;
};
const isRegExp = (obj) => {
return typeof obj === "object" && obj?.constructor === RegExp;
};
const isDate = (obj) => {
return typeof obj === "object" && obj?.constructor === Date;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BidiSerializer,
isDate,
isPlainObject,
isRegExp
});

View File

@@ -0,0 +1,259 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var firefoxPrefs_exports = {};
__export(firefoxPrefs_exports, {
createProfile: () => createProfile
});
module.exports = __toCommonJS(firefoxPrefs_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
/**
* @license
* Copyright 2023 Google Inc.
* SPDX-License-Identifier: Apache-2.0
*/
async function createProfile(options) {
if (!import_fs.default.existsSync(options.path)) {
await import_fs.default.promises.mkdir(options.path, {
recursive: true
});
}
await writePreferences({
preferences: {
...defaultProfilePreferences(options.preferences),
...options.preferences
},
path: options.path
});
}
function defaultProfilePreferences(extraPrefs) {
const server = "dummy.test";
const defaultPrefs = {
// Make sure Shield doesn't hit the network.
"app.normandy.api_url": "",
// Disable Firefox old build background check
"app.update.checkInstallTime": false,
// Disable automatically upgrading Firefox
"app.update.disabledForTesting": true,
// Increase the APZ content response timeout to 1 minute
"apz.content_response_timeout": 6e4,
// Prevent various error message on the console
// jest-puppeteer asserts that no error message is emitted by the console
"browser.contentblocking.features.standard": "-tp,tpPrivate,cookieBehavior0,-cm,-fp",
// Enable the dump function: which sends messages to the system
// console
// https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
"browser.dom.window.dump.enabled": true,
// Make sure newtab weather doesn't hit the network to retrieve weather data.
"browser.newtabpage.activity-stream.discoverystream.region-weather-config": "",
// Make sure newtab wallpapers don't hit the network to retrieve wallpaper data.
"browser.newtabpage.activity-stream.newtabWallpapers.enabled": false,
"browser.newtabpage.activity-stream.newtabWallpapers.v2.enabled": false,
// Make sure Topsites doesn't hit the network to retrieve sponsored tiles.
"browser.newtabpage.activity-stream.showSponsoredTopSites": false,
// Disable topstories
"browser.newtabpage.activity-stream.feeds.system.topstories": false,
// Always display a blank page
"browser.newtabpage.enabled": false,
// Background thumbnails in particular cause grief: and disabling
// thumbnails in general cannot hurt
"browser.pagethumbnails.capturing_disabled": true,
// Disable safebrowsing components.
"browser.safebrowsing.blockedURIs.enabled": false,
"browser.safebrowsing.downloads.enabled": false,
"browser.safebrowsing.malware.enabled": false,
"browser.safebrowsing.phishing.enabled": false,
// Disable updates to search engines.
"browser.search.update": false,
// Do not restore the last open set of tabs if the browser has crashed
"browser.sessionstore.resume_from_crash": false,
// Skip check for default browser on startup
"browser.shell.checkDefaultBrowser": false,
// Disable newtabpage
"browser.startup.homepage": "about:blank",
// Do not redirect user when a milstone upgrade of Firefox is detected
"browser.startup.homepage_override.mstone": "ignore",
// Start with a blank page about:blank
"browser.startup.page": 0,
// Do not allow background tabs to be zombified on Android: otherwise for
// tests that open additional tabs: the test harness tab itself might get
// unloaded
"browser.tabs.disableBackgroundZombification": false,
// Do not warn when closing all other open tabs
"browser.tabs.warnOnCloseOtherTabs": false,
// Do not warn when multiple tabs will be opened
"browser.tabs.warnOnOpen": false,
// Do not automatically offer translations, as tests do not expect this.
"browser.translations.automaticallyPopup": false,
// Disable the UI tour.
"browser.uitour.enabled": false,
// Turn off search suggestions in the location bar so as not to trigger
// network connections.
"browser.urlbar.suggest.searches": false,
// Disable first run splash page on Windows 10
"browser.usedOnWindows10.introURL": "",
// Do not warn on quitting Firefox
"browser.warnOnQuit": false,
// Defensively disable data reporting systems
"datareporting.healthreport.documentServerURI": `http://${server}/dummy/healthreport/`,
"datareporting.healthreport.logging.consoleEnabled": false,
"datareporting.healthreport.service.enabled": false,
"datareporting.healthreport.service.firstRun": false,
"datareporting.healthreport.uploadEnabled": false,
// Do not show datareporting policy notifications which can interfere with tests
"datareporting.policy.dataSubmissionEnabled": false,
"datareporting.policy.dataSubmissionPolicyBypassNotification": true,
// DevTools JSONViewer sometimes fails to load dependencies with its require.js.
// This doesn't affect Puppeteer but spams console (Bug 1424372)
"devtools.jsonview.enabled": false,
// Disable popup-blocker
"dom.disable_open_during_load": false,
// Enable the support for File object creation in the content process
// Required for |Page.setFileInputFiles| protocol method.
"dom.file.createInChild": true,
// Disable the ProcessHangMonitor
"dom.ipc.reportProcessHangs": false,
// Disable slow script dialogues
"dom.max_chrome_script_run_time": 0,
"dom.max_script_run_time": 0,
// Disable background timer throttling to allow tests to run in parallel
// without a decrease in performance.
"dom.min_background_timeout_value": 0,
"dom.min_background_timeout_value_without_budget_throttling": 0,
"dom.timeout.enable_budget_timer_throttling": false,
// Disable HTTPS-First upgrades
"dom.security.https_first": false,
// Only load extensions from the application and user profile
// AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
"extensions.autoDisableScopes": 0,
"extensions.enabledScopes": 5,
// Disable metadata caching for installed add-ons by default
"extensions.getAddons.cache.enabled": false,
// Disable installing any distribution extensions or add-ons.
"extensions.installDistroAddons": false,
// Disabled screenshots extension
"extensions.screenshots.disabled": true,
// Turn off extension updates so they do not bother tests
"extensions.update.enabled": false,
// Turn off extension updates so they do not bother tests
"extensions.update.notifyUser": false,
// Make sure opening about:addons will not hit the network
"extensions.webservice.discoverURL": `http://${server}/dummy/discoveryURL`,
// Allow the application to have focus even it runs in the background
"focusmanager.testmode": true,
// Disable useragent updates
"general.useragent.updates.enabled": false,
// Always use network provider for geolocation tests so we bypass the
// macOS dialog raised by the corelocation provider
"geo.provider.testing": true,
// Do not scan Wifi
"geo.wifi.scan": false,
// No hang monitor
"hangmonitor.timeout": 0,
// Show chrome errors and warnings in the error console
"javascript.options.showInConsole": true,
// Do not throttle rendering (requestAnimationFrame) in background tabs
"layout.testing.top-level-always-active": true,
// Disable download and usage of OpenH264: and Widevine plugins
"media.gmp-manager.updateEnabled": false,
// Disable the GFX sanity window
"media.sanity-test.disabled": true,
// Disable connectivity service pings
"network.connectivity-service.enabled": false,
// Disable experimental feature that is only available in Nightly
"network.cookie.sameSite.laxByDefault": false,
// Do not prompt for temporary redirects
"network.http.prompt-temp-redirect": false,
// Disable speculative connections so they are not reported as leaking
// when they are hanging around
"network.http.speculative-parallel-limit": 0,
// Do not automatically switch between offline and online
"network.manage-offline-status": false,
// Make sure SNTP requests do not hit the network
"network.sntp.pools": server,
// Disable Flash.
"plugin.state.flash": 0,
"privacy.trackingprotection.enabled": false,
// Can be removed once Firefox 89 is no longer supported
// https://bugzilla.mozilla.org/show_bug.cgi?id=1710839
"remote.enabled": true,
// Don't do network connections for mitm priming
"security.certerrors.mitm.priming.enabled": false,
// Local documents have access to all other local documents,
// including directory listings
"security.fileuri.strict_origin_policy": false,
// Do not wait for the notification button security delay
"security.notification_enable_delay": 0,
// Do not automatically fill sign-in forms with known usernames and
// passwords
"signon.autofillForms": false,
// Disable password capture, so that tests that include forms are not
// influenced by the presence of the persistent doorhanger notification
"signon.rememberSignons": false,
// Disable first-run welcome page
"startup.homepage_welcome_url": "about:blank",
// Disable first-run welcome page
"startup.homepage_welcome_url.additional": "",
// Disable browser animations (tabs, fullscreen, sliding alerts)
"toolkit.cosmeticAnimations.enabled": false,
// Prevent starting into safe mode after application crashes
"toolkit.startup.max_resumed_crashes": -1
};
return Object.assign(defaultPrefs, extraPrefs);
}
async function writePreferences(options) {
const prefsPath = import_path.default.join(options.path, "prefs.js");
const lines = Object.entries(options.preferences).map(([key, value]) => {
return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
});
const result = await Promise.allSettled([
import_fs.default.promises.writeFile(import_path.default.join(options.path, "user.js"), lines.join("\n")),
// Create a backup of the preferences file if it already exitsts.
import_fs.default.promises.access(prefsPath, import_fs.default.constants.F_OK).then(
async () => {
await import_fs.default.promises.copyFile(
prefsPath,
import_path.default.join(options.path, "prefs.js.playwright")
);
},
// Swallow only if file does not exist
() => {
}
)
]);
for (const command of result) {
if (command.status === "rejected") {
throw command.reason;
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createProfile
});

149
node_modules/playwright-core/lib/server/browser.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browser_exports = {};
__export(browser_exports, {
Browser: () => Browser
});
module.exports = __toCommonJS(browser_exports);
var import_artifact = require("./artifact");
var import_browserContext = require("./browserContext");
var import_download = require("./download");
var import_instrumentation = require("./instrumentation");
var import_page = require("./page");
var import_socksClientCertificatesInterceptor = require("./socksClientCertificatesInterceptor");
class Browser extends import_instrumentation.SdkObject {
constructor(parent, options) {
super(parent, "browser");
this._downloads = /* @__PURE__ */ new Map();
this._defaultContext = null;
this._startedClosing = false;
this._idToVideo = /* @__PURE__ */ new Map();
this._isCollocatedWithServer = true;
this.attribution.browser = this;
this.options = options;
this.instrumentation.onBrowserOpen(this);
}
static {
this.Events = {
Context: "context",
Disconnected: "disconnected"
};
}
sdkLanguage() {
return this.options.sdkLanguage || this.attribution.playwright.options.sdkLanguage;
}
async newContext(progress, options) {
(0, import_browserContext.validateBrowserContextOptions)(options, this.options);
let clientCertificatesProxy;
let context;
try {
if (options.clientCertificates?.length) {
clientCertificatesProxy = await import_socksClientCertificatesInterceptor.ClientCertificatesProxy.create(progress, options);
options = { ...options };
options.proxyOverride = clientCertificatesProxy.proxySettings();
options.internalIgnoreHTTPSErrors = true;
}
context = await progress.race(this.doCreateNewContext(options));
context._clientCertificatesProxy = clientCertificatesProxy;
if (options.__testHookBeforeSetStorageState)
await progress.race(options.__testHookBeforeSetStorageState());
await context.setStorageState(progress, options.storageState, "initial");
this.emit(Browser.Events.Context, context);
return context;
} catch (error) {
await context?.close({ reason: "Failed to create context" }).catch(() => {
});
await clientCertificatesProxy?.close().catch(() => {
});
throw error;
}
}
async newContextForReuse(progress, params) {
const hash = import_browserContext.BrowserContext.reusableContextHash(params);
if (!this._contextForReuse || hash !== this._contextForReuse.hash || !this._contextForReuse.context.canResetForReuse()) {
if (this._contextForReuse)
await this._contextForReuse.context.close({ reason: "Context reused" });
this._contextForReuse = { context: await this.newContext(progress, params), hash };
return this._contextForReuse.context;
}
await this._contextForReuse.context.resetForReuse(progress, params);
return this._contextForReuse.context;
}
contextForReuse() {
return this._contextForReuse?.context;
}
_downloadCreated(page, uuid, url, suggestedFilename) {
const download = new import_download.Download(page, this.options.downloadsPath || "", uuid, url, suggestedFilename);
this._downloads.set(uuid, download);
}
_downloadFilenameSuggested(uuid, suggestedFilename) {
const download = this._downloads.get(uuid);
if (!download)
return;
download._filenameSuggested(suggestedFilename);
}
_downloadFinished(uuid, error) {
const download = this._downloads.get(uuid);
if (!download)
return;
download.artifact.reportFinished(error ? new Error(error) : void 0);
this._downloads.delete(uuid);
}
_videoStarted(context, videoId, path, pageOrError) {
const artifact = new import_artifact.Artifact(context, path);
this._idToVideo.set(videoId, { context, artifact });
pageOrError.then((page) => {
if (page instanceof import_page.Page) {
page.video = artifact;
page.emitOnContext(import_browserContext.BrowserContext.Events.VideoStarted, artifact);
page.emit(import_page.Page.Events.Video, artifact);
}
});
}
_takeVideo(videoId) {
const video = this._idToVideo.get(videoId);
this._idToVideo.delete(videoId);
return video?.artifact;
}
_didClose() {
for (const context of this.contexts())
context._browserClosed();
if (this._defaultContext)
this._defaultContext._browserClosed();
this.emit(Browser.Events.Disconnected);
this.instrumentation.onBrowserClose(this);
}
async close(options) {
if (!this._startedClosing) {
if (options.reason)
this._closeReason = options.reason;
this._startedClosing = true;
await this.options.browserProcess.close();
}
if (this.isConnected())
await new Promise((x) => this.once(Browser.Events.Disconnected, x));
}
async killForTests() {
await this.options.browserProcess.kill();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Browser
});

View File

@@ -0,0 +1,696 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserContext_exports = {};
__export(browserContext_exports, {
BrowserContext: () => BrowserContext,
normalizeProxySettings: () => normalizeProxySettings,
validateBrowserContextOptions: () => validateBrowserContextOptions,
verifyClientCertificates: () => verifyClientCertificates,
verifyGeolocation: () => verifyGeolocation
});
module.exports = __toCommonJS(browserContext_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_crypto = require("./utils/crypto");
var import_debug = require("./utils/debug");
var import_clock = require("./clock");
var import_debugger = require("./debugger");
var import_dialog = require("./dialog");
var import_fetch = require("./fetch");
var import_fileUtils = require("./utils/fileUtils");
var import_stackTrace = require("../utils/isomorphic/stackTrace");
var import_harRecorder = require("./har/harRecorder");
var import_helper = require("./helper");
var import_instrumentation = require("./instrumentation");
var network = __toESM(require("./network"));
var import_page = require("./page");
var import_page2 = require("./page");
var import_recorderApp = require("./recorder/recorderApp");
var import_selectors = require("./selectors");
var import_tracing = require("./trace/recorder/tracing");
var rawStorageSource = __toESM(require("../generated/storageScriptSource"));
class BrowserContext extends import_instrumentation.SdkObject {
constructor(browser, options, browserContextId) {
super(browser, "browser-context");
this._pageBindings = /* @__PURE__ */ new Map();
this.requestInterceptors = [];
this._closedStatus = "open";
this._permissions = /* @__PURE__ */ new Map();
this._downloads = /* @__PURE__ */ new Set();
this._origins = /* @__PURE__ */ new Set();
this._harRecorders = /* @__PURE__ */ new Map();
this._tempDirs = [];
this._creatingStorageStatePage = false;
this.initScripts = [];
this._routesInFlight = /* @__PURE__ */ new Set();
this._playwrightBindingExposed = false;
this.attribution.context = this;
this._browser = browser;
this._options = options;
this._browserContextId = browserContextId;
this._isPersistentContext = !browserContextId;
this._closePromise = new Promise((fulfill) => this._closePromiseFulfill = fulfill);
this._selectors = new import_selectors.Selectors(options.selectorEngines || [], options.testIdAttributeName);
this.fetchRequest = new import_fetch.BrowserContextAPIRequestContext(this);
this.tracing = new import_tracing.Tracing(this, browser.options.tracesDir);
this.clock = new import_clock.Clock(this);
this.dialogManager = new import_dialog.DialogManager(this.instrumentation);
}
static {
this.Events = {
Console: "console",
Close: "close",
Page: "page",
// Can't use just 'error' due to node.js special treatment of error events.
// @see https://nodejs.org/api/events.html#events_error_events
PageError: "pageerror",
Request: "request",
Response: "response",
RequestFailed: "requestfailed",
RequestFinished: "requestfinished",
RequestAborted: "requestaborted",
RequestFulfilled: "requestfulfilled",
RequestContinued: "requestcontinued",
BeforeClose: "beforeclose",
VideoStarted: "videostarted",
RecorderEvent: "recorderevent"
};
}
isPersistentContext() {
return this._isPersistentContext;
}
selectors() {
return this._selectors;
}
async _initialize() {
if (this.attribution.playwright.options.isInternalPlaywright)
return;
this._debugger = new import_debugger.Debugger(this);
if ((0, import_debug.debugMode)() === "inspector")
await import_recorderApp.RecorderApp.show(this, { pauseOnNextStatement: true });
if (this._debugger.isPaused())
import_recorderApp.RecorderApp.showInspectorNoReply(this);
this._debugger.on(import_debugger.Debugger.Events.PausedStateChanged, () => {
if (this._debugger.isPaused())
import_recorderApp.RecorderApp.showInspectorNoReply(this);
});
if ((0, import_debug.debugMode)() === "console") {
await this.extendInjectedScript(`
function installConsoleApi(injectedScript) { injectedScript.consoleApi.install(); }
module.exports = { default: () => installConsoleApi };
`);
}
if (this._options.serviceWorkers === "block")
await this.addInitScript(void 0, `
if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };
`);
if (this._options.permissions)
await this.grantPermissions(this._options.permissions);
}
debugger() {
return this._debugger;
}
async _ensureVideosPath() {
if (this._options.recordVideo)
await (0, import_fileUtils.mkdirIfNeeded)(import_path.default.join(this._options.recordVideo.dir, "dummy"));
}
canResetForReuse() {
if (this._closedStatus !== "open")
return false;
return true;
}
static reusableContextHash(params) {
const paramsCopy = { ...params };
if (paramsCopy.selectorEngines?.length === 0)
delete paramsCopy.selectorEngines;
for (const k of Object.keys(paramsCopy)) {
const key = k;
if (paramsCopy[key] === defaultNewContextParamValues[key])
delete paramsCopy[key];
}
for (const key of paramsThatAllowContextReuse)
delete paramsCopy[key];
return JSON.stringify(paramsCopy);
}
async resetForReuse(progress, params) {
await this.tracing.resetForReuse(progress);
if (params) {
for (const key of paramsThatAllowContextReuse)
this._options[key] = params[key];
if (params.testIdAttributeName)
this.selectors().setTestIdAttributeName(params.testIdAttributeName);
}
let page = this.pages()[0];
const otherPages = this.possiblyUninitializedPages().filter((p) => p !== page);
for (const p of otherPages)
await p.close();
if (page && page.hasCrashed()) {
await page.close();
page = void 0;
}
await page?.mainFrame().gotoImpl(progress, "about:blank", {});
await this.clock.uninstall(progress);
await progress.race(this.setUserAgent(this._options.userAgent));
await progress.race(this.doUpdateDefaultEmulatedMedia());
await progress.race(this.doUpdateDefaultViewport());
await this.setStorageState(progress, this._options.storageState, "resetForReuse");
await page?.resetForReuse(progress);
}
_browserClosed() {
for (const page of this.pages())
page._didClose();
this._didCloseInternal();
}
_didCloseInternal() {
if (this._closedStatus === "closed") {
return;
}
this._clientCertificatesProxy?.close().catch(() => {
});
this.tracing.abort();
if (this._isPersistentContext)
this.onClosePersistent();
this._closePromiseFulfill(new Error("Context closed"));
this.emit(BrowserContext.Events.Close);
}
pages() {
return this.possiblyUninitializedPages().filter((page) => page.initializedOrUndefined());
}
async cookies(urls = []) {
if (urls && !Array.isArray(urls))
urls = [urls];
return await this.doGetCookies(urls);
}
async clearCookies(options) {
const currentCookies = await this.cookies();
await this.doClearCookies();
const matches = (cookie, prop, value) => {
if (!value)
return true;
if (value instanceof RegExp) {
value.lastIndex = 0;
return value.test(cookie[prop]);
}
return cookie[prop] === value;
};
const cookiesToReadd = currentCookies.filter((cookie) => {
return !matches(cookie, "name", options.name) || !matches(cookie, "domain", options.domain) || !matches(cookie, "path", options.path);
});
await this.addCookies(cookiesToReadd);
}
setHTTPCredentials(httpCredentials) {
return this.doSetHTTPCredentials(httpCredentials);
}
getBindingClient(name) {
return this._pageBindings.get(name)?.forClient;
}
async exposePlaywrightBindingIfNeeded() {
if (this._playwrightBindingExposed)
return;
this._playwrightBindingExposed = true;
await this.doExposePlaywrightBinding();
this.bindingsInitScript = import_page2.PageBinding.createInitScript();
this.initScripts.push(this.bindingsInitScript);
await this.doAddInitScript(this.bindingsInitScript);
await this.safeNonStallingEvaluateInAllFrames(this.bindingsInitScript.source, "main");
}
needsPlaywrightBinding() {
return this._playwrightBindingExposed;
}
async exposeBinding(progress, name, needsHandle, playwrightBinding, forClient) {
if (this._pageBindings.has(name))
throw new Error(`Function "${name}" has been already registered`);
for (const page of this.pages()) {
if (page.getBinding(name))
throw new Error(`Function "${name}" has been already registered in one of the pages`);
}
await progress.race(this.exposePlaywrightBindingIfNeeded());
const binding = new import_page2.PageBinding(name, playwrightBinding, needsHandle);
binding.forClient = forClient;
this._pageBindings.set(name, binding);
try {
await progress.race(this.doAddInitScript(binding.initScript));
await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
return binding;
} catch (error) {
this._pageBindings.delete(name);
throw error;
}
}
async removeExposedBindings(bindings) {
bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
for (const binding of bindings)
this._pageBindings.delete(binding.name);
await this.doRemoveInitScripts(bindings.map((binding) => binding.initScript));
const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
`).join("");
await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
}
async grantPermissions(permissions, origin) {
let resolvedOrigin = "*";
if (origin) {
const url = new URL(origin);
resolvedOrigin = url.origin;
}
const existing = new Set(this._permissions.get(resolvedOrigin) || []);
permissions.forEach((p) => existing.add(p));
const list = [...existing.values()];
this._permissions.set(resolvedOrigin, list);
await this.doGrantPermissions(resolvedOrigin, list);
}
async clearPermissions() {
this._permissions.clear();
await this.doClearPermissions();
}
async setExtraHTTPHeaders(progress, headers) {
const oldHeaders = this._options.extraHTTPHeaders;
this._options.extraHTTPHeaders = headers;
try {
await progress.race(this.doUpdateExtraHTTPHeaders());
} catch (error) {
this._options.extraHTTPHeaders = oldHeaders;
this.doUpdateExtraHTTPHeaders().catch(() => {
});
throw error;
}
}
async setOffline(progress, offline) {
const oldOffline = this._options.offline;
this._options.offline = offline;
try {
await progress.race(this.doUpdateOffline());
} catch (error) {
this._options.offline = oldOffline;
this.doUpdateOffline().catch(() => {
});
throw error;
}
}
async _loadDefaultContextAsIs(progress) {
if (!this.possiblyUninitializedPages().length) {
const waitForEvent = import_helper.helper.waitForEvent(progress, this, BrowserContext.Events.Page);
await Promise.race([waitForEvent.promise, this._closePromise]);
}
const page = this.possiblyUninitializedPages()[0];
if (!page)
return;
const pageOrError = await progress.race(page.waitForInitializedOrError());
if (pageOrError instanceof Error)
throw pageOrError;
await page.mainFrame()._waitForLoadState(progress, "load");
return page;
}
async _loadDefaultContext(progress) {
const defaultPage = await this._loadDefaultContextAsIs(progress);
if (!defaultPage)
return;
const browserName = this._browser.options.name;
if (this._options.isMobile && browserName === "chromium" || this._options.locale && browserName === "webkit") {
await this.newPage(progress);
await defaultPage.close();
}
}
_authenticateProxyViaHeader() {
const proxy = this._options.proxy || this._browser.options.proxy || { username: void 0, password: void 0 };
const { username, password } = proxy;
if (username) {
this._options.httpCredentials = { username, password };
const token = Buffer.from(`${username}:${password}`).toString("base64");
this._options.extraHTTPHeaders = network.mergeHeaders([
this._options.extraHTTPHeaders,
network.singleHeader("Proxy-Authorization", `Basic ${token}`)
]);
}
}
_authenticateProxyViaCredentials() {
const proxy = this._options.proxy || this._browser.options.proxy;
if (!proxy)
return;
const { username, password } = proxy;
if (username)
this._options.httpCredentials = { username, password: password || "" };
}
async addInitScript(progress, source) {
const initScript = new import_page.InitScript(source);
this.initScripts.push(initScript);
try {
const promise = this.doAddInitScript(initScript);
if (progress)
await progress.race(promise);
else
await promise;
return initScript;
} catch (error) {
this.removeInitScripts([initScript]).catch(() => {
});
throw error;
}
}
async removeInitScripts(initScripts) {
const set = new Set(initScripts);
this.initScripts = this.initScripts.filter((script) => !set.has(script));
await this.doRemoveInitScripts(initScripts);
}
async addRequestInterceptor(progress, handler) {
this.requestInterceptors.push(handler);
await this.doUpdateRequestInterception();
}
async removeRequestInterceptor(handler) {
const index = this.requestInterceptors.indexOf(handler);
if (index === -1)
return;
this.requestInterceptors.splice(index, 1);
await this.notifyRoutesInFlightAboutRemovedHandler(handler);
await this.doUpdateRequestInterception();
}
isClosingOrClosed() {
return this._closedStatus !== "open";
}
async _deleteAllDownloads() {
await Promise.all(Array.from(this._downloads).map((download) => download.artifact.deleteOnContextClose()));
}
async _deleteAllTempDirs() {
await Promise.all(this._tempDirs.map(async (dir) => await import_fs.default.promises.unlink(dir).catch((e) => {
})));
}
setCustomCloseHandler(handler) {
this._customCloseHandler = handler;
}
async close(options) {
if (this._closedStatus === "open") {
if (options.reason)
this._closeReason = options.reason;
this.emit(BrowserContext.Events.BeforeClose);
this._closedStatus = "closing";
for (const harRecorder of this._harRecorders.values())
await harRecorder.flush();
await this.tracing.flush();
const promises = [];
for (const { context, artifact } of this._browser._idToVideo.values()) {
if (context === this)
promises.push(artifact.finishedPromise());
}
if (this._customCloseHandler) {
await this._customCloseHandler();
} else {
await this.doClose(options.reason);
}
promises.push(this._deleteAllDownloads());
promises.push(this._deleteAllTempDirs());
await Promise.all(promises);
if (!this._customCloseHandler)
this._didCloseInternal();
}
await this._closePromise;
}
async newPage(progress, forStorageState) {
let page;
try {
this._creatingStorageStatePage = !!forStorageState;
page = await progress.race(this.doCreateNewPage());
const pageOrError = await progress.race(page.waitForInitializedOrError());
if (pageOrError instanceof import_page2.Page) {
if (pageOrError.isClosed())
throw new Error("Page has been closed.");
return pageOrError;
}
throw pageOrError;
} catch (error) {
await page?.close({ reason: "Failed to create page" }).catch(() => {
});
throw error;
} finally {
this._creatingStorageStatePage = false;
}
}
addVisitedOrigin(origin) {
this._origins.add(origin);
}
async storageState(progress, indexedDB = false) {
const result = {
cookies: await this.cookies(),
origins: []
};
const originsToSave = new Set(this._origins);
const collectScript = `(() => {
const module = {};
${rawStorageSource.source}
const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"});
return script.collect(${indexedDB});
})()`;
for (const page of this.pages()) {
const origin = page.mainFrame().origin();
if (!origin || !originsToSave.has(origin))
continue;
try {
const storage = await page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, "utility");
if (storage.localStorage.length || storage.indexedDB?.length)
result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
originsToSave.delete(origin);
} catch {
}
}
if (originsToSave.size) {
const page = await this.newPage(
progress,
true
/* forStorageState */
);
try {
await page.addRequestInterceptor(progress, (route) => {
route.fulfill({ body: "<html></html>" }).catch(() => {
});
}, "prepend");
for (const origin of originsToSave) {
const frame = page.mainFrame();
await frame.gotoImpl(progress, origin, {});
const storage = await progress.race(frame.evaluateExpression(collectScript, { world: "utility" }));
if (storage.localStorage.length || storage.indexedDB?.length)
result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
}
} finally {
await page.close();
}
}
return result;
}
isCreatingStorageStatePage() {
return this._creatingStorageStatePage;
}
async setStorageState(progress, state, mode) {
let page;
let interceptor;
try {
if (mode !== "initial") {
await progress.race(this.clearCache());
await progress.race(this.doClearCookies());
}
if (state?.cookies)
await progress.race(this.addCookies(state.cookies));
const newOrigins = new Map(state?.origins?.map((p) => [p.origin, p]) || []);
const allOrigins = /* @__PURE__ */ new Set([...this._origins, ...newOrigins.keys()]);
if (allOrigins.size) {
if (mode === "resetForReuse")
page = this.pages()[0];
if (!page)
page = await this.newPage(
progress,
mode !== "resetForReuse"
/* forStorageState */
);
interceptor = (route) => {
route.fulfill({ body: "<html></html>" }).catch(() => {
});
};
await page.addRequestInterceptor(progress, interceptor, "prepend");
for (const origin of allOrigins) {
const frame = page.mainFrame();
await frame.gotoImpl(progress, origin, {});
const restoreScript = `(() => {
const module = {};
${rawStorageSource.source}
const script = new (module.exports.StorageScript())(${this._browser.options.name === "firefox"});
return script.restore(${JSON.stringify(newOrigins.get(origin))});
})()`;
await progress.race(frame.evaluateExpression(restoreScript, { world: "utility" }));
}
}
this._origins = /* @__PURE__ */ new Set([...newOrigins.keys()]);
} catch (error) {
(0, import_stackTrace.rewriteErrorMessage)(error, `Error setting storage state:
` + error.message);
throw error;
} finally {
if (mode !== "resetForReuse")
await page?.close();
else if (interceptor)
await page?.removeRequestInterceptor(interceptor);
}
}
async extendInjectedScript(source, arg) {
const installInFrame = (frame) => frame.extendInjectedScript(source, arg).catch(() => {
});
const installInPage = (page) => {
page.on(import_page2.Page.Events.InternalFrameNavigatedToNewDocument, installInFrame);
return Promise.all(page.frames().map(installInFrame));
};
this.on(BrowserContext.Events.Page, installInPage);
return Promise.all(this.pages().map(installInPage));
}
async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
await Promise.all(this.pages().map((page) => page.safeNonStallingEvaluateInAllFrames(expression, world, options)));
}
harStart(page, options) {
const harId = (0, import_crypto.createGuid)();
this._harRecorders.set(harId, new import_harRecorder.HarRecorder(this, page, options));
return harId;
}
async harExport(harId) {
const recorder = this._harRecorders.get(harId || "");
return recorder.export();
}
addRouteInFlight(route) {
this._routesInFlight.add(route);
}
removeRouteInFlight(route) {
this._routesInFlight.delete(route);
}
async notifyRoutesInFlightAboutRemovedHandler(handler) {
await Promise.all([...this._routesInFlight].map((route) => route.removeHandler(handler)));
}
}
function validateBrowserContextOptions(options, browserOptions) {
if (options.noDefaultViewport && options.deviceScaleFactor !== void 0)
throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);
if (options.noDefaultViewport && !!options.isMobile)
throw new Error(`"isMobile" option is not supported with null "viewport"`);
if (options.acceptDownloads === void 0 && browserOptions.name !== "electron")
options.acceptDownloads = "accept";
else if (options.acceptDownloads === void 0 && browserOptions.name === "electron")
options.acceptDownloads = "internal-browser-default";
if (!options.viewport && !options.noDefaultViewport)
options.viewport = { width: 1280, height: 720 };
if (options.recordVideo) {
if (!options.recordVideo.size) {
if (options.noDefaultViewport) {
options.recordVideo.size = { width: 800, height: 600 };
} else {
const size = options.viewport;
const scale = Math.min(1, 800 / Math.max(size.width, size.height));
options.recordVideo.size = {
width: Math.floor(size.width * scale),
height: Math.floor(size.height * scale)
};
}
}
options.recordVideo.size.width &= ~1;
options.recordVideo.size.height &= ~1;
}
if (options.proxy)
options.proxy = normalizeProxySettings(options.proxy);
verifyGeolocation(options.geolocation);
}
function verifyGeolocation(geolocation) {
if (!geolocation)
return;
geolocation.accuracy = geolocation.accuracy || 0;
const { longitude, latitude, accuracy } = geolocation;
if (longitude < -180 || longitude > 180)
throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);
if (latitude < -90 || latitude > 90)
throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);
if (accuracy < 0)
throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);
}
function verifyClientCertificates(clientCertificates) {
if (!clientCertificates)
return;
for (const cert of clientCertificates) {
if (!cert.origin)
throw new Error(`clientCertificates.origin is required`);
if (!cert.cert && !cert.key && !cert.passphrase && !cert.pfx)
throw new Error("None of cert, key, passphrase or pfx is specified");
if (cert.cert && !cert.key)
throw new Error("cert is specified without key");
if (!cert.cert && cert.key)
throw new Error("key is specified without cert");
if (cert.pfx && (cert.cert || cert.key))
throw new Error("pfx is specified together with cert, key or passphrase");
}
}
function normalizeProxySettings(proxy) {
let { server, bypass } = proxy;
let url;
try {
url = new URL(server);
if (!url.host || !url.protocol)
url = new URL("http://" + server);
} catch (e) {
url = new URL("http://" + server);
}
if (url.protocol === "socks4:" && (proxy.username || proxy.password))
throw new Error(`Socks4 proxy protocol does not support authentication`);
if (url.protocol === "socks5:" && (proxy.username || proxy.password))
throw new Error(`Browser does not support socks5 proxy authentication`);
server = url.protocol + "//" + url.host;
if (bypass)
bypass = bypass.split(",").map((t) => t.trim()).join(",");
return { ...proxy, server, bypass };
}
const paramsThatAllowContextReuse = [
"colorScheme",
"forcedColors",
"reducedMotion",
"contrast",
"screen",
"userAgent",
"viewport",
"testIdAttributeName"
];
const defaultNewContextParamValues = {
noDefaultViewport: false,
ignoreHTTPSErrors: false,
javaScriptEnabled: true,
bypassCSP: false,
offline: false,
isMobile: false,
hasTouch: false,
acceptDownloads: "accept",
strictSelectors: false,
serviceWorkers: "allow",
locale: "en-US"
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserContext,
normalizeProxySettings,
validateBrowserContextOptions,
verifyClientCertificates,
verifyGeolocation
});

328
node_modules/playwright-core/lib/server/browserType.js generated vendored Normal file
View File

@@ -0,0 +1,328 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var browserType_exports = {};
__export(browserType_exports, {
BrowserType: () => BrowserType,
kNoXServerRunningError: () => kNoXServerRunningError
});
module.exports = __toCommonJS(browserType_exports);
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var import_browserContext = require("./browserContext");
var import_debug = require("./utils/debug");
var import_assert = require("../utils/isomorphic/assert");
var import_manualPromise = require("../utils/isomorphic/manualPromise");
var import_time = require("../utils/isomorphic/time");
var import_fileUtils = require("./utils/fileUtils");
var import_helper = require("./helper");
var import_instrumentation = require("./instrumentation");
var import_pipeTransport = require("./pipeTransport");
var import_processLauncher = require("./utils/processLauncher");
var import_protocolError = require("./protocolError");
var import_registry = require("./registry");
var import_socksClientCertificatesInterceptor = require("./socksClientCertificatesInterceptor");
var import_transport = require("./transport");
var import_debugLogger = require("./utils/debugLogger");
const kNoXServerRunningError = "Looks like you launched a headed browser without having a XServer running.\nSet either 'headless: true' or use 'xvfb-run <your-playwright-app>' before running Playwright.\n\n<3 Playwright Team";
class BrowserType extends import_instrumentation.SdkObject {
constructor(parent, browserName) {
super(parent, "browser-type");
this.attribution.browserType = this;
this._name = browserName;
this.logName = "browser";
}
executablePath() {
return import_registry.registry.findExecutable(this._name).executablePath(this.attribution.playwright.options.sdkLanguage) || "";
}
name() {
return this._name;
}
async launch(progress, options, protocolLogger) {
options = this._validateLaunchOptions(options);
const seleniumHubUrl = options.__testHookSeleniumRemoteURL || process.env.SELENIUM_REMOTE_URL;
if (seleniumHubUrl)
return this._launchWithSeleniumHub(progress, seleniumHubUrl, options);
return this._innerLaunchWithRetries(progress, options, void 0, import_helper.helper.debugProtocolLogger(protocolLogger)).catch((e) => {
throw this._rewriteStartupLog(e);
});
}
async launchPersistentContext(progress, userDataDir, options) {
const launchOptions = this._validateLaunchOptions(options);
let clientCertificatesProxy;
if (options.clientCertificates?.length) {
clientCertificatesProxy = await import_socksClientCertificatesInterceptor.ClientCertificatesProxy.create(progress, options);
launchOptions.proxyOverride = clientCertificatesProxy.proxySettings();
options = { ...options };
options.internalIgnoreHTTPSErrors = true;
}
try {
const browser = await this._innerLaunchWithRetries(progress, launchOptions, options, import_helper.helper.debugProtocolLogger(), userDataDir).catch((e) => {
throw this._rewriteStartupLog(e);
});
browser._defaultContext._clientCertificatesProxy = clientCertificatesProxy;
return browser._defaultContext;
} catch (error) {
await clientCertificatesProxy?.close().catch(() => {
});
throw error;
}
}
async _innerLaunchWithRetries(progress, options, persistent, protocolLogger, userDataDir) {
try {
return await this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);
} catch (error) {
const errorMessage = typeof error === "object" && typeof error.message === "string" ? error.message : "";
if (errorMessage.includes("Inconsistency detected by ld.so")) {
progress.log(`<restarting browser due to hitting race condition in glibc>`);
return this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);
}
throw error;
}
}
async _innerLaunch(progress, options, persistent, protocolLogger, maybeUserDataDir) {
options.proxy = options.proxy ? (0, import_browserContext.normalizeProxySettings)(options.proxy) : void 0;
const browserLogsCollector = new import_debugLogger.RecentLogsCollector();
const { browserProcess, userDataDir, artifactsDir, transport } = await this._launchProcess(progress, options, !!persistent, browserLogsCollector, maybeUserDataDir);
try {
if (options.__testHookBeforeCreateBrowser)
await progress.race(options.__testHookBeforeCreateBrowser());
const browserOptions = {
name: this._name,
isChromium: this._name === "chromium",
channel: options.channel,
slowMo: options.slowMo,
persistent,
headful: !options.headless,
artifactsDir,
downloadsPath: options.downloadsPath || artifactsDir,
tracesDir: options.tracesDir || artifactsDir,
browserProcess,
customExecutablePath: options.executablePath,
proxy: options.proxy,
protocolLogger,
browserLogsCollector,
wsEndpoint: transport instanceof import_transport.WebSocketTransport ? transport.wsEndpoint : void 0,
originalLaunchOptions: options
};
if (persistent)
(0, import_browserContext.validateBrowserContextOptions)(persistent, browserOptions);
copyTestHooks(options, browserOptions);
const browser = await progress.race(this.connectToTransport(transport, browserOptions, browserLogsCollector));
browser._userDataDirForTest = userDataDir;
if (persistent && !options.ignoreAllDefaultArgs)
await browser._defaultContext._loadDefaultContext(progress);
return browser;
} catch (error) {
await browserProcess.close().catch(() => {
});
throw error;
}
}
async _prepareToLaunch(options, isPersistent, userDataDir) {
const {
ignoreDefaultArgs,
ignoreAllDefaultArgs,
args = [],
executablePath = null
} = options;
await this._createArtifactDirs(options);
const tempDirectories = [];
const artifactsDir = await import_fs.default.promises.mkdtemp(import_path.default.join(import_os.default.tmpdir(), "playwright-artifacts-"));
tempDirectories.push(artifactsDir);
if (userDataDir) {
(0, import_assert.assert)(import_path.default.isAbsolute(userDataDir), "userDataDir must be an absolute path");
if (!await (0, import_fileUtils.existsAsync)(userDataDir))
await import_fs.default.promises.mkdir(userDataDir, { recursive: true, mode: 448 });
} else {
userDataDir = await import_fs.default.promises.mkdtemp(import_path.default.join(import_os.default.tmpdir(), `playwright_${this._name}dev_profile-`));
tempDirectories.push(userDataDir);
}
await this.prepareUserDataDir(options, userDataDir);
const browserArguments = [];
if (ignoreAllDefaultArgs)
browserArguments.push(...args);
else if (ignoreDefaultArgs)
browserArguments.push(...this.defaultArgs(options, isPersistent, userDataDir).filter((arg) => ignoreDefaultArgs.indexOf(arg) === -1));
else
browserArguments.push(...this.defaultArgs(options, isPersistent, userDataDir));
let executable;
if (executablePath) {
if (!await (0, import_fileUtils.existsAsync)(executablePath))
throw new Error(`Failed to launch ${this._name} because executable doesn't exist at ${executablePath}`);
executable = executablePath;
} else {
const registryExecutable = import_registry.registry.findExecutable(this.getExecutableName(options));
if (!registryExecutable || registryExecutable.browserName !== this._name)
throw new Error(`Unsupported ${this._name} channel "${options.channel}"`);
executable = registryExecutable.executablePathOrDie(this.attribution.playwright.options.sdkLanguage);
await import_registry.registry.validateHostRequirementsForExecutablesIfNeeded([registryExecutable], this.attribution.playwright.options.sdkLanguage);
}
return { executable, browserArguments, userDataDir, artifactsDir, tempDirectories };
}
async _launchProcess(progress, options, isPersistent, browserLogsCollector, userDataDir) {
const {
handleSIGINT = true,
handleSIGTERM = true,
handleSIGHUP = true
} = options;
const env = options.env ? (0, import_processLauncher.envArrayToObject)(options.env) : process.env;
const prepared = await progress.race(this._prepareToLaunch(options, isPersistent, userDataDir));
let transport = void 0;
let browserProcess = void 0;
const exitPromise = new import_manualPromise.ManualPromise();
const { launchedProcess, gracefullyClose, kill } = await (0, import_processLauncher.launchProcess)({
command: prepared.executable,
args: prepared.browserArguments,
env: this.amendEnvironment(env, prepared.userDataDir, isPersistent),
handleSIGINT,
handleSIGTERM,
handleSIGHUP,
log: (message) => {
progress.log(message);
browserLogsCollector.log(message);
},
stdio: "pipe",
tempDirectories: prepared.tempDirectories,
attemptToGracefullyClose: async () => {
if (options.__testHookGracefullyClose)
await options.__testHookGracefullyClose();
if (transport) {
this.attemptToGracefullyCloseBrowser(transport);
} else {
throw new Error("Force-killing the browser because no transport is available to gracefully close it.");
}
},
onExit: (exitCode, signal) => {
exitPromise.resolve();
if (browserProcess && browserProcess.onclose)
browserProcess.onclose(exitCode, signal);
}
});
async function closeOrKill(timeout) {
let timer;
try {
await Promise.race([
gracefullyClose(),
new Promise((resolve, reject) => timer = setTimeout(reject, timeout))
]);
} catch (ignored) {
await kill().catch((ignored2) => {
});
} finally {
clearTimeout(timer);
}
}
browserProcess = {
onclose: void 0,
process: launchedProcess,
close: () => closeOrKill(options.__testHookBrowserCloseTimeout || import_time.DEFAULT_PLAYWRIGHT_TIMEOUT),
kill
};
try {
const { wsEndpoint } = await progress.race([
this.waitForReadyState(options, browserLogsCollector),
exitPromise.then(() => ({ wsEndpoint: void 0 }))
]);
if (options.cdpPort !== void 0 || !this.supportsPipeTransport()) {
transport = await import_transport.WebSocketTransport.connect(progress, wsEndpoint);
} else {
const stdio = launchedProcess.stdio;
transport = new import_pipeTransport.PipeTransport(stdio[3], stdio[4]);
}
return { browserProcess, artifactsDir: prepared.artifactsDir, userDataDir: prepared.userDataDir, transport };
} catch (error) {
await closeOrKill(import_time.DEFAULT_PLAYWRIGHT_TIMEOUT).catch(() => {
});
throw error;
}
}
async _createArtifactDirs(options) {
if (options.downloadsPath)
await import_fs.default.promises.mkdir(options.downloadsPath, { recursive: true });
if (options.tracesDir)
await import_fs.default.promises.mkdir(options.tracesDir, { recursive: true });
}
async connectOverCDP(progress, endpointURL, options) {
throw new Error("CDP connections are only supported by Chromium");
}
async _launchWithSeleniumHub(progress, hubUrl, options) {
throw new Error("Connecting to SELENIUM_REMOTE_URL is only supported by Chromium");
}
_validateLaunchOptions(options) {
const { devtools = false } = options;
let { headless = !devtools, downloadsPath, proxy } = options;
if ((0, import_debug.debugMode)() === "inspector")
headless = false;
if (downloadsPath && !import_path.default.isAbsolute(downloadsPath))
downloadsPath = import_path.default.join(process.cwd(), downloadsPath);
if (options.socksProxyPort)
proxy = { server: `socks5://127.0.0.1:${options.socksProxyPort}` };
return { ...options, devtools, headless, downloadsPath, proxy };
}
_createUserDataDirArgMisuseError(userDataDirArg) {
switch (this.attribution.playwright.options.sdkLanguage) {
case "java":
return new Error(`Pass userDataDir parameter to 'BrowserType.launchPersistentContext(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`);
case "python":
return new Error(`Pass user_data_dir parameter to 'browser_type.launch_persistent_context(user_data_dir, **kwargs)' instead of specifying '${userDataDirArg}' argument`);
case "csharp":
return new Error(`Pass userDataDir parameter to 'BrowserType.LaunchPersistentContextAsync(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`);
default:
return new Error(`Pass userDataDir parameter to 'browserType.launchPersistentContext(userDataDir, options)' instead of specifying '${userDataDirArg}' argument`);
}
}
_rewriteStartupLog(error) {
if (!(0, import_protocolError.isProtocolError)(error))
return error;
return this.doRewriteStartupLog(error);
}
async waitForReadyState(options, browserLogsCollector) {
return {};
}
async prepareUserDataDir(options, userDataDir) {
}
supportsPipeTransport() {
return true;
}
getExecutableName(options) {
return options.channel || this._name;
}
}
function copyTestHooks(from, to) {
for (const [key, value] of Object.entries(from)) {
if (key.startsWith("__testHook"))
to[key] = value;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BrowserType,
kNoXServerRunningError
});

82
node_modules/playwright-core/lib/server/callLog.js generated vendored Normal file
View File

@@ -0,0 +1,82 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var callLog_exports = {};
__export(callLog_exports, {
compressCallLog: () => compressCallLog,
findRepeatedSubsequencesForTest: () => findRepeatedSubsequencesForTest
});
module.exports = __toCommonJS(callLog_exports);
function compressCallLog(log) {
const lines = [];
for (const block of findRepeatedSubsequences(log)) {
for (let i = 0; i < block.sequence.length; i++) {
const line = block.sequence[i];
const leadingWhitespace = line.match(/^\s*/);
const whitespacePrefix = " " + leadingWhitespace?.[0] || "";
const countPrefix = `${block.count} \xD7 `;
if (block.count > 1 && i === 0)
lines.push(whitespacePrefix + countPrefix + line.trim());
else if (block.count > 1)
lines.push(whitespacePrefix + " ".repeat(countPrefix.length - 2) + "- " + line.trim());
else
lines.push(whitespacePrefix + "- " + line.trim());
}
}
return lines;
}
function findRepeatedSubsequences(s) {
const n = s.length;
const result = [];
let i = 0;
const arraysEqual = (a1, a2) => {
if (a1.length !== a2.length)
return false;
for (let j = 0; j < a1.length; j++) {
if (a1[j] !== a2[j])
return false;
}
return true;
};
while (i < n) {
let maxRepeatCount = 1;
let maxRepeatSubstr = [s[i]];
let maxRepeatLength = 1;
for (let p = 1; p <= n - i; p++) {
const substr = s.slice(i, i + p);
let k = 1;
while (i + p * k <= n && arraysEqual(s.slice(i + p * (k - 1), i + p * k), substr))
k += 1;
k -= 1;
if (k > 1 && k * p > maxRepeatCount * maxRepeatLength) {
maxRepeatCount = k;
maxRepeatSubstr = substr;
maxRepeatLength = p;
}
}
result.push({ sequence: maxRepeatSubstr, count: maxRepeatCount });
i += maxRepeatLength * maxRepeatCount;
}
return result;
}
const findRepeatedSubsequencesForTest = findRepeatedSubsequences;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
compressCallLog,
findRepeatedSubsequencesForTest
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,391 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chromium_exports = {};
__export(chromium_exports, {
Chromium: () => Chromium,
waitForReadyState: () => waitForReadyState
});
module.exports = __toCommonJS(chromium_exports);
var import_fs = __toESM(require("fs"));
var import_os = __toESM(require("os"));
var import_path = __toESM(require("path"));
var import_chromiumSwitches = require("./chromiumSwitches");
var import_crBrowser = require("./crBrowser");
var import_crConnection = require("./crConnection");
var import_utils = require("../../utils");
var import_ascii = require("../utils/ascii");
var import_debugLogger = require("../utils/debugLogger");
var import_manualPromise = require("../../utils/isomorphic/manualPromise");
var import_network = require("../utils/network");
var import_userAgent = require("../utils/userAgent");
var import_browserContext = require("../browserContext");
var import_browserType = require("../browserType");
var import_helper = require("../helper");
var import_registry = require("../registry");
var import_transport = require("../transport");
var import_crDevTools = require("./crDevTools");
var import_browser = require("../browser");
var import_fileUtils = require("../utils/fileUtils");
var import_processLauncher = require("../utils/processLauncher");
const ARTIFACTS_FOLDER = import_path.default.join(import_os.default.tmpdir(), "playwright-artifacts-");
class Chromium extends import_browserType.BrowserType {
constructor(parent) {
super(parent, "chromium");
if ((0, import_utils.debugMode)() === "inspector")
this._devtools = this._createDevTools();
}
async connectOverCDP(progress, endpointURL, options) {
return await this._connectOverCDPInternal(progress, endpointURL, options);
}
async _connectOverCDPInternal(progress, endpointURL, options, onClose) {
let headersMap;
if (options.headers)
headersMap = (0, import_utils.headersArrayToObject)(options.headers, false);
if (!headersMap)
headersMap = { "User-Agent": (0, import_userAgent.getUserAgent)() };
else if (headersMap && !Object.keys(headersMap).some((key) => key.toLowerCase() === "user-agent"))
headersMap["User-Agent"] = (0, import_userAgent.getUserAgent)();
const artifactsDir = await progress.race(import_fs.default.promises.mkdtemp(ARTIFACTS_FOLDER));
const doCleanup = async () => {
await (0, import_fileUtils.removeFolders)([artifactsDir]);
const cb = onClose;
onClose = void 0;
await cb?.();
};
let chromeTransport;
const doClose = async () => {
await chromeTransport?.closeAndWait();
await doCleanup();
};
try {
const wsEndpoint = await urlToWSEndpoint(progress, endpointURL, headersMap);
chromeTransport = await import_transport.WebSocketTransport.connect(progress, wsEndpoint, { headers: headersMap });
const browserProcess = { close: doClose, kill: doClose };
const persistent = { noDefaultViewport: true };
const browserOptions = {
slowMo: options.slowMo,
name: "chromium",
isChromium: true,
persistent,
browserProcess,
protocolLogger: import_helper.helper.debugProtocolLogger(),
browserLogsCollector: new import_debugLogger.RecentLogsCollector(),
artifactsDir,
downloadsPath: options.downloadsPath || artifactsDir,
tracesDir: options.tracesDir || artifactsDir,
originalLaunchOptions: {}
};
(0, import_browserContext.validateBrowserContextOptions)(persistent, browserOptions);
const browser = await progress.race(import_crBrowser.CRBrowser.connect(this.attribution.playwright, chromeTransport, browserOptions));
browser._isCollocatedWithServer = false;
browser.on(import_browser.Browser.Events.Disconnected, doCleanup);
return browser;
} catch (error) {
await doClose().catch(() => {
});
throw error;
}
}
_createDevTools() {
const directory = import_registry.registry.findExecutable("chromium").directory;
return directory ? new import_crDevTools.CRDevTools(import_path.default.join(directory, "devtools-preferences.json")) : void 0;
}
async connectToTransport(transport, options, browserLogsCollector) {
let devtools = this._devtools;
if (options.__testHookForDevTools) {
devtools = this._createDevTools();
await options.__testHookForDevTools(devtools);
}
try {
return await import_crBrowser.CRBrowser.connect(this.attribution.playwright, transport, options, devtools);
} catch (e) {
if (browserLogsCollector.recentLogs().some((log) => log.includes("Failed to create a ProcessSingleton for your profile directory."))) {
throw new Error(
"Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."
);
}
throw e;
}
}
doRewriteStartupLog(error) {
if (!error.logs)
return error;
if (error.logs.includes("Missing X server"))
error.logs = "\n" + (0, import_ascii.wrapInASCIIBox)(import_browserType.kNoXServerRunningError, 1);
if (!error.logs.includes("crbug.com/357670") && !error.logs.includes("No usable sandbox!") && !error.logs.includes("crbug.com/638180"))
return error;
error.logs = [
`Chromium sandboxing failed!`,
`================================`,
`To avoid the sandboxing issue, do either of the following:`,
` - (preferred): Configure your environment to support sandboxing`,
` - (alternative): Launch Chromium without sandbox using 'chromiumSandbox: false' option`,
`================================`,
``
].join("\n");
return error;
}
amendEnvironment(env) {
return env;
}
attemptToGracefullyCloseBrowser(transport) {
const message = { method: "Browser.close", id: import_crConnection.kBrowserCloseMessageId, params: {} };
transport.send(message);
}
async _launchWithSeleniumHub(progress, hubUrl, options) {
await progress.race(this._createArtifactDirs(options));
if (!hubUrl.endsWith("/"))
hubUrl = hubUrl + "/";
const args = this._innerDefaultArgs(options);
args.push("--remote-debugging-port=0");
const isEdge = options.channel && options.channel.startsWith("msedge");
let desiredCapabilities = {
"browserName": isEdge ? "MicrosoftEdge" : "chrome",
[isEdge ? "ms:edgeOptions" : "goog:chromeOptions"]: { args }
};
if (process.env.SELENIUM_REMOTE_CAPABILITIES) {
const remoteCapabilities = parseSeleniumRemoteParams({ name: "capabilities", value: process.env.SELENIUM_REMOTE_CAPABILITIES }, progress);
if (remoteCapabilities)
desiredCapabilities = { ...desiredCapabilities, ...remoteCapabilities };
}
let headers = {};
if (process.env.SELENIUM_REMOTE_HEADERS) {
const remoteHeaders = parseSeleniumRemoteParams({ name: "headers", value: process.env.SELENIUM_REMOTE_HEADERS }, progress);
if (remoteHeaders)
headers = remoteHeaders;
}
progress.log(`<selenium> connecting to ${hubUrl}`);
const response = await (0, import_network.fetchData)(progress, {
url: hubUrl + "session",
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
...headers
},
data: JSON.stringify({
capabilities: { alwaysMatch: desiredCapabilities }
})
}, seleniumErrorHandler);
const value = JSON.parse(response).value;
const sessionId = value.sessionId;
progress.log(`<selenium> connected to sessionId=${sessionId}`);
const disconnectFromSelenium = async () => {
progress.log(`<selenium> disconnecting from sessionId=${sessionId}`);
await (0, import_network.fetchData)(void 0, {
url: hubUrl + "session/" + sessionId,
method: "DELETE",
headers
}).catch((error) => progress.log(`<error disconnecting from selenium>: ${error}`));
progress.log(`<selenium> disconnected from sessionId=${sessionId}`);
import_processLauncher.gracefullyCloseSet.delete(disconnectFromSelenium);
};
import_processLauncher.gracefullyCloseSet.add(disconnectFromSelenium);
try {
const capabilities = value.capabilities;
let endpointURL;
if (capabilities["se:cdp"]) {
progress.log(`<selenium> using selenium v4`);
const endpointURLString = addProtocol(capabilities["se:cdp"]);
endpointURL = new URL(endpointURLString);
if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1")
endpointURL.hostname = new URL(hubUrl).hostname;
progress.log(`<selenium> retrieved endpoint ${endpointURL.toString()} for sessionId=${sessionId}`);
} else {
progress.log(`<selenium> using selenium v3`);
const maybeChromeOptions = capabilities["goog:chromeOptions"];
const chromeOptions = maybeChromeOptions && typeof maybeChromeOptions === "object" ? maybeChromeOptions : void 0;
const debuggerAddress = chromeOptions && typeof chromeOptions.debuggerAddress === "string" ? chromeOptions.debuggerAddress : void 0;
const chromeOptionsURL = typeof maybeChromeOptions === "string" ? maybeChromeOptions : void 0;
const endpointURLString = addProtocol(debuggerAddress || chromeOptionsURL).replace("localhost", "127.0.0.1");
progress.log(`<selenium> retrieved endpoint ${endpointURLString} for sessionId=${sessionId}`);
endpointURL = new URL(endpointURLString);
if (endpointURL.hostname === "localhost" || endpointURL.hostname === "127.0.0.1") {
const sessionInfoUrl = new URL(hubUrl).origin + "/grid/api/testsession?session=" + sessionId;
try {
const sessionResponse = await (0, import_network.fetchData)(progress, {
url: sessionInfoUrl,
method: "GET",
headers
}, seleniumErrorHandler);
const proxyId = JSON.parse(sessionResponse).proxyId;
endpointURL.hostname = new URL(proxyId).hostname;
progress.log(`<selenium> resolved endpoint ip ${endpointURL.toString()} for sessionId=${sessionId}`);
} catch (e) {
progress.log(`<selenium> unable to resolve endpoint ip for sessionId=${sessionId}, running in standalone?`);
}
}
}
return await this._connectOverCDPInternal(progress, endpointURL.toString(), {
...options,
headers: (0, import_utils.headersObjectToArray)(headers)
}, disconnectFromSelenium);
} catch (e) {
await disconnectFromSelenium();
throw e;
}
}
defaultArgs(options, isPersistent, userDataDir) {
const chromeArguments = this._innerDefaultArgs(options);
chromeArguments.push(`--user-data-dir=${userDataDir}`);
if (options.cdpPort !== void 0)
chromeArguments.push(`--remote-debugging-port=${options.cdpPort}`);
else
chromeArguments.push("--remote-debugging-pipe");
if (isPersistent)
chromeArguments.push("about:blank");
else
chromeArguments.push("--no-startup-window");
return chromeArguments;
}
_innerDefaultArgs(options) {
const { args = [] } = options;
const userDataDirArg = args.find((arg) => arg.startsWith("--user-data-dir"));
if (userDataDirArg)
throw this._createUserDataDirArgMisuseError("--user-data-dir");
if (args.find((arg) => arg.startsWith("--remote-debugging-pipe")))
throw new Error("Playwright manages remote debugging connection itself.");
if (args.find((arg) => !arg.startsWith("-")))
throw new Error("Arguments can not specify page to be opened");
const chromeArguments = [...(0, import_chromiumSwitches.chromiumSwitches)(options.assistantMode, options.channel)];
if (import_os.default.platform() === "darwin") {
chromeArguments.push("--enable-unsafe-swiftshader");
}
if (options.devtools)
chromeArguments.push("--auto-open-devtools-for-tabs");
if (options.headless) {
chromeArguments.push("--headless");
chromeArguments.push(
"--hide-scrollbars",
"--mute-audio",
"--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"
);
}
if (options.chromiumSandbox !== true)
chromeArguments.push("--no-sandbox");
const proxy = options.proxyOverride || options.proxy;
if (proxy) {
const proxyURL = new URL(proxy.server);
const isSocks = proxyURL.protocol === "socks5:";
if (isSocks && !options.socksProxyPort) {
chromeArguments.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${proxyURL.hostname}"`);
}
chromeArguments.push(`--proxy-server=${proxy.server}`);
const proxyBypassRules = [];
if (options.socksProxyPort)
proxyBypassRules.push("<-loopback>");
if (proxy.bypass)
proxyBypassRules.push(...proxy.bypass.split(",").map((t) => t.trim()).map((t) => t.startsWith(".") ? "*" + t : t));
if (!process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK && !proxyBypassRules.includes("<-loopback>"))
proxyBypassRules.push("<-loopback>");
if (proxyBypassRules.length > 0)
chromeArguments.push(`--proxy-bypass-list=${proxyBypassRules.join(";")}`);
}
chromeArguments.push(...args);
return chromeArguments;
}
async waitForReadyState(options, browserLogsCollector) {
return waitForReadyState(options, browserLogsCollector);
}
getExecutableName(options) {
if (options.channel)
return options.channel;
return options.headless ? "chromium-headless-shell" : "chromium";
}
}
async function waitForReadyState(options, browserLogsCollector) {
if (options.cdpPort === void 0 && !options.args?.some((a) => a.startsWith("--remote-debugging-port")))
return {};
const result = new import_manualPromise.ManualPromise();
browserLogsCollector.onMessage((message) => {
if (message.includes("Failed to create a ProcessSingleton for your profile directory.")) {
result.reject(new Error("Failed to create a ProcessSingleton for your profile directory. This usually means that the profile is already in use by another instance of Chromium."));
}
const match = message.match(/DevTools listening on (.*)/);
if (match)
result.resolve({ wsEndpoint: match[1] });
});
return result;
}
async function urlToWSEndpoint(progress, endpointURL, headers) {
if (endpointURL.startsWith("ws"))
return endpointURL;
progress.log(`<ws preparing> retrieving websocket url from ${endpointURL}`);
const url = new URL(endpointURL);
if (!url.pathname.endsWith("/"))
url.pathname += "/";
url.pathname += "json/version/";
const httpURL = url.toString();
const json = await (0, import_network.fetchData)(
progress,
{
url: httpURL,
headers
},
async (_, resp) => new Error(`Unexpected status ${resp.statusCode} when connecting to ${httpURL}.
This does not look like a DevTools server, try connecting via ws://.`)
);
return JSON.parse(json).webSocketDebuggerUrl;
}
async function seleniumErrorHandler(params, response) {
const body = await streamToString(response);
let message = body;
try {
const json = JSON.parse(body);
message = json.value.localizedMessage || json.value.message;
} catch (e) {
}
return new Error(`Error connecting to Selenium at ${params.url}: ${message}`);
}
function addProtocol(url) {
if (!["ws://", "wss://", "http://", "https://"].some((protocol) => url.startsWith(protocol)))
return "http://" + url;
return url;
}
function streamToString(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
stream.on("error", reject);
stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
}
function parseSeleniumRemoteParams(env, progress) {
try {
const parsed = JSON.parse(env.value);
progress.log(`<selenium> using additional ${env.name} "${env.value}"`);
return parsed;
} catch (e) {
progress.log(`<selenium> ignoring additional ${env.name} "${env.value}": ${e}`);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Chromium,
waitForReadyState
});

View File

@@ -0,0 +1,93 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chromiumSwitches_exports = {};
__export(chromiumSwitches_exports, {
chromiumSwitches: () => chromiumSwitches
});
module.exports = __toCommonJS(chromiumSwitches_exports);
const disabledFeatures = (assistantMode) => [
// See https://github.com/microsoft/playwright/pull/10380
"AcceptCHFrame",
// See https://github.com/microsoft/playwright/issues/14047
"AvoidUnnecessaryBeforeUnloadCheckSync",
"DestroyProfileOnBrowserClose",
// See https://github.com/microsoft/playwright/pull/13854
"DialMediaRouteProvider",
"GlobalMediaControls",
// See https://github.com/microsoft/playwright/pull/27605
"HttpsUpgrades",
// Hides the Lens feature in the URL address bar. Its not working in unofficial builds.
"LensOverlay",
// See https://github.com/microsoft/playwright/pull/8162
"MediaRouter",
// See https://github.com/microsoft/playwright/issues/28023
"PaintHolding",
// See https://github.com/microsoft/playwright/issues/32230
"ThirdPartyStoragePartitioning",
// See https://github.com/microsoft/playwright/issues/16126
"Translate",
// See https://issues.chromium.org/u/1/issues/435410220
"AutoDeElevate",
assistantMode ? "AutomationControlled" : ""
].filter(Boolean);
const chromiumSwitches = (assistantMode, channel) => [
"--disable-field-trial-config",
// https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md
"--disable-background-networking",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-back-forward-cache",
// Avoids surprises like main request not being intercepted during page.goBack().
"--disable-breakpad",
"--disable-client-side-phishing-detection",
"--disable-component-extensions-with-background-pages",
"--disable-component-update",
// Avoids unneeded network activity after startup.
"--no-default-browser-check",
"--disable-default-apps",
"--disable-dev-shm-usage",
"--disable-extensions",
"--disable-features=" + disabledFeatures(assistantMode).join(","),
channel === "chromium-tip-of-tree" ? "--enable-features=CDPScreenshotNewSurface" : "",
"--allow-pre-commit-input",
"--disable-hang-monitor",
"--disable-ipc-flooding-protection",
"--disable-popup-blocking",
"--disable-prompt-on-repost",
"--disable-renderer-backgrounding",
"--force-color-profile=srgb",
"--metrics-recording-only",
"--no-first-run",
"--password-store=basic",
"--use-mock-keychain",
// See https://chromium-review.googlesource.com/c/chromium/src/+/2436773
"--no-service-autorun",
"--export-tagged-pdf",
// https://chromium-review.googlesource.com/c/chromium/src/+/4853540
"--disable-search-engine-choice-screen",
// https://issues.chromium.org/41491762
"--unsafely-disable-devtools-self-xss-warnings",
// Edge can potentially restart on Windows (msRelaunchNoCompatLayer) which looses its file descriptors (stdout/stderr) and CDP (3/4). Disable until fixed upstream.
"--edge-skip-compat-layer-relaunch",
assistantMode ? "" : "--enable-automation"
].filter(Boolean);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
chromiumSwitches
});

View File

@@ -0,0 +1,263 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var crAccessibility_exports = {};
__export(crAccessibility_exports, {
getAccessibilityTree: () => getAccessibilityTree
});
module.exports = __toCommonJS(crAccessibility_exports);
async function getAccessibilityTree(client, needle) {
const { nodes } = await client.send("Accessibility.getFullAXTree");
const tree = CRAXNode.createTree(client, nodes);
return {
tree,
needle: needle ? await tree._findElement(needle) : null
};
}
class CRAXNode {
constructor(client, payload) {
this._children = [];
this._richlyEditable = false;
this._editable = false;
this._focusable = false;
this._expanded = false;
this._hidden = false;
this._client = client;
this._payload = payload;
this._name = this._payload.name ? this._payload.name.value : "";
this._role = this._payload.role ? this._payload.role.value : "Unknown";
for (const property of this._payload.properties || []) {
if (property.name === "editable") {
this._richlyEditable = property.value.value === "richtext";
this._editable = true;
}
if (property.name === "focusable")
this._focusable = property.value.value;
if (property.name === "expanded")
this._expanded = property.value.value;
if (property.name === "hidden")
this._hidden = property.value.value;
}
}
_isPlainTextField() {
if (this._richlyEditable)
return false;
if (this._editable)
return true;
return this._role === "textbox" || this._role === "ComboBox" || this._role === "searchbox";
}
_isTextOnlyObject() {
const role = this._role;
return role === "LineBreak" || role === "text" || role === "InlineTextBox" || role === "StaticText";
}
_hasFocusableChild() {
if (this._cachedHasFocusableChild === void 0) {
this._cachedHasFocusableChild = false;
for (const child of this._children) {
if (child._focusable || child._hasFocusableChild()) {
this._cachedHasFocusableChild = true;
break;
}
}
}
return this._cachedHasFocusableChild;
}
children() {
return this._children;
}
async _findElement(element) {
const objectId = element._objectId;
const { node: { backendNodeId } } = await this._client.send("DOM.describeNode", { objectId });
const needle = this.find((node) => node._payload.backendDOMNodeId === backendNodeId);
return needle || null;
}
find(predicate) {
if (predicate(this))
return this;
for (const child of this._children) {
const result = child.find(predicate);
if (result)
return result;
}
return null;
}
isLeafNode() {
if (!this._children.length)
return true;
if (this._isPlainTextField() || this._isTextOnlyObject())
return true;
switch (this._role) {
case "doc-cover":
case "graphics-symbol":
case "img":
case "Meter":
case "scrollbar":
case "slider":
case "separator":
case "progressbar":
return true;
default:
break;
}
if (this._hasFocusableChild())
return false;
if (this._focusable && this._role !== "WebArea" && this._role !== "RootWebArea" && this._name)
return true;
if (this._role === "heading" && this._name)
return true;
return false;
}
isControl() {
switch (this._role) {
case "button":
case "checkbox":
case "ColorWell":
case "combobox":
case "DisclosureTriangle":
case "listbox":
case "menu":
case "menubar":
case "menuitem":
case "menuitemcheckbox":
case "menuitemradio":
case "radio":
case "scrollbar":
case "searchbox":
case "slider":
case "spinbutton":
case "switch":
case "tab":
case "textbox":
case "tree":
return true;
default:
return false;
}
}
isInteresting(insideControl) {
const role = this._role;
if (role === "Ignored" || this._hidden)
return false;
if (this._focusable || this._richlyEditable)
return true;
if (this.isControl())
return true;
if (insideControl)
return false;
return this.isLeafNode() && !!this._name;
}
normalizedRole() {
switch (this._role) {
case "RootWebArea":
return "WebArea";
case "StaticText":
return "text";
default:
return this._role;
}
}
serialize() {
const properties = /* @__PURE__ */ new Map();
for (const property of this._payload.properties || [])
properties.set(property.name.toLowerCase(), property.value.value);
if (this._payload.description)
properties.set("description", this._payload.description.value);
const node = {
role: this.normalizedRole(),
name: this._payload.name ? this._payload.name.value || "" : ""
};
const userStringProperties = [
"description",
"keyshortcuts",
"roledescription",
"valuetext"
];
for (const userStringProperty of userStringProperties) {
if (!properties.has(userStringProperty))
continue;
node[userStringProperty] = properties.get(userStringProperty);
}
const booleanProperties = [
"disabled",
"expanded",
"focused",
"modal",
"multiline",
"multiselectable",
"readonly",
"required",
"selected"
];
for (const booleanProperty of booleanProperties) {
if (booleanProperty === "focused" && (this._role === "WebArea" || this._role === "RootWebArea"))
continue;
const value = properties.get(booleanProperty);
if (!value)
continue;
node[booleanProperty] = value;
}
const numericalProperties = [
"level",
"valuemax",
"valuemin"
];
for (const numericalProperty of numericalProperties) {
if (!properties.has(numericalProperty))
continue;
node[numericalProperty] = properties.get(numericalProperty);
}
const tokenProperties = [
"autocomplete",
"haspopup",
"invalid",
"orientation"
];
for (const tokenProperty of tokenProperties) {
const value = properties.get(tokenProperty);
if (!value || value === "false")
continue;
node[tokenProperty] = value;
}
const axNode = node;
if (this._payload.value) {
if (typeof this._payload.value.value === "string")
axNode.valueString = this._payload.value.value;
if (typeof this._payload.value.value === "number")
axNode.valueNumber = this._payload.value.value;
}
if (properties.has("checked"))
axNode.checked = properties.get("checked") === "true" ? "checked" : properties.get("checked") === "false" ? "unchecked" : "mixed";
if (properties.has("pressed"))
axNode.pressed = properties.get("pressed") === "true" ? "pressed" : properties.get("pressed") === "false" ? "released" : "mixed";
return axNode;
}
static createTree(client, payloads) {
const nodeById = /* @__PURE__ */ new Map();
for (const payload of payloads)
nodeById.set(payload.nodeId, new CRAXNode(client, payload));
for (const node of nodeById.values()) {
for (const childId of node._payload.childIds || [])
node._children.push(nodeById.get(childId));
}
return nodeById.values().next().value;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getAccessibilityTree
});

View File

@@ -0,0 +1,532 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var crBrowser_exports = {};
__export(crBrowser_exports, {
CRBrowser: () => CRBrowser,
CRBrowserContext: () => CRBrowserContext
});
module.exports = __toCommonJS(crBrowser_exports);
var import_path = __toESM(require("path"));
var import_assert = require("../../utils/isomorphic/assert");
var import_crypto = require("../utils/crypto");
var import_artifact = require("../artifact");
var import_browser = require("../browser");
var import_browserContext = require("../browserContext");
var import_frames = require("../frames");
var network = __toESM(require("../network"));
var import_page = require("../page");
var import_crConnection = require("./crConnection");
var import_crPage = require("./crPage");
var import_crProtocolHelper = require("./crProtocolHelper");
var import_crServiceWorker = require("./crServiceWorker");
class CRBrowser extends import_browser.Browser {
constructor(parent, connection, options) {
super(parent, options);
this._clientRootSessionPromise = null;
this._contexts = /* @__PURE__ */ new Map();
this._crPages = /* @__PURE__ */ new Map();
this._backgroundPages = /* @__PURE__ */ new Map();
this._serviceWorkers = /* @__PURE__ */ new Map();
this._version = "";
this._tracingRecording = false;
this._userAgent = "";
this._connection = connection;
this._session = this._connection.rootSession;
this._connection.on(import_crConnection.ConnectionEvents.Disconnected, () => this._didDisconnect());
this._session.on("Target.attachedToTarget", this._onAttachedToTarget.bind(this));
this._session.on("Target.detachedFromTarget", this._onDetachedFromTarget.bind(this));
this._session.on("Browser.downloadWillBegin", this._onDownloadWillBegin.bind(this));
this._session.on("Browser.downloadProgress", this._onDownloadProgress.bind(this));
}
static async connect(parent, transport, options, devtools) {
options = { ...options };
const connection = new import_crConnection.CRConnection(parent, transport, options.protocolLogger, options.browserLogsCollector);
const browser = new CRBrowser(parent, connection, options);
browser._devtools = devtools;
if (browser.isClank())
browser._isCollocatedWithServer = false;
const session = connection.rootSession;
if (options.__testHookOnConnectToBrowser)
await options.__testHookOnConnectToBrowser();
const version = await session.send("Browser.getVersion");
browser._version = version.product.substring(version.product.indexOf("/") + 1);
browser._userAgent = version.userAgent;
browser.options.headful = !version.userAgent.includes("Headless");
if (!options.persistent) {
await session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
return browser;
}
browser._defaultContext = new CRBrowserContext(browser, void 0, options.persistent);
await Promise.all([
session.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }).then(async () => {
await session.send("Target.getTargetInfo");
}),
browser._defaultContext._initialize()
]);
await browser._waitForAllPagesToBeInitialized();
return browser;
}
async doCreateNewContext(options) {
const proxy = options.proxyOverride || options.proxy;
let proxyBypassList = void 0;
if (proxy) {
if (process.env.PLAYWRIGHT_DISABLE_FORCED_CHROMIUM_PROXIED_LOOPBACK)
proxyBypassList = proxy.bypass;
else
proxyBypassList = "<-loopback>" + (proxy.bypass ? `,${proxy.bypass}` : "");
}
const { browserContextId } = await this._session.send("Target.createBrowserContext", {
disposeOnDetach: true,
proxyServer: proxy ? proxy.server : void 0,
proxyBypassList
});
const context = new CRBrowserContext(this, browserContextId, options);
await context._initialize();
this._contexts.set(browserContextId, context);
return context;
}
contexts() {
return Array.from(this._contexts.values());
}
version() {
return this._version;
}
userAgent() {
return this._userAgent;
}
_platform() {
if (this._userAgent.includes("Windows"))
return "win";
if (this._userAgent.includes("Macintosh"))
return "mac";
return "linux";
}
isClank() {
return this.options.name === "clank";
}
async _waitForAllPagesToBeInitialized() {
await Promise.all([...this._crPages.values()].map((crPage) => crPage._page.waitForInitializedOrError()));
}
_onAttachedToTarget({ targetInfo, sessionId }) {
if (targetInfo.type === "browser")
return;
const session = this._session.createChildSession(sessionId);
(0, import_assert.assert)(targetInfo.browserContextId, "targetInfo: " + JSON.stringify(targetInfo, null, 2));
let context = this._contexts.get(targetInfo.browserContextId) || null;
if (!context) {
context = this._defaultContext;
}
if (targetInfo.type === "other" && targetInfo.url.startsWith("devtools://devtools") && this._devtools) {
this._devtools.install(session);
return;
}
const treatOtherAsPage = targetInfo.type === "other" && process.env.PW_CHROMIUM_ATTACH_TO_OTHER;
if (!context || targetInfo.type === "other" && !treatOtherAsPage) {
session.detach().catch(() => {
});
return;
}
(0, import_assert.assert)(!this._crPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
(0, import_assert.assert)(!this._backgroundPages.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
(0, import_assert.assert)(!this._serviceWorkers.has(targetInfo.targetId), "Duplicate target " + targetInfo.targetId);
if (targetInfo.type === "background_page") {
const backgroundPage = new import_crPage.CRPage(session, targetInfo.targetId, context, null, { hasUIWindow: false, isBackgroundPage: true });
this._backgroundPages.set(targetInfo.targetId, backgroundPage);
return;
}
if (targetInfo.type === "page" || treatOtherAsPage) {
const opener = targetInfo.openerId ? this._crPages.get(targetInfo.openerId) || null : null;
const crPage = new import_crPage.CRPage(session, targetInfo.targetId, context, opener, { hasUIWindow: targetInfo.type === "page", isBackgroundPage: false });
this._crPages.set(targetInfo.targetId, crPage);
return;
}
if (targetInfo.type === "service_worker") {
const serviceWorker = new import_crServiceWorker.CRServiceWorker(context, session, targetInfo.url);
this._serviceWorkers.set(targetInfo.targetId, serviceWorker);
context.emit(CRBrowserContext.CREvents.ServiceWorker, serviceWorker);
return;
}
session.detach().catch(() => {
});
}
_onDetachedFromTarget(payload) {
const targetId = payload.targetId;
const crPage = this._crPages.get(targetId);
if (crPage) {
this._crPages.delete(targetId);
crPage.didClose();
return;
}
const backgroundPage = this._backgroundPages.get(targetId);
if (backgroundPage) {
this._backgroundPages.delete(targetId);
backgroundPage.didClose();
return;
}
const serviceWorker = this._serviceWorkers.get(targetId);
if (serviceWorker) {
this._serviceWorkers.delete(targetId);
serviceWorker.didClose();
return;
}
}
_didDisconnect() {
for (const crPage of this._crPages.values())
crPage.didClose();
this._crPages.clear();
for (const backgroundPage of this._backgroundPages.values())
backgroundPage.didClose();
this._backgroundPages.clear();
for (const serviceWorker of this._serviceWorkers.values())
serviceWorker.didClose();
this._serviceWorkers.clear();
this._didClose();
}
_findOwningPage(frameId) {
for (const crPage of this._crPages.values()) {
const frame = crPage._page.frameManager.frame(frameId);
if (frame)
return crPage;
}
return null;
}
_onDownloadWillBegin(payload) {
const page = this._findOwningPage(payload.frameId);
if (!page) {
return;
}
page.willBeginDownload();
let originPage = page._page.initializedOrUndefined();
if (!originPage && page._opener)
originPage = page._opener._page.initializedOrUndefined();
if (!originPage)
return;
this._downloadCreated(originPage, payload.guid, payload.url, payload.suggestedFilename);
}
_onDownloadProgress(payload) {
if (payload.state === "completed")
this._downloadFinished(payload.guid, "");
if (payload.state === "canceled")
this._downloadFinished(payload.guid, this._closeReason || "canceled");
}
async _closePage(crPage) {
await this._session.send("Target.closeTarget", { targetId: crPage._targetId });
}
async newBrowserCDPSession() {
return await this._connection.createBrowserSession();
}
async startTracing(page, options = {}) {
(0, import_assert.assert)(!this._tracingRecording, "Cannot start recording trace while already recording trace.");
this._tracingClient = page ? page.delegate._mainFrameSession._client : this._session;
const defaultCategories = [
"-*",
"devtools.timeline",
"v8.execute",
"disabled-by-default-devtools.timeline",
"disabled-by-default-devtools.timeline.frame",
"toplevel",
"blink.console",
"blink.user_timing",
"latencyInfo",
"disabled-by-default-devtools.timeline.stack",
"disabled-by-default-v8.cpu_profiler",
"disabled-by-default-v8.cpu_profiler.hires"
];
const {
screenshots = false,
categories = defaultCategories
} = options;
if (screenshots)
categories.push("disabled-by-default-devtools.screenshot");
this._tracingRecording = true;
await this._tracingClient.send("Tracing.start", {
transferMode: "ReturnAsStream",
categories: categories.join(",")
});
}
async stopTracing() {
(0, import_assert.assert)(this._tracingClient, "Tracing was not started.");
const [event] = await Promise.all([
new Promise((f) => this._tracingClient.once("Tracing.tracingComplete", f)),
this._tracingClient.send("Tracing.end")
]);
const tracingPath = import_path.default.join(this.options.artifactsDir, (0, import_crypto.createGuid)() + ".crtrace");
await (0, import_crProtocolHelper.saveProtocolStream)(this._tracingClient, event.stream, tracingPath);
this._tracingRecording = false;
const artifact = new import_artifact.Artifact(this, tracingPath);
artifact.reportFinished();
return artifact;
}
isConnected() {
return !this._connection._closed;
}
async _clientRootSession() {
if (!this._clientRootSessionPromise)
this._clientRootSessionPromise = this._connection.createBrowserSession();
return this._clientRootSessionPromise;
}
}
class CRBrowserContext extends import_browserContext.BrowserContext {
static {
this.CREvents = {
BackgroundPage: "backgroundpage",
ServiceWorker: "serviceworker"
};
}
constructor(browser, browserContextId, options) {
super(browser, options, browserContextId);
this._authenticateProxyViaCredentials();
}
async _initialize() {
(0, import_assert.assert)(!Array.from(this._browser._crPages.values()).some((page) => page._browserContext === this));
const promises = [super._initialize()];
if (this._browser.options.name !== "clank" && this._options.acceptDownloads !== "internal-browser-default") {
promises.push(this._browser._session.send("Browser.setDownloadBehavior", {
behavior: this._options.acceptDownloads === "accept" ? "allowAndName" : "deny",
browserContextId: this._browserContextId,
downloadPath: this._browser.options.downloadsPath,
eventsEnabled: true
}));
}
await Promise.all(promises);
}
_crPages() {
return [...this._browser._crPages.values()].filter((crPage) => crPage._browserContext === this);
}
possiblyUninitializedPages() {
return this._crPages().map((crPage) => crPage._page);
}
async doCreateNewPage() {
const { targetId } = await this._browser._session.send("Target.createTarget", { url: "about:blank", browserContextId: this._browserContextId });
return this._browser._crPages.get(targetId)._page;
}
async doGetCookies(urls) {
const { cookies } = await this._browser._session.send("Storage.getCookies", { browserContextId: this._browserContextId });
return network.filterCookies(cookies.map((c) => {
const { name, value, domain, path: path2, expires, httpOnly, secure, sameSite } = c;
const copy = {
name,
value,
domain,
path: path2,
expires,
httpOnly,
secure,
sameSite: sameSite ?? "Lax"
};
if (c.partitionKey) {
copy._crHasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor;
copy.partitionKey = c.partitionKey.topLevelSite;
}
return copy;
}), urls);
}
async addCookies(cookies) {
function toChromiumCookie(cookie) {
const { name, value, url, domain, path: path2, expires, httpOnly, secure, sameSite, partitionKey, _crHasCrossSiteAncestor } = cookie;
const copy = {
name,
value,
url,
domain,
path: path2,
expires,
httpOnly,
secure,
sameSite
};
if (partitionKey) {
copy.partitionKey = {
topLevelSite: partitionKey,
// _crHasCrossSiteAncestor is non-standard, set it true by default if the cookie is partitioned.
hasCrossSiteAncestor: _crHasCrossSiteAncestor ?? true
};
}
return copy;
}
await this._browser._session.send("Storage.setCookies", {
cookies: network.rewriteCookies(cookies).map(toChromiumCookie),
browserContextId: this._browserContextId
});
}
async doClearCookies() {
await this._browser._session.send("Storage.clearCookies", { browserContextId: this._browserContextId });
}
async doGrantPermissions(origin, permissions) {
const webPermissionToProtocol = /* @__PURE__ */ new Map([
["geolocation", "geolocation"],
["midi", "midi"],
["notifications", "notifications"],
["camera", "videoCapture"],
["microphone", "audioCapture"],
["background-sync", "backgroundSync"],
["ambient-light-sensor", "sensors"],
["accelerometer", "sensors"],
["gyroscope", "sensors"],
["magnetometer", "sensors"],
["clipboard-read", "clipboardReadWrite"],
["clipboard-write", "clipboardSanitizedWrite"],
["payment-handler", "paymentHandler"],
// chrome-specific permissions we have.
["midi-sysex", "midiSysex"],
["storage-access", "storageAccess"],
["local-fonts", "localFonts"]
]);
const filtered = permissions.map((permission) => {
const protocolPermission = webPermissionToProtocol.get(permission);
if (!protocolPermission)
throw new Error("Unknown permission: " + permission);
return protocolPermission;
});
await this._browser._session.send("Browser.grantPermissions", { origin: origin === "*" ? void 0 : origin, browserContextId: this._browserContextId, permissions: filtered });
}
async doClearPermissions() {
await this._browser._session.send("Browser.resetPermissions", { browserContextId: this._browserContextId });
}
async setGeolocation(geolocation) {
(0, import_browserContext.verifyGeolocation)(geolocation);
this._options.geolocation = geolocation;
for (const page of this.pages())
await page.delegate.updateGeolocation();
}
async doUpdateExtraHTTPHeaders() {
for (const page of this.pages())
await page.delegate.updateExtraHTTPHeaders();
for (const sw of this.serviceWorkers())
await sw.updateExtraHTTPHeaders();
}
async setUserAgent(userAgent) {
this._options.userAgent = userAgent;
for (const page of this.pages())
await page.delegate.updateUserAgent();
}
async doUpdateOffline() {
for (const page of this.pages())
await page.delegate.updateOffline();
for (const sw of this.serviceWorkers())
await sw.updateOffline();
}
async doSetHTTPCredentials(httpCredentials) {
this._options.httpCredentials = httpCredentials;
for (const page of this.pages())
await page.delegate.updateHttpCredentials();
for (const sw of this.serviceWorkers())
await sw.updateHttpCredentials();
}
async doAddInitScript(initScript) {
for (const page of this.pages())
await page.delegate.addInitScript(initScript);
}
async doRemoveInitScripts(initScripts) {
for (const page of this.pages())
await page.delegate.removeInitScripts(initScripts);
}
async doUpdateRequestInterception() {
for (const page of this.pages())
await page.delegate.updateRequestInterception();
for (const sw of this.serviceWorkers())
await sw.updateRequestInterception();
}
async doUpdateDefaultViewport() {
}
async doUpdateDefaultEmulatedMedia() {
}
async doExposePlaywrightBinding() {
for (const page of this._crPages())
await page.exposePlaywrightBinding();
}
async doClose(reason) {
await this.dialogManager.closeBeforeUnloadDialogs();
if (!this._browserContextId) {
await this.stopVideoRecording();
await this._browser.close({ reason });
return;
}
await this._browser._session.send("Target.disposeBrowserContext", { browserContextId: this._browserContextId });
this._browser._contexts.delete(this._browserContextId);
for (const [targetId, serviceWorker] of this._browser._serviceWorkers) {
if (serviceWorker.browserContext !== this)
continue;
serviceWorker.didClose();
this._browser._serviceWorkers.delete(targetId);
}
}
async stopVideoRecording() {
await Promise.all(this._crPages().map((crPage) => crPage._mainFrameSession._stopVideoRecording()));
}
onClosePersistent() {
for (const [targetId, backgroundPage] of this._browser._backgroundPages.entries()) {
if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined()) {
backgroundPage.didClose();
this._browser._backgroundPages.delete(targetId);
}
}
}
async clearCache() {
for (const page of this._crPages())
await page._networkManager.clearCache();
}
async cancelDownload(guid) {
await this._browser._session.send("Browser.cancelDownload", {
guid,
browserContextId: this._browserContextId
});
}
backgroundPages() {
const result = [];
for (const backgroundPage of this._browser._backgroundPages.values()) {
if (backgroundPage._browserContext === this && backgroundPage._page.initializedOrUndefined())
result.push(backgroundPage._page);
}
return result;
}
serviceWorkers() {
return Array.from(this._browser._serviceWorkers.values()).filter((serviceWorker) => serviceWorker.browserContext === this);
}
async newCDPSession(page) {
let targetId = null;
if (page instanceof import_page.Page) {
targetId = page.delegate._targetId;
} else if (page instanceof import_frames.Frame) {
const session = page._page.delegate._sessions.get(page._id);
if (!session)
throw new Error(`This frame does not have a separate CDP session, it is a part of the parent frame's session`);
targetId = session._targetId;
} else {
throw new Error("page: expected Page or Frame");
}
const rootSession = await this._browser._clientRootSession();
return rootSession.attachToTarget(targetId);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CRBrowser,
CRBrowserContext
});

View File

@@ -0,0 +1,202 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var crConnection_exports = {};
__export(crConnection_exports, {
CDPSession: () => CDPSession,
CRConnection: () => CRConnection,
CRSession: () => CRSession,
ConnectionEvents: () => ConnectionEvents,
kBrowserCloseMessageId: () => kBrowserCloseMessageId
});
module.exports = __toCommonJS(crConnection_exports);
var import_utils = require("../../utils");
var import_debugLogger = require("../utils/debugLogger");
var import_helper = require("../helper");
var import_protocolError = require("../protocolError");
var import_instrumentation = require("../instrumentation");
const ConnectionEvents = {
Disconnected: Symbol("ConnectionEvents.Disconnected")
};
const kBrowserCloseMessageId = -9999;
class CRConnection extends import_instrumentation.SdkObject {
constructor(parent, transport, protocolLogger, browserLogsCollector) {
super(parent, "cr-connection");
this._lastId = 0;
this._sessions = /* @__PURE__ */ new Map();
this._closed = false;
this.setMaxListeners(0);
this._transport = transport;
this._protocolLogger = protocolLogger;
this._browserLogsCollector = browserLogsCollector;
this.rootSession = new CRSession(this, null, "");
this._sessions.set("", this.rootSession);
this._transport.onmessage = this._onMessage.bind(this);
this._transport.onclose = this._onClose.bind(this);
}
_rawSend(sessionId, method, params) {
const id = ++this._lastId;
const message = { id, method, params };
if (sessionId)
message.sessionId = sessionId;
this._protocolLogger("send", message);
this._transport.send(message);
return id;
}
async _onMessage(message) {
this._protocolLogger("receive", message);
if (message.id === kBrowserCloseMessageId)
return;
const session = this._sessions.get(message.sessionId || "");
if (session)
session._onMessage(message);
}
_onClose(reason) {
this._closed = true;
this._transport.onmessage = void 0;
this._transport.onclose = void 0;
this._browserDisconnectedLogs = import_helper.helper.formatBrowserLogs(this._browserLogsCollector.recentLogs(), reason);
this.rootSession.dispose();
Promise.resolve().then(() => this.emit(ConnectionEvents.Disconnected));
}
close() {
if (!this._closed)
this._transport.close();
}
async createBrowserSession() {
const { sessionId } = await this.rootSession.send("Target.attachToBrowserTarget");
return new CDPSession(this.rootSession, sessionId);
}
}
class CRSession extends import_instrumentation.SdkObject {
constructor(connection, parentSession, sessionId, eventListener) {
super(connection, "cr-session");
this._callbacks = /* @__PURE__ */ new Map();
this._crashed = false;
this._closed = false;
this.setMaxListeners(0);
this._connection = connection;
this._parentSession = parentSession;
this._sessionId = sessionId;
this._eventListener = eventListener;
this.on = super.on;
this.addListener = super.addListener;
this.off = super.removeListener;
this.removeListener = super.removeListener;
this.once = super.once;
}
_markAsCrashed() {
this._crashed = true;
}
createChildSession(sessionId, eventListener) {
const session = new CRSession(this._connection, this, sessionId, eventListener);
this._connection._sessions.set(sessionId, session);
return session;
}
async send(method, params) {
if (this._crashed || this._closed || this._connection._closed || this._connection._browserDisconnectedLogs)
throw new import_protocolError.ProtocolError(this._crashed ? "crashed" : "closed", void 0, this._connection._browserDisconnectedLogs);
const id = this._connection._rawSend(this._sessionId, method, params);
return new Promise((resolve, reject) => {
this._callbacks.set(id, { resolve, reject, error: new import_protocolError.ProtocolError("error", method) });
});
}
_sendMayFail(method, params) {
return this.send(method, params).catch((error) => import_debugLogger.debugLogger.log("error", error));
}
_onMessage(object) {
if (object.id && this._callbacks.has(object.id)) {
const callback = this._callbacks.get(object.id);
this._callbacks.delete(object.id);
if (object.error) {
callback.error.setMessage(object.error.message);
callback.reject(callback.error);
} else {
callback.resolve(object.result);
}
} else if (object.id && object.error?.code === -32001) {
} else {
(0, import_utils.assert)(!object.id, object?.error?.message || void 0);
Promise.resolve().then(() => {
if (this._eventListener)
this._eventListener(object.method, object.params);
this.emit(object.method, object.params);
});
}
}
async detach() {
if (this._closed)
throw new Error(`Session already detached. Most likely the page has been closed.`);
if (!this._parentSession)
throw new Error("Root session cannot be closed");
await this._sendMayFail("Runtime.runIfWaitingForDebugger");
await this._parentSession.send("Target.detachFromTarget", { sessionId: this._sessionId });
this.dispose();
}
dispose() {
this._closed = true;
this._connection._sessions.delete(this._sessionId);
for (const callback of this._callbacks.values()) {
callback.error.setMessage(`Internal server error, session closed.`);
callback.error.type = this._crashed ? "crashed" : "closed";
callback.error.logs = this._connection._browserDisconnectedLogs;
callback.reject(callback.error);
}
this._callbacks.clear();
}
}
class CDPSession extends import_instrumentation.SdkObject {
constructor(parentSession, sessionId) {
super(parentSession, "cdp-session");
this._listeners = [];
this._session = parentSession.createChildSession(sessionId, (method, params) => this.emit(CDPSession.Events.Event, { method, params }));
this._listeners = [import_utils.eventsHelper.addEventListener(parentSession, "Target.detachedFromTarget", (event) => {
if (event.sessionId === sessionId)
this._onClose();
})];
}
static {
this.Events = {
Event: "event",
Closed: "close"
};
}
async send(method, params) {
return await this._session.send(method, params);
}
async detach() {
return await this._session.detach();
}
async attachToTarget(targetId) {
const { sessionId } = await this.send("Target.attachToTarget", { targetId, flatten: true });
return new CDPSession(this._session, sessionId);
}
_onClose() {
import_utils.eventsHelper.removeEventListeners(this._listeners);
this._session.dispose();
this.emit(CDPSession.Events.Closed);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CDPSession,
CRConnection,
CRSession,
ConnectionEvents,
kBrowserCloseMessageId
});

Some files were not shown because too many files have changed in this diff Show More