@testim/testim-cli 4.116.0 → 4.117.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +1 -1
- package/cli.js.map +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -19,7 +19,7 @@ Testim had missing write access to ${r||e}
|
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
20
|
`))},ou=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:au,argv:lu,exit:nu,cwd:Pt}=global.process,Sv=["trace","debug","info","warn","error","silent"];_c(lu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));cu.description("Testim.io CLI").option("-h --help","output usage information",Pf).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Tv).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",Me,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(au.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,iu.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,iu.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${ou.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Me,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",Me,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",Me,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(lu);p=cu.opts(),Ev=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Iv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Rf=s=>{var r;if(!L.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=no.readFileSync(s);(r=Jl)!=null&&r.containsEncryptedCredentials(t.toString())&&Jl.injectProxyCredentialsStoreToGlobal()},Rv=async()=>{var T,E,b,v,I,C,D,B;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!lu.slice(2).length)throw Pf(),new Br;if(p.version){let R="Testim CLI Version: ";au.npm_package_version&&(console.log(R,au.npm_package_version),nu(0));let A=mt();A&&(console.log(R,A),nu(0)),console.log("Could not find version, please check the package.json manually"),nu(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&fm(),p.clearFileCache&&Jr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=Ne.resolve(n);dm(R)}if(p.usePrefechedData&&gm(),p.playerRequirePath){let R=Ne.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let A=Ne.join(R,"tsconfig.node.json"),U=require("ts-node").register({project:A,ignore:[/node_modules/,new RegExp(`^${$t.escapeRegExp(Ne.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(Te(),Ue(Zt)).options.playerPath=R;let Y=require("module"),X=Y.prototype.require;Y.prototype.require=function(tt){return tt==="rox-alias"?X.call(this,"rox-node"):tt==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=no.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new x("missing --proxy option");if(mf(p))return ff(p);try{let R={};p.configFile?(Rf(p.configFile),R=require(Ne.join(Pt(),p.configFile)).config):p.optionsFile&&(R=require(Ne.join(Pt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(A=>{let _=bv(A);p[_]=wv(p[_],R[A])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let i=((T=p.testConfig)==null?void 0:T.length)||((E=p.testConfigId)==null?void 0:E.length),o=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((I=p.suite)==null?void 0:I.length)||((C=p.suiteId)==null?void 0:C.length);if(p.seleniumCapsFile)try{r=require(Ne.join(Pt(),p.seleniumCapsFile))}catch(R){throw new x(`Failed to parse selenium caps file file error: ${R.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new x("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new x("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new x("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Ne.join(Pt(),p.chromeExtraPrefs))}catch(R){throw new x(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let A of R){let[_]=A.split("=");If.includes(_)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(A),_==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${_}), allowed values: ${JSON.stringify(If)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Rf(p.paramsFile),s={...s,...require(Ne.join(Pt(),p.paramsFile))}}catch(R){throw new x(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new x(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new x("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Ev(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(Ne.join(Pt(),p.sauceOptions)),A=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let U=R.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let _=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!A&&p.browser==="chrome"&&_)throw new x("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new x(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new x("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Iv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(Ne.join(Pt(),p.browserstackOptions)),A=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!A&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new x("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new x(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(Ne.join(Pt(),p.perfectoOptions)),A={location:"US East",securityToken:p.perfectoToken};p.perfecto={...A,...R}}catch(R){throw new x(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(Ne.join(Pt(),p.testobjectOptions)),A={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...A,...R}}catch(R){throw new x(`Failed to parse test object options file error: ${R.message}`)}if(!p.project){let A=await(await Promise.resolve().then(()=>(so(),su))).getProjectId();if(A)p.project=A;else throw new x("missing project-id info, either --login to provide new credentials or use --project <project-id>")}L.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let A=await(await Promise.resolve().then(()=>(so(),su))).getToken();if(A)p.token=A;else throw new x("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let d=R=>R<=0||!Number.isInteger(R);if(d(p.retries))throw new x("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new x("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new x("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new x("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new x("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new x("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new x("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new x("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new x(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Sr,...hn].includes(p.browser))throw new x(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new x("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!Sv.includes(p.appiumLogLevel))throw new x(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new x("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new x("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new x("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new x("please define exactly one of --grid or --grid-id or --host");if((B=p.host)!=null&&B.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=xf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(A=>A.trim()).filter(Boolean);let R=p.resultLabel.filter(A=>A.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new x("A result label cannot exceed 250 characters")}let u=af(p),g=Xi(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new x("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new x("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new x("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||o))throw new x("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!$t.inRange($t.parseInt(p.setRetention),1,11))throw new x("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new x(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new x(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new x("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new x("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new x("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new x("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&$t.difference(p.codeCoverageReporter,ou).length){let R=$t.difference(p.codeCoverageReporter,ou);throw new x(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let f={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(f).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new x(`${y.map(A=>f[A]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=no.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new x(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new x("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(vv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new x("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new x("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new x("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},A=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...A}}catch(R){throw new x(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
|
|
21
21
|
When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new x("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||g,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Mf={};H(Mf,{installAllLazyDependencies:()=>Cv,lazyRequire:()=>at});async function at(s,e={}){let t=Wc(s);if(t)return t;let r;e.silent||(r=(0,Of.default)(`Installing ${s} before first usage...`).start());try{let n=await xv(s);return r&&r.succeed(),n}catch(n){Av.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Df(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function xv(s){return ss.has(s)||(ss.set(s,Lf(s)),ss.get(s).catch(()=>{ss.delete(s)})),ss.get(s)}async function Lf(s){let e=Wc(s);if(e)return e;let t=Df(s),r=`${s}@${t}`;return await Li(ft(),r),Yt(s)}async function Cv(){let s=Object.keys(Xa);for(let e of s)await Lf(e)}function Df(s){let e=Object.entries(Xa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Of,Av,ss,yn=w(()=>{"use strict";Of=S(require("ora"));Xr();W();F();oi();Xs();Av=P("lazy-require"),ss=new Map});var Uf={};H(Uf,{preloadTests:()=>bn});async function bn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ht(async()=>{let t=await ae(s.testId,r=>cl({...e,testId:r}),{concurrency:2});return Nf.keyBy(t,"testData.id")},"loadTests",Pv,[e,s.testId])()}var Nf,Pv,io=w(()=>{"use strict";Nf=S(require("lodash"));Bt();he();F();Pv=1e3*60*60*10});function uu(){return mt()}async function jf(){if(!Oe)try{let s=await oe(_v(),5e3,"The API call to NPM timed out"),e=uu();e&&Bf.lt(e,s)&&console.log(Ff.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){kv.warn("Failed to get NPM version",{err:s})}}var Ff,Bf,kv,_v,pu=w(()=>{"use strict";Ff=S(require("chalk")),Bf=S(require("semver"));F();pe();Xr();Bt();W();kv=P("npm-driver"),_v=ht(()=>wm("@testim/testim-cli"),"getNpmVersion")});var du,Lv,ns,$f,Wf,mu,Vf,Gf=w(()=>{"use strict";F();J();W();yn();du=P("testimNgrok"),Lv=".whitelisted-ngrok.testim.io",ns="",Wf=async(s,e={})=>{if(!e.ngrokToken)throw new x("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${se()}-${s.projectData.projectId}${Lv}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let i=await(await at("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(du.info("replace https to http"),ns=i.replace("https://","http://")):ns=i,s.tunnelDiagnostics&&mu(),s.baseUrl=ns},mu=async(s=!0)=>{try{let t=(await at("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===ns);console.log("ngrok stats",n),du.info("ngrok stats",{tunnel:n})}catch(e){du.error("error collecting ngrok stats",{err:e})}s&&($f=setTimeout(()=>mu(),1e4))},Vf=async s=>{if(!ns)return;clearTimeout($f),s.tunnelDiagnostics&&await mu(!1),await(await at("ngrok")).disconnect(ns)}});var er,gu,Hf,Mv,Nv,fu,oo,co,ao,Uv,qf,zf,Kf=w(()=>{"use strict";er=S(require("os")),gu=S(require("fs")),Hf=S(require("child_process"));F();he();Mv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Nv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},fu=er.tmpdir(),oo=`${fu}/cloudflared`,co=null,ao=null,Uv=async()=>{if(await ge(oo))return;let e=Nv[er.platform()+er.arch()];if(!e)throw new Error(`tunnel on ${er.platform()+er.arch()} platform is not supported.`);let t=e.extract?fu+e.path:oo;await Ye(`${Mv}/${e.path}`,t),e.extract&&await nt(t,fu),await gu.promises.chmod(oo,"755")},qf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([kl(s.company.companyId,t),Uv()]);co=r._id,ao=Hf.spawn(oo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await _l(s.company.companyId,co),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await gu.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},zf=async s=>{let e=[];return co&&e.push(Ol(s.company.companyId,co)),ao&&e.push(new Promise((t,r)=>{ao.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ao.kill()})),await Promise.all(e)}});function Hv(s,e){if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=`${e.width}x${e.height}`;return qv(s,t)}function qv(s,e){if(e){if(!Vv.includes(e)){wn.warn("Default resolution is used because the resolution is not supported by LT",{resolutionString:e,testResultId:s});return}return e}}function Jf(s,e){if(e){if(!Gv.includes(e)){wn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var Yf,Xf,Wt,Qf,Zf,eg,lo,tg,wn,Bv,jv,Tn,$v,Wv,re,Vv,Gv,uo=w(()=>{"use strict";Yf=S(require("ms")),Xf=S(require("p-retry")),Wt=S(require("os")),Qf=S(require("portfinder")),Zf=S(require("child_process"));F();He();he();eg=S(require("fs")),lo=S(require("fs/promises")),tg=require("path");J();W();Qi();ne();le();F();wn=P("lambdatestService"),Bv="https://downloads.lambdatest.com/tunnel/v3",jv={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},Tn=`${Wt.tmpdir()}/LT`,$v=`${Tn}/LT`,Wv=(0,Yf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.TESTIM_LAMBDATEST||e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=Sl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Wv:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge($v))return;let t=jv[Wt.platform()+Wt.arch()];if(!t)throw new Error(`tunnel on ${Wt.platform()+Wt.arch()} platform is not supported.`);let r=`${Tn}.zip`;await Ye(`${Bv}/${t}`,r),await nt(r,Tn)}static async chmodLtTunnel(e){if(!(Wt.platform()==="win32"||!await ge(e))){try{await lo.access(e,eg.constants.X_OK);return}catch{}try{await lo.chmod(e,"777")}catch(r){throw wn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Qf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(L.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(L.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Oc(u)])}if(L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new x("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new x("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,tg.join)(Tn,"LT")),re.tunnel=Zf.spawn("./LT",c,{cwd:Tn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Xf.default)(()=>be(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});wn.info("LT tunnel info",u)}catch(u){throw wn.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,i,o,a,l){var T,E;if(!this.isActive)return{};let c=re.lambdatestConfig.CAPABILITIES[t]||{},d={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},m=[],{canary:u,ext:g,extensionPath:h,installCustomExtension:f}=e,y={platform:Jf(n,a==null?void 0:a.os)||Jf(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||re.lambdatestConfig.PLATFORM,resolution:Hv(n,a==null?void 0:a.resolution)||re.lambdatestConfig.RESOLUTION,version:t==="safari"&&((E=o==null?void 0:o.lt)==null?void 0:E.safari_version)||c.version};if(l===q.EXTENSION&&!g){let b=Kl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&_e(h)&&(m=[...m,h])}return f&&_e(f)&&(m=[...m,f]),{build:r,name:`${n} - ${i}`,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,timezone:re.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:L.flags.LTNetworkCapabilities.isEnabled(),ntlm:L.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Vv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"],Gv=["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"]});var hu={};H(hu,{connect:()=>mo,disconnect:()=>fo,serveTunneling:()=>Kv});var po,rg,sg,zv,mo,fo,Kv,yu=w(()=>{"use strict";Gf();mn();Kf();ot();po=S(require("ora"));W();ne();uo();rg=P("tunnel"),sg=s=>{var e;return[O.TESTIM_LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},zv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},mo=async s=>{if(!s.tunnel)return;let e=Tr(),t;try{sg(s)?(t=(0,po.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):zv(s)?(t=(0,po.default)("Starting testim cloudflare tunnel...").start(),await qf(s)):(t=(0,po.default)("Starting testim ngrok tunnel...").start(),await Wf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw rg.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},fo=async s=>{if(s.tunnel)try{sg(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await zf(s):await Vf(s)}catch(e){let t="catch error - failed to close tunnel";throw rg.error(t,{err:e}),new Error(t)}},Kv=async(s,e=new Promise(()=>{}))=>(await mo(s),ts(()=>fo(s)),await e)});function Jv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.TESTIM_LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=ng.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function Yv(s){let e=ng.exec(s);return e==null?void 0:e[3]}function ho(s){var b,v,I,C,D,B,R,A,_,U,G;let e=s&&Yv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&Jv(s),i=s==null?void 0:s.token,o=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(I=s==null?void 0:s.external)==null?void 0:I.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&((B=(D=(C=s.hybrid)==null?void 0:C.external)==null?void 0:D[s.hybrid.tunnel])==null?void 0:B.user):l,u=d===O.HYBRID?a&&((_=(A=(R=s.hybrid)==null?void 0:R.external)==null?void 0:A[s.hybrid.tunnel])==null?void 0:_.key):c,g=s==null?void 0:s.name,h=s&&(s._id||s.gridId),f=s==null?void 0:s.provider,y=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.androidToken,T=(G=s==null?void 0:s.mobileTokens)==null?void 0:G.iosToken,E=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:g,provider:f,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:E}}async function og(s,e,t,r,n){let i;try{i=await n()}catch(o){throw Ze.error("failed to get grid",{projectId:s,companyId:e,err:o}),new Error(gt.UNKNOWN)}if(Ze.info("get grid info",{...i,projectId:s,companyId:e}),!i||!["success","error"].includes(i.status))throw Ze.error("invalid response - get grid",{res:i}),new Error(gt.UNKNOWN);if(i.status==="success"){let o=ho(i.grid);return Xv(t,e,o.gridId,o.slotId,r),o}throw i.code==="not-found"?new Ke(gt.NOT_FOUND):i.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Ze.error("invalid code error response - get grid",{res:i}),new Ke(gt.UNKNOWN))}function Qv(s,e,t,r,n,i){return og(t,e,s,n,()=>Hi(e,t,r,n,i))}function Zv(s,e,t,r,n,i,o){return og(t,e,s,n,()=>{var c;let l=(c=o.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Hi(e,t,l._id,n,i):Tl(e,t,r,n,i)})}function ag(s){return vl(s)}async function cg(s,e,t){let n=(t||await ag(s)).find(i=>i._id===e);if(!n)throw new x(`Failed to find grid id: ${e}`);return ho(n)}async function eS(s,e,t){let n=(t||await ag(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new x(`Failed to find grid name: ${e}`);return ho(n)}async function bu(s,e){let t=vn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o}=t;if(delete vn[s],!r){Ze.warn("failed to find grid slot id",{projectId:e});return}Ze.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await yl(o,e,r,n,i)}catch(a){Ze.error("failed to release slot",{projectId:e,err:a})}}async function tS(s){let e=Object.values(vn).filter(Boolean);if(e.length!==0){Ze.info("keep alive worker slots",{projectId:s,slots:e});try{await hl(s,e)}catch(t){Ze.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function rS(s){ig=global.setInterval(tS,1e4,s)}async function sS(s){let e=Object.keys(vn);if(e.length){Ze.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>bu(Number(t),s))}catch(t){Ze.error("failed to release all slots",{err:t,projectId:s})}}}async function nS(s){await sS(s),clearInterval(ig)}function iS(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function oS(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function lg(s){let t=(()=>go.isEmpty(s.testobjectSauce)?go.isEmpty(s.saucelabs)?go.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=iS(t,s),l=oS(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a}}async function ug(s,e){let t=s.company.companyId;return await cg(t,e.gridId,s.allGrids)}async function pg(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return lg(s);let c=t==null?void 0:t.companyId;if(a)return cg(c,a,e);if(l)return eS(c,l,e);if(Hs(s)||s.tunnelOnlyMode){Ze.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new Ke("Missing host or grid configuration")}async function dg(s,e,t,r){let{host:n,project:i,grid:o,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return lg(t);if(a)return Qv(r,u,i,a,s,e);if(o)return Zv(r,u,i,o,s,e,t);throw new Ke("Missing host or grid configuration")}var go,Ze,vn,ng,ig,Xv,Sn,mg,is=w(()=>{"use strict";go=S(require("lodash"));he();W();F();ne();J();Ze=P("grid-service"),vn={},ng=/(^(https?):\/{2})?(.*)/,ig=null;Xv=(s,e,t,r,n)=>{vn[s]={gridId:t,companyId:e,slotId:r,browser:n}};Sn={start:rS,end:nS};mg=async(s={},e={},t={},r={},n={})=>{var h,f,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===O.TESTIM_LAMBDATEST||a===O.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!i||!l||!d||!m))return e;let u=await bl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Ze.info("handling hybrid grid",{response:u,companyId:i});let g=ho({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((f=r.disable)==null||f.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});async function Tu(s,e,t){let r=os[s];if(!r)return;let{slotId:n}=r;if(delete os[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Fl(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function aS(s,e){let t=Object.values(os).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await jl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function cS(s,e){fg=global.setInterval(()=>aS(s,e),1e4)}async function lS(s,e){let t=Object.keys(os);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await ae(t,r=>Tu(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function uS(s,e){await lS(s,e),clearInterval(fg)}async function hg(s,e,t){let r;try{r=await Ul(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(gt.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(gt.UNKNOWN);if(r.status==="success")return gg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new Ke(gt.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new Ke(gt.UNKNOWN))}async function yg(s,e,t,r){let n=os[r];if(!n)throw new Error("slot not found");Object.assign(n,t),gg(r,n),await Bl(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,os,fg,gg,In,as=w(()=>{"use strict";he();W();F();ne();J();ct=P("slot-service"),os={},fg=null,gg=(s,e)=>{os[s]=e};In={start:cS,end:uS}});function An(){return yo||"master"}function bg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){yo="master";return}if(s!=null&&s.isArchived)throw new x(`Branch ${s.branch} is archived, run aborted.`);if(s){yo=s.branch||s;return}yo=e?"master":void 0}var yo,wu=w(()=>{"use strict";J()});var xn,vu,pS,Su,dS,bo,To,wo,vo,So,Eo=w(()=>{"use strict";F();ne();xn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},vu=s=>{let{status:e}=s;return e===de.ABORTED},pS=s=>{let{status:e}=s;return e===de.PASSED},Su=s=>s.runnerStatus===Ac.SKIPPED,dS=s=>s.testStatus===Xe.EVALUATING,bo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Su(t)&&(Qe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,To=s=>Object.values(s).filter(e=>xn(e)&&dS(e)).length,wo=s=>Object.values(s).filter(xn),vo=s=>Object.values(s).filter(pS),So=s=>Object.values(s).filter(vu)});function fS(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Eu,Io,mS,Ro,wg=w(()=>{"use strict";Eu=S(require("lodash"));W();Eo();Io=P("debug-reporter"),mS=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],Ro=class{constructor(e){this.options=e}onTestStarted(e,t){Io.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;Io.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Eu.default.omit(this.options,mS),company:Eu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=fS(process.argv);Io.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=vo(e).length,a=Object.keys(e).length-o;Io.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Iu,kt,Cn=w(()=>{"use strict";ne();Iu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},kt=new Iu});var Au={};H(Au,{Reporter:()=>gS});var tr,Pn,Er,Ao,vg,Ru,gS,xu=w(()=>{"use strict";tr=S(require("chalk")),Pn=S(require("lodash"));F();ne();Cn();Eo();Er={success:tr.default.green,warn:tr.default.yellow,error:tr.default.red},{CLI_MODE:Ao}=Ut,vg="device",Ru=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${tr.default.underline(ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,i=Er[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${wi(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Er.error("Failed runs are:")),console.log(Er.error(t.join(`
|
|
22
|
-
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=wo(e),a=vo(e),l=So(e),c=a.length,d=l.length,m=o.length,u="",g="";if(kt.isTestStatusEnabled){let E=To(e);u=` FAILED-EVALUATING: ${E}`,m-=E,g=` SKIPPED: ${bo(e,this.options)}`}let h=this.buildTestPlanName(i,t),f,y=Er[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${g} Duration: ${wi(r)}`;h.trim()===""||h.trim()==="Anonymous"?f=`Tests completed. ${T} (Execution ID: ${n})`:f=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(f)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Pn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Pn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Pn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Pn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((g,h)=>{var T;let f=(T=g.testData)!=null&&T.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",h+1,":",`${g.name}${Qe(g,this.options)?"-quarantine":""}`,y,f)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ao.APPIUM?vg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${tr.default.underline(n)} slot from ${tr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ao.APPIUM?vg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${tr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Ao.APPIUM?"device":"browser";if(n)console.log(Er.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Er.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Ao.APPIUM?"Appium":"Selenium";console.log(Er.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},gS=Ru});var ku={};H(ku,{Reporter:()=>vS});function hS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function yS(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function bS(s){return`${s.visitedUrlsJson||""}`}async function TS(s,e,t,r,n,i){function o(u){let g=ze(s,t,u.testId,u.resultId,r),h={$:{name:hS(u),classname:n,time:Lc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":g};if(xn(u)||vu(u)){let f=`Step Failed: ${u.failureReason||u.reason}`,y=xn(u)?`${f} More info at: ${g}`:f;h.failure={$:{message:y}}}return Su(u)&&Qe(u,i)&&kt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=yS(u),h["visited-urls-json"]=bS(u)),h}function a(u){let{results:g,testPlanName:h,configName:f}=u,y=g||{},E={name:(f&&h?`${h} with config '${f}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){E.skipped=bo(y,i);let b=To(y);E.failures-=b,E["failure-evaluating"]=b}return{$:E,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let g=Object.keys(u).map(f=>u[f].startTime),h=Math.min.apply(null,g);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return wo(u).length+So(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Pu.Builder().buildObject(m)}catch(u){return wS(u)}}function wS(s){let e=new Pu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Pu,Sg,Cu,vS,_u=w(()=>{"use strict";Pu=S(require("xml2js"));F();Sg=require("fs");Cn();Eo();Cu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await TS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Sg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};vS=Cu});var Eg={};H(Eg,{Reporter:()=>SS});function cs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Ou,Lu,SS,Ig=w(()=>{"use strict";W();Ou=P("team-city-reporter");Lu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return cs(n)}onTestStarted(e,t,r,n){if(r){Ou.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Ou.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${cs(t)}' details='${cs(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Ou.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${cs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${cs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${cs(t)}']`)}},SS=Lu});var Rg={};H(Rg,{Reporter:()=>ES});var Du,ES,Ag=w(()=>{"use strict";Du=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},ES=Du});var xg={};H(xg,{Reporter:()=>IS});var Mu,IS,Cg=w(()=>{"use strict";F();Ql();Mu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return to(t)}},IS=Mu});var Nu,ee,_t=w(()=>{"use strict";wg();Nu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new Ro(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(xu(),Au));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(_u(),ku));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ig(),Eg)),r.includes("console")&&Promise.resolve().then(()=>(xu(),Au)),r.includes("junit")&&Promise.resolve().then(()=>(_u(),ku)),r.includes("json")&&Promise.resolve().then(()=>(Ag(),Rg)),r.includes("chrome")&&Promise.resolve().then(()=>(Cg(),xg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},ee=new Nu});function kg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function _g({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:g,appSource:h,gridType:f}){let y=kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:Pg(c,d),isStartUp:u,projectType:g,gridType:f,...["android","ios"].includes(g)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function Og({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:g,isStartUp:h,projectType:f,appSource:y,gridType:T}){try{let E=kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Pg(d,m),isStartUp:h,projectType:f,gridType:T,...["android","ios"].includes(f)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",E);return}yt("test-run-ci-fail",{...E,failureReason:n.failureReason})}catch(E){g.error("failed to update test end analytics",{err:E})}}function Lg(s){yt("batch-run-ci",s)}var Pg,Uu=w(()=>{"use strict";rs();Vi();Pg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Zr&&e?"ci-with-user":Zr?"ci":e?"cli-with-user":s});var Mg,xo,Ng=w(()=>{"use strict";Mg=require("istanbul-lib-report"),xo=class extends Mg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Ug,Fg,Bg,kn,bt,jg,Co,Fu,$g,RS,Wg,Vg,AS,xS,Gg,CS,PS,kS,_S,OS,Hg,qg=w(()=>{"use strict";Ug=S(require("ora")),Fg=S(require("dayjs")),Bg=S(require("test-exclude")),kn=S(require("fs")),bt=S(require("path")),jg=S(require("istanbul-reports")),Co=S(require("istanbul-lib-report"));he();J();F();W();yn();Ng();Fu=P("test-run-status"),$g=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},RS=s=>!!$g(s).search,Wg=s=>s?$g(s).pathname.substring(1):"",Vg=(s,e)=>{let t=Wg(e);return!new Bg.default({relativePath:!1,include:s}).shouldInstrument(t)},AS=s=>s.substring(0,s.indexOf("?")),xS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await at("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Gg=(s,e)=>`${bt.resolve(s,Wg(e))}.js`,CS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await ae(i.sources,async(o,a)=>{if(Vg(r,o))return;let l=Gg(e,o);await kn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await kn.promises.writeFile(l,i.sourcesContent[a])})})},PS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(RS(e)&&(e=AS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},kS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Co.createContext({dir:t,coverageMap:e,watermarks:Co.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Gg(r,a);return kn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new xo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:PS}),jg.create(a,l).execute(o)}),i},_S=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await at("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Vg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},OS=async(s,e)=>{let{mergeProcessCovs:r}=await at("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Il(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await ln(l,9e4);await ae(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await ol(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Hg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Fu.info("start js coverage process");let n=(0,Ug.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Fg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([at("istanbul-lib-coverage"),OS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Fu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ae(c.result,async({url:h,functions:f})=>{let{text:y,sourceMapType:T}=d.get(h),E=await xS({sourceMapType:T,source:y,sourceMapDir:a});u[h]=E;let b=await _S(s,{source:y,sourceMap:E,functions:f});m.merge(b)}),await CS(s,o,u);let g=await kS(s,m,i,o);return n.succeed(),g}catch(l){let c="Failed to report coverage information";l instanceof x?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Fu.error(c,{err:l})}}});var zg={};H(zg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Ir});var xe,LS,Ir,ls=w(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},LS=["ALL",...Object.values(xe)],Ir=class{constructor(){this.marks=Object.fromEntries(LS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ei(r,50)],[`${t}_P95`,Ei(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Xg={};H(Xg,{initServer:()=>NS,mapFilesToLocalDrive:()=>ju});function ju(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Po[t.id]?{screenshot:Po[t.id]}:{})),Object.keys(ko).forEach(t=>{s.assets||={},s.assets[Yg[t]]=ko[t]}),s.assets||={},s.assets.screenshots=Object.values(Po)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function NS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await at("multer"),n=typeof t=="string"?t:DS;await Bu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=_n.join(n,m.testResultId);try{await Bu.promises.mkdir(u,{recursive:!0})}catch(g){return d(g,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let g=_n.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Jg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Po[d.stepId]=l.file.path),d.testResultId&&MS.includes(d.subType)&&(ko[d.subType]||=[],ko[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new x(`Port ${s} is already in use`));default:return c(u)}}})}var Bu,Kg,_n,Jg,DS,Po,ko,Yg,MS,$u=w(()=>{"use strict";Bu=S(require("fs")),Kg=S(require("os")),_n=S(require("path")),Jg=S(require("express"));J();yn();DS=_n.join(Kg.tmpdir(),"testim/rca/"),Po={},ko={},Yg={"test-log":"consoleLogs","har-file":"networkLogs"},MS=Object.keys(Yg)});var rr,Wu,_o,Qg=w(()=>{"use strict";rr=S(require("lodash"));F();W();Wu=P("override-test-data-builder"),_o=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return rr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!rr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Wu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(rr.isObject(e.overrideAllTestsData)&&!rr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Wu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Wu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return rr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=se();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Oo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var Rr,et,US,FS,BS,jS,Lo,Zg=w(()=>{"use strict";Rr=S(require("lodash"));F();ne();is();as();he();J();W();_t();mn();qg();ls();$u();pe();le();Qg();Cn();et=P("test-run-status"),US=fr(),FS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,BS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,jS=mt();Lo=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Gs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:li||t.parallel||1,browser:i,gitBranch:US,gitCommit:FS,gitRepoUrl:BS,runnerVersion:jS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:g,testOwnerName:h,testOwnerEmail:f,testLabels:y,testSuites:T,allLabels:E}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:g,testOwnerName:h,testOwnerEmail:f,testLabels:y,testSuites:T,allLabels:E},Cl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,ee.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await zi(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,wr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Qe(e,this.options))return;let n=this.exportsGlobal;try{let i=await Oo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw et.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},et.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Xe.EVALUATING&&kt.isTestStatusEnabled){ee.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(c){ee.onTestPassed(i);return}ee.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);ee.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Dc();t.isOverThreshold&&et.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&ju(o,et),o.resultUrl=ze(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),ee.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Oo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){et.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await wr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Pc;return e&&(n=i),Vr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var g,h,f;let l=e.browser?zs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Gr(L,n)&&qs(a.nativeApp)&&!e.appId,d=mr(e)&&(Vr(a.nativeApp,n)||c),m=Qe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Xe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((g=a.testData)==null?void 0:g.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((f=a.testData)==null?void 0:f.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await In.end(r,t),e==="mongo"&&await Sn.end(t)}async executionStart(e,t,r,n,i){et.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;ts(()=>Promise.all([this.endKeepAlive(d,t,c),Gi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...L.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Oo(o.beforeSuite,m),g=new _o(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,f=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){f.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let E=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ae(Object.keys(b),async C=>{var _;let D=b[C],B=(_=D.config)==null?void 0:_.testData,R=D.testId,A=await zi(t,R,C,B,l.defaults);A&&(delete D.config.testData,D.config.testDataUrl=A)});let v=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),I=pl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:v,intersections:o.intersections});return this.executionStartedPromise=I,I.catch(C=>et.error(C)),I};try{await E()}catch(b){et.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Nc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&i++,m===de.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Oo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Hg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Gi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ul(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function WS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function oh(s){return rh.readFileSync(s,{encoding:"base64"})}function ah(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=oh(s);us.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Hu(r)} current extension count: ${e.length}`),e.push(r)}}function ch(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=L.flags.testimHeadlessExtensionDownloadUrl.getValue({projectId:s.project});if(s.extensionPath||(s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;us.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;i&&(a=Do.basename(i));let l=Do.join(process.cwd(),a),c=oh(l);us.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Hu(c)} current extension count: ${e.length}`),e.push(c)}function VS(s,e,t,r,n,i,o,a){var f,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ih];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Vu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Vu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};Gu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Gu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Vu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(f=e.projectData)==null?void 0:f.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+xc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),ah(r,c,o),a===q.EXTENSION&&ch(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let g={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[g]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${g}`]=m),s}function HS(s,e,t){let r={"pdfjs.disabled":!0};return L.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":th.join(","),"browser.helperApps.neverAsk.openFile":th.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function qS(s){return`${s.width}x${s.height}`}function zS(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let i={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let o=(0,nh.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(i["sauce:options"].screenResolution=qS(r.resolution||t.sl.screenResolution),delete o.screenResolution),lt.merge(o,i,n)}return lt.merge(i,n)}return{}}function KS(s,e,t){return lt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function JS(s){return s.perfecto?s.perfecto:{}}function YS(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function XS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=Ka(i,o)),a}function Mo(s){var E,b,v,I;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let C=[],D=[...ih],B={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(B.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&ch(t,C,D,null,c),ah(o,C,c),{logLevel:eh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:C,...B},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,g=XS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:eh,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!lt.isEmpty(g)&&{headers:g},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Gu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let f=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);lt.merge(h.desiredCapabilities,zS(t,r,n,e),KS(t,r,n),JS(t),YS(t,y,f),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((E=i.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&L.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=GS(h,t,n,o,i,T,c,d);break;case"firefox":h=HS(h,t,c);break;case"safari":case"safari technology preview":h=WS(h,y);break;default:break}lt.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let C={"hub.lambdatest.com":"lambdatest",[L.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[C[h.host]],B=_=>{var U,G;return D(_)||_[(U=h.desiredCapabilities)==null?void 0:U.browserName]||_[(G=h.desiredCapabilities)==null?void 0:G.version]||_||{}},R=JSON.parse(L.flags.addCustomCapabilities.getValue()||"{}"),A=B(B(R));Object.keys(A).length&&(us.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(h.desiredCapabilities,A))}catch(C){us.error("Failed to load custom capabilities",{error:C,customCapabilities:L.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&($S(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let C=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),B=(v=D==null?void 0:D.capabilities)==null?void 0:v.alwaysMatch,R=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var U,G;B!=null&&B[_]&&(B[_].extensions=(G=(U=C==null?void 0:C[_])==null?void 0:U.extensions)==null?void 0:G.map(R))}),B!=null&&B.loadExtension&&(B.loadExtension=(I=C==null?void 0:C.loadExtension)==null?void 0:I.map(R));let A=require("util");console.log(A.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var rh,Do,sh,lt,nh,us,eh,Vu,ih,Hu,Gu,$S,GS,th,qu=w(()=>{"use strict";rh=S(require("fs")),Do=S(require("path")),sh=S(require("crypto")),lt=S(require("lodash"));F();pe();W();le();ne();uo();nh=require("lodash"),us=P("testim-desired-capabilities-builder"),eh=ci?"debug":"silent",Vu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ih=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Hu=(...s)=>sh.createHash("sha256").update(s.join("")).digest("hex"),Gu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",$S=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=L.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{us.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};GS=lt.memoize(VS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(lt.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Hu(o,a,l,r,c,i)}),th=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Be(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function uh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var zu=w(()=>{"use strict"});function Ku(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,g){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(g(h))return h;return null}function n(u,g){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(g(h))return h;return null}function i(u,g){if(!u||!g)return null;u instanceof DocumentFragment&&(u=u.host);let f=window.getComputedStyle(u).getPropertyValue(g);if(f&&f!=="inherit")return f;let y=t(u);return i(y,g)}function o(u){let g=u.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let f=i(u,"stroke-width");return!!f&&parseInt(f,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(f=>f.nodeType===Node.TEXT_NODE?!0:e(f)?o(f):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!o(g)?!0:l(g))}function c(u){var g;return u?(g=u.parentNode)!=null&&g.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Ku(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var ph=w(()=>{"use strict"});var dh,mh,Vt,QS,ZS,No,fh=w(()=>{"use strict";dh=S(require("promise-queue")),mh=S(require("webdriverio"));pe();We();F();W();Ur();ph();zu();ls();Vt=P("WebDriverApi"),QS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},ZS={implicit:0,pageLoad:1,script:2},No=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().substr(0,2e3):"";throw Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Qa!==void 0&&(e=Qa);let t=1/0;this.queue=new dh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var i,o;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(i=this.seleniumPerfStats)==null?void 0:i.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await mh.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(o=this.seleniumPerfStats)==null||o.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){Vt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Be(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Ku,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Be(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(uh(e,this.isSafari(),Vt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[ZS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Be(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(QS);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(De(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Be(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var gh={};H(gh,{doubleClick:()=>eE});var eE,hh=w(()=>{"use strict";eE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function g(E,b,v){return v>E&&v<b}let h=u.pointerPosition||{},f=r.getBoundingClientRect(),y=h.originX&&g(f.left,f.left+f.width,h.originX)?h.originX:f.left+f.width/2,T=h.originY&&g(f.top,f.top+f.height,h.originY)?h.originY:f.top+f.height/2;return{x:y,y:T}},a=function(u,g){return{screenX:0,screenY:0,clientX:u,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,g,h){if(!window.PointerEvent)return;let f=a(g,h);return new window.PointerEvent(u,f)},c=function(u,g,h){let f=document.createEvent("MouseEvents");return f.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,g,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),f},d=function(){var g;let u=document.activeElement;for(;(g=u.shadowRoot)!=null&&g.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let g=o(u),h=u.event;return t.includes(h)?l(h,g.x,g.y):c(h,g.x,g.y)};try{n.map(g=>m(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>tE});function tE(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Ln=w(()=>{"use strict"});var vh={};H(vh,{WebDriver:()=>xr});async function iE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await sE(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var ps,Th,wh,je,sr,rE,yh,sE,nr,nE,bh,Ar,xr,Dn=w(()=>{"use strict";ps=S(require("lodash"));F();We();qu();Th=S(require("p-retry")),wh=S(require("ua-parser-js"));Ur();W();zu();fh();J();le();ls();je=P("webdriver"),[sr,rE]=[0,2],{extractElementId:yh,getCdpAddressForHost:sE}=K,nr=()=>(Te(),Ue(Zt)).getSessionPlayer().codeSnippets,nE=()=>(Te(),Ue(Zt)).getSessionPlayer().locatorBuilderUtils,bh=()=>(Te(),Ue(Zt)).getSessionPlayer().utils,Ar=()=>(Te(),Ue(Zt)).getSessionPlayer().positionUtils;xr=class extends No{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,I,C,D,B,R,A;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:g,printFinalCaps:h,mode:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((I=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:I.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Mo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:g,overrideConfiguration:r,printFinalCaps:h,mode:f});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(g==null?void 0:g.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,E=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await iE(_),N("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),L.flags.dontFocusOnInit.isEnabled()||await E(),N("after focus and delay in webdriver.js init")}catch(_){let U=JSON.stringify(ps.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:_,capabilitiesAsString:U});let G=((D=(C=n==null?void 0:n.company)==null?void 0:C.activePlan)==null?void 0:D.plan)==="free";throw(B=_.stack)!=null&&B.includes("at startWebDriverSession")&&((R=_.message)!=null&&R.startsWith("Failed to create session"))&&((A=_.message)!=null&&A.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/Invalid username or password/)?new jr(_.message):_.message.match(/capabilit(y|ies)/)?new di(_.message):_.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):_.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ps.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(l=>je.warn("failed to click on alert",{err:l}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;je.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=yh(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new mi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||L.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
|
+
\r`)))}onTestPlanFinished(e,t,r,n,i){let o=wo(e),a=vo(e),l=So(e),c=a.length,d=l.length,m=o.length,u="",g="";if(kt.isTestStatusEnabled){let E=To(e);u=` FAILED-EVALUATING: ${E}`,m-=E,g=` SKIPPED: ${bo(e,this.options)}`}let h=this.buildTestPlanName(i,t),f,y=Er[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${g} Duration: ${wi(r)}`;h.trim()===""||h.trim()==="Anonymous"?f=`Tests completed. ${T} (Execution ID: ${n})`:f=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(f)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Pn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Pn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Pn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Pn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((g,h)=>{var T;let f=(T=g.testData)!=null&&T.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",h+1,":",`${g.name}${Qe(g,this.options)?"-quarantine":""}`,y,f)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ao.APPIUM?vg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${tr.default.underline(n)} slot from ${tr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ao.APPIUM?vg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${tr.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,i=this.options.mode===Ao.APPIUM?"device":"browser";if(n)console.log(Er.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(Er.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===Ao.APPIUM?"Appium":"Selenium";console.log(Er.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},gS=Ru});var ku={};H(ku,{Reporter:()=>vS});function hS(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function yS(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function bS(s){return`${s.visitedUrlsJson||""}`}async function TS(s,e,t,r,n,i){function o(u){let g=ze(s,t,u.testId,u.resultId,r),h={$:{name:hS(u),classname:n,time:Lc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":g};if(xn(u)||vu(u)){let f=`Step Failed: ${u.failureReason||u.reason}`,y=xn(u)?`${f} More info at: ${g}`:f;h.failure={$:{message:y}}}return Su(u)&&Qe(u,i)&&kt.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=yS(u),h["visited-urls-json"]=bS(u)),h}function a(u){let{results:g,testPlanName:h,configName:f}=u,y=g||{},E={name:(f&&h?`${h} with config '${f}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){E.skipped=bo(y,i);let b=To(y);E.failures-=b,E["failure-evaluating"]=b}return{$:E,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let g=Object.keys(u).map(f=>u[f].startTime),h=Math.min.apply(null,g);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return wo(u).length+So(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Pu.Builder().buildObject(m)}catch(u){return wS(u)}}function wS(s){let e=new Pu.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var Pu,Sg,Cu,vS,_u=w(()=>{"use strict";Pu=S(require("xml2js"));F();Sg=require("fs");Cn();Eo();Cu=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await TS(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Sg.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};vS=Cu});var Eg={};H(Eg,{Reporter:()=>SS});function cs(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Ou,Lu,SS,Ig=w(()=>{"use strict";W();Ou=P("team-city-reporter");Lu=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return cs(n)}onTestStarted(e,t,r,n){if(r){Ou.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Ou.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${cs(t)}' details='${cs(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Ou.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${cs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${cs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${cs(t)}']`)}},SS=Lu});var Rg={};H(Rg,{Reporter:()=>ES});var Du,ES,Ag=w(()=>{"use strict";Du=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},ES=Du});var xg={};H(xg,{Reporter:()=>IS});var Mu,IS,Cg=w(()=>{"use strict";F();Ql();Mu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return to(t)}},IS=Mu});var Nu,ee,_t=w(()=>{"use strict";wg();Nu=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new Ro(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(xu(),Au));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(_u(),ku));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ig(),Eg)),r.includes("console")&&Promise.resolve().then(()=>(xu(),Au)),r.includes("junit")&&Promise.resolve().then(()=>(_u(),ku)),r.includes("json")&&Promise.resolve().then(()=>(Ag(),Rg)),r.includes("chrome")&&Promise.resolve().then(()=>(Cg(),xg))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},ee=new Nu});function kg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function _g({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:g,appSource:h,gridType:f}){let y=kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:Pg(c,d),isStartUp:u,projectType:g,gridType:f,...["android","ios"].includes(g)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function Og({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:g,isStartUp:h,projectType:f,appSource:y,gridType:T}){try{let E=kg({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Pg(d,m),isStartUp:h,projectType:f,gridType:T,...["android","ios"].includes(f)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",E);return}yt("test-run-ci-fail",{...E,failureReason:n.failureReason})}catch(E){g.error("failed to update test end analytics",{err:E})}}function Lg(s){yt("batch-run-ci",s)}var Pg,Uu=w(()=>{"use strict";rs();Vi();Pg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Zr&&e?"ci-with-user":Zr?"ci":e?"cli-with-user":s});var Mg,xo,Ng=w(()=>{"use strict";Mg=require("istanbul-lib-report"),xo=class extends Mg.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Ug,Fg,Bg,kn,bt,jg,Co,Fu,$g,RS,Wg,Vg,AS,xS,Gg,CS,PS,kS,_S,OS,Hg,qg=w(()=>{"use strict";Ug=S(require("ora")),Fg=S(require("dayjs")),Bg=S(require("test-exclude")),kn=S(require("fs")),bt=S(require("path")),jg=S(require("istanbul-reports")),Co=S(require("istanbul-lib-report"));he();J();F();W();yn();Ng();Fu=P("test-run-status"),$g=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},RS=s=>!!$g(s).search,Wg=s=>s?$g(s).pathname.substring(1):"",Vg=(s,e)=>{let t=Wg(e);return!new Bg.default({relativePath:!1,include:s}).shouldInstrument(t)},AS=s=>s.substring(0,s.indexOf("?")),xS=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await at("convert-source-map");if(t==="file"&&!e)throw new x("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Gg=(s,e)=>`${bt.resolve(s,Wg(e))}.js`,CS=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await ae(i.sources,async(o,a)=>{if(Vg(r,o))return;let l=Gg(e,o);await kn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await kn.promises.writeFile(l,i.sourcesContent[a])})})},PS={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(RS(e)&&(e=AS(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},kS=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=Co.createContext({dir:t,coverageMap:e,watermarks:Co.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Gg(r,a);return kn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new xo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:PS}),jg.create(a,l).execute(o)}),i},_S=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await at("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Vg(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},OS=async(s,e)=>{let{mergeProcessCovs:r}=await at("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await Il(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await ln(l,9e4);await ae(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await ol(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Hg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Fu.info("start js coverage process");let n=(0,Ug.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,Fg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([at("istanbul-lib-coverage"),OS(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Fu.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ae(c.result,async({url:h,functions:f})=>{let{text:y,sourceMapType:T}=d.get(h),E=await xS({sourceMapType:T,source:y,sourceMapDir:a});u[h]=E;let b=await _S(s,{source:y,sourceMap:E,functions:f});m.merge(b)}),await CS(s,o,u);let g=await kS(s,m,i,o);return n.succeed(),g}catch(l){let c="Failed to report coverage information";l instanceof x?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Fu.error(c,{err:l})}}});var zg={};H(zg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Ir});var xe,LS,Ir,ls=w(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},LS=["ALL",...Object.values(xe)],Ir=class{constructor(){this.marks=Object.fromEntries(LS.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,Ei(r,50)],[`${t}_P95`,Ei(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Xg={};H(Xg,{initServer:()=>NS,mapFilesToLocalDrive:()=>ju});function ju(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Po[t.id]?{screenshot:Po[t.id]}:{})),Object.keys(ko).forEach(t=>{s.assets||={},s.assets[Yg[t]]=ko[t]}),s.assets||={},s.assets.screenshots=Object.values(Po)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function NS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await at("multer"),n=typeof t=="string"?t:DS;await Bu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=_n.join(n,m.testResultId);try{await Bu.promises.mkdir(u,{recursive:!0})}catch(g){return d(g,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let g=_n.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,Jg.default)();o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Po[d.stepId]=l.file.path),d.testResultId&&MS.includes(d.subType)&&(ko[d.subType]||=[],ko[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new x(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new x(`Port ${s} is already in use`));default:return c(u)}}})}var Bu,Kg,_n,Jg,DS,Po,ko,Yg,MS,$u=w(()=>{"use strict";Bu=S(require("fs")),Kg=S(require("os")),_n=S(require("path")),Jg=S(require("express"));J();yn();DS=_n.join(Kg.tmpdir(),"testim/rca/"),Po={},ko={},Yg={"test-log":"consoleLogs","har-file":"networkLogs"},MS=Object.keys(Yg)});var rr,Wu,_o,Qg=w(()=>{"use strict";rr=S(require("lodash"));F();W();Wu=P("override-test-data-builder"),_o=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return rr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!rr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Wu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(rr.isObject(e.overrideAllTestsData)&&!rr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Wu.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Wu.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return rr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=se();return{...e,resultId:i,testData:{value:r,index:n+1,total:t.length||1}}})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function Oo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw et.warn("failed to run hook",{err:t}),new x(`failed to run hook promise ${t.message}`)}}var Rr,et,US,FS,BS,jS,Lo,Zg=w(()=>{"use strict";Rr=S(require("lodash"));F();ne();is();as();he();J();W();_t();mn();qg();ls();$u();pe();le();Qg();Cn();et=P("test-run-status"),US=fr(),FS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,BS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,jS=mt();Lo=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Gs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:li||t.parallel||1,browser:i,gitBranch:US,gitCommit:FS,gitRepoUrl:BS,runnerVersion:jS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:g,testOwnerName:h,testOwnerEmail:f,testLabels:y,testSuites:T,allLabels:E}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:g,testOwnerName:h,testOwnerEmail:f,testLabels:y,testSuites:T,allLabels:E},Cl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,ee.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await zi(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){et.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,wr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Qe(e,this.options))return;let n=this.exportsGlobal;try{let i=await Oo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw et.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},et.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Xe.EVALUATING&&kt.isTestStatusEnabled){ee.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(c){ee.onTestPassed(i);return}ee.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);ee.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Dc();t.isOverThreshold&&et.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&ju(o,et),o.resultUrl=ze(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),ee.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await Oo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){et.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await wr(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw et.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=Pc;return e&&(n=i),Vr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var g,h,f;let l=e.browser?zs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Gr(L,n)&&qs(a.nativeApp)&&!e.appId,d=mr(e)&&(Vr(a.nativeApp,n)||c),m=Qe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Xe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((g=a.testData)==null?void 0:g.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((f=a.testData)==null?void 0:f.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await In.end(r,t),e==="mongo"&&await Sn.end(t)}async executionStart(e,t,r,n,i){et.info("execution started",{executionId:e});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;ts(()=>Promise.all([this.endKeepAlive(d,t,c),Gi("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...L.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await Oo(o.beforeSuite,m),g=new _o(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=g.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,f=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){f.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let E=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ae(Object.keys(b),async C=>{var _;let D=b[C],B=(_=D.config)==null?void 0:_.testData,R=D.testId,A=await zi(t,R,C,B,l.defaults);A&&(delete D.config.testData,D.config.testDataUrl=A)});let v=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),I=pl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:v,intersections:o.intersections});return this.executionStartedPromise=I,I.catch(C=>et.error(C)),I};try{await E()}catch(b){et.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:f,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=Nc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&i++,m===de.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Oo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),et.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Hg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Gi("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw et.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ul(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function WS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function oh(s){return rh.readFileSync(s,{encoding:"base64"})}function ah(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=oh(s);us.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Hu(r)} current extension count: ${e.length}`),e.push(r)}}function ch(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=L.flags.testimHeadlessExtensionDownloadUrl.getValue({projectId:s.project});if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;us.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Do.basename(i));let l=Do.join(process.cwd(),a),c=oh(l);us.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Hu(c)} current extension count: ${e.length}`),e.push(c)}function VS(s,e,t,r,n,i,o,a){var f,y;let l=t.seleniumName||t.browserValue,c=[],d=[...ih];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Vu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Vu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1,"profile.password_manager_leak_detection":!1},w3c:!0};Gu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Gu(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Vu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(f=e.projectData)==null?void 0:f.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+xc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),ah(r,c,o),a===q.EXTENSION&&ch(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let g={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return re.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[g]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${g}`]=m),s}function HS(s,e,t){let r={"pdfjs.disabled":!0};return L.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":th.join(","),"browser.helperApps.neverAsk.openFile":th.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function qS(s){return`${s.width}x${s.height}`}function zS(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let i={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let o=(0,nh.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(i["sauce:options"].screenResolution=qS(r.resolution||t.sl.screenResolution),delete o.screenResolution),lt.merge(o,i,n)}return lt.merge(i,n)}return{}}function KS(s,e,t){return lt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function JS(s){return s.perfecto?s.perfecto:{}}function YS(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function XS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=Ka(i,o)),a}function Mo(s){var E,b,v,I;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let C=[],D=[...ih],B={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(B.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&ch(t,C,D,null,c),ah(o,C,c),{logLevel:eh,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:C,...B},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,g=XS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:eh,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!lt.isEmpty(g)&&{headers:g},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Gu(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let f=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);lt.merge(h.desiredCapabilities,zS(t,r,n,e),KS(t,r,n),JS(t),YS(t,y,f),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((E=i.host)!=null&&E.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&L.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=GS(h,t,n,o,i,T,c,d);break;case"firefox":h=HS(h,t,c);break;case"safari":case"safari technology preview":h=WS(h,y);break;default:break}lt.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let C={"hub.lambdatest.com":"lambdatest",[L.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=_=>_[i.provider]||_[h.host]||_[C[h.host]],B=_=>{var U,G;return D(_)||_[(U=h.desiredCapabilities)==null?void 0:U.browserName]||_[(G=h.desiredCapabilities)==null?void 0:G.version]||_||{}},R=JSON.parse(L.flags.addCustomCapabilities.getValue()||"{}"),A=B(B(R));Object.keys(A).length&&(us.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(h.desiredCapabilities,A))}catch(C){us.error("Failed to load custom capabilities",{error:C,customCapabilities:L.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&($S(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let C=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),B=(v=D==null?void 0:D.capabilities)==null?void 0:v.alwaysMatch,R=_=>_.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(_=>{var U,G;B!=null&&B[_]&&(B[_].extensions=(G=(U=C==null?void 0:C[_])==null?void 0:U.extensions)==null?void 0:G.map(R))}),B!=null&&B.loadExtension&&(B.loadExtension=(I=C==null?void 0:C.loadExtension)==null?void 0:I.map(R));let A=require("util");console.log(A.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var rh,Do,sh,lt,nh,us,eh,Vu,ih,Hu,Gu,$S,GS,th,qu=w(()=>{"use strict";rh=S(require("fs")),Do=S(require("path")),sh=S(require("crypto")),lt=S(require("lodash"));F();pe();W();le();ne();uo();nh=require("lodash"),us=P("testim-desired-capabilities-builder"),eh=ci?"debug":"silent",Vu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ih=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],Hu=(...s)=>sh.createHash("sha256").update(s.join("")).digest("hex"),Gu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",$S=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=L.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{us.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};GS=lt.memoize(VS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(lt.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Hu(o,a,l,r,c,i)}),th=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Be(s){var e,t,r,n,i,o,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function uh(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var zu=w(()=>{"use strict"});function Ku(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,g){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(g(h))return h;return null}function n(u,g){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(g(h))return h;return null}function i(u,g){if(!u||!g)return null;u instanceof DocumentFragment&&(u=u.host);let f=window.getComputedStyle(u).getPropertyValue(g);if(f&&f!=="inherit")return f;let y=t(u);return i(y,g)}function o(u){let g=u.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let f=i(u,"stroke-width");return!!f&&parseInt(f,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(f=>f.nodeType===Node.TEXT_NODE?!0:e(f)?o(f):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!o(g)?!0:l(g))}function c(u){var g;return u?(g=u.parentNode)!=null&&g.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Ku(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var ph=w(()=>{"use strict"});var dh,mh,Vt,QS,ZS,No,fh=w(()=>{"use strict";dh=S(require("promise-queue")),mh=S(require("webdriverio"));pe();We();F();W();Ur();ph();zu();ls();Vt=P("WebDriverApi"),QS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},ZS={implicit:0,pageLoad:1,script:2},No=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,i=t?t.toString().substr(0,2e3):"";throw Vt.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Qa!==void 0&&(e=Qa);let t=1/0;this.queue=new dh.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var i,o;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),N("right before addToQueue");let n=(i=this.seleniumPerfStats)==null?void 0:i.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{Vt.info("requesting browser",{testResultId:r,testName:t}),N("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await mh.remote(e),this.logGridStatus(r)}),N("after client init")}finally{(o=this.seleniumPerfStats)==null||o.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Vt.info("grid status is not supported by the grid",{testResultId:e});return}Vt.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Vt.info("grid status",{gridStatusMsg:i.message,ready:i.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();t=t.map(a=>{if(a===null){Vt.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await o()}catch(a){if(Be(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Be(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(Ku,{ELEMENT:e,[Ht]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Be(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(uh(e,this.isSafari(),Vt))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let i=[];return i[ZS[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Be(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(QS);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(De(e))})}submitFormManually(e){return this.addToQueue(async()=>{var i;let t=await((i=this.client)==null?void 0:i.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Be(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Vt.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return Vt.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var gh={};H(gh,{doubleClick:()=>eE});var eE,hh=w(()=>{"use strict";eE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function g(E,b,v){return v>E&&v<b}let h=u.pointerPosition||{},f=r.getBoundingClientRect(),y=h.originX&&g(f.left,f.left+f.width,h.originX)?h.originX:f.left+f.width/2,T=h.originY&&g(f.top,f.top+f.height,h.originY)?h.originY:f.top+f.height/2;return{x:y,y:T}},a=function(u,g){return{screenX:0,screenY:0,clientX:u,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,g,h){if(!window.PointerEvent)return;let f=a(g,h);return new window.PointerEvent(u,f)},c=function(u,g,h){let f=document.createEvent("MouseEvents");return f.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,g,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),f},d=function(){var g;let u=document.activeElement;for(;(g=u.shadowRoot)!=null&&g.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let g=o(u),h=u.event;return t.includes(h)?l(h,g.x,g.y):c(h,g.x,g.y)};try{n.map(g=>m(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>tE});function tE(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var Ln=w(()=>{"use strict"});var vh={};H(vh,{WebDriver:()=>xr});async function iE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await sE(r):void 0}catch(r){je.info("Error getting cdpAddress",r);return}}var ps,Th,wh,je,sr,rE,yh,sE,nr,nE,bh,Ar,xr,Dn=w(()=>{"use strict";ps=S(require("lodash"));F();We();qu();Th=S(require("p-retry")),wh=S(require("ua-parser-js"));Ur();W();zu();fh();J();le();ls();je=P("webdriver"),[sr,rE]=[0,2],{extractElementId:yh,getCdpAddressForHost:sE}=K,nr=()=>(Te(),Ue(Zt)).getSessionPlayer().codeSnippets,nE=()=>(Te(),Ue(Zt)).getSessionPlayer().locatorBuilderUtils,bh=()=>(Te(),Ue(Zt)).getSessionPlayer().utils,Ar=()=>(Te(),Ue(Zt)).getSessionPlayer().positionUtils;xr=class extends No{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,v,I,C,D,B,R,A;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:g,printFinalCaps:h,mode:f}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((I=(v=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:v.premiumFeatures)==null?void 0:I.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Mo({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:g,overrideConfiguration:r,printFinalCaps:h,mode:f});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(g==null?void 0:g.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,E=u?()=>null:()=>this.executeJS("window.focus()");try{N("before initClient in webdriver.js init");let _=await this.initClient(y,i,d);N("after initResult before getCdpAddress in init"),this.cdpUrl=await iE(_),N("after getCdpAddress in webdriver.js init"),je.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),L.flags.dontFocusOnInit.isEnabled()||await E(),N("after focus and delay in webdriver.js init")}catch(_){let U=JSON.stringify(ps.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));je.error("failed to init webdriver",{err:_,capabilitiesAsString:U});let G=((D=(C=n==null?void 0:n.company)==null?void 0:C.activePlan)==null?void 0:D.plan)==="free";throw(B=_.stack)!=null&&B.includes("at startWebDriverSession")&&((R=_.message)!=null&&R.startsWith("Failed to create session"))&&((A=_.message)!=null&&A.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):_.message.match(/Invalid username or password/)?new jr(_.message):_.message.match(/capabilit(y|ies)/)?new di(_.message):_.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):_.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${_.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ps.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=se();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,je.warn("close unexpected alert open"),await this.alertAccept().catch(l=>je.warn("failed to click on alert",{err:l}));return}if(je.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;je.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=yh(r.value);return await this.switchToFrame({ELEMENT:n,[Ht]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new mi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||L.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
23
23
|
var fn = ${nr().getLocatedElementCode};
|
|
24
24
|
return fn.apply(null, arguments);
|
|
25
25
|
`,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
|