const __importMetaUrl = require('url').pathToFileURL(__filename).href; "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/request/constants.ts var REG_EXPS; var init_constants = __esm({ "src/request/constants.ts"() { "use strict"; REG_EXPS = { commandName: /.*\/session\/[0-9a-f-]+\/(.*)/, execFn: /return \(([\s\S]*)\)\.apply\(null, arguments\)/ }; } }); // src/request/error.ts var import_utils, WebDriverError, WebDriverRequestError; var init_error = __esm({ "src/request/error.ts"() { "use strict"; import_utils = require("@wdio/utils"); init_constants(); 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 { body: cmdJson } = requestOptions; if (typeof cmdJson !== "object") { return ""; } const transformedRes = (0, import_utils.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)}"` : ""; } }; 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 errorCode = typeof err.cause === "object" && err.cause && "code" in err.cause && typeof err.cause.code === "string" ? err.cause.code : "code" in err && typeof err.code === "string" ? err.code : void 0; if (errorCode) { this.code = errorCode; this.message = errorCode === "UND_ERR_CONNECT_TIMEOUT" ? 'Request timed out! Consider increasing the "connectionRetryTimeout" option.' : "Request failed with error code " + errorCode; } this.message = this.computeErrorMessage(); } }; } }); // src/request/request.ts var import_node_perf_hooks, import_node_dns, import_index, FetchRequest; var init_request = __esm({ "src/request/request.ts"() { "use strict"; import_node_perf_hooks = require("node:perf_hooks"); import_node_dns = __toESM(require("node:dns"), 1); import_index = __toESM(require("./index.js"), 1); init_error(); if ("process" in globalThis && globalThis.process.versions?.node) { import_node_dns.default.setDefaultResultOrder("ipv4first"); } FetchRequest = class extends import_index.default { 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 WebDriverRequestError( new Error(`Failed to fetch ${url.href}: ${err.message || err || "Unknown error"}`), url, opts ); } throw new WebDriverRequestError(err, url, opts); } } _libPerformanceNow() { return import_node_perf_hooks.performance.now(); } }; } }); // src/command.ts var command_exports = {}; __export(command_exports, { default: () => command_default }); function command_default(method, endpointUri, commandInfo, doubleEncodeVariables = false) { const { command: command2, deprecated, ref, parameters, variables = [], isHubCommand = false } = commandInfo; return async function protocolCommand(...args) { const isBidiCommand = BIDI_COMMANDS.includes(command2); 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 = `${command2}(${commandParams.map((p) => p.name).join(", ")})`; const moreInfo = ` For more info see ${ref} `; const body = {}; if (typeof deprecated === "string" && !process.env.DISABLE_WEBDRIVERIO_DEPRECATION_WARNINGS) { const warning = deprecated.replace("This command", `The "${command2}" command`); log.warn(warning); console.warn(`\u26A0\uFE0F [WEBDRIVERIO DEPRECATION NOTICE] ${warning}`); } if (isBidiCommand) { throw new Error( `Failed to execute WebDriver Bidi command "${command2}" 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 ${command2} 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 (!(0, import_utils2.isValidParameter)(arg, commandParam.type)) { if (typeof arg === "undefined" && !commandParam.required) { continue; } const actual = commandParam.type.endsWith("[]") ? `(${(Array.isArray(arg) ? arg : [arg]).map((a) => (0, import_utils2.getArgumentType)(a))})[]` : (0, import_utils2.getArgumentType)(arg); throw new Error( `Malformed type for "${commandParam.name}" parameter of command ${command2} 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: command2, method, endpoint, body }); log.info("COMMAND", (0, import_utils2.commandCallStructure)(command2, args)); return request.makeRequest(this.options, this.sessionId).then((result) => { if (typeof result.value !== "undefined") { let resultLog = result.value; if (/screenshot|recording/i.test(command2) && typeof result.value === "string" && result.value.length > 64) { resultLog = `${result.value.slice(0, 61)}...`; } else if (command2 === "executeScript" && body.script && body.script.includes("(() => window.__wdioEvents__)")) { resultLog = `[${result.value.length} framework events captured]`; } log.info("RESULT", resultLog); } this.emit("result", { command: command2, method, endpoint, body, result }); if (command2 === "deleteSession") { const shutdownDriver = body.deleteSessionOpts?.shutdownDriver !== false; if (shutdownDriver && "wdio:driverPID" in this.capabilities && this.capabilities["wdio:driverPID"]) { log.info(`Kill driver process with PID ${this.capabilities["wdio:driverPID"]}`); const killedSuccessfully = process.kill(this.capabilities["wdio:driverPID"], "SIGKILL"); if (!killedSuccessfully) { log.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); } if (!process.env.WDIO_WORKER_ID) { import_logger.default.clearLogger(); } } return result.value; }); }; } var import_logger, import_utils2, import_protocols, log, BIDI_COMMANDS; var init_command = __esm({ "src/command.ts"() { "use strict"; import_logger = __toESM(require("@wdio/logger"), 1); import_utils2 = require("@wdio/utils"); import_protocols = require("@wdio/protocols"); init_request(); log = (0, import_logger.default)("webdriver"); BIDI_COMMANDS = Object.values(import_protocols.WebDriverBidiProtocol).map((def) => def.socket.command); } }); // src/index.cts function command(method, encodeUri, commandInfo, doubleEncodeVariables = false) { return async function protocolCommand(...args) { const commandESM = await Promise.resolve().then(() => (init_command(), command_exports)); return commandESM.default(method, encodeUri, commandInfo, doubleEncodeVariables).apply(this, args); }; } var WebDriver = class _WebDriver { static async newSession(options, modifier, userPrototype = {}, customCommandWrapper) { const WebDriver2 = (await import("./index.js")).default; return WebDriver2.newSession(options, modifier, userPrototype, customCommandWrapper); } /** * allows user to attach to existing sessions */ static async attachToSession(options, modifier, userPrototype = {}, commandWrapper) { const WebDriver2 = (await import("./index.js")).default; return WebDriver2.attachToSession(options, modifier, userPrototype, commandWrapper); } /** * 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) { const WebDriver2 = (await import("./index.js")).default; return WebDriver2.reloadSession(instance); } static get WebDriver() { return _WebDriver; } static get command() { return command; } }; module.exports = WebDriver; exports.command = command;