Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

webdriver

Package Overview
Dependencies
Maintainers
3
Versions
483
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webdriver - npm Package Compare versions

Comparing version 9.0.0-alpha.426 to 9.0.0

7

build/bidi/core.d.ts

@@ -1,2 +0,2 @@

import type { ClientOptions, WebSocket } from 'ws';
import type { ClientOptions, RawData, WebSocket } from 'ws';
import type { CommandData } from './remoteTypes.js';

@@ -11,2 +11,7 @@ import type { CommandResponse } from './localTypes.js';

get isConnected(): boolean;
/**
* for testing purposes only
* @internal
*/
get __handleResponse(): (data: RawData) => void;
send(params: Omit<CommandData, 'id'>): Promise<CommandResponse>;

@@ -13,0 +18,0 @@ sendAsync(params: Omit<CommandData, 'id'>): number;

@@ -1,165 +0,1625 @@

import logger from '@wdio/logger';
import { webdriverMonad, sessionEnvironmentDetector, startWebDriver } from '@wdio/utils';
import { validateConfig } from '@wdio/config';
import command from './command.js';
import { DEFAULTS } from './constants.js';
import { startWebDriverSession, getPrototype, getEnvironmentVars, setupDirectConnect, initiateBidi, parseBidiMessage } from './utils.js';
const log = logger('webdriver');
export default class WebDriver {
static async newSession(options, modifier, userPrototype = {}, customCommandWrapper) {
const envLogLevel = process.env.WDIO_LOG_LEVEL;
options.logLevel = envLogLevel ?? options.logLevel;
const params = validateConfig(DEFAULTS, options);
if (params.logLevel && (!options.logLevels || !options.logLevels.webdriver)) {
logger.setLevel('webdriver', params.logLevel);
}
log.info('Initiate new session using the WebDriver protocol');
const driverProcess = await startWebDriver(params);
const requestedCapabilities = { ...params.capabilities };
const { sessionId, capabilities } = await startWebDriverSession(params);
const environment = sessionEnvironmentDetector({ capabilities, requestedCapabilities });
const environmentPrototype = getEnvironmentVars(environment);
const protocolCommands = getPrototype(environment);
/**
* attach driver process to instance capabilities so we can kill the driver process
* even after attaching to this session
*/
if (driverProcess?.pid) {
capabilities['wdio:driverPID'] = driverProcess.pid;
}
/**
* initiate WebDriver Bidi
*/
const bidiPrototype = {};
if (capabilities.webSocketUrl) {
log.info(`Register BiDi handler for session with id ${sessionId}`);
Object.assign(bidiPrototype, initiateBidi(capabilities.webSocketUrl, options.strictSSL));
}
const monad = webdriverMonad({ ...params, requestedCapabilities }, modifier, {
...protocolCommands,
...environmentPrototype,
...userPrototype,
...bidiPrototype
});
const client = monad(sessionId, customCommandWrapper);
/**
* parse and propagate all Bidi events to the browser instance
*/
if (capabilities.webSocketUrl) {
// make sure the Bidi connection is established before returning
await client._bidiHandler.connect();
client._bidiHandler?.socket.on('message', parseBidiMessage.bind(client));
}
/**
* if the server responded with direct connect information, update the
* client options to speak directly to the appium host instead of a load
* balancer (see https://github.com/appium/python-client#direct-connect-urls
* for example). But only do this if the user has enabled this
* behavior in the first place.
*/
if (params.enableDirectConnect) {
setupDirectConnect(client);
}
return client;
// src/index.ts
import logger5 from "@wdio/logger";
import { webdriverMonad, sessionEnvironmentDetector, startWebDriver } from "@wdio/utils";
import { validateConfig } from "@wdio/config";
// src/command.ts
import logger4 from "@wdio/logger";
import { commandCallStructure, isValidParameter, getArgumentType } from "@wdio/utils";
import {
WebDriverBidiProtocol as WebDriverBidiProtocol2
} from "@wdio/protocols";
// src/request/request.ts
import { performance } from "node:perf_hooks";
import dns from "node:dns";
// src/request/index.ts
import path from "node:path";
import { EventEmitter } from "node:events";
import { WebDriverProtocol as WebDriverProtocol2 } from "@wdio/protocols";
import { URL } from "node:url";
import logger3 from "@wdio/logger";
import { transformCommandLogResult as transformCommandLogResult2 } from "@wdio/utils";
// src/utils.ts
import { deepmergeCustom } from "deepmerge-ts";
import logger2 from "@wdio/logger";
import {
WebDriverProtocol,
MJsonWProtocol,
AppiumProtocol,
ChromiumProtocol,
SauceLabsProtocol,
SeleniumProtocol,
GeckoProtocol,
WebDriverBidiProtocol
} from "@wdio/protocols";
import { transformCommandLogResult } from "@wdio/utils";
import { CAPABILITY_KEYS } from "@wdio/protocols";
// src/bidi/core.ts
import logger from "@wdio/logger";
// src/bidi/socket.ts
var BrowserSocket = class {
#callbacks = /* @__PURE__ */ new Set();
#ws;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(wsUrl, opts) {
this.#ws = new globalThis.WebSocket(wsUrl);
this.#ws.onmessage = this.handleMessage.bind(this);
}
handleMessage(event) {
for (const callback of this.#callbacks) {
callback(event.data);
}
}
send(data) {
this.#ws.send(data);
}
on(event, callback) {
if (event === "open") {
this.#ws.onopen = callback;
} else if (event === "close") {
this.#ws.onclose = callback;
} else if (event === "error") {
this.#ws.onerror = callback;
} else {
this.#callbacks.add(callback);
}
return this;
}
off(event, callback) {
this.#callbacks.delete(callback);
return this;
}
close() {
this.#ws.close();
}
};
var socket_default = globalThis.window ? BrowserSocket : (await import("ws")).default;
// src/bidi/core.ts
var log = logger("webdriver");
var RESPONSE_TIMEOUT = 1e3 * 60;
var BidiCore = class {
constructor(_webSocketUrl, opts) {
this._webSocketUrl = _webSocketUrl;
log.info(`Connect to webSocketUrl ${this._webSocketUrl}`);
this.#ws = new socket_default(this._webSocketUrl, opts);
this.#ws.on("message", this.#handleResponse.bind(this));
}
#id = 0;
#ws;
#isConnected = false;
#pendingCommands = /* @__PURE__ */ new Map();
async connect() {
if (process.env.VITEST_WORKER_ID && this._webSocketUrl === "ws://webdriver.io") {
return;
}
return new Promise((resolve) => this.#ws.on("open", () => {
log.info("Connected session to Bidi protocol");
this.#isConnected = true;
resolve();
}));
}
get socket() {
return this.#ws;
}
get isConnected() {
return this.#isConnected;
}
/**
* for testing purposes only
* @internal
*/
get __handleResponse() {
return this.#handleResponse.bind(this);
}
#handleResponse(data) {
try {
const payload = JSON.parse(data.toString());
if (!payload.id) {
return;
}
log.debug("BIDI RESULT", data.toString());
const resolve = this.#pendingCommands.get(payload.id);
if (!resolve) {
log.error(`Couldn't resolve command with id ${payload.id}`);
return;
}
this.#pendingCommands.delete(payload.id);
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 payload = await new Promise((resolve, reject) => {
const t = setTimeout(() => {
reject(new Error(`Command ${params.method} with id ${id} (with the following parameter: ${JSON.stringify(params.params)}) timed out`));
this.#pendingCommands.delete(id);
}, RESPONSE_TIMEOUT);
this.#pendingCommands.set(id, (payload2) => {
clearTimeout(t);
resolve(payload2);
});
});
if (payload.error) {
failError.message += ` with error: ${payload.error} - ${payload.message}`;
if (payload.stacktrace) {
const driverStack = payload.stacktrace.split("\n").filter(Boolean).map((line) => ` at ${line}`).join("\n");
failError.stack += `
Driver Stack:
${driverStack}`;
}
throw failError;
}
return payload;
}
sendAsync(params) {
if (!this.#isConnected) {
throw new Error("No connection to WebDriver Bidi was established");
}
log.info("BIDI COMMAND", ...parseBidiCommand(params));
const id = ++this.#id;
this.#ws.send(JSON.stringify({ id, ...params }));
return id;
}
};
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 logString = JSON.stringify({
...param,
functionDeclaration: `<Function[${new TextEncoder().encode(param.functionDeclaration).length} bytes]>`
});
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.EmptyResult>`
**/
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.SessionSubscriptionRequest` {@link https://w3c.github.io/webdriver-bidi/#command-session-subscribe | command parameter}
* @returns `Promise<local.EmptyResult>`
**/
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.SessionSubscriptionRequest` {@link https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe | command parameter}
* @returns `Promise<local.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyParams` {@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.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.EmptyResult>`
**/
async browserRemoveUserContext(params) {
const result = await this.send({
method: "browser.removeUserContext",
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
async browsingContextReload(params) {
const result = await this.send({
method: "browsingContext.reload",
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.EmptyResult>`
**/
async browsingContextSetViewport(params) {
const result = await this.send({
method: "browsingContext.setViewport",
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 "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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
async networkContinueWithAuth(params) {
const result = await this.send({
method: "network.continueWithAuth",
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.EmptyResult>`
**/
async networkFailRequest(params) {
const result = await this.send({
method: "network.failRequest",
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.EmptyResult>`
**/
async networkProvideResponse(params) {
const result = await this.send({
method: "network.provideResponse",
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.EmptyResult>`
**/
async networkRemoveIntercept(params) {
const result = await this.send({
method: "network.removeIntercept",
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
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.EmptyResult>`
**/
async inputSetFiles(params) {
const result = await this.send({
method: "input.setFiles",
params
});
return result.result;
}
};
// src/constants.ts
import os from "node:os";
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: (path2) => {
if (!path2.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 Selenium server
*/
connectionRetryCount: {
type: "number",
default: 3
},
/**
* 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",
default: process.env.WEBDRIVER_CACHE_DIR || os.tmpdir()
}
};
var REG_EXPS = {
commandName: /.*\/session\/[0-9a-f-]+\/(.*)/,
execFn: /return \(([\s\S]*)\)\.apply\(null, arguments\)/
};
var ELEMENT_KEY = "element-6066-11e4-a52e-4f735466cecf";
var SHADOW_ELEMENT_KEY = "shadow-6066-11e4-a52e-4f735466cecf";
// src/utils.ts
var log2 = logger2("webdriver");
var deepmerge = deepmergeCustom({ mergeArrays: false });
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) {
if (params.capabilities) {
const extensionCaps = Object.keys(params.capabilities).filter((cap) => cap.includes(":"));
const invalidWebDriverCaps = Object.keys(params.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.`
);
}
}
const [w3cCaps, jsonwpCaps] = params.capabilities && "alwaysMatch" in params.capabilities ? [params.capabilities, params.capabilities.alwaysMatch] : [{ alwaysMatch: params.capabilities, firstMatch: [{}] }, params.capabilities];
if (!w3cCaps.alwaysMatch["wdio:enforceWebDriverClassic"] && typeof w3cCaps.alwaysMatch.browserName === "string" && w3cCaps.alwaysMatch.browserName !== "safari") {
w3cCaps.alwaysMatch.webSocketUrl = true;
}
if (!jsonwpCaps["wdio:enforceWebDriverClassic"] && typeof jsonwpCaps.browserName === "string" && jsonwpCaps.browserName !== "safari") {
jsonwpCaps.webSocketUrl = true;
}
const sessionRequest = new FetchRequest(
"POST",
"/session",
{
capabilities: w3cCaps,
// W3C compliant
desiredCapabilities: jsonwpCaps
// JSONWP compliant
}
);
let response;
try {
response = await sessionRequest.makeRequest(params);
} catch (err) {
log2.error(err);
const message = getSessionError(err, params);
throw new Error("Failed to create session.\n" + message);
}
const sessionId = response.value.sessionId || response.sessionId;
params.capabilities = response.value.capabilities || response.value;
return { sessionId, capabilities: params.capabilities };
}
function isSuccessfulResponse(statusCode, body) {
if (!body || typeof body.value === "undefined") {
log2.debug("request failed due to missing body");
return false;
}
if (body.status === 7 && body.value && body.value.message && (body.value.message.toLowerCase().startsWith("no such element") || // Appium
body.value.message === "An element could not be located on the page using the given search parameters." || // Internet Explorer
body.value.message.toLowerCase().startsWith("unable to find element"))) {
return true;
}
if (body.status && body.status !== 0) {
log2.debug(`request failed due to status ${body.status}`);
return false;
}
const hasErrorResponse = body.value && (body.value.error || body.value.stackTrace || body.value.stacktrace);
if (statusCode === 200 && !hasErrorResponse) {
return true;
}
if (statusCode === 404 && body.value && body.value.error === "no such element") {
return true;
}
if (hasErrorResponse) {
log2.debug("request failed due to response error:", body.value.error);
return false;
}
return true;
}
function getPrototype({ isW3C, isChromium, isFirefox, isMobile, isSauce, isSeleniumStandalone }) {
const prototype = {};
const ProtocolCommands = deepmerge(
/**
* allows user to attach to existing sessions
* if mobile apply JSONWire and WebDriver protocol because
* some legacy JSONWire commands are still used in Appium
* (e.g. set/get geolocation)
*/
static attachToSession(options, modifier, userPrototype = {}, commandWrapper) {
if (!options || typeof options.sessionId !== 'string') {
throw new Error('sessionId is required to attach to existing session');
}
// logLevel can be undefined in watch mode when SIGINT is called
if (options.logLevel) {
logger.setLevel('webdriver', options.logLevel);
}
options.capabilities = options.capabilities || {};
options.isW3C = options.isW3C === false ? false : true;
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 environment = sessionEnvironmentDetector({ capabilities: options.capabilities, requestedCapabilities: options.capabilities });
options = Object.assign(environment, options);
const environmentPrototype = getEnvironmentVars(options);
const protocolCommands = getPrototype(options);
/**
* initiate WebDriver Bidi
*/
const bidiPrototype = {};
const webSocketUrl = options.capabilities?.webSocketUrl;
if (typeof webSocketUrl === 'string') {
log.info(`Register BiDi handler for session with id ${options.sessionId}`);
Object.assign(bidiPrototype, initiateBidi(webSocketUrl, options.strictSSL));
}
const prototype = { ...protocolCommands, ...environmentPrototype, ...userPrototype, ...bidiPrototype };
const monad = webdriverMonad(options, modifier, prototype);
const client = monad(options.sessionId, commandWrapper);
/**
* parse and propagate all Bidi events to the browser instance
*/
if (webSocketUrl) {
client._bidiHandler?.socket.on('message', parseBidiMessage.bind(client));
}
return client;
}
isMobile ? deepmerge(AppiumProtocol, WebDriverProtocol) : WebDriverProtocol,
/**
* 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
* enable Bidi protocol for W3C sessions
*/
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];
}
isW3C ? WebDriverBidiProtocol : {},
/**
* only apply mobile protocol if session is actually for mobile
*/
isMobile ? deepmerge(MJsonWProtocol, AppiumProtocol) : {},
/**
* 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 getErrorFromResponseBody(body, requestOptions) {
if (!body) {
return new Error("Response has empty body");
}
if (typeof body === "string" && body.length) {
return new Error(body);
}
if (typeof body !== "object") {
return new Error("Unknown error");
}
return new CustomRequestError(body, requestOptions);
}
var CustomRequestError = class _CustomRequestError extends Error {
constructor(body, requestOptions) {
const errorObj = body.value || body;
let errorMessage = errorObj.message || errorObj.error || errorObj.class || "unknown error";
if (typeof errorMessage === "string" && errorMessage.includes("invalid locator")) {
errorMessage = `The selector "${requestOptions.value}" used with strategy "${requestOptions.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, _CustomRequestError);
}
};
function getEnvironmentVars({ isW3C, isMobile, isIOS, isAndroid, isFirefox, isSauce, isSeleniumStandalone, isBidi, isChromium }) {
return {
isW3C: { value: isW3C },
isMobile: { value: isMobile },
isIOS: { value: isIOS },
isAndroid: { value: isAndroid },
isFirefox: { value: isFirefox },
isSauce: { value: isSauce },
isSeleniumStandalone: { value: isSeleniumStandalone },
isBidi: { value: isBidi },
isChromium: { value: isChromium }
};
}
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?.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 getTimeoutError(error, requestOptions, url) {
const cmdName = getExecCmdName(url);
const cmdArgs = getExecCmdArgs(requestOptions);
const cmdInfoMsg = `when running "${cmdName}" with method "${requestOptions.method}"`;
const cmdArgsMsg = cmdArgs ? ` and args ${cmdArgs}` : "";
const timeoutErr = new Error(`${error.message} ${cmdInfoMsg}${cmdArgsMsg}`);
return Object.assign(timeoutErr, error);
}
function getExecCmdName(url) {
const { href } = url;
const res = href.match(REG_EXPS.commandName) || [];
return res[1] || href;
}
function getExecCmdArgs(requestOptions) {
const { body: cmdJson } = requestOptions;
if (typeof cmdJson !== "object") {
return "";
}
const transformedRes = transformCommandLogResult(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)}"` : "";
}
function initiateBidi(socketUrl, strictSSL = true) {
socketUrl = socketUrl.replace("localhost", "127.0.0.1");
const bidiReqOpts = strictSSL ? {} : { rejectUnauthorized: false };
const handler = new BidiHandler(socketUrl, bidiReqOpts);
handler.connect().then(() => log2.info(`Connected to WebDriver Bidi interface at ${socketUrl}`));
return {
_bidiHandler: { value: handler },
...Object.values(WebDriverBidiProtocol).map((def) => def.socket).reduce((acc, cur) => {
acc[cur.command] = {
value: handler[cur.command]?.bind(handler)
};
return acc;
}, {})
};
}
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}`);
}
}
// package.json
var package_default = {
name: "webdriver",
version: "9.0.0-alpha.0",
description: "A Node.js bindings implementation for the W3C WebDriver and Mobile JSONWire Protocol",
author: "Christian Bromann <mail@bromann.dev>",
homepage: "https://github.com/webdriverio/webdriverio/tree/main/packages/webdriver",
license: "MIT",
main: "./build/index.cjs",
type: "module",
module: "./build/index.js",
exports: {
".": {
types: "./build/index.d.ts",
import: "./build/index.js",
requireSource: "./src/index.cts",
require: "./build/index.cjs"
}
},
types: "./build/index.d.ts",
typeScriptVersion: "3.8.3",
engines: {
node: ">=18"
},
repository: {
type: "git",
url: "git://github.com/webdriverio/webdriverio.git",
directory: "packages/webdriver"
},
keywords: [
"webdriver"
],
bugs: {
url: "https://github.com/webdriverio/webdriverio/issues"
},
dependencies: {
"@types/node": "^20.1.0",
"@types/ws": "^8.5.3",
"@wdio/config": "workspace:*",
"@wdio/logger": "workspace:*",
"@wdio/protocols": "workspace:*",
"@wdio/types": "workspace:*",
"@wdio/utils": "workspace:*",
"deepmerge-ts": "^7.0.3",
ws: "^8.8.0"
}
};
// src/request/index.ts
var ERRORS_TO_EXCLUDE_FROM_RETRY = [
"detached shadow root",
"move target out of bounds"
];
var RequestLibError = class extends Error {
statusCode;
body;
code;
};
var COMMANDS_WITHOUT_RETRY = [
findCommandPathByName("performActions")
];
var DEFAULT_HEADERS = {
"Content-Type": "application/json; charset=utf-8",
"Connection": "keep-alive",
"Accept": "application/json",
"User-Agent": "webdriver/" + package_default.version
};
var log3 = logger3("webdriver");
var WebDriverRequest = class extends EventEmitter {
#requestTimeout;
body;
method;
endpoint;
isHubCommand;
requiresSessionId;
constructor(method, endpoint, body, isHubCommand = false) {
super();
this.body = body;
this.method = method;
this.endpoint = endpoint;
this.isHubCommand = isHubCommand;
this.requiresSessionId = Boolean(this.endpoint.match(/:sessionId/));
}
async makeRequest(options, sessionId) {
const { url, requestOptions } = await this._createOptions(options, sessionId);
let fullRequestOptions = Object.assign(
{ method: this.method },
requestOptions
);
if (typeof options.transformRequest === "function") {
fullRequestOptions = options.transformRequest(fullRequestOptions);
}
this.emit("request", fullRequestOptions);
return this._request(url, fullRequestOptions, options.transformResponse, options.connectionRetryCount, 0);
}
async _createOptions(options, sessionId, isBrowser = false) {
const controller = new AbortController();
this.#requestTimeout = setTimeout(
() => controller.abort(),
options.connectionRetryTimeout || DEFAULTS.connectionRetryTimeout.default
);
const requestOptions = {
signal: controller.signal
};
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")) {
const contentLength = Buffer.byteLength(JSON.stringify(this.body), "utf8");
requestOptions.body = this.body;
requestHeaders.set("Content-Length", `${contentLength}`);
}
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 : path.join(options.path || "", endpoint)}`);
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 };
}
async _libRequest(url, options) {
throw new Error("This function must be implemented");
}
_libPerformanceNow() {
throw new Error("This function must be implemented");
}
async _request(url, fullRequestOptions, transformResponse, totalRetryCount = 0, retryCount = 0) {
log3.info(`[${fullRequestOptions.method}] ${url.href}`);
if (fullRequestOptions.body && Object.keys(fullRequestOptions.body).length) {
log3.info("DATA", transformCommandLogResult2(fullRequestOptions.body));
}
const { ...requestLibOptions } = fullRequestOptions;
const startTime = this._libPerformanceNow();
let response = await this._libRequest(url, requestLibOptions).catch((err) => err);
const durationMillisecond = this._libPerformanceNow() - startTime;
if (this.#requestTimeout) {
clearTimeout(this.#requestTimeout);
}
const retry = (error2, msg) => {
if (retryCount >= totalRetryCount || error2.message.includes("invalid session id")) {
log3.error(`Request failed with status ${response.statusCode} due to ${error2}`);
this.emit("response", { error: error2 });
this.emit("performance", { request: fullRequestOptions, durationMillisecond, success: false, error: error2, retryCount });
throw error2;
}
++retryCount;
this.emit("retry", { error: error2, retryCount });
this.emit("performance", { request: fullRequestOptions, durationMillisecond, success: false, error: error2, retryCount });
log3.warn(msg);
log3.info(`Retrying ${retryCount}/${totalRetryCount}`);
return this._request(url, fullRequestOptions, transformResponse, totalRetryCount, retryCount);
};
if (response instanceof Error) {
if (response.code === "ETIMEDOUT") {
const error2 = getTimeoutError(response, fullRequestOptions, url);
return retry(error2, 'Request timed out! Consider increasing the "connectionRetryTimeout" option.');
}
this.emit("performance", { request: fullRequestOptions, durationMillisecond, success: false, error: response, retryCount });
throw response;
}
if (typeof transformResponse === "function") {
response = transformResponse(response, fullRequestOptions);
}
const error = getErrorFromResponseBody(response.body, fullRequestOptions.body);
if (error.message === "java.net.ConnectException: Connection refused: connect") {
return retry(error, "Connection to Selenium Standalone server was refused.");
}
if (this.isHubCommand) {
if (typeof response.body === "string" && response.body.startsWith("<!DOCTYPE html>")) {
this.emit("performance", { 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 (isSuccessfulResponse(response.statusCode, response.body)) {
this.emit("response", { result: response.body });
this.emit("performance", { request: fullRequestOptions, durationMillisecond, success: true, retryCount });
return response.body;
}
if (error.name === "stale element reference") {
log3.warn("Request encountered a stale element - terminating request");
this.emit("response", { error });
this.emit("performance", { request: fullRequestOptions, durationMillisecond, success: false, error, retryCount });
throw error;
}
if (ERRORS_TO_EXCLUDE_FROM_RETRY.includes(error.name)) {
throw error;
}
return retry(error, `Request failed with status ${response.statusCode} due to ${error.message}`);
}
};
function findCommandPathByName(commandName) {
const command = Object.entries(WebDriverProtocol2).find(
([, command2]) => Object.values(command2).find(
(cmd) => cmd.command === commandName
)
);
if (!command) {
throw new Error(`Couldn't find command "${commandName}"`);
}
return command[0];
}
// src/request/request.ts
if ("process" in globalThis && globalThis.process.versions?.node) {
dns.setDefaultResultOrder("ipv4first");
}
var FetchRequest = class extends WebDriverRequest {
constructor(method, endpoint, body, isHubCommand = false) {
super(method, endpoint, body, isHubCommand);
}
async _libRequest(url, opts) {
try {
const response = await fetch(url, {
method: opts.method,
body: JSON.stringify(opts.body),
headers: opts.headers,
signal: opts.signal
});
const resp = response.clone();
return {
statusCode: resp.status,
body: await resp.json() ?? {}
};
} catch (err) {
if (!(err instanceof Error)) {
throw new RequestLibError(`Failed to fetch ${url.href}: ${err.message || err}`);
}
throw err;
}
}
_libPerformanceNow() {
return performance.now();
}
};
// src/command.ts
var log4 = logger4("webdriver");
var BIDI_COMMANDS = Object.values(WebDriverBidiProtocol2).map((def) => def.socket.command);
function command_default(method, endpointUri, commandInfo, doubleEncodeVariables = false) {
const { command, deprecated, ref, parameters, variables = [], isHubCommand = false } = commandInfo;
return async function protocolCommand(...args) {
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 body = {};
if (typeof deprecated === "string") {
log4.warn(deprecated.replace("This command", `The "${command}" command`));
}
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 (args.length < minAllowedParams || args.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
);
}
for (const [it, arg] of Object.entries(args)) {
if (isBidiCommand) {
break;
}
const i = parseInt(it, 10);
const commandParam = commandParams[i];
if (!isValidParameter(arg, commandParam.type)) {
if (typeof arg === "undefined" && !commandParam.required) {
continue;
}
/**
* if we have been running a local session before, delete connection details
* in order to start a new session on a potential new driver
*/
let driverProcess;
if (params.hostname === 'localhost' && newCapabilities?.browserName) {
delete params.port;
delete params.hostname;
driverProcess = await startWebDriver(params);
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;
}
body[commandParams[i].name] = arg;
}
const request = new FetchRequest(method, endpoint, body, isHubCommand);
request.on("performance", (...args2) => this.emit("request.performance", ...args2));
this.emit("command", { command, method, endpoint, body });
log4.info("COMMAND", commandCallStructure(command, args));
return request.makeRequest(this.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" && body.script && body.script.includes("(() => window.__wdioEvents__)")) {
resultLog = `[${result.value.length} framework events captured]`;
}
const { sessionId, capabilities: newSessionCapabilities } = await startWebDriverSession(params);
/**
* attach driver process to instance capabilities so we can kill the driver process
* even after attaching to this session
*/
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];
log4.info("RESULT", resultLog);
}
this.emit("result", { command, method, endpoint, body, result });
if (command === "deleteSession") {
const shutdownDriver = body.deleteSessionOpts?.shutdownDriver !== false;
if (shutdownDriver && "wdio:driverPID" in this.capabilities && this.capabilities["wdio:driverPID"]) {
log4.info(`Kill driver process with PID ${this.capabilities["wdio:driverPID"]}`);
const killedSuccessfully = process.kill(this.capabilities["wdio:driverPID"], "SIGKILL");
if (!killedSuccessfully) {
log4.warn("Failed to kill driver process, manually clean-up might be required");
}
setTimeout(() => {
for (const handle of process._getActiveHandles()) {
if (handle.servername && handle.servername.includes("edgedl.me")) {
handle.destroy();
}
}
}, 10);
}
for (const prop in instance.requestedCapabilities) {
delete instance.requestedCapabilities[prop];
if (!process.env.WDIO_WORKER_ID) {
logger4.clearLogger();
}
instance.sessionId = sessionId;
instance.capabilities = newSessionCapabilities;
Object.assign(instance.requestedCapabilities, capabilities);
return sessionId;
}
return result.value;
});
};
}
// src/bidi/localTypes.ts
var localTypes_exports = {};
// src/bidi/remoteTypes.ts
var remoteTypes_exports = {};
// src/index.ts
var log5 = logger5("webdriver");
var WebDriver = class _WebDriver {
static async newSession(options, modifier, userPrototype = {}, customCommandWrapper) {
const envLogLevel = process.env.WDIO_LOG_LEVEL;
options.logLevel = envLogLevel ?? options.logLevel;
const params = validateConfig(DEFAULTS, options);
if (params.logLevel && (!options.logLevels || !options.logLevels.webdriver)) {
logger5.setLevel("webdriver", params.logLevel);
}
static get WebDriver() {
return WebDriver;
log5.info("Initiate new session using the WebDriver protocol");
const driverProcess = await startWebDriver(params);
const requestedCapabilities = { ...params.capabilities };
const { sessionId, capabilities } = await startWebDriverSession(params);
const environment = sessionEnvironmentDetector({ capabilities, requestedCapabilities });
const environmentPrototype = getEnvironmentVars(environment);
const protocolCommands = getPrototype(environment);
if (driverProcess?.pid) {
capabilities["wdio:driverPID"] = driverProcess.pid;
}
}
/**
* Helper methods consumed by webdriverio package
*/
export { getPrototype, DEFAULTS, command, getEnvironmentVars, initiateBidi, parseBidiMessage };
export * from './types.js';
export * from './constants.js';
export * from './bidi/handler.js';
export * as local from './bidi/localTypes.js';
export * as remote from './bidi/remoteTypes.js';
const bidiPrototype = {};
if (capabilities.webSocketUrl) {
log5.info(`Register BiDi handler for session with id ${sessionId}`);
Object.assign(bidiPrototype, initiateBidi(capabilities.webSocketUrl, options.strictSSL));
}
const monad = webdriverMonad(
{ ...params, requestedCapabilities },
modifier,
{
...protocolCommands,
...environmentPrototype,
...userPrototype,
...bidiPrototype
}
);
const client = monad(sessionId, customCommandWrapper);
if (capabilities.webSocketUrl) {
await client._bidiHandler.connect();
client._bidiHandler?.socket.on("message", parseBidiMessage.bind(client));
}
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) {
logger5.setLevel("webdriver", options.logLevel);
}
options.capabilities = options.capabilities || {};
options.isW3C = options.isW3C === false ? false : true;
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 environment = sessionEnvironmentDetector({ capabilities: options.capabilities, requestedCapabilities: options.capabilities });
options = Object.assign(environment, options);
const environmentPrototype = getEnvironmentVars(options);
const protocolCommands = getPrototype(options);
const bidiPrototype = {};
const webSocketUrl = options.capabilities?.webSocketUrl;
if (typeof webSocketUrl === "string") {
log5.info(`Register BiDi handler for session with id ${options.sessionId}`);
Object.assign(bidiPrototype, initiateBidi(webSocketUrl, options.strictSSL));
}
const prototype = { ...protocolCommands, ...environmentPrototype, ...userPrototype, ...bidiPrototype };
const monad = webdriverMonad(options, modifier, prototype);
const client = monad(options.sessionId, commandWrapper);
if (webSocketUrl) {
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];
}
instance.sessionId = sessionId;
instance.capabilities = newSessionCapabilities;
Object.assign(instance.requestedCapabilities, capabilities);
return sessionId;
}
static get WebDriver() {
return _WebDriver;
}
};
export {
BidiHandler,
DEFAULTS,
ELEMENT_KEY,
REG_EXPS,
SHADOW_ELEMENT_KEY,
command_default as command,
WebDriver as default,
getEnvironmentVars,
getPrototype,
initiateBidi,
localTypes_exports as local,
parseBidiMessage,
remoteTypes_exports as remote
};

29

package.json
{
"name": "webdriver",
"version": "9.0.0-alpha.426+d760644c4",
"version": "9.0.0",
"description": "A Node.js bindings implementation for the W3C WebDriver and Mobile JSONWire Protocol",

@@ -12,11 +12,8 @@ "author": "Christian Bromann <mail@bromann.dev>",

"exports": {
".": [
{
"types": "./build/index.d.ts",
"import": "./build/index.js",
"require": "./build/index.cjs"
},
"./build/index.cjs"
],
"./package.json": "./package.json"
".": {
"types": "./build/index.d.ts",
"import": "./build/index.js",
"requireSource": "./src/index.cts",
"require": "./build/index.cjs"
}
},

@@ -42,11 +39,11 @@ "types": "./build/index.d.ts",

"@types/ws": "^8.5.3",
"@wdio/config": "9.0.0-alpha.426+d760644c4",
"@wdio/logger": "9.0.0-alpha.426+d760644c4",
"@wdio/protocols": "9.0.0-alpha.426+d760644c4",
"@wdio/types": "9.0.0-alpha.426+d760644c4",
"@wdio/utils": "9.0.0-alpha.426+d760644c4",
"@wdio/config": "9.0.0",
"@wdio/logger": "9.0.0",
"@wdio/protocols": "9.0.0",
"@wdio/types": "9.0.0",
"@wdio/utils": "9.0.0",
"deepmerge-ts": "^7.0.3",
"ws": "^8.8.0"
},
"gitHead": "d760644c4c6e1ef910c0bee120cb422e25dbbe06"
"gitHead": "957693463371a4cb329395dcdbce8fb0c930ab93"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc