webdriver
Version:
A Node.js bindings implementation for the W3C WebDriver and WebDriver Bidi protocols
3,029 lines • 118 kB
JavaScript
// src/node.ts
import os from "node:os";
import ws from "ws";
// src/index.ts
import logger4 from "@wdio/logger";
import { webdriverMonad, sessionEnvironmentDetector, startWebDriver, isBidi } from "@wdio/utils";
import { validateConfig } from "@wdio/config";
// src/command.ts
import logger3 from "@wdio/logger";
import { commandCallStructure, isValidParameter, getArgumentType, transformCommandLogResult } from "@wdio/utils";
import { WebDriverBidiProtocol as WebDriverBidiProtocol2 } from "@wdio/protocols";
// src/environment.ts
var isNode = !!(typeof process !== "undefined" && process.version);
var environment = {
value: {
get Request() {
throw new Error("Request is not available in this environment");
},
get Socket() {
throw new Error("Socket is not available in this environment");
},
get createBidiConnection() {
throw new Error("createBidiConnection is not available in this environment");
},
get killDriverProcess() {
throw new Error("killDriverProcess is not available in this environment");
},
get variables() {
return {};
}
}
};
// src/types.ts
var CommandRuntimeOptions = class {
// mask the text parameter value of the command
mask;
constructor(options) {
this.mask = options.mask;
}
};
// src/utils.ts
import { deepmergeCustom } from "deepmerge-ts";
import logger2, { SENSITIVE_DATA_REPLACER as SENSITIVE_DATA_REPLACER2 } from "@wdio/logger";
import {
WebDriverProtocol,
AppiumProtocol,
ChromiumProtocol,
SauceLabsProtocol,
SeleniumProtocol,
GeckoProtocol,
WebDriverBidiProtocol
} from "@wdio/protocols";
import { CAPABILITY_KEYS } from "@wdio/protocols";
// src/bidi/core.ts
import logger, { SENSITIVE_DATA_REPLACER } from "@wdio/logger";
// src/constants.ts
var DEFAULT_RESPONSE_TIMEOUT = 1e3 * 180;
var DEFAULT_CONNECT_TIMEOUT = 1e3 * 10;
var SESSION_ENDED_ERROR = "session ended";
var DEFAULTS = {
/**
* protocol of automation driver
*/
protocol: {
type: "string",
default: "http",
match: /(http|https)/
},
/**
* hostname of automation driver
*/
hostname: {
type: "string",
default: "localhost"
},
/**
* port of automation driver
*/
port: {
type: "number"
},
/**
* path to WebDriver endpoints
*/
path: {
type: "string",
validate: (path) => {
if (!path.startsWith("/")) {
throw new TypeError('The option "path" needs to start with a "/"');
}
return true;
},
default: "/"
},
/**
* A key-value store of query parameters to be added to every selenium request
*/
queryParams: {
type: "object"
},
/**
* cloud user if applicable
*/
user: {
type: "string"
},
/**
* access key to user
*/
key: {
type: "string"
},
/**
* capability of WebDriver session
*/
capabilities: {
type: "object",
required: true
},
/**
* Level of logging verbosity
*/
logLevel: {
type: "string",
default: "info",
match: /(trace|debug|info|warn|error|silent)/
},
/**
* directory for log files
*/
outputDir: {
type: "string"
},
/**
* Timeout for any WebDriver request to a driver or grid
*/
connectionRetryTimeout: {
type: "number",
default: 12e4
},
/**
* Count of request retries to the WebDriver server
*/
connectionRetryCount: {
type: "number",
default: 3
},
/**
* Timeout for a WebDriver Bidi command to receive a response from the browser
*/
bidiResponseTimeout: {
type: "number",
default: DEFAULT_RESPONSE_TIMEOUT,
validate: (timeout) => {
if (!Number.isFinite(timeout) || timeout <= 0) {
throw new TypeError('The option "bidiResponseTimeout" needs to be a positive number');
}
return true;
}
},
/**
* Timeout for the browser to accept the WebDriver Bidi connection. After it the
* session continues with WebDriver Classic. Node.js only.
*/
bidiConnectTimeout: {
type: "number",
default: DEFAULT_CONNECT_TIMEOUT,
validate: (timeout) => {
if (!Number.isFinite(timeout) || timeout <= 0) {
throw new TypeError('The option "bidiConnectTimeout" needs to be a positive number');
}
return true;
}
},
/**
* Override default agent
*/
logLevels: {
type: "object"
},
/**
* Pass custom headers
*/
headers: {
type: "object"
},
/**
* Function transforming the request options before the request is made
*/
transformRequest: {
type: "function",
default: (requestOptions) => requestOptions
},
/**
* Function transforming the response object after it is received
*/
transformResponse: {
type: "function",
default: (response) => response
},
/**
* Appium direct connect options server (https://appiumpro.com/editions/86-connecting-directly-to-appium-hosts-in-distributed-environments)
* Whether to allow direct connect caps to adjust endpoint details (Appium only)
*/
enableDirectConnect: {
type: "boolean",
default: true
},
/**
* Whether it requires SSL certificates to be valid in HTTP/s requests
* for an environment which cannot get process environment well.
*/
strictSSL: {
type: "boolean",
default: true
},
/**
* The path to the root of the cache directory. This directory is used to store all drivers that are downloaded
* when attempting to start a session.
*/
cacheDir: {
type: "string"
},
/**
* Mask sensitive data in logs by replacing matching string or all captured groups for the provided regular expressions as string
*/
maskingPatterns: {
type: "string",
default: void 0
}
};
var ELEMENT_KEY = "element-6066-11e4-a52e-4f735466cecf";
var SHADOW_ELEMENT_KEY = "shadow-6066-11e4-a52e-4f735466cecf";
var BASE_64_REGEX = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;
var BASE_64_SAFE_STRING_TO_PROCESS_LENGTH = 2e5;
var APPIUM_MASKING_HEADER = { "x-appium-is-sensitive": "true" };
// src/bidi/utils.ts
function isBase64Safe(str) {
if (typeof str !== "string") {
return false;
}
if (str.length === 0) {
return true;
}
if (str.length % 4 !== 0) {
return false;
}
const length = str.length;
const digitCount = length.toString().length;
if (length > BASE_64_SAFE_STRING_TO_PROCESS_LENGTH) {
const chunkSize = Math.floor(length / digitCount / 4) * 4;
for (let i = 0; i < length; i += chunkSize) {
const chunk = str.slice(i, i + chunkSize);
if (!BASE_64_REGEX.test(chunk)) {
return false;
}
}
return true;
}
return BASE_64_REGEX.test(str);
}
// src/bidi/core.ts
var SCRIPT_PREFIX = "/* __wdio script__ */";
var SCRIPT_SUFFIX = "/* __wdio script end__ */";
var log = logger("webdriver");
var BIDI_MASK = /* @__PURE__ */ Symbol.for("wdio.bidi.mask");
var BIDI_SCRIPT_TIMEOUT = /* @__PURE__ */ Symbol.for("wdio.bidi.scriptTimeout");
var MAX_TIMER_DELAY = 2 ** 31 - 1;
var MAX_EXPIRED_COMMANDS = 1e3;
var BidiCore = class {
#id = 0;
#ws;
#waitForConnected;
#resolveWaitForConnected;
#webSocketUrl;
#clientOptions;
#responseTimeout;
#connectTimeout;
#pendingCommands = /* @__PURE__ */ new Map();
/**
* the socket listeners, kept to remove them again in `close()`
*/
#onMessage = this.#handleResponse.bind(this);
#onClose;
/**
* commands that ran out of their script timeout: their late result is ignored
*/
#expiredCommands = /* @__PURE__ */ new Set();
client;
/**
* @private
*/
_isConnected = false;
/**
* the connection was open and is closed now (not: it never connected)
*/
#closed = false;
constructor(webSocketUrl, opts, responseTimeout = DEFAULT_RESPONSE_TIMEOUT, connectTimeout) {
if (!Number.isFinite(responseTimeout) || responseTimeout <= 0) {
throw new TypeError('The option "bidiResponseTimeout" needs to be a positive number');
}
if (connectTimeout !== void 0 && (!Number.isFinite(connectTimeout) || connectTimeout <= 0)) {
throw new TypeError('The option "bidiConnectTimeout" needs to be a positive number');
}
this.#webSocketUrl = webSocketUrl;
this.#clientOptions = opts;
this.#responseTimeout = responseTimeout;
this.#connectTimeout = connectTimeout;
this.#resolveWaitForConnected = () => {
};
this.#waitForConnected = new Promise((resolve) => {
this.#resolveWaitForConnected = resolve;
});
}
/**
* We initiate the Bidi instance before a WebdriverIO instance is created.
* In order to emit Bidi events we have to attach the WebdriverIO instance
* to the Bidi instance afterwards.
*/
attachClient(client) {
this.client = client;
}
async connect() {
log.info(`Connecting to webSocketUrl ${this.#webSocketUrl}`);
this.#closed = false;
try {
this.#ws = await environment.value.createBidiConnection(this.#webSocketUrl, this.#clientOptions, this.#connectTimeout);
} catch (err) {
this.#resolveWaitForConnected(false);
throw err;
}
this._isConnected = Boolean(this.#ws);
this.#resolveWaitForConnected(this._isConnected);
const ws2 = this.#ws;
if (ws2) {
ws2.on("message", this.#onMessage);
this.#onClose = (code) => {
if (this.#ws === ws2) {
this.#handleClose(code);
}
};
ws2.on("close", this.#onClose);
}
return this._isConnected;
}
close() {
if (!this._isConnected) {
return;
}
log.info(`Close Bidi connection to ${this.#webSocketUrl}`);
this._isConnected = false;
this.#closed = true;
this.#expiredCommands.clear();
this.#rejectPendingCommands("the connection was closed");
const ws2 = this.#ws;
this.#ws = void 0;
if (ws2) {
ws2.off("message", this.#onMessage);
if (this.#onClose) {
ws2.off("close", this.#onClose);
}
ws2.close();
if (typeof ws2.terminate === "function") {
ws2.terminate();
}
}
}
/**
* Close a connection that can not serve the session: the handler is then in the
* state of a connection that could not be made, so the session does not count as ended
*/
discard() {
this.close();
this.#closed = false;
}
/**
* The browser or the driver closed the socket (for example a browser crash, a
* cloud timeout or a lost network): no pending command can get a result anymore.
*/
#handleClose(code) {
log.info(`Bidi connection to ${this.#webSocketUrl} closed${typeof code === "number" ? ` (code ${code})` : ""}`);
this._isConnected = false;
this.#closed = true;
this.#expiredCommands.clear();
this.#ws = void 0;
this.#rejectPendingCommands(
`the browser or the driver closed the connection${typeof code === "number" ? ` (code ${code})` : ""}`
);
}
/**
* Reject the pending commands at once: without a connection, they would wait
* for `bidiResponseTimeout` and then fail with a misleading timeout error.
*/
#rejectPendingCommands(reason) {
const pending = [...this.#pendingCommands.values()];
this.#pendingCommands.clear();
for (const command of pending) {
command.reject(reason);
}
}
reconnect(webSocketUrl, opts) {
log.info(`Reconnect to new Bidi session at ${webSocketUrl}`);
this.close();
this.#webSocketUrl = webSocketUrl;
this.#clientOptions = opts;
return this.connect();
}
/**
* Helper function that allows to wait until Bidi connection establishes
* @returns a promise that resolves once the connection to WebDriver Bidi protocol was established
*/
waitForConnected() {
return this.#waitForConnected;
}
get socket() {
return this.#ws;
}
get isConnected() {
return this._isConnected;
}
/**
* `true` when the connection was open and is closed now: after `close()` (e.g. by
* `deleteSession`), or when the browser or the driver closed the socket. `false` before
* the first connection and when the connection could not be made.
*/
get isClosed() {
return this.#closed;
}
#handleResponse(data) {
try {
const payload = JSON.parse(data.toString());
if (!payload.id) {
return;
}
let resultLog = data.toString();
if (typeof payload.result === "object" && payload.result && "data" in payload.result && typeof payload.result.data === "string" && isBase64Safe(payload.result.data)) {
resultLog = JSON.stringify({
...payload.result,
data: `Base64 string [${payload.result.data.length} chars]`
});
}
log.info("BIDI RESULT", resultLog);
this.client?.emit("bidiResult", payload);
const command = this.#pendingCommands.get(payload.id);
if (!command) {
if (this.#expiredCommands.delete(payload.id)) {
log.debug(`Ignore the result of command with id ${payload.id}, it ran out of its script timeout`);
return;
}
log.error(`Couldn't resolve command with id ${payload.id}`);
return;
}
this.#pendingCommands.delete(payload.id);
command.resolve(payload);
} catch (err) {
const error = err instanceof Error ? err : new Error(`Failed parse message: ${String(err)}`);
log.error(`Failed parse message: ${error.message}`);
}
}
async send(params) {
const id = this.sendAsync(params);
const failError = new Error(`WebDriver Bidi command "${params.method}" failed`);
const scriptTimeout = params.params?.[BIDI_SCRIPT_TIMEOUT];
const payload = await new Promise((resolve, reject) => {
const t = setTimeout(() => {
clearTimeout(scriptTimer);
reject(new Error(
`Command ${params.method} with id ${id} timed out after ${this.#responseTimeout}ms! Consider increasing the "bidiResponseTimeout" option.`
));
this.#pendingCommands.delete(id);
}, this.#responseTimeout);
const scriptTimer = typeof scriptTimeout === "number" && scriptTimeout >= 0 && scriptTimeout <= MAX_TIMER_DELAY ? setTimeout(() => {
clearTimeout(t);
const error = new Error(
`script timeout: the script did not finish within ${scriptTimeout}ms. Set a longer "script" timeout with \`browser.setTimeout({ script })\` if it needs more time.`
);
error.name = "script timeout";
reject(error);
this.#pendingCommands.delete(id);
if (this.#expiredCommands.size >= MAX_EXPIRED_COMMANDS) {
this.#expiredCommands.delete(this.#expiredCommands.values().next().value);
}
this.#expiredCommands.add(id);
}, scriptTimeout) : void 0;
this.#pendingCommands.set(id, {
resolve: (payload2) => {
clearTimeout(t);
clearTimeout(scriptTimer);
resolve(payload2);
},
/**
* `failError` has the stack of the line that sent the command
*/
reject: (reason) => {
clearTimeout(t);
clearTimeout(scriptTimer);
failError.message = `WebDriver Bidi command "${params.method}" with id ${id} got no result: ${reason}`;
failError.name = SESSION_ENDED_ERROR;
reject(failError);
}
});
});
if (payload.type === "error" || "error" in payload) {
const error = payload;
failError.message += ` with error: ${payload.error} - ${error.message}`;
if (error.stacktrace && typeof error.stacktrace === "string") {
const driverStack = error.stacktrace.split("\n").filter(Boolean).map((line) => ` at ${line}`).join("\n");
failError.stack += `
Driver Stack:
${driverStack}`;
}
throw failError;
}
return payload;
}
sendAsync(params) {
if (!this.#ws || !this._isConnected) {
const error = new Error("No connection to WebDriver Bidi was established");
if (this.#closed) {
error.name = SESSION_ENDED_ERROR;
}
throw error;
}
const logged = maskBidiCommand(params);
log.info("BIDI COMMAND", ...parseBidiCommand(logged));
const id = ++this.#id;
this.client?.emit("bidiCommand", { ...logged, id });
this.#ws.send(JSON.stringify({ id, ...params }));
return id;
}
};
function maskBidiCommand(params) {
const raw = params.params;
if (!raw || !raw[BIDI_MASK]) {
return params;
}
if (params.method === "input.performActions") {
const param = params.params;
return {
...params,
params: {
...param,
actions: param.actions.map((source) => source.type !== "key" ? source : {
...source,
actions: source.actions.map((action) => "value" in action ? { ...action, value: SENSITIVE_DATA_REPLACER } : action)
})
}
};
}
return { ...params, params: SENSITIVE_DATA_REPLACER };
}
function parseBidiCommand(params) {
const commandName = params.method;
if (commandName === "script.addPreloadScript") {
const param = params.params;
const logString = `{ functionDeclaration: <PreloadScript[${new TextEncoder().encode(param.functionDeclaration).length} bytes]>, contexts: ${JSON.stringify(param.contexts)} }`;
return [commandName, logString];
} else if (commandName === "script.callFunction") {
const param = params.params;
const fn = param.functionDeclaration;
let fnName = "";
if (fn.includes(SCRIPT_PREFIX)) {
const internalFn = fn.slice(
fn.indexOf(SCRIPT_PREFIX) + SCRIPT_PREFIX.length,
fn.indexOf(SCRIPT_SUFFIX)
);
const functionPrefix = "function ";
if (internalFn.startsWith(functionPrefix)) {
fnName = internalFn.slice(
internalFn.indexOf(functionPrefix) + functionPrefix.length,
internalFn.indexOf("(")
);
}
}
const logString = JSON.stringify({
...param,
functionDeclaration: `<Function[${new TextEncoder().encode(param.functionDeclaration).length} bytes] ${fnName || "anonymous"}>`
});
return [commandName, logString];
}
return [commandName, JSON.stringify(params.params)];
}
// src/bidi/handler.ts
var BidiHandler = class extends BidiCore {
/**
* WebDriver Bidi command to send command method "session.status" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-session-status
* @param params `remote.EmptyParams` {@link https://w3c.github.io/webdriver-bidi/#command-session-status | command parameter}
* @returns `Promise<local.SessionStatusResult>`
**/
async sessionStatus(params) {
const result = await this.send({
method: "session.status",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "session.new" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-session-new
* @param params `remote.SessionNewParameters` {@link https://w3c.github.io/webdriver-bidi/#command-session-new | command parameter}
* @returns `Promise<local.SessionNewResult>`
**/
async sessionNew(params) {
const result = await this.send({
method: "session.new",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "session.end" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-session-end
* @param params `remote.EmptyParams` {@link https://w3c.github.io/webdriver-bidi/#command-session-end | command parameter}
* @returns `Promise<local.SessionEndResult>`
**/
async sessionEnd(params) {
const result = await this.send({
method: "session.end",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "session.subscribe" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-session-subscribe
* @param params `remote.SessionSubscribeParameters` {@link https://w3c.github.io/webdriver-bidi/#command-session-subscribe | command parameter}
* @returns `Promise<local.SessionSubscribeResult>`
**/
async sessionSubscribe(params) {
const result = await this.send({
method: "session.subscribe",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "session.unsubscribe" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe
* @param params `remote.SessionUnsubscribeParameters` {@link https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe | command parameter}
* @returns `Promise<local.SessionUnsubscribeResult>`
**/
async sessionUnsubscribe(params) {
const result = await this.send({
method: "session.unsubscribe",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.close" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-close
* @param params `remote.EmptyParams` {@link https://w3c.github.io/webdriver-bidi/#command-browser-close | command parameter}
* @returns `Promise<local.BrowserCloseResult>`
**/
async browserClose(params) {
const result = await this.send({
method: "browser.close",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.createUserContext" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-createUserContext
* @param params `remote.BrowserCreateUserContextParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browser-createUserContext | command parameter}
* @returns `Promise<local.BrowserCreateUserContextResult>`
**/
async browserCreateUserContext(params) {
const result = await this.send({
method: "browser.createUserContext",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.getClientWindows" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-getClientWindows
* @param params `remote.EmptyParams` {@link https://w3c.github.io/webdriver-bidi/#command-browser-getClientWindows | command parameter}
* @returns `Promise<local.BrowserGetClientWindowsResult>`
**/
async browserGetClientWindows(params) {
const result = await this.send({
method: "browser.getClientWindows",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.getUserContexts" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-getUserContexts
* @param params `remote.EmptyParams` {@link https://w3c.github.io/webdriver-bidi/#command-browser-getUserContexts | command parameter}
* @returns `Promise<local.BrowserGetUserContextsResult>`
**/
async browserGetUserContexts(params) {
const result = await this.send({
method: "browser.getUserContexts",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.removeUserContext" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-removeUserContext
* @param params `remote.BrowserRemoveUserContextParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browser-removeUserContext | command parameter}
* @returns `Promise<local.BrowserRemoveUserContextResult>`
**/
async browserRemoveUserContext(params) {
const result = await this.send({
method: "browser.removeUserContext",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.setClientWindowState" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-setClientWindowState
* @param params `remote.BrowserSetClientWindowStateParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browser-setClientWindowState | command parameter}
* @returns `Promise<local.BrowserSetClientWindowStateResult>`
**/
async browserSetClientWindowState(params) {
const result = await this.send({
method: "browser.setClientWindowState",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browser.setDownloadBehavior" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browser-setDownloadBehavior
* @param params `remote.BrowserSetDownloadBehaviorParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browser-setDownloadBehavior | command parameter}
* @returns `Promise<local.BrowserSetDownloadBehaviorResult>`
**/
async browserSetDownloadBehavior(params) {
const result = await this.send({
method: "browser.setDownloadBehavior",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.activate" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-activate
* @param params `remote.BrowsingContextActivateParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-activate | command parameter}
* @returns `Promise<local.BrowsingContextActivateResult>`
**/
async browsingContextActivate(params) {
const result = await this.send({
method: "browsingContext.activate",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.captureScreenshot" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-captureScreenshot
* @param params `remote.BrowsingContextCaptureScreenshotParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-captureScreenshot | command parameter}
* @returns `Promise<local.BrowsingContextCaptureScreenshotResult>`
**/
async browsingContextCaptureScreenshot(params) {
const result = await this.send({
method: "browsingContext.captureScreenshot",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.close" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-close
* @param params `remote.BrowsingContextCloseParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-close | command parameter}
* @returns `Promise<local.BrowsingContextCloseResult>`
**/
async browsingContextClose(params) {
const result = await this.send({
method: "browsingContext.close",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.create" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-create
* @param params `remote.BrowsingContextCreateParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-create | command parameter}
* @returns `Promise<local.BrowsingContextCreateResult>`
**/
async browsingContextCreate(params) {
const result = await this.send({
method: "browsingContext.create",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.getTree" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree
* @param params `remote.BrowsingContextGetTreeParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree | command parameter}
* @returns `Promise<local.BrowsingContextGetTreeResult>`
**/
async browsingContextGetTree(params) {
const result = await this.send({
method: "browsingContext.getTree",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.handleUserPrompt" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-handleUserPrompt
* @param params `remote.BrowsingContextHandleUserPromptParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-handleUserPrompt | command parameter}
* @returns `Promise<local.BrowsingContextHandleUserPromptResult>`
**/
async browsingContextHandleUserPrompt(params) {
const result = await this.send({
method: "browsingContext.handleUserPrompt",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.locateNodes" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes
* @param params `remote.BrowsingContextLocateNodesParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes | command parameter}
* @returns `Promise<local.BrowsingContextLocateNodesResult>`
**/
async browsingContextLocateNodes(params) {
const result = await this.send({
method: "browsingContext.locateNodes",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.navigate" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-navigate
* @param params `remote.BrowsingContextNavigateParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-navigate | command parameter}
* @returns `Promise<local.BrowsingContextNavigateResult>`
**/
async browsingContextNavigate(params) {
const result = await this.send({
method: "browsingContext.navigate",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.print" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-print
* @param params `remote.BrowsingContextPrintParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-print | command parameter}
* @returns `Promise<local.BrowsingContextPrintResult>`
**/
async browsingContextPrint(params) {
const result = await this.send({
method: "browsingContext.print",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.reload" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload
* @param params `remote.BrowsingContextReloadParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload | command parameter}
* @returns `Promise<local.BrowsingContextReloadResult>`
**/
async browsingContextReload(params) {
const result = await this.send({
method: "browsingContext.reload",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.setBypassCSP" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-setBypassCSP
* @param params `remote.BrowsingContextSetBypassCspParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-setBypassCSP | command parameter}
* @returns `Promise<local.BrowsingContextSetBypassCspResult>`
**/
async browsingContextSetBypassCsp(params) {
const result = await this.send({
method: "browsingContext.setBypassCSP",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.setViewport" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-setViewport
* @param params `remote.BrowsingContextSetViewportParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-setViewport | command parameter}
* @returns `Promise<local.BrowsingContextSetViewportResult>`
**/
async browsingContextSetViewport(params) {
const result = await this.send({
method: "browsingContext.setViewport",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.startScreencast" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-startScreencast
* @param params `remote.BrowsingContextStartScreencastParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-startScreencast | command parameter}
* @returns `Promise<local.BrowsingContextStartScreencastResult>`
**/
async browsingContextStartScreencast(params) {
const result = await this.send({
method: "browsingContext.startScreencast",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.stopScreencast" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-stopScreencast
* @param params `remote.BrowsingContextStopScreencastParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-stopScreencast | command parameter}
* @returns `Promise<local.BrowsingContextStopScreencastResult>`
**/
async browsingContextStopScreencast(params) {
const result = await this.send({
method: "browsingContext.stopScreencast",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "browsingContext.traverseHistory" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory
* @param params `remote.BrowsingContextTraverseHistoryParameters` {@link https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory | command parameter}
* @returns `Promise<local.BrowsingContextTraverseHistoryResult>`
**/
async browsingContextTraverseHistory(params) {
const result = await this.send({
method: "browsingContext.traverseHistory",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setForcedColorsModeThemeOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setForcedColorsModeThemeOverride
* @param params `remote.EmulationSetForcedColorsModeThemeOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setForcedColorsModeThemeOverride | command parameter}
* @returns `Promise<local.EmulationSetForcedColorsModeThemeOverrideResult>`
**/
async emulationSetForcedColorsModeThemeOverride(params) {
const result = await this.send({
method: "emulation.setForcedColorsModeThemeOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setGeolocationOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setGeolocationOverride
* @param params `remote.EmulationSetGeolocationOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setGeolocationOverride | command parameter}
* @returns `Promise<local.EmulationSetGeolocationOverrideResult>`
**/
async emulationSetGeolocationOverride(params) {
const result = await this.send({
method: "emulation.setGeolocationOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setLocaleOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setLocaleOverride
* @param params `remote.EmulationSetLocaleOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setLocaleOverride | command parameter}
* @returns `Promise<local.EmulationSetLocaleOverrideResult>`
**/
async emulationSetLocaleOverride(params) {
const result = await this.send({
method: "emulation.setLocaleOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setMediaFeaturesOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setMediaFeaturesOverride
* @param params `remote.EmulationSetMediaFeaturesOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setMediaFeaturesOverride | command parameter}
* @returns `Promise<local.EmulationSetMediaFeaturesOverrideResult>`
**/
async emulationSetMediaFeaturesOverride(params) {
const result = await this.send({
method: "emulation.setMediaFeaturesOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setNetworkConditions" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setNetworkConditions
* @param params `remote.EmulationSetNetworkConditionsParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setNetworkConditions | command parameter}
* @returns `Promise<local.EmulationSetNetworkConditionsResult>`
**/
async emulationSetNetworkConditions(params) {
const result = await this.send({
method: "emulation.setNetworkConditions",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setScreenSettingsOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenSettingsOverride
* @param params `remote.EmulationSetScreenSettingsOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenSettingsOverride | command parameter}
* @returns `Promise<local.EmulationSetScreenSettingsOverrideResult>`
**/
async emulationSetScreenSettingsOverride(params) {
const result = await this.send({
method: "emulation.setScreenSettingsOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setScreenOrientationOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenOrientationOverride
* @param params `remote.EmulationSetScreenOrientationOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setScreenOrientationOverride | command parameter}
* @returns `Promise<local.EmulationSetScreenOrientationOverrideResult>`
**/
async emulationSetScreenOrientationOverride(params) {
const result = await this.send({
method: "emulation.setScreenOrientationOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setUserAgentOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setUserAgentOverride
* @param params `remote.EmulationSetUserAgentOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setUserAgentOverride | command parameter}
* @returns `Promise<local.EmulationSetUserAgentOverrideResult>`
**/
async emulationSetUserAgentOverride(params) {
const result = await this.send({
method: "emulation.setUserAgentOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setViewportMetaOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setViewportMetaOverride
* @param params `remote.EmulationSetViewportMetaOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setViewportMetaOverride | command parameter}
* @returns `Promise<local.EmulationSetViewportMetaOverrideResult>`
**/
async emulationSetViewportMetaOverride(params) {
const result = await this.send({
method: "emulation.setViewportMetaOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setScriptingEnabled" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setScriptingEnabled
* @param params `remote.EmulationSetScriptingEnabledParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setScriptingEnabled | command parameter}
* @returns `Promise<local.EmulationSetScriptingEnabledResult>`
**/
async emulationSetScriptingEnabled(params) {
const result = await this.send({
method: "emulation.setScriptingEnabled",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setScrollbarTypeOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setScrollbarTypeOverride
* @param params `remote.EmulationSetScrollbarTypeOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setScrollbarTypeOverride | command parameter}
* @returns `Promise<local.EmulationSetScrollbarTypeOverrideResult>`
**/
async emulationSetScrollbarTypeOverride(params) {
const result = await this.send({
method: "emulation.setScrollbarTypeOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setTextLayoutModeOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setTextLayoutModeOverride
* @param params `remote.EmulationSetTextLayoutModeOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setTextLayoutModeOverride | command parameter}
* @returns `Promise<local.EmulationSetTextLayoutModeOverrideResult>`
**/
async emulationSetTextLayoutModeOverride(params) {
const result = await this.send({
method: "emulation.setTextLayoutModeOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setTimezoneOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setTimezoneOverride
* @param params `remote.EmulationSetTimezoneOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setTimezoneOverride | command parameter}
* @returns `Promise<local.EmulationSetTimezoneOverrideResult>`
**/
async emulationSetTimezoneOverride(params) {
const result = await this.send({
method: "emulation.setTimezoneOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "emulation.setTouchOverride" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-emulation-setTouchOverride
* @param params `remote.EmulationSetTouchOverrideParameters` {@link https://w3c.github.io/webdriver-bidi/#command-emulation-setTouchOverride | command parameter}
* @returns `Promise<local.EmulationSetTouchOverrideResult>`
**/
async emulationSetTouchOverride(params) {
const result = await this.send({
method: "emulation.setTouchOverride",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.addDataCollector" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-addDataCollector
* @param params `remote.NetworkAddDataCollectorParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-addDataCollector | command parameter}
* @returns `Promise<local.NetworkAddDataCollectorResult>`
**/
async networkAddDataCollector(params) {
const result = await this.send({
method: "network.addDataCollector",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.addIntercept" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-addIntercept
* @param params `remote.NetworkAddInterceptParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-addIntercept | command parameter}
* @returns `Promise<local.NetworkAddInterceptResult>`
**/
async networkAddIntercept(params) {
const result = await this.send({
method: "network.addIntercept",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.continueRequest" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-continueRequest
* @param params `remote.NetworkContinueRequestParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-continueRequest | command parameter}
* @returns `Promise<local.NetworkContinueRequestResult>`
**/
async networkContinueRequest(params) {
const result = await this.send({
method: "network.continueRequest",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.continueResponse" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-continueResponse
* @param params `remote.NetworkContinueResponseParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-continueResponse | command parameter}
* @returns `Promise<local.NetworkContinueResponseResult>`
**/
async networkContinueResponse(params) {
const result = await this.send({
method: "network.continueResponse",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.continueWithAuth" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-continueWithAuth
* @param params `remote.NetworkContinueWithAuthParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-continueWithAuth | command parameter}
* @returns `Promise<local.NetworkContinueWithAuthResult>`
**/
async networkContinueWithAuth(params) {
const result = await this.send({
method: "network.continueWithAuth",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.disownData" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-disownData
* @param params `remote.NetworkDisownDataParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-disownData | command parameter}
* @returns `Promise<local.NetworkDisownDataResult>`
**/
async networkDisownData(params) {
const result = await this.send({
method: "network.disownData",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.failRequest" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-failRequest
* @param params `remote.NetworkFailRequestParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-failRequest | command parameter}
* @returns `Promise<local.NetworkFailRequestResult>`
**/
async networkFailRequest(params) {
const result = await this.send({
method: "network.failRequest",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.getData" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-getData
* @param params `remote.NetworkGetDataParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-getData | command parameter}
* @returns `Promise<local.NetworkGetDataResult>`
**/
async networkGetData(params) {
const result = await this.send({
method: "network.getData",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.provideResponse" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-provideResponse
* @param params `remote.NetworkProvideResponseParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-provideResponse | command parameter}
* @returns `Promise<local.NetworkProvideResponseResult>`
**/
async networkProvideResponse(params) {
const result = await this.send({
method: "network.provideResponse",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.removeDataCollector" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-removeDataCollector
* @param params `remote.NetworkRemoveDataCollectorParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-removeDataCollector | command parameter}
* @returns `Promise<local.NetworkRemoveDataCollectorResult>`
**/
async networkRemoveDataCollector(params) {
const result = await this.send({
method: "network.removeDataCollector",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.removeIntercept" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-removeIntercept
* @param params `remote.NetworkRemoveInterceptParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-removeIntercept | command parameter}
* @returns `Promise<local.NetworkRemoveInterceptResult>`
**/
async networkRemoveIntercept(params) {
const result = await this.send({
method: "network.removeIntercept",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.setCacheBehavior" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-setCacheBehavior
* @param params `remote.NetworkSetCacheBehaviorParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-setCacheBehavior | command parameter}
* @returns `Promise<local.NetworkSetCacheBehaviorResult>`
**/
async networkSetCacheBehavior(params) {
const result = await this.send({
method: "network.setCacheBehavior",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "network.setExtraHeaders" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-network-setExtraHeaders
* @param params `remote.NetworkSetExtraHeadersParameters` {@link https://w3c.github.io/webdriver-bidi/#command-network-setExtraHeaders | command parameter}
* @returns `Promise<local.NetworkSetExtraHeadersResult>`
**/
async networkSetExtraHeaders(params) {
const result = await this.send({
method: "network.setExtraHeaders",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.addPreloadScript" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-addPreloadScript
* @param params `remote.ScriptAddPreloadScriptParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-addPreloadScript | command parameter}
* @returns `Promise<local.ScriptAddPreloadScriptResult>`
**/
async scriptAddPreloadScript(params) {
const result = await this.send({
method: "script.addPreloadScript",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.disown" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-disown
* @param params `remote.ScriptDisownParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-disown | command parameter}
* @returns `Promise<local.ScriptDisownResult>`
**/
async scriptDisown(params) {
const result = await this.send({
method: "script.disown",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.callFunction" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-callFunction
* @param params `remote.ScriptCallFunctionParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-callFunction | command parameter}
* @returns `Promise<local.ScriptCallFunctionResult>`
**/
async scriptCallFunction(params) {
const result = await this.send({
method: "script.callFunction",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.evaluate" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-evaluate
* @param params `remote.ScriptEvaluateParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-evaluate | command parameter}
* @returns `Promise<local.ScriptEvaluateResult>`
**/
async scriptEvaluate(params) {
const result = await this.send({
method: "script.evaluate",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.getRealms" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-getRealms
* @param params `remote.ScriptGetRealmsParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-getRealms | command parameter}
* @returns `Promise<local.ScriptGetRealmsResult>`
**/
async scriptGetRealms(params) {
const result = await this.send({
method: "script.getRealms",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "script.removePreloadScript" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-script-removePreloadScript
* @param params `remote.ScriptRemovePreloadScriptParameters` {@link https://w3c.github.io/webdriver-bidi/#command-script-removePreloadScript | command parameter}
* @returns `Promise<local.ScriptRemovePreloadScriptResult>`
**/
async scriptRemovePreloadScript(params) {
const result = await this.send({
method: "script.removePreloadScript",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "storage.getCookies" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-storage-getCookies
* @param params `remote.StorageGetCookiesParameters` {@link https://w3c.github.io/webdriver-bidi/#command-storage-getCookies | command parameter}
* @returns `Promise<local.StorageGetCookiesResult>`
**/
async storageGetCookies(params) {
const result = await this.send({
method: "storage.getCookies",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "storage.setCookie" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-storage-setCookie
* @param params `remote.StorageSetCookieParameters` {@link https://w3c.github.io/webdriver-bidi/#command-storage-setCookie | command parameter}
* @returns `Promise<local.StorageSetCookieResult>`
**/
async storageSetCookie(params) {
const result = await this.send({
method: "storage.setCookie",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "storage.deleteCookies" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-storage-deleteCookies
* @param params `remote.StorageDeleteCookiesParameters` {@link https://w3c.github.io/webdriver-bidi/#command-storage-deleteCookies | command parameter}
* @returns `Promise<local.StorageDeleteCookiesResult>`
**/
async storageDeleteCookies(params) {
const result = await this.send({
method: "storage.deleteCookies",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "input.performActions" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-input-performActions
* @param params `remote.InputPerformActionsParameters` {@link https://w3c.github.io/webdriver-bidi/#command-input-performActions | command parameter}
* @returns `Promise<local.InputPerformActionsResult>`
**/
async inputPerformActions(params) {
const result = await this.send({
method: "input.performActions",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "input.releaseActions" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-input-releaseActions
* @param params `remote.InputReleaseActionsParameters` {@link https://w3c.github.io/webdriver-bidi/#command-input-releaseActions | command parameter}
* @returns `Promise<local.InputReleaseActionsResult>`
**/
async inputReleaseActions(params) {
const result = await this.send({
method: "input.releaseActions",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "input.setFiles" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-input-setFiles
* @param params `remote.InputSetFilesParameters` {@link https://w3c.github.io/webdriver-bidi/#command-input-setFiles | command parameter}
* @returns `Promise<local.InputSetFilesResult>`
**/
async inputSetFiles(params) {
const result = await this.send({
method: "input.setFiles",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "webExtension.install" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-webExtension-install
* @param params `remote.WebExtensionInstallParameters` {@link https://w3c.github.io/webdriver-bidi/#command-webExtension-install | command parameter}
* @returns `Promise<local.WebExtensionInstallResult>`
**/
async webExtensionInstall(params) {
const result = await this.send({
method: "webExtension.install",
params
});
return result.result;
}
/**
* WebDriver Bidi command to send command method "webExtension.uninstall" with parameters.
* @url https://w3c.github.io/webdriver-bidi/#command-webExtension-uninstall
* @param params `remote.WebExtensionUninstallParameters` {@link https://w3c.github.io/webdriver-bidi/#command-webExtension-uninstall | command parameter}
* @returns `Promise<local.WebExtensionUninstallResult>`
**/
async webExtensionUninstall(params) {
const result = await this.send({
method: "webExtension.uninstall",
params
});
return result.result;
}
};
// src/utils.ts
var log2 = logger2("webdriver");
var deepmerge = deepmergeCustom({ mergeArrays: false });
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) {
return false;
}
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
return false;
}
for (const key of keysA) {
if (!keysB.includes(key) || !deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
var BROWSER_DRIVER_ERRORS = [
"unknown command: wd/hub/session",
// chromedriver
"HTTP method not allowed",
// geckodriver
"'POST /wd/hub/session' was not found.",
// safaridriver
"Command not found"
// iedriver
];
async function startWebDriverSession(params) {
const capabilities = params.capabilities && "alwaysMatch" in params.capabilities ? params.capabilities : { alwaysMatch: params.capabilities, firstMatch: [{}] };
if (
/**
* except, if user does not want to opt-in
*/
!capabilities.alwaysMatch["wdio:enforceWebDriverClassic"] && /**
* or user requests a Safari session which does not support Bidi
*/
typeof capabilities.alwaysMatch.browserName === "string" && capabilities.alwaysMatch.browserName.toLowerCase() !== "safari"
) {
capabilities.alwaysMatch.webSocketUrl = true;
capabilities.alwaysMatch.unhandledPromptBehavior = "ignore";
if (isAppiumAndroidChrome(capabilities.alwaysMatch) && !hasAppiumCapability(capabilities.alwaysMatch, "chromedriverForwardBiDi")) {
capabilities.alwaysMatch["appium:chromedriverForwardBiDi"] = true;
}
}
validateCapabilities(capabilities.alwaysMatch);
const keysToNormalize = new Set(Object.keys(capabilities.alwaysMatch));
if (capabilities.firstMatch) {
capabilities.firstMatch.forEach((match) => {
Object.keys(match).forEach((key) => keysToNormalize.add(key));
});
for (const key of keysToNormalize) {
const alwaysVal = capabilities.alwaysMatch[key];
if (alwaysVal === void 0) {
continue;
}
const hasConflict = capabilities.firstMatch.some(
(match) => key in match && !deepEqual(match[key], alwaysVal)
);
if (hasConflict) {
delete capabilities.alwaysMatch[key];
capabilities.firstMatch.forEach((match) => {
if (!(key in match)) {
match[key] = alwaysVal;
}
});
} else {
capabilities.firstMatch.forEach((match) => {
if (key in match) {
delete match[key];
}
});
}
}
}
const sessionRequest = new environment.value.Request(
"POST",
"/session",
{ capabilities }
);
let response;
try {
response = await sessionRequest.makeRequest(params);
} catch (err) {
log2.error(err);
const message = getSessionError(err, params);
throw new Error(message);
}
const sessionId = response.value?.sessionId;
const sessionCapabilities = response.value?.capabilities;
if (!sessionId || !sessionCapabilities) {
throw new Error(
"WebDriver new session response is missing a session id or capabilities. WebdriverIO requires a W3C WebDriver server."
);
}
params.capabilities = sessionCapabilities;
return { sessionId, capabilities: sessionCapabilities };
}
function hasAppiumCapability(capabilities, name) {
return getAppiumCapability(capabilities, name) !== void 0;
}
function getAppiumCapability(capabilities, name) {
const appiumOptions = capabilities["appium:options"];
return appiumOptions?.[name] ?? capabilities[`appium:${name}`];
}
function getAppiumBidiAdvice(capabilities, requestedCapabilities) {
const requested = "alwaysMatch" in requestedCapabilities ? requestedCapabilities.alwaysMatch : requestedCapabilities;
if (getAppiumCapability(requested, "chromedriverForwardBiDi") === false) {
return 'Appium answers WebDriver Bidi itself, because "appium:chromedriverForwardBiDi" is false. ';
}
if (/^android$/i.test(capabilities.platformName || "")) {
return "For WebDriver Bidi with Chrome on Android, use Appium 3.9.0 or later with the UiAutomator2 driver 8.7.3 or later. ";
}
return "";
}
function isAppiumAndroidChrome(capabilities) {
const automationName = getAppiumCapability(capabilities, "automationName");
return /^android$/i.test(capabilities.platformName || "") && /^(chrome|chromium)$/i.test(capabilities.browserName || "") && typeof automationName === "string" && /^uiautomator2$/i.test(automationName);
}
function validateCapabilities(capabilities) {
const chromeArgs = capabilities["goog:chromeOptions"]?.args || [];
if (chromeArgs.includes("incognito") || chromeArgs.includes("--incognito")) {
throw new Error(
'Please remove "incognito" from `"goog:chromeOptions".args` as it is not supported running Chrome with WebDriver. WebDriver sessions are always incognito mode and do not persist across browser sessions.'
);
}
if (capabilities) {
const extensionCaps = Object.keys(capabilities).filter((cap) => cap.includes(":"));
const invalidWebDriverCaps = Object.keys(capabilities).filter((cap) => !CAPABILITY_KEYS.includes(cap) && !cap.includes(":"));
if (extensionCaps.length && invalidWebDriverCaps.length) {
throw new Error(
`Invalid or unsupported WebDriver capabilities found ("${invalidWebDriverCaps.join('", "')}"). Ensure to only use valid W3C WebDriver capabilities (see https://w3c.github.io/webdriver/#capabilities).If you run your tests on a remote vendor, like Sauce Labs or BrowserStack, make sure that you put them into vendor specific capabilities, e.g. "sauce:options" or "bstack:options". Please reach out to your vendor support team if you have further questions.`
);
}
}
}
function isSuccessfulResponse(statusCode, body) {
if (!body || typeof body !== "object" || !("value" in body) || typeof body.value === "undefined") {
log2.debug("request failed due to missing body");
return false;
}
const hasErrorResponse = body.value && (typeof body.value === "object" && "error" in body.value && body.value.error || typeof body.value === "object" && "stackTrace" in body.value && body.value.stackTrace || typeof body.value === "object" && "stacktrace" in body.value && body.value.stacktrace);
if (statusCode === 200 && !hasErrorResponse) {
return true;
}
if (statusCode === 404 && typeof body.value === "object" && body.value && "error" in body.value && body.value.error === "no such element") {
return true;
}
if (hasErrorResponse) {
const errMsg = typeof body.value === "object" && body.value && "error" in body.value ? body.value.error : body.value;
log2.debug("request failed due to response error:", errMsg);
return false;
}
return true;
}
function getPrototype({ isChromium, isFirefox, isMobile, isSauce, isSeleniumStandalone }) {
const prototype = {};
const ProtocolCommands = deepmerge(
/**
* if mobile also apply Appium protocol (geolocation, orientation,
* context, settings, and other endpoints current Appium 3 drivers still expose)
*/
isMobile ? deepmerge(AppiumProtocol, WebDriverProtocol) : WebDriverProtocol,
/**
* v10 sessions are W3C, so the BiDi command set is always present.
* A live BiDi connection still depends on `webSocketUrl`.
*/
WebDriverBidiProtocol,
/**
* only apply special Chromium commands if session is using Chrome or Edge
*/
isChromium ? ChromiumProtocol : {},
/**
* only apply special Firefox commands if session is using Firefox
*/
isFirefox ? GeckoProtocol : {},
/**
* only Sauce Labs specific vendor commands
*/
isSauce ? SauceLabsProtocol : {},
/**
* only apply special commands when running tests using
* Selenium Grid or Selenium Standalone server
*/
isSeleniumStandalone ? SeleniumProtocol : {},
{}
);
for (const [endpoint, methods] of Object.entries(ProtocolCommands)) {
for (const [method, commandData] of Object.entries(methods)) {
prototype[commandData.command] = { value: command_default(method, endpoint, commandData, isSeleniumStandalone) };
}
}
return prototype;
}
function getEnvironmentVars({ isMobile, isIOS, isAndroid, isFirefox, isSauce, isSeleniumStandalone, isChromium, isWindowsApp, isMacApp }) {
return {
isMobile: { value: isMobile },
isIOS: { value: isIOS },
isAndroid: { value: isAndroid },
isFirefox: { value: isFirefox },
isSauce: { value: isSauce },
isSeleniumStandalone: { value: isSeleniumStandalone },
isBidi: {
/**
* Return the value of this flag dynamically based on whether the
* BidiHandler was able to connect to the `webSocketUrl` url provided
* by the session response.
*/
get: function() {
return Boolean(this._bidiHandler?.isConnected);
}
},
isChromium: { value: isChromium },
isWindowsApp: { value: isWindowsApp },
isMacApp: { value: isMacApp }
};
}
function setupDirectConnect(client) {
const capabilities = client.capabilities;
const directConnectProtocol = capabilities["appium:directConnectProtocol"];
const directConnectHost = capabilities["appium:directConnectHost"];
const directConnectPath = capabilities["appium:directConnectPath"];
const directConnectPort = capabilities["appium:directConnectPort"];
if (directConnectProtocol && directConnectHost && directConnectPort && (directConnectPath || directConnectPath === "")) {
log2.info(`Found direct connect information in new session response. Will connect to server at ${directConnectProtocol}://${directConnectHost}:${directConnectPort}${directConnectPath}`);
client.options.protocol = directConnectProtocol;
client.options.hostname = directConnectHost;
client.options.port = directConnectPort;
client.options.path = directConnectPath;
}
}
var getSessionError = (err, params = {}) => {
if (err.code === "ECONNREFUSED") {
return `Unable to connect to "${params.protocol}://${params.hostname}:${params.port}${params.path}", make sure browser driver is running on that address.
It seems like the service failed to start or is rejecting any connections.`;
}
if (err.message === "unhandled request") {
return `The browser driver couldn't start the session. Make sure you have set the "path" correctly!`;
}
if (!err.message) {
return "See wdio.* logs for more information.";
}
if (err.message.includes("Whoops! The URL specified routes to this help page.")) {
return "It seems you are running a Selenium Standalone server and point to a wrong path. Please set `path: '/wd/hub'` in your wdio.conf.js!";
}
if (BROWSER_DRIVER_ERRORS.some((m) => err && err.message && err.message.includes(m))) {
return "Make sure to set `path: '/'` in your wdio.conf.js!";
}
if (err.message.includes("Bad Request - Invalid Hostname") && err.message.includes("HTTP Error 400")) {
return "Run edge driver on 127.0.0.1 instead of localhost, ex: --host=127.0.0.1, or set `hostname: 'localhost'` in your wdio.conf.js";
}
const w3cCapMessage = '\nMake sure to add vendor prefix like "goog:", "appium:", "moz:", etc to non W3C capabilities.\nSee more https://www.w3.org/TR/webdriver/#capabilities';
if (err.message.includes("Illegal key values seen in w3c capabilities")) {
return err.message + w3cCapMessage;
}
if (err.message === "Response has empty body") {
return "Make sure to connect to valid hostname:port or the port is not in use.\nIf you use a grid server " + w3cCapMessage;
}
if (err.message.includes("failed serving request POST /wd/hub/session: Unauthorized") && (params.hostname === "saucelabs.com" || params.hostname?.endsWith(".saucelabs.com"))) {
return "Session request was not authorized because you either did provide a wrong access key or tried to run in a region that has not been enabled for your user. If have registered a free trial account it is connected to a specific region. Ensure this region is set in your configuration (https://webdriver.io/docs/options.html#region).";
}
return err.message;
};
function getBidiRequestOptions(strictSSL = true, headers) {
const bidiReqOpts = { followRedirects: true, maxRedirects: 10 };
if (!strictSSL) {
bidiReqOpts.rejectUnauthorized = false;
}
if (headers) {
bidiReqOpts.headers = headers;
}
return bidiReqOpts;
}
function initiateBidi(socketUrl, strictSSL = true, userHeaders, responseTimeout, connectTimeout) {
const isUnitTesting = environment.value.variables.WDIO_UNIT_TESTS;
if (isUnitTesting) {
log2.info("Skip connecting to WebDriver Bidi interface due to unit tests");
return {
_bidiHandler: {
value: {
isConnected: true,
waitForConnected: () => Promise.resolve(),
socket: { on: () => {
}, off: () => {
} }
}
}
};
}
socketUrl = socketUrl.replace("localhost", "127.0.0.1");
const bidiReqOpts = getBidiRequestOptions(strictSSL, userHeaders);
const handler = new BidiHandler(socketUrl, bidiReqOpts, responseTimeout, connectTimeout);
handler.connect().then(
(isConnected) => isConnected && log2.info(`Connected to WebDriver Bidi interface at ${socketUrl}`),
(err) => log2.error(`Could not connect to WebDriver Bidi interface at ${socketUrl}: ${err.message}`)
);
return {
_bidiHandler: { value: handler },
...Object.values(WebDriverBidiProtocol).map((def) => def.socket).reduce((acc, cur) => {
acc[cur.command] = {
value: function(...args) {
const bidiFn = handler[cur.command];
handler.attachClient(this);
this.emit(cur.command, args);
return bidiFn?.apply(handler, args);
}
};
return acc;
}, {})
};
}
async function discardBidiWithoutBrowsingContext(handler, timeout, advice = "") {
let timer;
try {
await Promise.race([
handler.browsingContextGetTree({ maxDepth: 0 }),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`no answer within ${timeout}ms`)), timeout);
})
]);
return true;
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
log2.warn(
`The WebDriver Bidi server of this mobile session can not run browser commands (${reason}), continue with WebDriver Classic. ${advice}To skip this check, set "wdio:enforceWebDriverClassic": true.`
);
handler.discard();
return false;
} finally {
clearTimeout(timer);
}
}
function parseBidiMessage(data) {
try {
const payload = JSON.parse(data.toString());
if (payload.type !== "event") {
return;
}
this.emit(payload.method, payload.params);
} catch (err) {
log2.error(`Failed parse WebDriver Bidi message: ${err.message}`);
}
}
function mask(commandInfo, options, body, args) {
const unmaskedResult = { maskedBody: body, maskedArgs: args, isMasked: false };
if (!options.mask) {
return unmaskedResult;
}
const textValueParamIndex = commandInfo.parameters.findIndex((param) => param.name === "text");
if (textValueParamIndex === -1) {
return unmaskedResult;
}
const textValueIndexInArgs = (commandInfo.variables?.length ?? 0) + textValueParamIndex;
const text = args[textValueIndexInArgs];
if (typeof text !== "string" || !text) {
return unmaskedResult;
}
const maskedBody = {
...body,
text: SENSITIVE_DATA_REPLACER2
};
const textValueArgsIndex = textValueParamIndex + (commandInfo.variables?.length ?? 0);
const maskedArgs = args.slice(0, textValueArgsIndex).concat(SENSITIVE_DATA_REPLACER2).concat(args.slice(textValueArgsIndex + 1));
return {
maskedBody,
maskedArgs,
isMasked: true
};
}
// src/command.ts
var log3 = logger3("webdriver");
var BIDI_COMMANDS = Object.values(WebDriverBidiProtocol2).map((def) => def.socket.command);
var sessionAbortListeners = /* @__PURE__ */ new Map();
function command_default(method, endpointUri, commandInfo, doubleEncodeVariables = false) {
const { command, deprecated, ref, parameters, variables = [], isHubCommand = false } = commandInfo;
return async function protocolCommand(...unmaskedArgs) {
let runtimeOptions = {};
if (unmaskedArgs.length > 0 && unmaskedArgs[unmaskedArgs.length - 1] instanceof CommandRuntimeOptions) {
runtimeOptions = unmaskedArgs.pop();
}
const isBidiCommand = BIDI_COMMANDS.includes(command);
let endpoint = endpointUri;
const commandParams = [...variables.map((v) => Object.assign(v, {
/**
* url variables are:
*/
required: true,
// always required as they are part of the endpoint
type: "string"
// have to be always type of string
})), ...parameters];
const commandUsage = `${command}(${commandParams.map((p) => p.name).join(", ")})`;
const moreInfo = `
For more info see ${ref}
`;
const DISABLE_WEBDRIVERIO_DEPRECATION_WARNINGS = globalThis.process && globalThis.process.env ? globalThis.process.env.DISABLE_WEBDRIVERIO_DEPRECATION_WARNINGS : void 0;
if (typeof deprecated === "string" && !DISABLE_WEBDRIVERIO_DEPRECATION_WARNINGS) {
const warning = deprecated.replace("This command", `The "${command}" command`);
log3.warn(warning);
console.warn(`\u26A0\uFE0F [WEBDRIVERIO DEPRECATION NOTICE] ${warning}`);
}
if (isBidiCommand) {
throw new Error(
`Failed to execute WebDriver Bidi command "${command}" as no Bidi session was established. Make sure you enable it by setting "webSocketUrl: true" in your capabilities and verify that your environment and browser supports it.`
);
}
const minAllowedParams = commandParams.filter((param) => param.required).length;
if (unmaskedArgs.length < minAllowedParams || unmaskedArgs.length > commandParams.length) {
const parameterDescription = commandParams.length ? `
Property Description:
${commandParams.map((p) => ` "${p.name}" (${p.type}): ${p.description}`).join("\n")}` : "";
throw new Error(
`Wrong parameters applied for ${command}
Usage: ${commandUsage}` + parameterDescription + moreInfo
);
}
const unmaskedBody = {};
for (const [it, arg] of Object.entries(unmaskedArgs)) {
if (isBidiCommand) {
break;
}
const i = parseInt(it, 10);
const commandParam = commandParams[i];
if (!isValidParameter(arg, commandParam.type)) {
if (typeof arg === "undefined" && !commandParam.required) {
continue;
}
const actual = commandParam.type.endsWith("[]") ? `(${(Array.isArray(arg) ? arg : [arg]).map((a) => getArgumentType(a))})[]` : getArgumentType(arg);
throw new Error(
`Malformed type for "${commandParam.name}" parameter of command ${command}
Expected: ${commandParam.type}
Actual: ${actual}` + moreInfo
);
}
if (i < variables.length) {
const encodedArg = doubleEncodeVariables ? encodeURIComponent(encodeURIComponent(arg)) : encodeURIComponent(arg);
endpoint = endpoint.replace(`:${commandParams[i].name}`, encodedArg);
continue;
}
unmaskedBody[commandParams[i].name] = arg;
}
const { maskedBody, maskedArgs, isMasked } = mask(commandInfo, runtimeOptions, unmaskedBody, unmaskedArgs);
const { isAborted, abortSignal, cleanup } = manageSessionAbortions.call(this);
const requiresSession = endpointUri.includes("/:sessionId/");
if (isAborted && command !== "deleteSession" && requiresSession) {
const error = new Error(`Trying to run command "${commandCallStructure(command, maskedArgs)}" after session has been deleted, aborting request without executing it`);
error.name = SESSION_ENDED_ERROR;
throw error;
}
const request = new environment.value.Request(method, endpoint, unmaskedBody, abortSignal, isHubCommand, {
onPerformance: (data) => this.emit("request.performance", { ...data, request: {
...data.request,
body: isMasked ? maskedBody : data.request.body
} }),
onRequest: (data) => this.emit("request.start", { ...data, body: isMasked ? maskedBody : data.body }),
onResponse: (data) => this.emit("request.end", data),
onRetry: (data) => this.emit("request.retry", data),
onLogData: (data) => log3.info("DATA", transformCommandLogResult(isMasked ? maskedBody : data))
});
if (isMasked) {
request.maskedBody = maskedBody;
}
this.emit("command", { command, method, endpoint, body: maskedBody });
log3.info("COMMAND", commandCallStructure(command, maskedArgs));
const options = isMasked ? { ...this.options, headers: { ...this.options.headers, ...APPIUM_MASKING_HEADER } } : this.options;
let sessionCleanedUp = false;
const cleanUpSession = async (deleted) => {
if (command !== "deleteSession" || sessionCleanedUp) {
return;
}
sessionCleanedUp = true;
const browser = this;
browser._bidiHandler?.close();
const shutdownDriver = maskedBody.deleteSessionOpts?.shutdownDriver !== false;
await environment.value.killDriverProcess(this.capabilities, shutdownDriver, deleted ? this.requestedCapabilities : void 0);
if (!environment.value.variables.WDIO_WORKER_ID) {
logger3.clearLogger();
}
};
return request.makeRequest(options, this.sessionId).then((result) => {
if (typeof result.value !== "undefined") {
let resultLog = result.value;
if (/screenshot|recording/i.test(command) && typeof result.value === "string" && result.value.length > 64) {
resultLog = `${result.value.slice(0, 61)}...`;
} else if (command === "executeScript" && typeof maskedBody.script === "string" && maskedBody.script.includes("(() => window.__wdioEvents__)")) {
resultLog = `[${result.value.length} framework events captured]`;
}
log3.info("RESULT", resultLog);
}
this.emit("result", { command, method, endpoint, body: maskedBody, result });
const value = result.value;
return command === "deleteSession" ? cleanUpSession(true).then(() => value) : value;
}).catch((error) => {
this.emit("result", { command, method, endpoint, body: maskedBody, result: { error } });
if (command === "deleteSession") {
return cleanUpSession(false).then(() => {
throw error;
});
}
throw error;
}).finally(() => {
cleanup();
});
};
}
function manageSessionAbortions() {
const abort2 = new AbortController();
const abortOnSessionEnd = (result) => {
if (result.command !== "deleteSession") {
return;
}
const abortListeners = sessionAbortListeners.get(this.sessionId);
if (abortListeners) {
for (const abortListener of abortListeners) {
abortListener.abort();
}
abortListeners.clear();
sessionAbortListeners.set(this.sessionId, null);
}
this.off("result", abortOnSessionEnd);
};
let abortListenerForCurrentSession = sessionAbortListeners.get(this.sessionId);
if (typeof abortListenerForCurrentSession === "undefined") {
abortListenerForCurrentSession = /* @__PURE__ */ new Set();
sessionAbortListeners.set(this.sessionId, abortListenerForCurrentSession);
this.on("result", abortOnSessionEnd);
}
if (abortListenerForCurrentSession === null) {
return { isAborted: true, abortSignal: void 0, cleanup: () => {
} };
}
abortListenerForCurrentSession.add(abort2);
return {
isAborted: false,
abortSignal: abort2.signal,
cleanup: () => {
abortListenerForCurrentSession?.delete(abort2);
}
};
}
// src/classicProtocolCommand.ts
import { WebDriverProtocol as WebDriverProtocol2 } from "@wdio/protocols";
var protocol = WebDriverProtocol2;
var CLASSIC_HISTORY_COMMANDS = {
back: {
method: "POST",
endpoint: "/session/:sessionId/back"
},
forward: {
method: "POST",
endpoint: "/session/:sessionId/forward"
}
};
async function runClassicProtocolCommand(commandName) {
const definition = CLASSIC_HISTORY_COMMANDS[commandName];
if (!definition) {
throw new Error(`Unknown classic protocol command "${String(commandName)}"`);
}
const commandInfo = protocol[definition.endpoint]?.POST;
if (!commandInfo || commandInfo.command !== commandName) {
throw new Error(`Classic protocol command "${commandName}" is not defined`);
}
const run = command_default(
definition.method,
definition.endpoint,
commandInfo,
Boolean(this.isSeleniumStandalone)
);
await run.call(this);
}
// src/sessionEnded.ts
function isSessionEndedError(err) {
const name = err instanceof Error ? err.name : void 0;
return name === SESSION_ENDED_ERROR || name === "invalid session id";
}
function isBidiConnectionClosed(client) {
return client?._bidiHandler?.isClosed === true;
}
// src/bidi/localTypes.ts
var localTypes_exports = {};
// src/bidi/remoteTypes.ts
var remoteTypes_exports = {};
// src/index.ts
var log4 = logger4("webdriver");
async function listenToBidiEvents(client, handler, capabilities, requestedCapabilities, isMobile, checkTimeout) {
if (isMobile && capabilities.browserName && !await discardBidiWithoutBrowsingContext(handler, checkTimeout, getAppiumBidiAdvice(capabilities, requestedCapabilities))) {
delete capabilities.webSocketUrl;
return;
}
handler.socket?.on("message", parseBidiMessage.bind(client));
}
var WebDriver = class _WebDriver {
static async newSession(options, modifier, userPrototype = {}, customCommandWrapper, implicitWaitExclusionList = []) {
const envLogLevel = environment.value.variables.WDIO_LOG_LEVEL;
options.logLevel = envLogLevel ?? options.logLevel;
const params = validateConfig(DEFAULTS, options);
if (params.logLevel && (!options.logLevels || !options.logLevels.webdriver)) {
logger4.setLevel("webdriver", params.logLevel);
}
log4.info("Initiate new session using the WebDriver protocol");
const driverProcess = await startWebDriver(params);
const requestedCapabilities = { ...params.capabilities };
const { sessionId, capabilities } = await startWebDriverSession(params);
const environment2 = sessionEnvironmentDetector({ capabilities, requestedCapabilities });
const environmentPrototype = getEnvironmentVars(environment2);
const protocolCommands = getPrototype(environment2);
if (driverProcess?.pid) {
capabilities["wdio:driverPID"] = driverProcess.pid;
}
const bidiPrototype = {};
if (isBidi(capabilities)) {
log4.info(`Register BiDi handler for session with id ${sessionId}`);
Object.assign(bidiPrototype, initiateBidi(
capabilities.webSocketUrl,
options.strictSSL,
options.headers,
params.bidiResponseTimeout,
params.bidiConnectTimeout
));
}
const monad = webdriverMonad(
{ ...params, requestedCapabilities },
modifier,
{
...protocolCommands,
...environmentPrototype,
...userPrototype,
...bidiPrototype
}
);
const client = monad(sessionId, customCommandWrapper, implicitWaitExclusionList);
if (isBidi(capabilities)) {
if (await client._bidiHandler.waitForConnected()) {
await listenToBidiEvents(client, client._bidiHandler, capabilities, requestedCapabilities, environment2.isMobile, params.bidiConnectTimeout ?? DEFAULT_CONNECT_TIMEOUT);
}
}
if (params.enableDirectConnect) {
setupDirectConnect(client);
}
return client;
}
/**
* allows user to attach to existing sessions
*/
static attachToSession(options, modifier, userPrototype = {}, commandWrapper) {
if (!options || typeof options.sessionId !== "string") {
throw new Error("sessionId is required to attach to existing session");
}
if (options.logLevel) {
logger4.setLevel("webdriver", options.logLevel);
}
options.capabilities = options.capabilities || {};
options.protocol = options.protocol || DEFAULTS.protocol.default;
options.hostname = options.hostname || DEFAULTS.hostname.default;
options.port = options.port || DEFAULTS.port.default;
options.path = options.path || DEFAULTS.path.default;
const environment2 = sessionEnvironmentDetector({ capabilities: options.capabilities, requestedCapabilities: options.capabilities });
const attachOptions = { ...options };
delete attachOptions.isW3C;
options = Object.assign(environment2, attachOptions);
const environmentPrototype = getEnvironmentVars(options);
const protocolCommands = getPrototype(options);
const bidiPrototype = {};
if (isBidi(options.capabilities || {})) {
const webSocketUrl = options.capabilities?.webSocketUrl;
log4.info(`Register BiDi handler for session with id ${options.sessionId}`);
Object.assign(bidiPrototype, initiateBidi(
webSocketUrl,
options.strictSSL,
options.headers,
options.bidiResponseTimeout,
options.bidiConnectTimeout
));
}
const prototype = { ...protocolCommands, ...environmentPrototype, ...userPrototype, ...bidiPrototype };
const monad = webdriverMonad(options, modifier, prototype);
const client = monad(options.sessionId, commandWrapper);
if (isBidi(options.capabilities || {})) {
client._bidiHandler?.waitForConnected().then((isConnected) => {
if (isConnected) {
client._bidiHandler?.socket?.on("message", parseBidiMessage.bind(client));
}
});
}
return client;
}
/**
* Changes The instance session id and browser capabilities for the new session
* directly into the passed in browser object
*
* @param {object} instance the object we get from a new browser session.
* @returns {string} the new session id of the browser
*/
static async reloadSession(instance, newCapabilities) {
const capabilities = newCapabilities ? newCapabilities : Object.assign({}, instance.requestedCapabilities);
let params = { ...instance.options, capabilities };
for (const prop of ["protocol", "hostname", "port", "path", "queryParams", "user", "key"]) {
if (prop in capabilities) {
params = { ...params, [prop]: capabilities[prop] };
delete capabilities[prop];
}
}
let driverProcess;
if (params.hostname === "localhost" && newCapabilities?.browserName) {
delete params.port;
delete params.hostname;
driverProcess = await startWebDriver(params);
}
const { sessionId, capabilities: newSessionCapabilities } = await startWebDriverSession(params);
if (driverProcess?.pid) {
newSessionCapabilities["wdio:driverPID"] = driverProcess.pid;
}
for (const prop of ["protocol", "hostname", "port", "path", "queryParams", "user", "key"]) {
if (prop in params) {
instance.options[prop] = params[prop];
}
}
for (const prop in instance.requestedCapabilities) {
delete instance.requestedCapabilities[prop];
}
const driverPid = instance.capabilities["wdio:driverPID"];
instance.sessionId = sessionId;
instance.capabilities = newSessionCapabilities;
if (!driverProcess?.pid) {
instance.capabilities["wdio:driverPID"] = driverPid;
}
Object.assign(instance.requestedCapabilities, capabilities);
if (isBidi(instance.capabilities || {})) {
const bidiReqOpts = getBidiRequestOptions(instance.options.strictSSL, instance.options.headers);
const isConnected = await instance._bidiHandler?.reconnect(newSessionCapabilities.webSocketUrl, bidiReqOpts);
if (instance._bidiHandler && isConnected) {
const { isMobile } = sessionEnvironmentDetector({ capabilities: newSessionCapabilities, requestedCapabilities: capabilities });
await listenToBidiEvents(instance, instance._bidiHandler, newSessionCapabilities, capabilities, isMobile, instance.options.bidiConnectTimeout ?? DEFAULT_CONNECT_TIMEOUT);
}
}
return sessionId;
}
static get WebDriver() {
return _WebDriver;
}
};
// src/request/node.ts
import dns from "node:dns";
import { fetch as fetch2, Agent, ProxyAgent, getGlobalDispatcher } from "undici";
// src/request/request.ts
import logger5 from "@wdio/logger";
import { sleep } from "@wdio/utils";
// src/request/error.ts
import { transformCommandLogResult as transformCommandLogResult2 } from "@wdio/utils";
// src/request/abort.ts
var timeoutSignals = /* @__PURE__ */ new WeakSet();
var timers = /* @__PURE__ */ new WeakMap();
function clearAbortTimer(signal) {
if (!signal) {
return;
}
const timer = timers.get(signal);
if (timer === void 0) {
return;
}
clearTimeout(timer);
timers.delete(signal);
}
function isConnectionTimeoutSignal(signal) {
return Boolean(signal && timeoutSignals.has(signal));
}
function unrefTimer(timer) {
if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") {
timer.unref();
}
}
function timeoutReason() {
return new DOMException("The operation was aborted due to timeout", "TimeoutError");
}
function abort(controller, reason) {
if (controller.signal.aborted) {
return;
}
if (reason === void 0) {
controller.abort();
return;
}
try {
controller.abort(reason);
} catch {
controller.abort();
}
if (!("reason" in controller.signal) || controller.signal.reason !== reason) {
try {
Object.defineProperty(controller.signal, "reason", {
configurable: true,
value: reason
});
} catch {
}
}
}
function createRequestSignal(timeout, signal) {
const controller = new AbortController();
const timer = setTimeout(() => {
timeoutSignals.add(controller.signal);
abort(controller, timeoutReason());
}, timeout);
unrefTimer(timer);
timers.set(controller.signal, timer);
const onCallerAbort = () => {
const reason = signal && "reason" in signal ? signal.reason : void 0;
abort(controller, reason);
};
if (signal) {
if (signal.aborted) {
onCallerAbort();
return controller.signal;
}
signal.addEventListener("abort", onCallerAbort);
}
controller.signal.addEventListener("abort", () => {
clearAbortTimer(controller.signal);
signal?.removeEventListener("abort", onCallerAbort);
});
return controller.signal;
}
// src/request/constants.ts
var RETRYABLE_STATUS_CODES = [408, 413, 429, 500, 502, 503, 504];
var RETRYABLE_ERROR_CODES = [
"ETIMEDOUT",
"ECONNRESET",
"EADDRINUSE",
"ECONNREFUSED",
"EPIPE",
"ENOTFOUND",
"ENETUNREACH",
"EAI_AGAIN",
// additional error codes we like to retry
"UND_ERR_CONNECT_TIMEOUT",
"UND_ERR_SOCKET"
];
var REG_EXPS = {
commandName: /.*\/session\/[0-9a-f-]+\/(.*)/,
execFn: /return \(([\s\S]*)\)\.apply\(null, arguments\)/
};
// src/request/error.ts
function errorCause(err) {
if (!("cause" in err)) {
return void 0;
}
return err.cause;
}
function parseRequestBody(body) {
if (typeof body === "string") {
try {
body = JSON.parse(body);
} catch {
return void 0;
}
}
return body && typeof body === "object" && !Array.isArray(body) ? body : void 0;
}
var WebDriverError = class extends Error {
/**
* return timeout error with information about the executing command on which the test hangs
*/
computeErrorMessage() {
const cmdName = this.#getExecCmdName();
const cmdArgs = this.#getExecCmdArgs(this.opts);
const cmdInfoMsg = `when running "${cmdName}" with method "${this.opts.method}"`;
const cmdArgsMsg = cmdArgs ? ` and args ${cmdArgs}` : "";
return `WebDriverError: ${this.message} ${cmdInfoMsg}${cmdArgsMsg}`;
}
#getExecCmdName() {
const { href } = this.url;
const res = href.match(REG_EXPS.commandName) || [];
return res[1] || href;
}
#getExecCmdArgs(requestOptions) {
const cmdJson = parseRequestBody(requestOptions.body);
if (!cmdJson) {
return "";
}
const transformedRes = transformCommandLogResult2(cmdJson);
if (typeof transformedRes === "string") {
return transformedRes;
}
if (typeof cmdJson.script === "string") {
const scriptRes = cmdJson.script.match(REG_EXPS.execFn) || [];
return `"${scriptRes[1] || cmdJson.script}"`;
}
return Object.keys(cmdJson).length ? `"${JSON.stringify(cmdJson)}"` : "";
}
};
var WebDriverRequestError = class extends WebDriverError {
url;
opts;
statusCode;
body;
code;
constructor(err, url, opts) {
let message = err.message;
if (err.message === "fetch failed") {
message = `Failed to fetch [${opts.method}] ${url.href}: please make sure you have a WebDriver compatible server running on ${url.origin}`;
}
super(message);
this.url = url;
this.opts = opts;
const cause = errorCause(err);
const isAbortTimeout = err.name === "TimeoutError" || isConnectionTimeoutSignal(this.opts.signal);
const errorCode = typeof cause === "object" && cause && "code" in cause && typeof cause.code === "string" ? cause.code : "code" in err && typeof err.code === "string" ? err.code : isAbortTimeout ? "ETIMEDOUT" : void 0;
if (errorCode) {
this.code = errorCode;
this.message = errorCode === "UND_ERR_CONNECT_TIMEOUT" || isAbortTimeout ? 'Request timed out! Consider increasing the "connectionRetryTimeout" option.' : "Request failed with error code " + errorCode;
}
if (typeof cause === "object" && cause) {
this.statusCode = "statusCode" in cause && typeof cause.statusCode === "number" ? cause.statusCode : void 0;
this.body = "body" in cause ? cause.body : void 0;
}
this.message = this.computeErrorMessage();
}
};
var WebDriverResponseError = class _WebDriverResponseError extends WebDriverError {
url;
opts;
constructor(response, url, opts) {
const errorObj = !response || typeof response !== "object" || !("body" in response) || !response.body ? new Error("Response has empty body") : typeof response.body === "string" && response.body.length ? new Error(response.body) : typeof response.body !== "object" ? new Error("Unknown error") : "value" in response.body && response.body.value ? response.body.value : response.body;
let errorMessage = errorObj.message || errorObj.error || errorObj.class || "unknown error";
if (typeof errorMessage === "string" && errorMessage.includes("invalid locator")) {
const requestBody = parseRequestBody(opts.body);
errorMessage = `The selector "${requestBody?.value}" used with strategy "${requestBody?.using}" is invalid!`;
}
super(errorMessage);
if (errorObj.error) {
this.name = errorObj.error;
} else if (errorMessage && errorMessage.includes("stale element reference")) {
this.name = "stale element reference";
} else {
this.name = errorObj.name || "WebDriver Error";
}
Error.captureStackTrace(this, _WebDriverResponseError);
this.url = url;
this.opts = opts;
this.message = this.computeErrorMessage();
}
};
// package.json
var package_default = {
name: "webdriver",
version: "10.1.0",
description: "A Node.js bindings implementation for the W3C WebDriver and WebDriver Bidi protocols",
author: "Christian Bromann <mail@bromann.dev>",
homepage: "https://github.com/webdriverio/webdriverio/tree/main/packages/webdriver",
license: "MIT",
type: "module",
main: "./build/index.cjs",
module: "./build/index.js",
exports: {
".": {
types: "./build/index.d.ts",
browserSource: "./src/browser.js",
browser: "./build/index.js",
importSource: "./src/node.ts",
import: "./build/node.js",
requireSource: "./src/index.cts",
require: "./build/index.cjs"
}
},
types: "./build/index.d.ts",
typeScriptVersion: "6.0.3",
engines: {
node: ">=22.23.4 <23 || >=24.22.1 <25 || >=26.12.1"
},
repository: {
type: "git",
url: "git+https://github.com/webdriverio/webdriverio.git",
directory: "packages/webdriver"
},
keywords: [
"webdriver"
],
bugs: {
url: "https://github.com/webdriverio/webdriverio/issues"
},
dependencies: {
"@types/node": "^22.20.4",
"@types/ws": "^8.5.3",
"@wdio/config": "workspace:*",
"@wdio/logger": "workspace:*",
"@wdio/protocols": "workspace:*",
"@wdio/types": "workspace:*",
"@wdio/utils": "workspace:*",
"deepmerge-ts": "^8.0.0",
"https-proxy-agent": "^9.1.0",
undici: "^8.12.3",
ws: "^8.21.0"
}
};
// src/request/request.ts
var ERRORS_TO_EXCLUDE_FROM_RETRY = [
"detached shadow root",
"move target out of bounds",
"element click intercepted",
"element not interactable",
"invalid element state",
/**
* Well-formed W3C errors the driver answers deterministically. Repeating
* the request gives the same answer and re-runs its side effects.
* `unknown error` stays retryable, it is what a Grid or proxy sends when
* it hiccups.
*/
"invalid argument",
"invalid cookie domain",
"invalid selector",
"invalid session id",
"javascript error",
"no such alert",
"no such cookie",
"no such element",
"no such frame",
"no such shadow root",
"no such window",
"script timeout",
"session not created",
"timeout",
"unable to capture screen",
"unable to set cookie",
"unexpected alert open",
"unknown command",
"unknown method",
"unsupported operation"
];
var DEFAULT_HEADERS = {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
"User-Agent": "webdriver/" + package_default.version
};
var log5 = logger5("webdriver");
function hasLoggableBody(body) {
if (typeof body === "string") {
return body.length > 0;
}
if (body instanceof URLSearchParams || body instanceof FormData) {
return !body.keys().next().done;
}
if (body instanceof Blob) {
return body.size > 0;
}
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
return body.byteLength > 0;
}
return Object.keys(body).length > 0;
}
function toLoggableBody(body) {
if (typeof body !== "string") {
return body;
}
try {
return JSON.parse(body);
} catch {
return body;
}
}
var WebDriverRequest = class {
body;
/**
* body with sensitive values replaced, shown in errors instead of `body`
*/
maskedBody;
method;
endpoint;
isHubCommand;
requiresSessionId;
eventHandler;
abortSignal;
connectionRetryTimeout = DEFAULTS.connectionRetryTimeout.default;
constructor(method, endpoint, body, abortSignal, isHubCommand = false, eventHandler = {}) {
this.body = body;
this.method = method;
this.endpoint = endpoint;
this.isHubCommand = isHubCommand;
this.requiresSessionId = Boolean(this.endpoint.match(/:sessionId/));
this.eventHandler = eventHandler;
this.abortSignal = abortSignal;
}
/**
* errors carry the request options, they must never expose masked values
*/
errorOptions(opts) {
return this.maskedBody ? { ...opts, body: JSON.stringify(this.maskedBody) } : opts;
}
async makeRequest(options, sessionId) {
const { url, requestOptions } = await this.createOptions(options, sessionId);
this.eventHandler.onRequest?.(requestOptions);
return this._request(url, requestOptions, options.transformResponse, options.connectionRetryCount, 0);
}
async createOptions(options, sessionId, isBrowser = false) {
this.connectionRetryTimeout = options.connectionRetryTimeout || DEFAULTS.connectionRetryTimeout.default;
const requestOptions = {
method: this.method,
redirect: "follow",
signal: this.abortSignal
};
const requestHeaders = new Headers({
...DEFAULT_HEADERS,
...typeof options.headers === "object" ? options.headers : {}
});
const searchParams = isBrowser ? void 0 : typeof options.queryParams === "object" ? options.queryParams : void 0;
if (this.body && (Object.keys(this.body).length || this.method === "POST")) {
requestOptions.body = JSON.stringify(this.body);
}
let endpoint = this.endpoint;
if (this.requiresSessionId) {
if (!sessionId) {
throw new Error("A sessionId is required for this command");
}
endpoint = endpoint.replace(":sessionId", sessionId);
}
const url = new URL(`${options.protocol}://${options.hostname}:${options.port}${this.isHubCommand ? this.endpoint : `${options.path || ""}/${endpoint}`.replace(/(\/){2,}/g, "/")}`);
if (searchParams) {
url.search = new URLSearchParams(searchParams).toString();
}
if (this.endpoint === "/session" && options.user && options.key) {
requestHeaders.set("Authorization", "Basic " + btoa(options.user + ":" + options.key));
}
requestOptions.headers = requestHeaders;
return {
url,
requestOptions: typeof options.transformRequest === "function" ? options.transformRequest(requestOptions) : requestOptions
};
}
async _libRequest(url, opts) {
try {
const response = await this.fetch(url, opts);
return await this.parseResponse(response);
} catch (err) {
if (!(err instanceof Error)) {
throw new WebDriverRequestError(
new Error(`Failed to fetch ${url.href}: ${err.message || err || "Unknown error"}`),
url,
this.errorOptions(opts)
);
}
throw new WebDriverRequestError(err, url, this.errorOptions(opts));
}
}
async parseResponse(response) {
const rawBody = await response.text();
try {
return {
statusCode: response.status,
body: rawBody ? JSON.parse(rawBody) : {}
};
} catch {
const error = new Error(`Could not parse response body: "${rawBody}"`);
Object.defineProperty(error, "cause", {
configurable: true,
value: {
statusCode: response.status,
body: rawBody
}
});
throw error;
}
}
async _request(url, fullRequestOptions, transformResponse, totalRetryCount = 0, retryCount = 0) {
log5.info(`[${fullRequestOptions.method}] ${url.href}`);
const loggableBody = fullRequestOptions.body && toLoggableBody(fullRequestOptions.body);
if (loggableBody && hasLoggableBody(loggableBody)) {
this.eventHandler.onLogData?.(loggableBody);
}
const signal = createRequestSignal(this.connectionRetryTimeout, fullRequestOptions.signal);
const requestLibOptions = {
...fullRequestOptions,
signal
};
const startTime = performance.now();
let response = await this._libRequest(url, requestLibOptions).catch((err) => err).finally(() => clearAbortTimer(signal));
const durationMillisecond = performance.now() - startTime;
const retry = async (error2) => {
if (retryCount >= totalRetryCount || error2.name === "invalid session id") {
log5.error(error2.message);
this.eventHandler.onResponse?.({ error: error2 });
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error: error2, retryCount });
throw error2;
}
if (retryCount > 0) {
await sleep(Math.min(1e4, 250 * Math.pow(2, retryCount)));
}
++retryCount;
this.eventHandler.onRetry?.({ error: error2, retryCount });
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error: error2, retryCount });
log5.warn(error2.message);
log5.info(`Retrying ${retryCount}/${totalRetryCount}`);
return this._request(url, fullRequestOptions, transformResponse, totalRetryCount, retryCount);
};
if (response instanceof Error) {
const resError = response;
if (!(this.abortSignal && this.abortSignal.aborted) && (resError.code && RETRYABLE_ERROR_CODES.includes(resError.code) || resError.statusCode && RETRYABLE_STATUS_CODES.includes(resError.statusCode))) {
return retry(resError);
}
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error: response, retryCount });
throw response;
}
if (typeof transformResponse === "function") {
response = transformResponse(response, fullRequestOptions);
}
if (isSuccessfulResponse(response.statusCode, response.body)) {
this.eventHandler.onResponse?.({ result: response.body });
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: true, retryCount });
return response.body;
}
const error = new WebDriverResponseError(response, url, this.errorOptions(fullRequestOptions));
if (this.isHubCommand) {
if (typeof response.body === "string" && response.body.startsWith("<!DOCTYPE html>")) {
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error, retryCount });
return Promise.reject(new Error("Command can only be called to a Selenium Hub"));
}
return { value: response.body || null };
}
if (error.name === "stale element reference") {
log5.warn("Request encountered a stale element - terminating request");
this.eventHandler.onResponse?.({ error });
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error, retryCount });
throw error;
}
if (ERRORS_TO_EXCLUDE_FROM_RETRY.includes(error.name)) {
this.eventHandler.onResponse?.({ error });
this.eventHandler.onPerformance?.({ request: fullRequestOptions, durationMillisecond, success: false, error, retryCount });
throw error;
}
return retry(error);
}
};
// src/request/node.ts
dns.setDefaultResultOrder("ipv4first");
var SESSION_DISPATCHERS = /* @__PURE__ */ new Map();
var FetchRequest = class extends WebDriverRequest {
async fetch(url, opts) {
return await fetch2(url, opts);
}
async makeRequest(options, sessionId) {
try {
return await super.makeRequest(options, sessionId);
} finally {
const sessionIdToClean = this.method === "DELETE" ? this.getDeletedSessionId(sessionId) : void 0;
if (sessionIdToClean) {
this.cleanupSessionDispatcher(sessionIdToClean);
}
}
}
/**
* regex should only target the delete session request, not other
* delete requests, full list: https://www.w3.org/TR/webdriver2/#endpoints
*/
getDeletedSessionId(sessionId) {
const id = this.endpoint.match(/\/session\/([^/]+)$/)?.[1];
return id === ":sessionId" ? sessionId : id;
}
getDispatcher(url, options, sessionId) {
if (sessionId && SESSION_DISPATCHERS.has(sessionId)) {
return SESSION_DISPATCHERS.get(sessionId);
}
try {
const globalDispatcher = getGlobalDispatcher();
if (globalDispatcher && (globalDispatcher.constructor.name === "ProxyAgent" || globalDispatcher.constructor.name === "MockAgent" || "proxy" in globalDispatcher || // Also check for other custom dispatcher types
globalDispatcher.constructor.name !== "Agent" && globalDispatcher.constructor.name !== "MockAgent")) {
return globalDispatcher;
}
} catch {
}
const { PROXY_URL, NO_PROXY } = environment.value.variables;
const shouldUseProxy = PROXY_URL && !NO_PROXY?.some((str) => url.hostname.endsWith(str));
const tlsOptions = options.strictSSL === false ? { rejectUnauthorized: false } : void 0;
const dispatcher = shouldUseProxy ? new ProxyAgent({
uri: PROXY_URL,
connectTimeout: options.connectionRetryTimeout,
headersTimeout: options.connectionRetryTimeout,
bodyTimeout: options.connectionRetryTimeout,
...tlsOptions ? { requestTls: tlsOptions, proxyTls: tlsOptions } : {}
}) : new Agent({
connectTimeout: options.connectionRetryTimeout,
headersTimeout: options.connectionRetryTimeout,
bodyTimeout: options.connectionRetryTimeout,
...tlsOptions ? { connect: tlsOptions } : {}
});
if (sessionId) {
SESSION_DISPATCHERS.set(sessionId, dispatcher);
}
return dispatcher;
}
cleanupSessionDispatcher(sessionId) {
const dispatcher = SESSION_DISPATCHERS.get(sessionId);
if (dispatcher && typeof dispatcher.close === "function") {
dispatcher.close();
}
SESSION_DISPATCHERS.delete(sessionId);
}
async createOptions(options, sessionId, isBrowser = false) {
const { url, requestOptions } = await super.createOptions(options, sessionId, isBrowser);
requestOptions.dispatcher = this.getDispatcher(url, options, sessionId);
return { url, requestOptions };
}
};
// src/request/web.ts
var FetchRequest2 = class extends WebDriverRequest {
fetch(url, opts) {
return fetch(url, opts);
}
};
// src/node/bidi.ts
import { isIP } from "node:net";
import dns2 from "node:dns/promises";
import logger6 from "@wdio/logger";
import WebSocket from "ws";
import { HttpsProxyAgent } from "https-proxy-agent";
var log6 = logger6("webdriver");
async function createBidiConnection(webSocketUrl, options, connectTimeout) {
const candidateUrls = await listWebsocketCandidateUrls(webSocketUrl);
return connectWebsocket(candidateUrls, options, connectTimeout);
}
async function listWebsocketCandidateUrls(webSocketUrl) {
const parsedUrl = new URL(webSocketUrl);
const candidateUrls = [webSocketUrl];
if (isIP(parsedUrl.hostname)) {
return candidateUrls;
}
try {
const candidateIps = await dns2.lookup(parsedUrl.hostname, { family: 0, all: true });
if (candidateIps.length > 1) {
const hostnameMapper = (result) => {
const candidateUrl = new URL(webSocketUrl);
candidateUrl.hostname = isIP(result.address) === 6 ? `[${result.address}]` : result.address;
return candidateUrl.toString();
};
candidateUrls.push(...candidateIps.map(hostnameMapper));
}
} catch (error) {
log6.error(`Could not resolve hostname ${parsedUrl.hostname}: ${error}`);
}
return candidateUrls;
}
async function connectWebsocket(candidateUrls, options, connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
const websockets = candidateUrls.map((candidateUrl) => {
log6.debug(`Attempt to connect to webSocketUrl ${candidateUrl}`);
try {
const finalizedOptions = { ...options };
const { PROXY_URL, NO_PROXY } = environment.value.variables;
const shouldUseProxy = PROXY_URL && !NO_PROXY?.some((str) => {
try {
return new URL(candidateUrl).hostname.endsWith(str);
} catch {
return false;
}
});
if (shouldUseProxy) {
log6.debug(`Adding proxy ${PROXY_URL} for webSocketUrl ${candidateUrl}`);
finalizedOptions.agent = new HttpsProxyAgent(PROXY_URL);
}
const ws2 = new WebSocket(candidateUrl, finalizedOptions);
return ws2;
} catch {
return void 0;
}
}).filter(Boolean);
const wsConnectPromises = websockets.map((ws2, index) => {
const promise = new Promise((resolve) => {
ws2.once("open", () => resolve({ ws: ws2, isConnected: true, index }));
ws2.once("error", (err) => {
log6.debug(`Could not connect to Bidi protocol at ${candidateUrls[index]}: ${err.message}`);
resolve({ ws: ws2, isConnected: false, errorMessage: err.message, index });
});
});
return { promise, index };
});
let timeoutId;
const connectionTimeoutPromise = new Promise((resolve) => {
timeoutId = setTimeout(() => {
log6.error(
`Could not connect to Bidi protocol of any candidate url within ${connectTimeout}ms: "${candidateUrls.join('", "')}". If the browser is slow to accept the connection, increase the "bidiConnectTimeout" option.`
);
return resolve(void 0);
}, connectTimeout);
});
const wsInfo = await Promise.race([
firstResolved(wsConnectPromises),
connectionTimeoutPromise
]);
clearTimeout(timeoutId);
const socketsToCleanup = wsInfo ? websockets.filter((_, index) => wsInfo.index !== index) : websockets;
for (const socket of socketsToCleanup) {
socket.terminate();
}
if (wsInfo?.isConnected) {
log6.info(`Connected to Bidi protocol at ${candidateUrls[wsInfo.index]}`);
return wsInfo.ws;
}
return void 0;
}
function firstResolved(promises, errorMessages = []) {
if (promises.length === 0) {
const sep = "\n - ";
const errorMessage = errorMessages.length > 0 ? sep + errorMessages.join(sep) : "";
log6.error("Could not connect to Bidi protocol" + errorMessage);
return Promise.resolve(void 0);
}
return Promise.race(promises.map(({ promise }) => promise)).then((result) => {
if (result.isConnected) {
return result;
}
return firstResolved(
promises.filter(({ index }) => index !== result.index),
[...errorMessages, result.errorMessage || "unknown error"]
);
});
}
// src/node/utils.ts
import fs from "node:fs";
import logger7 from "@wdio/logger";
var log7 = logger7("webdriver");
var PROFILE_REMOVAL_TIMEOUT = 2e3;
var PROFILE_POLL_INTERVAL = 10;
function kill(pid) {
log7.info(`Kill driver process with PID ${pid}`);
try {
const killedSuccessfully = process.kill(pid, "SIGKILL");
if (!killedSuccessfully) {
log7.warn("Failed to kill driver process, manually clean-up might be required");
}
} catch (err) {
log7.warn("Failed to kill driver process", err);
}
setTimeout(() => {
for (const handle of process._getActiveHandles()) {
if (handle.servername && handle.servername.includes("edgedl.me")) {
handle.destroy();
}
}
}, 10);
}
function driverProfileOf(capabilities, requestedCapabilities) {
const w3c = requestedCapabilities;
const requests = [w3c?.alwaysMatch || requestedCapabilities, ...w3c?.firstMatch || []].filter(Boolean);
if (!requests.some((request) => request.browserName) || requests.some((request) => "chrome" in request || "msedge" in request)) {
return void 0;
}
const args = requests.flatMap((request) => [...request["goog:chromeOptions"]?.args || [], ...request["ms:edgeOptions"]?.args || []]);
if (args.some((arg) => typeof arg === "string" && arg.includes("user-data-dir"))) {
return void 0;
}
const caps = capabilities;
return caps.chrome?.userDataDir || caps.msedge?.userDataDir;
}
async function waitForRemoval(profile) {
const start = Date.now();
while (fs.existsSync(profile)) {
if (Date.now() - start >= PROFILE_REMOVAL_TIMEOUT) {
log7.warn(`The driver did not delete its temporary profile ${profile} within ${PROFILE_REMOVAL_TIMEOUT}ms`);
return;
}
await new Promise((resolve) => setTimeout(resolve, PROFILE_POLL_INTERVAL));
}
}
async function killDriverProcess(capabilities, shutdownDriver, requestedCapabilities) {
if (!shutdownDriver || !("wdio:driverPID" in capabilities) || !capabilities["wdio:driverPID"]) {
return;
}
const profile = driverProfileOf(capabilities, requestedCapabilities);
if (profile) {
await waitForRemoval(profile);
}
kill(capabilities["wdio:driverPID"]);
}
// src/node.ts
var node_default = WebDriver;
environment.value = {
Request: (
/**
* Prefer undici MockAgent (set by `@wdio/webdriver-mock-service`) when opted in.
* Otherwise unit tests and explicit native-fetch runs use the web `fetch` impl.
*/
process.env.WDIO_USE_UNDICI_MOCK ? FetchRequest : process.env.WDIO_USE_NATIVE_FETCH || process.env.WDIO_UNIT_TESTS ? FetchRequest2 : FetchRequest
),
Socket: ws,
createBidiConnection,
killDriverProcess,
variables: {
WDIO_LOG_LEVEL: process.env.WDIO_LOG_LEVEL,
WDIO_UNIT_TESTS: process.env.WDIO_UNIT_TESTS,
/**
* set by @wdio/local-runner for each worker: `deleteSession` then keeps the
* worker's log file open instead of reopening `WDIO_LOG_PATH`
*/
WDIO_WORKER_ID: process.env.WDIO_WORKER_ID,
WEBDRIVER_CACHE_DIR: process.env.WEBDRIVER_CACHE_DIR || os.tmpdir(),
PROXY_URL: process.env.HTTP_PROXY || process.env.HTTPS_PROXY,
NO_PROXY: process.env.NO_PROXY && process.env.NO_PROXY.trim() ? process.env.NO_PROXY.trim().split(/[\s,;]+/) : []
}
};
export {
APPIUM_MASKING_HEADER,
BASE_64_REGEX,
BASE_64_SAFE_STRING_TO_PROCESS_LENGTH,
BIDI_MASK,
BIDI_SCRIPT_TIMEOUT,
BidiHandler,
CommandRuntimeOptions,
DEFAULTS,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_RESPONSE_TIMEOUT,
ELEMENT_KEY,
SESSION_ENDED_ERROR,
SHADOW_ELEMENT_KEY,
WebDriver,
command_default as command,
node_default as default,
getEnvironmentVars,
getPrototype,
initiateBidi,
isBidiConnectionClosed,
isSessionEndedError,
localTypes_exports as local,
parseBidiMessage,
remoteTypes_exports as remote,
runClassicProtocolCommand
};