UNPKG

appium-geckodriver

Version:

Appium driver for Gecko-based browsers and web views

252 lines 9.28 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GeckoDriverServer = exports.GeckoProxy = exports.GECKO_SERVER_HOST = void 0; const lodash_1 = __importDefault(require("lodash")); const node_os_1 = __importDefault(require("node:os")); const node_path_1 = __importDefault(require("node:path")); const driver_1 = require("appium/driver"); const support_1 = require("appium/support"); const teen_process_1 = require("teen_process"); const asyncbox_1 = require("asyncbox"); const portscanner_1 = require("portscanner"); const node_child_process_1 = require("node:child_process"); const constants_1 = require("./constants"); const GD_BINARY = `geckodriver${support_1.system.isWindows() ? '.exe' : ''}`; const STARTUP_TIMEOUT_MS = 10000; // 10 seconds const GECKO_PORT_RANGE = [5200, 5300]; const GECKO_SERVER_GUARD = support_1.util.getLockFileGuard(node_path_1.default.resolve(node_os_1.default.tmpdir(), 'gecko_server_guard.lock'), { timeout: 5, tryRecovery: true }); const DEFAULT_MARIONETTE_PORT = 2828; exports.GECKO_SERVER_HOST = '127.0.0.1'; class GeckoProxy extends driver_1.JWProxy { didProcessExit; async proxyCommand(url, method, body = null) { if (this.didProcessExit) { throw new driver_1.errors.InvalidContextError(`'${method} ${url}' cannot be proxied to Gecko Driver server because ` + 'its process is not running (probably crashed). Check the Appium log for more details'); } return await super.proxyCommand(url, method, body); } } exports.GeckoProxy = GeckoProxy; class GeckoDriverProcess { noReset; verbosity; androidStorage; marionettePort; _port; log; _proc = null; constructor(log, opts = {}) { this.noReset = opts.noReset; this.verbosity = opts.verbosity; this.androidStorage = opts.androidStorage; this.marionettePort = opts.marionettePort; this._port = opts.systemPort; this.log = log; } get isRunning() { return !!(this._proc?.isRunning); } get port() { return this._port; } get proc() { return this._proc; } async init() { if (this.isRunning) { return; } if (!this._port) { await GECKO_SERVER_GUARD(async () => { const [startPort, endPort] = GECKO_PORT_RANGE; try { this._port = await (0, portscanner_1.findAPortNotInUse)(startPort, endPort); } catch { throw new Error(`Cannot find any free port in range ${startPort}..${endPort}. ` + `Double check the processes that are locking ports within this range and terminate ` + `these which are not needed anymore or set any free port number to the 'systemPort' capability`); } }); } let driverBin; try { driverBin = await support_1.fs.which(GD_BINARY); } catch { throw new Error(`${GD_BINARY} binary cannot be found in PATH. ` + `Please make sure it is present on your system`); } const args = []; /* #region Options */ switch (lodash_1.default.toLower(this.verbosity)) { case constants_1.VERBOSITY.DEBUG: args.push('-v'); break; case constants_1.VERBOSITY.TRACE: args.push('-vv'); break; } if (this.noReset) { args.push('--connect-existing'); // https://firefox-source-docs.mozilla.org/testing/geckodriver/Flags.html#code-connect-existing-code if (lodash_1.default.isNil(this.marionettePort)) { this.log.info(`'marionettePort' capability value is not provided while 'noReset' is enabled`); this.log.info(`Assigning 'marionettePort' to the default value (${DEFAULT_MARIONETTE_PORT})`); } args.push('--marionette-port', `${this.marionettePort ?? DEFAULT_MARIONETTE_PORT}`); } else if (!lodash_1.default.isNil(this.marionettePort)) { args.push('--marionette-port', `${this.marionettePort}`); } /* #endregion */ args.push('-p', `${this._port}`); if (this.androidStorage) { args.push('--android-storage', this.androidStorage); } this._proc = new teen_process_1.SubProcess(driverBin, args); this._proc.on('output', (stdout, stderr) => { const line = lodash_1.default.trim(stdout || stderr); if (line) { this.log.debug(`[${GD_BINARY}] ${line}`); } }); this._proc.on('exit', (code, signal) => { this.log.info(`${GD_BINARY} has exited with code ${code}, signal ${signal}`); }); this.log.info(`Starting '${driverBin}' with args ${JSON.stringify(args)}`); await this._proc.start(0); } async stop() { if (this.isRunning) { await this._proc?.stop('SIGTERM'); } } async kill() { if (this.isRunning) { try { await this._proc?.stop('SIGKILL'); } catch { } } } } const RUNNING_PROCESS_IDS = []; process.once('exit', () => { if (lodash_1.default.isEmpty(RUNNING_PROCESS_IDS)) { return; } const command = support_1.system.isWindows() ? ('taskkill.exe ' + RUNNING_PROCESS_IDS.filter((pid) => pid !== undefined).map((pid) => `/PID ${pid}`).join(' ')) : `kill ${RUNNING_PROCESS_IDS.filter((pid) => pid !== undefined).join(' ')}`; try { (0, node_child_process_1.execSync)(command); } catch { } }); class GeckoDriverServer { _proxy = null; _process; log; constructor(log, caps) { this._process = new GeckoDriverProcess(log, caps); this.log = log; this._proxy = null; } get proxy() { if (!this._proxy) { throw new Error('Gecko proxy is not initialized'); } return this._proxy; } get isRunning() { return !!(this._process?.isRunning); } async start(geckoCaps, opts = {}) { await this._process.init(); const proxyOpts = { server: exports.GECKO_SERVER_HOST, port: this._process.port, log: this.log, base: '', keepAlive: true, }; if (opts.reqBasePath) { proxyOpts.reqBasePath = opts.reqBasePath; } this._proxy = new GeckoProxy(proxyOpts); this._proxy.didProcessExit = false; this._process?.proc?.on('exit', () => { if (this._proxy) { this._proxy.didProcessExit = true; } }); try { await (0, asyncbox_1.waitForCondition)(async () => { try { await this._proxy?.command('/status', 'GET'); return true; } catch (err) { if (this._proxy?.didProcessExit) { throw new Error(err.message); } return false; } }, { waitMs: STARTUP_TIMEOUT_MS, intervalMs: 1000, }); } catch (e) { if (this._process.isRunning) { // avoid "frozen" processes, await this._process.kill(); } if (/Condition unmet/.test(e.message)) { throw new Error(`Gecko Driver server is not listening within ${STARTUP_TIMEOUT_MS}ms timeout. ` + `Make sure it could be started manually from a terminal`); } throw e; } const pid = this._process.proc?.pid; if (pid) { RUNNING_PROCESS_IDS.push(pid); this._process.proc?.on('exit', () => void lodash_1.default.pull(RUNNING_PROCESS_IDS, pid)); } return await this._proxy.command('/session', 'POST', { capabilities: { firstMatch: [{}], alwaysMatch: geckoCaps, } }); } async stop() { if (!this.isRunning) { this.log.info(`Gecko Driver session cannot be stopped, because the server is not running`); return; } if (this._proxy?.sessionId) { try { await this._proxy.command(`/session/${this._proxy.sessionId}`, 'DELETE'); } catch (e) { this.log.info(`Gecko Driver session cannot be deleted. Original error: ${e.message}`); } } try { await this._process.stop(); } catch (e) { this.log.warn(`Gecko Driver process cannot be stopped (${e.message}). Killing it forcefully`); await this._process.kill(); } } } exports.GeckoDriverServer = GeckoDriverServer; exports.default = GeckoDriverServer; //# sourceMappingURL=gecko.js.map