|
| 1 | +import { Chromedriver, ChromedriverOpts } from 'appium-chromedriver'; |
| 2 | +import { fs, node, system, tempDir, zip } from '@appium/support'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { cdpRequest, downloadFile, sleep, MODULE_NAME } from '../util'; |
| 5 | +import { NovaWindowsDriver } from '../driver'; |
| 6 | +import { errors } from '@appium/base-driver'; |
| 7 | + |
| 8 | +const NATIVE_APP = 'NATIVE_APP'; |
| 9 | +const WEBVIEW = 'WEBVIEW'; |
| 10 | +const WEBVIEW_BASE = `${WEBVIEW}_`; |
| 11 | + |
| 12 | +export async function getCurrentContext(this: NovaWindowsDriver): Promise<string> { |
| 13 | + return this.currentContext ??= NATIVE_APP; |
| 14 | +} |
| 15 | + |
| 16 | +export async function setContext(this: NovaWindowsDriver, name?: string | null): Promise<void> { |
| 17 | + if (!name || name === NATIVE_APP) { |
| 18 | + this.chromedriver?.stop(); |
| 19 | + this.chromedriver = null; |
| 20 | + this.jwpProxyActive = false; |
| 21 | + this.proxyReqRes = null; |
| 22 | + this.proxyCommand = null; |
| 23 | + this.currentContext = NATIVE_APP; |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const webViewDetails = await this.getWebViewDetails(); |
| 28 | + |
| 29 | + if (!(webViewDetails.pages ?? []).map((page) => page.id).includes(name.replace(WEBVIEW_BASE, ''))) { |
| 30 | + throw new errors.InvalidArgumentError(`Web view not found: ${name}`); |
| 31 | + } |
| 32 | + |
| 33 | + const browser = webViewDetails.info?.Browser ?? ''; |
| 34 | + const match = browser.match(/(Chrome|Edg)\/([\d.]+)/); |
| 35 | + |
| 36 | + if (!match?.[1] || (match[1] !== 'Edg' && match[1] !== 'Chrome')) { |
| 37 | + throw new errors.InvalidArgumentError(`Unsupported browser type: ${match?.[1]}`); |
| 38 | + } |
| 39 | + |
| 40 | + const browserType = match[1] === 'Edg' ? 'Edge' : 'Chrome'; |
| 41 | + const browserVersion = match?.[2] ?? ''; |
| 42 | + |
| 43 | + const DRIVER_VERSION_REGEX = /^\d+(\.\d+){3}$/; |
| 44 | + if (!DRIVER_VERSION_REGEX.test(browserVersion)) { |
| 45 | + throw new errors.InvalidArgumentError(`Invalid browser version: ${browserVersion}`); |
| 46 | + } |
| 47 | + |
| 48 | + this.log.debug(`Type: ${browserType}, Version: ${browserVersion}`); |
| 49 | + |
| 50 | + const executable: string = await getDriverExecutable.call(this, browserType, browserVersion); |
| 51 | + |
| 52 | + const chromedriverOpts: ChromedriverOpts & { details?: WebViewDetails } = { |
| 53 | + executable, |
| 54 | + details: webViewDetails, |
| 55 | + }; |
| 56 | + |
| 57 | + if (this.basePath) { |
| 58 | + chromedriverOpts.reqBasePath = this.basePath; |
| 59 | + } |
| 60 | + |
| 61 | + const cd = new Chromedriver(chromedriverOpts); |
| 62 | + this.chromedriver = cd; |
| 63 | + |
| 64 | + const page = webViewDetails.pages?.find((p) => p.id === name.replace(WEBVIEW_BASE, '')); |
| 65 | + |
| 66 | + const debuggerAddress = (page?.webSocketDebuggerUrl ?? '') |
| 67 | + .replace('ws://', '') |
| 68 | + .split('/')[0]; |
| 69 | + |
| 70 | + const options = { debuggerAddress }; |
| 71 | + |
| 72 | + const caps = { |
| 73 | + 'ms:edgeOptions': options, |
| 74 | + 'goog:chromeOptions': options, |
| 75 | + }; |
| 76 | + |
| 77 | + this.currentContext = name; |
| 78 | + await this.chromedriver.start(caps); |
| 79 | + this.log.debug('Chromedriver started. Session ID:', cd.sessionId()); |
| 80 | + |
| 81 | + this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver); |
| 82 | + this.proxyCommand = this.chromedriver.jwproxy.command.bind(this.chromedriver.jwproxy); |
| 83 | + this.jwpProxyActive = true; |
| 84 | +} |
| 85 | + |
| 86 | +export async function getContexts(this: NovaWindowsDriver): Promise<string[]> { |
| 87 | + const webViewDetails = await this.getWebViewDetails(); |
| 88 | + return [ |
| 89 | + NATIVE_APP, |
| 90 | + ...(webViewDetails.pages?.map((page) => `${WEBVIEW_BASE}${page.id}`) ?? []), |
| 91 | + ]; |
| 92 | +} |
| 93 | + |
| 94 | +export interface WebViewDetails { |
| 95 | + /** |
| 96 | + * Web view details as returned by /json/version CDP endpoint |
| 97 | + * @example |
| 98 | + * { |
| 99 | + * "Browser": "Edg/145.0.3800.97", |
| 100 | + * "Protocol-Version": "1.3", |
| 101 | + * "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0", |
| 102 | + * "V8-Version": "14.5.40.9", |
| 103 | + * "WebKit-Version": "537.36 (@f4c49d5241f148220b99eb7f045ac370a1694a15)", |
| 104 | + * "webSocketDebuggerUrl": "ws://localhost:10900/devtools/browser/7039e1b9-f75d-44eb-8583-7279c107bb18" |
| 105 | + * } |
| 106 | + */ |
| 107 | + info?: CDPVersionResponse; |
| 108 | + |
| 109 | + /** |
| 110 | + * Web view details as returned by /json/list CDP endpoint |
| 111 | + * @example // TODO: change example to not include Spotify / use mock data |
| 112 | + * [ { |
| 113 | + * "description": "", |
| 114 | + * "devtoolsFrontendUrl": "https://chrome-devtools-frontend.appspot.com/serve_rev/@80be69ef794ba862ff256b0b23f051cbbc32e1ed/inspector.html?ws=localhost:9222/devtools/page/21C6035BC3E0A67D0BB6AE10F4A66D4A", |
| 115 | + * "faviconUrl": "https://xpui.app.spotify.com/favicon.ico", |
| 116 | + * "id": "21C6035BC3E0A67D0BB6AE10F4A66D4A", |
| 117 | + * "title": "Spotify - Web Player: Music for everyone", |
| 118 | + * "type": "page", |
| 119 | + * "url": "https://xpui.app.spotify.com/index.html", |
| 120 | + * "webSocketDebuggerUrl": "ws://localhost:9222/devtools/page/21C6035BC3E0A67D0BB6AE10F4A66D4A" |
| 121 | + * }, { |
| 122 | + * "description": "", |
| 123 | + * "devtoolsFrontendUrl": "https://chrome-devtools-frontend.appspot.com/serve_rev/@80be69ef794ba862ff256b0b23f051cbbc32e1ed/inspector.html?ws=localhost:9222/devtools/page/7E7008B3C464CD91224ADF976115101F", |
| 124 | + * "id": "7E7008B3C464CD91224ADF976115101F", |
| 125 | + * "title": "", |
| 126 | + * "type": "worker", |
| 127 | + * "url": "", |
| 128 | + * "webSocketDebuggerUrl": "ws://localhost:10900/devtools/page/7E7008B3C464CD91224ADF976115101F" |
| 129 | + * } ] |
| 130 | + */ |
| 131 | + pages?: CDPListResponse; |
| 132 | +} |
| 133 | + |
| 134 | +interface CDPVersionResponse { |
| 135 | + 'Browser': string, |
| 136 | + 'Protocol-Version': string, |
| 137 | + 'User-Agent': string, |
| 138 | + 'V8-Version': string, |
| 139 | + 'WebKit-Version': string, |
| 140 | + 'webSocketDebuggerUrl': string, |
| 141 | +} |
| 142 | + |
| 143 | +interface CDPListResponseEntry { |
| 144 | + 'description': string, |
| 145 | + 'devtoolsFrontendUrl': string, |
| 146 | + 'faviconUrl': string, |
| 147 | + 'id': string, |
| 148 | + 'title': string, |
| 149 | + 'type': string, |
| 150 | + 'url': string, |
| 151 | + 'webSocketDebuggerUrl': string, |
| 152 | +} |
| 153 | + |
| 154 | +type CDPListResponse = CDPListResponseEntry[]; |
| 155 | + |
| 156 | +export async function getWebViewDetails(this: NovaWindowsDriver, waitForWebviewMs?: number): Promise<WebViewDetails> { |
| 157 | + if (!this.caps.webviewEnabled) { |
| 158 | + throw new errors.InvalidArgumentError('WebView support is not enabled. Please set the "enableWebView" capability to true and try again.'); |
| 159 | + } |
| 160 | + |
| 161 | + this.log.debug(`Getting a list of available webviews`); |
| 162 | + |
| 163 | + const waitMs = waitForWebviewMs ? Number(waitForWebviewMs) : 0; |
| 164 | + if (waitMs) { |
| 165 | + this.log.debug(`waiting for ${waitMs} ms`); |
| 166 | + await sleep(waitMs); |
| 167 | + } |
| 168 | + |
| 169 | + const host = 'localhost'; |
| 170 | + |
| 171 | + if ((this.caps.app === 'none' || this.caps.app === 'root' || this.caps.appTopLevelWindow != null) && this.caps.webviewDevtoolsPort == null) { |
| 172 | + throw new errors.InvalidArgumentError(`Capability "webviewDevtoolsPort" must be set when using "none", "root", or "appTopLevelWindow" with "enableWebView"`); |
| 173 | + } |
| 174 | + |
| 175 | + const port = this.webviewDevtoolsPort ??= this.caps.webviewDevtoolsPort ?? null; |
| 176 | + |
| 177 | + const info = await (cdpRequest.call(this, ({ host, port, endpoint: '/json/version', timeout: 10000 })) as Promise<CDPVersionResponse>).catch(() => undefined); |
| 178 | + const pages = await (cdpRequest.call(this, ({ host, port, endpoint: '/json/list', timeout: 10000 })) as Promise<CDPListResponse>).catch(() => undefined); |
| 179 | + |
| 180 | + const webViewDetails: WebViewDetails = { info, pages }; |
| 181 | + |
| 182 | + return webViewDetails; |
| 183 | +} |
| 184 | + |
| 185 | +async function getDriverExecutable(this: NovaWindowsDriver, browserType: 'Edge' | 'Chrome', browserVersion: `${number}.${number}.${number}.${number}`): Promise<string> { |
| 186 | + let driverType: string; |
| 187 | + |
| 188 | + if (browserType === 'Chrome') { |
| 189 | + driverType = 'chromedriver'; |
| 190 | + } else { |
| 191 | + driverType = 'edgedriver'; |
| 192 | + } |
| 193 | + |
| 194 | + const root = node.getModuleRootSync(MODULE_NAME, __filename); |
| 195 | + if (!root) { |
| 196 | + throw new errors.InvalidArgumentError(`Cannot find the root folder of the ${MODULE_NAME} Node.js module`); |
| 197 | + } |
| 198 | + |
| 199 | + const driverDir = path.join(root, driverType); |
| 200 | + |
| 201 | + if (!(await fs.exists(driverDir))) { |
| 202 | + await fs.mkdir(driverDir); |
| 203 | + } |
| 204 | + |
| 205 | + const fileName = browserType === 'Edge' ? 'msedgedriver.exe' : 'chromedriver.exe'; |
| 206 | + const finalPath = path.join(driverDir, browserVersion, fileName); |
| 207 | + |
| 208 | + if (await fs.exists(finalPath)) { |
| 209 | + return finalPath; |
| 210 | + } |
| 211 | + |
| 212 | + const executablePath = browserType === 'Edge' |
| 213 | + ? this.caps.edgedriverExecutablePath |
| 214 | + : this.caps.chromedriverExecutablePath; |
| 215 | + |
| 216 | + if (executablePath) { |
| 217 | + const exists = await fs.exists(executablePath); |
| 218 | + if (!exists) { |
| 219 | + throw new errors.InvalidArgumentError(`Driver executable not found at path: ${executablePath}`); |
| 220 | + } |
| 221 | + |
| 222 | + this.log.debug( |
| 223 | + `Using local ${browserType} driver executable at ${executablePath}. ` + |
| 224 | + `Automatic download is disabled and CDN URLs are ignored. ` + |
| 225 | + `You must ensure this binary matches the WebView/Chromium version (${browserVersion}).` |
| 226 | + ); |
| 227 | + |
| 228 | + return executablePath; |
| 229 | + } |
| 230 | + |
| 231 | + const arch = await system.arch(); |
| 232 | + const zipFilename = `${driverType}${browserType === 'Edge' ? '_' : '-'}win${arch}.zip`; |
| 233 | + |
| 234 | + const CHROME_BASE_URL = this.caps.chromedriverCdnUrl || 'https://storage.googleapis.com/chrome-for-testing-public'; |
| 235 | + const EDGE_BASE_URL = this.caps.edgedriverCdnUrl || 'https://msedgedriver.microsoft.com'; |
| 236 | + |
| 237 | + let downloadUrl = ''; |
| 238 | + |
| 239 | + if (browserType === 'Chrome') { |
| 240 | + const url = new URL(CHROME_BASE_URL); |
| 241 | + url.pathname = path.posix.join(url.pathname, browserVersion, `win${arch}`, zipFilename); |
| 242 | + downloadUrl = url.toString(); |
| 243 | + } else { |
| 244 | + const url = new URL(EDGE_BASE_URL); |
| 245 | + url.pathname = path.posix.join(url.pathname, browserVersion, zipFilename); |
| 246 | + downloadUrl = url.toString(); |
| 247 | + } |
| 248 | + |
| 249 | + this.log.debug(`Downloading ${browserType} driver version ${browserVersion}...`); |
| 250 | + const tmpRoot = await tempDir.openDir(); |
| 251 | + await downloadFile(downloadUrl, tmpRoot); |
| 252 | + |
| 253 | + try { |
| 254 | + await zip.extractAllTo(path.join(tmpRoot, zipFilename), tmpRoot); |
| 255 | + |
| 256 | + const driverPath = await fs.walkDir( |
| 257 | + tmpRoot, |
| 258 | + true, |
| 259 | + (itemPath, isDirectory) => !isDirectory && path.parse(itemPath).base.toLowerCase() === fileName); |
| 260 | + |
| 261 | + if (!driverPath) { |
| 262 | + throw new errors.UnknownError(`The archive was unzipped properly, but did not find any ${driverType} executable.`); |
| 263 | + } |
| 264 | + |
| 265 | + this.log.debug(`Moving the extracted '${fileName}' to '${finalPath}'`); |
| 266 | + await fs.mv(driverPath, finalPath, { mkdirp: true }); |
| 267 | + } finally { |
| 268 | + await fs.rimraf(tmpRoot); |
| 269 | + } |
| 270 | + |
| 271 | + return finalPath; |
| 272 | +} |
0 commit comments