@testim/testim-cli 4.37.0 → 4.38.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 +18 -18
- package/cli.js.map +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -17,8 +17,8 @@ Testim had missing write access to ${l||s}
|
|
|
17
17
|
`).filter(y=>!t(y)&&!e(y)&&!s(y)&&!r(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!m(y)&&!d(y)&&!p(y)&&!g(y)).join(`
|
|
18
18
|
`))},Tw=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Tm.default.yellow(`
|
|
19
19
|
WARNING: ${s} is deprecated. ${t}
|
|
20
|
-
`))},gl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:hl,argv:bl,exit:dl,cwd:It}=global.process,ww=["trace","debug","info","warn","error","silent"];Qa(bl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));yl.description("Testim.io CLI").option("-h --help","output usage information",Em).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",yw).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("--is-regression-baseline-run","save doms and run results as regression baseline data").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",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).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("--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("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).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("--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(hl.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,ml.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,ml.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: ${gl.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").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("--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").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",Le,[]).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)",Le,[]).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)",Le,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(bl);u=yl.opts(),vw=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},Ew=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},Sw=async()=>{var y,v,S,b,T,I,C,k;u.inspect&&require("inspector").open(u.inspect);let s={},e={},t=[],r={};if(!bl.slice(2).length)throw Em(),new Lr;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(Qr(),sn)),M=await R.getProjectId(),O=await R.getToken();(!M||!O)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(Qr(),sn))).doLogin(),{loginMode:!0};if(u.version){let R="Testim CLI Version: ";hl.npm_package_version&&(console.log(R,hl.npm_package_version),dl(0));let M=it();M&&(console.log(R,M),dl(0)),console.log("Could not find version, please check the package.json manually"),dl(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Ed();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=De.resolve(n);wd(R)}if(u.usePrefechedData&&Sd(),u.playerRequirePath){let R=De.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let M=De.join(R,"tsconfig.node.json"),D=require("ts-node").register({project:M,ignore:[/node_modules/,new RegExp(`^${Ft.escapeRegExp(De.relative(It(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:D.config.options.paths,baseUrl:D.config.options.baseUrl}),(be(),fe(Yt)).options.playerPath=R;let H=require("module"),J=H.prototype.require;H.prototype.require=function(de){return de==="rox-alias"?J.call(this,"rox-node"):J.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=fl.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new P("missing --proxy option");if(dm(u))return mm(u);try{let R={};u.configFile?R=require(De.join(It(),u.configFile)).config:u.optionsFile&&(R=require(De.join(It(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(M=>{let O=hw(M);u[O]=bw(u[O],R[M])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((y=u.testConfig)==null?void 0:y.length)||((v=u.testConfigId)==null?void 0:v.length),i=((S=u.testPlan)==null?void 0:S.length)||((b=u.testPlanId)==null?void 0:b.length),a=((T=u.suite)==null?void 0:T.length)||((I=u.suiteId)==null?void 0:I.length);if(u.seleniumCapsFile)try{r=require(De.join(It(),u.seleniumCapsFile))}catch(R){throw new P(`Failed to parse selenium caps file file error: ${R.message}`)}if((C=u.reporters)!=null&&C.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(De.join(It(),u.chromeExtraPrefs))}catch(R){throw new P(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let M of R){let[O]=M.split("=");bm.includes(O)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(M),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(bm)}`)}}if(u.paramsFile)try{s=Object.assign({},s,require(De.join(It(),u.paramsFile)))}catch(R){throw new P(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{s=Object.assign({},s,JSON.parse(u.params))}catch(R){throw new P(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(vw(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(De.join(It(),u.sauceOptions)),M=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let D=R.browserName.toLowerCase();switch(D){case"microsoftedge":u.browser="edge";break;default:u.browser=D}}u.browser==="edge"&&parseFloat(R.version)>=va&&(u.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!M&&u.browser==="chrome"&&O)throw new P("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new P(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(Ew(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(De.join(It(),u.browserstackOptions)),M=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=va&&(u.browser="edge-chromium"),!M&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new P(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(De.join(It(),u.perfectoOptions)),M={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},M,R)}catch(R){throw new P(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(De.join(It(),u.testobjectOptions)),M={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},M,R)}catch(R){throw new P(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let M=await(await Promise.resolve().then(()=>(Qr(),sn))).getProjectId();if(M)u.project=M;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.mode??="extension",u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Y.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let M=await(await Promise.resolve().then(()=>(Qr(),sn))).getToken();if(M)u.token=M;else throw new P("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 l=R=>R<=0||!Number.isInteger(R);if(l(u.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(u.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(u.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(u.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(u.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(u.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(u.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(u.mode))throw new P(`runner mode <${u.mode}> is not supported`);if(u.mode!==Y.SELENIUM&&u.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!ww.includes(u.appiumLogLevel))throw new P(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new P("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(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((k=u.host)!=null&&k.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=wm.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(M=>M.trim()).filter(Boolean);let R=u.resultLabel.filter(M=>M.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&mr()&&u.resultLabel.unshift(mr()),R.length)throw new P("A result label cannot exceed 250 characters")}let d=im(u),p=Oo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new P("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(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new P("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(u.setRetention&&!Ft.inRange(Ft.parseInt(u.setRetention),1,11))throw new P("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)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&Ft.difference(u.codeCoverageReporter,gl).length){let R=Ft.difference(u.codeCoverageReporter,gl);throw new P(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.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"},h=Object.keys(f).filter(R=>Boolean(u[R]));if(u.mode!==Y.EXTENSION&&h.length){let R=h.length>1?"are":"is";throw new P(`${h.map(M=>f[M]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=fl.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new P(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(Tw("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.setNoReset&&u.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},M=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,M)}catch(R){throw new P(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Y.EXTENSION&&(u.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"});if(typeof u.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?mr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:s,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,customTag:u.customTag,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,setNoReset:u.setNoReset,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||d].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||p,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var Pm={};G(Pm,{installAllLazyDependencies:()=>xw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=ac(s);if(t)return t;let r;e.silent||(r=(0,Im.default)(`Installing ${s} before first usage...`).start());try{let n=await Iw(s);return r&&r.succeed(),n}catch(n){Rw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Am(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`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 ${c}${i}`;throw r&&r.fail(l),n}}async function Iw(s){return Zr.has(s)||(Zr.set(s,xm(s)),Zr.get(s).catch(()=>{Zr.delete(s)})),Zr.get(s)}async function xm(s){let e=ac(s);if(e)return e;let t=Am(s),r=`${s}@${t}`;return await go(at(),r),zt(s)}async function xw(){let s=Object.keys(Ia);for(let e of s)await xm(e)}function Am(s){let e=Object.entries(Ia).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Im,Rw,Zr,wr=w(()=>{"use strict";Im=E(require("ora"));Vs();B();j();Gn();Gs();Rw=x("lazy-require"),Zr=new Map});var km={};G(km,{preloadTests:()=>nn});async function nn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ct(async()=>{let t=await ie(s.testId,r=>Rc({...e,testId:r}),{concurrency:2});return Cm.keyBy(t,"testData.id")},"loadTests",Aw,[e,s.testId])()}var Cm,Aw,No=w(()=>{"use strict";Cm=E(require("lodash"));qt();ye();j();Aw=1e3*60*60*10});function Tl(){return it()}async function Lm(){if(!Ce)try{let s=await ae(Cw(),5e3,"The API call to NPM timed out"),e=Tl();e&&_m.lt(e,s)&&console.log(Om.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){Pw.warn("Failed to get NPM version",{err:s})}}var Om,_m,Pw,Cw,wl=w(()=>{"use strict";Om=E(require("chalk")),_m=E(require("semver"));j();le();Vs();qt();B();Pw=x("npm-driver"),Cw=ct(()=>Ad("@testim/testim-cli"),"getNpmVersion")});var vl,Ow,es,Dm,Mm,El,Nm,Um=w(()=>{"use strict";j();z();B();wr();vl=x("testimNgrok"),Ow=".whitelisted-ngrok.testim.io",es="",Mm=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${s.projectData.projectId}${Ow}`);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 o=await(await Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(vl.info("replace https to http"),es=o.replace("https://","http://")):es=o,s.tunnelDiagnostics&&El(),s.baseUrl=es},El=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===es);console.log("ngrok stats",n),vl.info("ngrok stats",{tunnel:n})}catch(e){vl.error("error collecting ngrok stats",{err:e})}s&&(Dm=setTimeout(()=>El(),1e4))},Nm=async s=>{if(!es)return;clearTimeout(Dm),s.tunnelDiagnostics&&await El(!1),await(await Ee("ngrok")).disconnect(es)}});var Xt,Rl,Fm,Lw,Dw,Sl,Uo,Bo,Fo,Mw,Bm,jm,$m=w(()=>{"use strict";Xt=E(require("os")),Rl=E(require("fs")),Fm=E(require("child_process"));j();ye();Lw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Dw={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"}},Sl=Xt.tmpdir(),Uo=`${Sl}/cloudflared`,Bo=null,Fo=null,Mw=async()=>{if(await ge(Uo))return;let e=Dw[Xt.platform()+Xt.arch()];if(!e)throw new Error(`tunnel on ${Xt.platform()+Xt.arch()} platform is not supported.`);let t=e.extract?Sl+e.path:Uo;await He(`${Lw}/${e.path}`,t),e.extract&&await Ze(t,Sl),await Rl.promises.chmod(Uo,"755")},Bm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([zc(s.company.companyId,t),Mw()]);Bo=r._id,Fo=Fm.spawn(Uo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Kc(s.company.companyId,Bo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Rl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},jm=async s=>{let e=[];return Bo&&e.push(Jc(s.company.companyId,Bo)),Fo&&e.push(new Promise((t,r)=>{Fo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Fo.kill()})),await Promise.all(e)}});var V,Gm,Uw,Fw,Bw,Wm,jo,Il,N,Te=w(()=>{"use strict";V=E(require("rox-node"));B();j();le();Gm=x("FeatureFlagsService"),Uw=!Ce&&!0&&!Ap,Fw=2e4,Bw=60*60*24,Wm=["labs","disabled","enabled"],jo=class extends V.default.Variant{constructor(e="disabled"){super(e,Wm)}getValue(){let e=super.getValue();return Wm.includes(e)?e:(Gm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Il=class{constructor(){this.flags={useNewWSCLI:new V.default.Flag,useSafariWebdriverVisibilityChecks:new V.default.Flag,useClickimVisibilityChecks:new V.default.Flag,runGetElementCodeInAut:new V.default.Flag,enableFrameSwitchOptimization:new V.default.Flag,maximumJsResultSize:new V.default.Configuration(2e3*1024),skipFileInputClicks:new V.default.Flag,errorMessageOnBadNetwork:new V.default.Flag(!0),warnOnBadNetwork:new V.default.Flag(!1),overrideAzureStorageUrl:new V.default.Flag,useJsInputCodeInSafari:new V.default.Flag,useJsInputCodeInFirefox:new V.default.Flag,useJsInputCodeInEdgeChromium:new V.default.Flag,autoSaveDownloadFileFireFox:new V.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new V.default.Flag(!0),experimentalPreCodeCompilation:new V.default.Flag(!0),experimentalAsyncCustomCode:new V.default.Flag,useSameBrowserForMultiTests:new jo("labs"),highSpeedMode:new jo,usePortedHtml5DragDrop:new V.default.Flag,testNamesToBeforeSuiteHook:new V.default.Flag,addCustomCapabilities:new V.default.Variant("{}"),LTNetworkCapabilities:new V.default.Flag,downloadToBase64:new V.default.Flag,publicGridURL:new V.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new V.default.Flag(!0),unsupportedCapsFields:new V.default.Variant("[]"),useLinkedomToParseHtml:new V.default.Flag,dontFocusOnInit:new V.default.Flag,retryOnSeleniumHubError:new V.default.Flag,removeEdgeChromeDefaultVersion:new V.default.Flag,enableLambdaTestTunnelNTLM:new V.default.Flag,enableLambdaTestTunnelSkipUpgrade:new V.default.Flag,tdcHsPreventNetworkCapture:new V.default.Flag},V.default.register("default",this.flags)}setProjectId(e){V.default.setCustomStringProperty("projectId",e)}setProjectType(e){V.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){V.default.setCustomStringProperty("productType",e)}setCompanyId(e){V.default.setCustomStringProperty("companyId",e)}setPlanType(e){V.default.setCustomStringProperty("planType",e)}setIsPOC(e){V.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){V.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){V.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Uw)return;let e={fetchIntervalInSec:Bw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ae(V.default.setup(Ip,e),Fw).catch(t=>Gm.error("failed to get feature flag status",t))}},N=new Il});var Hm,qm,Qt,zm,Km,Vm,jw,$w,$o,Ww,Gw,ne,Wo=w(()=>{"use strict";Hm=E(require("ms")),qm=E(require("p-retry")),Qt=E(require("os")),zm=E(require("portfinder")),Km=E(require("child_process"));j();Ve();ye();z();B();_o();ce();Te();Vm=x("lambdatestService"),jw="https://downloads.lambdatest.com/tunnel/v3",$w={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"},$o=`${Qt.tmpdir()}/LT`,Ww=`${$o}/LT`,Gw=(0,Hm.default)("15m"),ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===U.LAMBDATEST||e.type===U.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Bc(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Gw:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Ww))return;let t=$w[Qt.platform()+Qt.arch()];if(!t)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let r=`${$o}.zip`;await He(`${jw}/${t}`,r),await Ze(r,$o)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await zm.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;ne.tunnelName=te();let a=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(N.flags.enableLambdaTestTunnelNTLM.isEnabled()&&(a=[...a,"--ntlm"]),N.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(a=[...a,"--skip-upgrade"]),e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)a=[...a,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let m=new URL(i);a=[...a,"--proxy-host",m.hostname],m.port&&(a=[...a,"--proxy-port",m.port]),m.username&&m.password&&(a=[...a,"--proxy-user",m.username,"--proxy-pass",m.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),ne.tunnel=Km.spawn("./LT",a,{cwd:$o});let c="",l="";ne.tunnel.stdout.on("data",m=>{c+=m.toString()}),ne.tunnel.stderr.on("data",m=>{l+=m.toString()});try{let m=await(0,qm.default)(()=>Ne(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});Vm.info("LT tunnel info",m)}catch(m){throw Vm.error("Failed to start LT tunnel",{err:m,stdoutResult:c,stderrResult:l}),m}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=ne.lambdatestConfig.CAPABILITIES[t]||{},a={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},c=[],{mode:l,canary:m,ext:d,extensionPath:p,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!d){let f=il({canary:m},!0);!p&&f[t]&&(c=[...c,f[t]]),p&&je(p)&&(c=[...c,p])}return g&&je(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:ne.lambdatestConfig.PLATFORM,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,resolution:ne.lambdatestConfig.RESOLUTION,timezone:ne.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:N.flags.LTNetworkCapabilities.isEnabled(),ntlm:N.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:N.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var xl={};G(xl,{connect:()=>Vo,disconnect:()=>Ho,serveTunneling:()=>Hw});var Go,Jm,Ym,Vw,Vo,Ho,Hw,Al=w(()=>{"use strict";Um();en();$m();Rt();Go=E(require("ora"));B();ce();Wo();Jm=x("tunnel"),Ym=s=>{var e;return[U.LAMBDATEST,U.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Vw=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===U.HYBRID&&s.gridData.tunnel==="cloudflare"},Vo=async s=>{if(!s.tunnel)return;let e=Mt(),t;try{Ym(s)?(t=(0,Go.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):Vw(s)?(t=(0,Go.default)("Starting testim cloudflare tunnel...").start(),await Bm(s)):(t=(0,Go.default)("Starting testim ngrok tunnel...").start(),await Mm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Jm.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Ho=async s=>{if(s.tunnel)try{Ym(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await jm(s):await Nm(s)}catch(e){let t="catch error - failed to close tunnel";throw Jm.error(t,{err:e}),new Error(t)}},Hw=async(s,e=new Promise(()=>{}))=>(await Vo(s),Yr(()=>Ho(s)),await e)});function qw(s){if(s.protocol)return s.protocol;if([U.TESTIM,U.BROWSERSTACK,U.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([U.TESTIM_ENTERPRISE,U.LAMBDATEST,U.DEVICE_FARM].includes(s.type)){let e=Xm.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zw(s){let e=Xm.exec(s);return e==null?void 0:e[3]}function zo(s){var y,v,S,b,T,I,C,k,R;let e=s&&zw(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&qw(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(v=s==null?void 0:s.external)==null?void 0:v.user,l=(S=s==null?void 0:s.external)==null?void 0:S.key,m=s==null?void 0:s.type,d=m===U.HYBRID?a&&((I=(T=(b=s.hybrid)==null?void 0:b.external)==null?void 0:T[s.hybrid.tunnel])==null?void 0:I.user):c,p=m===U.HYBRID?a&&((R=(k=(C=s.hybrid)==null?void 0:C.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:R.key):l,g=s==null?void 0:s.name,f=s&&(s._id||s.gridId),h=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:m,name:g,provider:h,tunnelUser:d,tunnelKey:p}}async function Zm(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Je.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(jr.UNKNOWN)}if(Je.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Je.error("invalid response - get grid",{res:o}),new Error(jr.UNKNOWN);if(o.status==="success"){let i=zo(o.grid);return Kw(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new Tt(jr.NOT_FOUND):o.code==="no-available-slot"?new Mr(`Failed to run test on ${r} - concurrency limit reached`):(Je.error("invalid code error response - get grid",{res:o}),new Tt(jr.UNKNOWN))}function Jw(s,e,t,r,n,o){return Zm(t,e,s,n,()=>Io(e,t,r,n,o))}function Yw(s,e,t,r,n,o,i){return Zm(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(m=>(m.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Io(e,t,c._id,n,o):Nc(e,t,r,n,o)})}function ef(s){return Fc(s)}async function tf(s,e,t){let n=(t||await ef(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return zo(n)}async function Xw(s,e,t){let n=(t||await ef(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return zo(n)}async function Pl(s,e){let t=on[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete on[s],!r){Je.warn("failed to find grid slot id",{projectId:e});return}Je.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Dc(i,e,r,n,o)}catch(a){Je.error("failed to release slot",{projectId:e,err:a})}}async function Qw(s){let e=Object.values(on).filter(Boolean);if(e.length!==0){Je.info("keep alive worker slots",{projectId:s,slots:e});try{await Lc(s,e)}catch(t){Je.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zw(s){Qm=global.setInterval(Qw,1e4,s)}async function ev(s){let e=Object.keys(on);if(e.length){Je.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>Pl(Number(t),s))}catch(t){Je.error("failed to release all slots",{err:t,projectId:s})}}}async function tv(s){await ev(s),clearInterval(Qm)}function rv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function rf(s){let t=(()=>qo.isEmpty(s.testobjectSauce)?qo.isEmpty(s.saucelabs)?qo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=rv(t,s),c=sv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function sf(s,e){let t=s.company.companyId;return await tf(t,e.gridId,s.allGrids)}async function nf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return rf(s);let l=t==null?void 0:t.companyId;if(a)return tf(l,a,e);if(c)return Xw(l,c,e);if(Us(s)||s.tunnelOnlyMode){Je.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Tt("Missing host or grid configuration")}async function of(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:m,company:d}=t,p=d==null?void 0:d.companyId;if(l||m||c)return{mode:"local"};if(n)return rf(t);if(a)return Jw(r,p,o,a,s,e);if(i)return Yw(r,p,o,i,s,e,t);throw new Tt("Missing host or grid configuration")}var qo,Je,on,Xm,Qm,Kw,an,af,ts=w(()=>{"use strict";qo=E(require("lodash"));ye();B();j();ce();z();Je=x("grid-service"),on={},Xm=/(^(https?):\/{2})?(.*)/,Qm=null;Kw=(s,e,t,r,n)=>{on[s]={gridId:t,companyId:e,slotId:r,browser:n}};an={start:Zw,end:tv};af=async(s={},e={},t={},r={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:m,currentRetry:d}=n;if(!i||!a||(a===U.LAMBDATEST&&await((f=r.enableIfNeeded)==null?void 0:f.call(r,e)),a!==U.HYBRID||!o||!c||!m||!d))return e;let p=await Mc({companyId:o,gridId:i,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Je.info("handling hybrid grid",{response:p,companyId:o});let g=zo({...e,...p.connectionDetails,provider:p.provider});return p.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),p.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});function ln(){return Ko||"master"}function cf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Ko="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){Ko=s.branch||s;return}Ko=e?"master":void 0}var Ko,Cl=w(()=>{"use strict";z()});var un,kl,nv,Ol,ov,Jo,Yo,Xo,Qo,Zo,ei=w(()=>{"use strict";j();ce();un=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},kl=s=>{let{status:e}=s;return e===pe.ABORTED},nv=s=>{let{status:e}=s;return e===pe.PASSED},Ol=s=>s.runnerStatus===za.SKIPPED,ov=s=>s.testStatus===qe.EVALUATING,Jo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(ze(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Yo=s=>Object.values(s).filter(e=>un(e)&&ov(e)).length,Xo=s=>Object.values(s).filter(un),Qo=s=>Object.values(s).filter(nv),Zo=s=>Object.values(s).filter(kl)});function av(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var _l,ti,iv,ri,uf=w(()=>{"use strict";_l=E(require("lodash"));B();ei();ti=x("debug-reporter"),iv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ri=class{constructor(e){this.options=e}onTestStarted(e,t){ti.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,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;ti.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:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{..._l.default.omit(this.options,iv),company:_l.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=av(process.argv);ti.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=Qo(e).length,a=Object.keys(e).length-i;ti.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ll,xt,pn=w(()=>{"use strict";ce();Ll=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===U.DEVICE_FARM}},xt=new Ll});var Ml={};G(Ml,{Reporter:()=>cv});var Zt,dn,vr,si,pf,Dl,cv,Nl=w(()=>{"use strict";Zt=E(require("chalk")),dn=E(require("lodash"));j();ce();pn();ei();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:si}=Lt,pf="device",Dl=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: ${Zt.default.underline(ot(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?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${to(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ot(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
21
|
-
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=Xo(e),a=Qo(e),c=Zo(e),l=a.length,m=c.length,d=i.length,p="",g="";if(xt.isTestStatusEnabled){let S=Yo(e);p=` FAILED-EVALUATING: ${S}`,d-=S,g=` SKIPPED: ${Jo(e,this.options)}`}let f=this.buildTestPlanName(o,t),h,y=vr[d?"error":"success"],v=`PASSED: ${l} FAILED: ${d}${p} ABORTED: ${m}${g} Duration: ${to(r)}`;f.trim()===""||f.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${f} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=dn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=dn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=dn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=dn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=p=>{p.forEach((g,f)=>{var v;let h=(v=g.testData)!=null&&v.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${ze(g,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${d} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===si.APPIUM?pf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===si.APPIUM?pf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.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,o=this.options.mode===si.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===si.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},cv=Dl});var Bl={};G(Bl,{Reporter:()=>fv});function lv(s){let e=s.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function uv(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 pv(s){return`${s.visitedUrlsJson||""}`}async function dv(s,e,t,r,n,o){function i(p){let g=ot(s,t,p.testId,p.resultId,r),f={$:{name:lv(p),classname:n,time:Za(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":g};if(un(p)||kl(p)){let h=`Step Failed: ${p.failureReason||p.reason}`,y=un(p)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Ol(p)&&ze(p,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=uv(p),f["visited-urls-json"]=pv(p)),f}function a(p){let{results:g,testPlanName:f,configName:h}=p,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:m(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=Jo(y,o);let b=Yo(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(p){let g=Object.keys(p).map(h=>p[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function m(p){return Xo(p).length+Zo(p).length}let d={testsuites:{testsuite:e.map(p=>a(p))}};try{return new Fl.Builder().buildObject(d)}catch(p){return mv(p)}}function mv(s){let e=new Fl.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 Fl,df,Ul,fv,jl=w(()=>{"use strict";Fl=E(require("xml2js"));j();df=require("fs");pn();ei();Ul=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 dv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await df.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};fv=Ul});var mf={};G(mf,{Reporter:()=>gv});function rs(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 $l,Wl,gv,ff=w(()=>{"use strict";B();$l=x("team-city-reporter");Wl=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 rs(n)}onTestStarted(e,t,r,n){if(r){$l.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){$l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${rs(t)}' details='${rs(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){$l.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='${rs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${rs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${rs(t)}']`)}},gv=Wl});var gf={};G(gf,{Reporter:()=>hv});var Gl,hv,hf=w(()=>{"use strict";Gl=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,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},hv=Gl});var yf={};G(yf,{Reporter:()=>yv});var Vl,yv,bf=w(()=>{"use strict";j();al();Vl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ot(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Do(t)}},yv=Vl});var mx,Hl,X,At=w(()=>{"use strict";uf();B();mx=x("reporter"),Hl=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 ri(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Nl(),Ml));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(jl(),Bl));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(ff(),mf)),r.includes("console")&&Promise.resolve().then(()=>(Nl(),Ml)),r.includes("junit")&&Promise.resolve().then(()=>(jl(),Bl)),r.includes("json")&&Promise.resolve().then(()=>(hf(),gf)),r.includes("chrome")&&Promise.resolve().then(()=>(bf(),yf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},X=new Hl});function wf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function vf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:p,projectType:g,appSource:f,gridType:h}){let y=wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Tf(l,m),isStartUp:p,projectType:g,gridType:h,...["android","ios"].includes(g)&&f&&{appSource:f}},d);lt("test-run-ci",y)}function Ef({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:p,logger:g,isStartUp:f,projectType:h,appSource:y,gridType:v}){try{let S=wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Tf(m,d),isStartUp:f,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},p);if(n.success){lt("test-run-ci-success",S);return}lt("test-run-ci-fail",Object.assign({},S,{failureReason:n.failureReason}))}catch(S){g.error("failed to update test end analytics",{err:S})}}function Sf(s){lt("batch-run-ci",s)}var Tf,ql=w(()=>{"use strict";Xr();Eo();Tf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Kr&&e?"ci-with-user":Kr?"ci":e?"cli-with-user":s});var If,ni,xf=w(()=>{"use strict";If=require("istanbul-lib-report"),ni=class extends If.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 Af,Pf,Cf,mn,ut,kf,oi,zl,Of,bv,_f,Lf,Tv,wv,Df,vv,Ev,Sv,Rv,Iv,Mf,Nf=w(()=>{"use strict";Af=E(require("ora")),Pf=E(require("dayjs")),Cf=E(require("test-exclude")),mn=E(require("fs")),ut=E(require("path")),kf=E(require("istanbul-reports")),oi=E(require("istanbul-lib-report"));ye();z();j();B();wr();xf();zl=x("test-run-status"),Of=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},bv=s=>!!Of(s).search,_f=s=>s?Of(s).pathname.substring(1):"",Lf=(s,e)=>{let t=_f(e);return!new Cf.default({relativePath:!1,include:s}).shouldInstrument(t)},Tv=s=>s.substring(0,s.indexOf("?")),wv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Df=(s,e)=>`${ut.resolve(s,_f(e))}.js`,vv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Lf(r,i))return;let c=Df(e,i);await mn.promises.mkdir(ut.parse(c).dir,{recursive:!0}),await mn.promises.writeFile(c,o.sourcesContent[a])})})},Ev={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(bv(e)&&(e=Tv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ut.dirname(this.getPath(s));return ut.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Sv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=oi.createContext({dir:t,coverageMap:e,watermarks:oi.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Df(r,a);return mn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ni({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Ev}),kf.create(a,c).execute(i)}),o},Rv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Lf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Iv=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await $c(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Xs(c,9e4);await ie(l,async m=>{if(!o.has(m.url)){let d=m.text;m.sourceUrl&&(o.set(m.url,"TEMP"),d=await Ec(m.sourceUrl)),o.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Mf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;zl.info("start js coverage process");let n=(0,Af.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ut.resolve(s.codeCoverageReportPath||"./coverage"),i=ut.resolve(o,`.js/${(0,Pf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ut.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([Ee("istanbul-lib-coverage"),Iv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}zl.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),p={};await ie(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:v}=m.get(f),S=await wv({sourceMapType:v,source:y,sourceMapDir:a});p[f]=S;let b=await Rv(s,{source:y,sourceMap:S,functions:h});d.merge(b)}),await vv(s,i,p);let g=await Sv(s,d,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof P?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),zl.error(l,{err:c})}}});var Uf={};G(Uf,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Bt});var xe,xv,Bt,ss=w(()=>{"use strict";j();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},xv=["ALL",...Object.values(xe)],Bt=class{constructor(){this.marks=Object.fromEntries(xv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=te();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`,no(r,50)],[`${t}_P95`,no(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var $f={};G($f,{initServer:()=>Cv,mapFilesToLocalDrive:()=>Jl});function Jl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ii[t.id]?{screenshot:ii[t.id]}:{})),Object.keys(ai).forEach(t=>{s.assets||={},s.assets[jf[t]]=ai[t]}),s.assets||={},s.assets.screenshots=Object.values(ii)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Cv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Av;await Kl.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let p=fn.join(n,d.testResultId);try{await Kl.promises.mkdir(p,{recursive:!0})}catch(g){return m(g,"")}return m(null,p)},filename(c,l,m){let{fileName:d}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(p.stepId){let g=fn.extname(d);return m(null,`step_${p.stepId}_${p.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),i=(0,Bf.default)();i.post("/",o.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(ii[m.stepId]=c.file.path),m.testResultId&&Pv.includes(m.subType)&&(ai[m.subType]||=[],ai[m.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(i);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new P(`Port ${s} is already in use`));default:return l(p)}}})}var Kl,Ff,fn,Bf,Av,ii,ai,jf,Pv,Yl=w(()=>{"use strict";Kl=E(require("fs")),Ff=E(require("os")),fn=E(require("path")),Bf=E(require("express"));z();wr();Av=fn.join(Ff.tmpdir(),"testim/rca/"),ii={},ai={},jf={"test-log":"consoleLogs","har-file":"networkLogs"},Pv=Object.keys(jf)});var er,Xl,ci,Wf=w(()=>{"use strict";er=E(require("lodash"));j();B();Xl=x("override-test-data-builder"),ci=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Xl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Xl.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}Xl.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 er.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 o=r.map(m=>this.generateTestUniqId(m)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=te();return Object.assign({},e,{resultId:o,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 li(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ye.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Er,Ye,kv,Ov,_v,Lv,ui,Gf=w(()=>{"use strict";Er=E(require("lodash"));j();ce();ts();ye();z();B();At();en();Nf();ss();Yl();le();Te();Wf();pn();Ye=x("test-run-status"),kv=mr(),Ov=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,_v=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Lv=it();ui=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 Bt;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ns(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:zn||t.parallel||1,browser:o,gitBranch:kv,gitCommit:Ov,gitRepoUrl:_v,runnerVersion:Lv,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(d=>d.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:i,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(m=t.gridData)==null?void 0:m.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:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:i,testStatus:d};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}),Hc({projectId:n,runId:o,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,X.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ao(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(m){Ye.error("failed to upload test data artifact (runner)",{err:m})}let c=Er.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(ze(e,this.options))return;let n=this.exportsGlobal;try{let o=await li(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ye.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ye.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===qe.EVALUATING&&xt.isTestStatusEnabled){X.onTestIgnored(e,r,`test in ${qe.EVALUATING} status`);return}if(l){X.onTestPassed(o);return}X.onTestFailed(r,r.failureReason,ot(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);X.onTestIgnored(e,r,`test in ${qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=ec();if(t.isOverThreshold){let r=N.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ye.info(`using ${r} to parse html`,{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,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Jl(i,Ye),i.resultUrl=ot(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),X.onTestFinished(i,e,o);let c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await li(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ye.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await br(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 Ye.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t){let r="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=Ya;return e&&(r=n),$r(t)&&(r=o),r}calcTestRunStatus(){let{options:e,testInfoList:t}=this,r=e.company.companyId,n=t.map(o=>{var d,p,g;let i=e.browser?$s(e.browser,e.saucelabs,e.browserstack):o.runConfig,a=!N.flags.allowAppFromDeviceRuns.isEnabled()&&Fs(o.nativeApp),c=Bs(e)&&($r(o.nativeApp)||a),l=ze(o,e)||c,m={testId:o.testId,status:l?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,testStatus:o.testStatus||qe.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:this.getMobileRunSkippedReason(a,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:r,testData:((d=o.testData)==null?void 0:d.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((p=o.testData)==null?void 0:p.total)||null,testDataIndex:((g=o.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,m]});return Object.fromEntries(n)}async executionStart(e,t,r,n,o){Ye.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Yr(()=>Promise.all([an.end(t),Ro("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...N.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},m=await li(i.beforeSuite,l),d=new ci(m,Er.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=m;let{testInfoList:p}=this,g=[],f=[],h=[];for(let v of p){if(v.isBeforeTestPlan){g.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}f.push(v)}let y=async()=>{let v=Er.cloneDeep(this.testRunStatus);await ie(Object.keys(v),async I=>{var O;let C=v[I],k=(O=C.config)==null?void 0:O.testData,R=C.testId,M=await Ao(t,R,I,k,c.defaults);M&&(delete C.config.testData,C.config.testDataUrl=M)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},T=Ac(b);return this.executionStartedPromise=T,T.catch(I=>Ye.error(I)),T};try{await y()}catch(v){Ye.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){Er.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 m;let t=rc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:p}of t)d===pe.PASSED&&n++,d===pe.SKIPPED&&o++,d===pe.FAILED&&p===qe.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await li(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ye.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Mf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Ro("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Ye.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await xc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});var Vf,Pt,Ql,pt,pi=w(()=>{"use strict";B();ce();le();ye();Ve();Vf=E(require("ora")),Pt=x("mobile-grid-service"),Ql=class{constructor(){this.gridsAppIdGetter={[U.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getTdcAppPath(t),[U.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getHeadspinAppPath(t),[U.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getBrowserStackAppPath(t),[U.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===U.TESTIM_TDC||e===U.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===U.TESTIM_HEADSPIN?`${Dp}/devices`:e===U.TESTIM_TDC?`${Mp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await $e({url:r,headers:n,body:o})}catch(i){throw Pt.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Ne(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Pt.error("error while getting automation config for device",{error:o,deviceId:t}),o}}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if([U.BROWSERSTACK,U.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,c;if(t===U.TESTIM_HEADSPIN||t===U.TESTIM_TDC){let l=await Xc({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}return t===U.BROWSERSTACK?(c=e.mobile)==null?void 0:c.version.split("-")[0]:t===U.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r){var y;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:m="",type:d=""}={}}=r,p=t.capabilities,g=await this.getDeviceNameFromSessionCaps({capabilities:p,gridType:d,projectId:a,projectType:c,companyId:l,gridId:m}),f=p.platformVersion;!f&&d===U.BROWSERSTACK&&(f=(y=p.mobile)==null?void 0:y.version.split("-")[1]);let h={name:g,model:p.deviceModel,osVersion:f,udid:p.udid,osType:p.platformName,scaleFactor:p.pixelRatio,isVirtual:!1};return await br(a,n,o,i,"RUNNING",{device:h}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h}),h}async getTmaDeviceDetails(e){let t=await Ne(`${Np}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);return r?{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}:{}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await kc({appId:e,projectId:t});if(!i)throw Pt.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Pt.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Lp*60))+1)*60*1e3,Math.max(_p,t)}async getAppInfoForRemoteRun({testRunHandler:e,options:t}){let r="",n,{executionId:o,testResultId:i}=e,{appId:a,project:c,authData:{token:l=""}={},gridData:{gridId:m="",type:d="",host:p=""}={}}=t;if(a){Pt.info("getting appData by appId",{appId:a,projectId:c,testResultId:i,executionId:o});let y=await this.getMobileAppDataByAppId({appId:a,projectId:c,token:l,executionId:o,testResultId:i});r=y.appUrl,n=y.mobileApp,e.nativeApp=n}else Pt.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:i,executionId:o}),r=e.downloadableAppPublicLink||"";let g=this.gridsAppIdGetter[d]({testRunHandler:e,mobileApp:n,gridHost:p}),f=!!g&&d===U.TESTIM_TDC,h=!!g&&d===U.TESTIM_HEADSPIN;if(g&&(r=g),!g&&U.BROWSERSTACK===d){if(e.isAppFromDevice)throw new Error("The selected application from your device is not supported by the BrowserStack grid. Please choose a compatible application for testing.");let y=n||e.mobileApp,v=(0,Vf.default)("uploading app to browserstack please wait..").start();try{Pt.info("uploading app to browserstack",{appId:a,projectId:c,testResultId:e.testResultId,executionId:e.executionId});let S=await Qc({projectId:c,gridId:m,app:y,timeout:this.calculateUploadRequestTimeOut(y.fileSize)});v.succeed("app uploaded successfully to browserstack"),r=S.browserStackAppId}catch(S){throw v.fail("failed to upload app to browserstack"),Pt.error("failed to upload app to browserstack",{error:S}),new Error("failed to upload app to browserstack")}}return{appPath:r,isTdcAppIdExists:f,isHSAppIdExists:h}}},pt=new Ql});function Mv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function su(s){return zf.readFileSync(s,{encoding:"base64"})}function Xf(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=su(s);ns.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${ru(r)} current extension count: ${e.length}`),e.push(r)}}function Qf(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,m=`--load-extension=${l}`;ns.info(`adding extension: testim unpacked , path: ${l}`),t.push(m);return}let o=s.canary?"-master.zip":".zip",i=tu.join(process.cwd(),`testim-headless${o}`),a=su(i);ns.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${ru(a)} current extension count: ${e.length}`),e.push(a)}function Nv(s,e,t,r,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...Yf];e.headless&&l.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Zl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Zl.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},w3c:!0};eu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),eu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Zl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function d(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Ka.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}d(),Xf(r,c,i),e.mode===Y.EXTENSION&&Qf(e,c,l,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=l;let p={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[p]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${g}:${p}`]=m),s}function Fv(s,e,t){let r={"pdfjs.disabled":!0};if(N.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":qf.join(","),"browser.helperApps.neverAsk.openFile":qf.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.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=tu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=su(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Bv(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let o=(0,Jf.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),Object.assign({},o,r,n)}return Object.assign({},r,n)}return{}}function jv(s,e,t){return dt.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}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function $v(s){return s.perfecto?s.perfecto:{}}function Wv(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 Gv(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ea(o,i)),a}function mi(s,e,t,r,n,o,i,a=null){var h,y;if(r.mode==="local"){let v=[],S=[...Yf],b={};return s.headless&&S.push("--headless"),s.silentDebuggerExtensionApi&&S.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&S.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(T=>S.push(`--${T}`)),s.chromeBinaryLocation&&(b.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&Qf(s,v,S,null,a),Xf(n,v,a),{logLevel:Hf,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:S,extensions:v,...b},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,m=Gv(s,r),d={hostname:r.host,host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:Hf,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!dt.isEmpty(m)&&{headers:m},...s.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};eu(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs||={},s.saucelabs.username||=r.user,s.saucelabs.accessKey||=r.key),r.type==="browserstack"&&(s.browserstack||={},s.browserstack["browserstack.user"]||=r.user,s.browserstack["browserstack.key"]||=r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let p=Number(s.browserTimeout/1e3),g=s.browser||(t==null?void 0:t.browserValue);dt.merge(d.desiredCapabilities,Bv(s,e,t),jv(s,e,t),$v(s),Wv(s,g,p),a==null?void 0:a.getCapabilities(s,g,o,i,e));let f=null;switch(!s.ext&&!s.extensionPath&&((h=r.host)!=null&&h.endsWith(".testim.io"))&&!s.canary&&s.mode===Y.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&N.flags.removeEdgeChromeDefaultVersion.isEnabled()?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),!N.flags.removeEdgeChromeDefaultVersion.isEnabled()&&((y=r.host)!=null&&y.endsWith(".testim.io"))&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=Uv(d,s,t,n,r,f,a);break;case"firefox":d=Fv(d,s,a);break;case"safari":case"safari technology preview":d=Mv(d,g);break;default:break}dt.merge(d.desiredCapabilities,s.seleniumCapsFileContent);try{let v={"hub.lambdatest.com":"lambdatest",[N.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},S=C=>C[r.provider]||C[d.host]||C[v[d.host]],b=C=>{var k,R;return S(C)||C[(k=d.desiredCapabilities)==null?void 0:k.browserName]||C[(R=d.desiredCapabilities)==null?void 0:R.version]||C||{}},T=JSON.parse(N.flags.addCustomCapabilities.getValue()||"{}"),I=b(b(T));Object.keys(I).length&&(ns.info(`Adding custom capabilities: ${JSON.stringify(I)}`),Object.assign(d.desiredCapabilities,I))}catch(v){ns.error("Failed to load custom capabilities",{error:v,customCapabilities:N.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(Dv(d),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}function nu({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let r=[U.BROWSERSTACK,U.SAUCELABS,U.TESTIM_HEADSPIN,U.TESTIM_TDC];if(t.mode!=="local"&&!r.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function Vv({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==U.TESTIM_TDC&&e.type!==U.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function Hv(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function Zf(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===U.TESTIM_TDC?"tdc":"headspin";return{[`${i}:capture`]:!0,...N.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${i}:capture.network`]:!1},...o&&{[`${i}:controlLock`]:!0},[`${i}:retryNewSessionFailure`]:!1,[`${i}:sessionTags`]:Hv(t),[`${i}:enableBatch`]:!0,...!r&&{"appium:noReset":n}}}function di(s){return"id"in s?s.id:s.packageName}function eg({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o,isHSAppIdExists:i,isTdcAppIdExists:a}){let{fullReset:c,setNoReset:l,resetOnSessionStartOnly:m}=t,d={"appium:app":n};switch(i&&(d={"headspin:app.id":n}),a&&(d={"tdc:app.id":n}),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...c&&{"appium:fullReset":c,"appium:resetOnSessionStartOnly":m},...r&&{"appium:bundleId":di(r)},...n&&d};case"android":return{...e,platformName:"Android","appium:fullReset":!!c,"appium:autoGrantPermissions":!l,"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...r&&{"appium:appPackage":di(r),"appium:appActivity":r.activity},...n&&d};default:throw Error(`unsupported mobile project ${s}`)}}function tg({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isHSAppIdExists:i}){let a=Zf(U.TESTIM_HEADSPIN,o,n);return a=eg({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isHSAppIdExists:i}),a}function rg({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isTdcAppIdExists:i}){let a=Zf(U.TESTIM_TDC,o,n);return a=eg({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isTdcAppIdExists:i}),a}function qv({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function zv({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o,selectedGrid:i}=e;return s||(n!=null&&n.deviceName?n.deviceName:o!=null&&o.deviceNameRegex?o.deviceNameRegex:((i==null?void 0:i.type)===U.BROWSERSTACK||r===U.BROWSERSTACK)&&t==="ios"?"iPhone.*":".*")}function Kv({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,p=d===U.BROWSERSTACK?"browserstack":"saucelabs",g=qv({osVersion:c,mobileConfig:m}),f=zv({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h={...d===U.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===U.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${p}.user`]:o.user,[`${p}.key`]:o.key,[`${p}.debug`]:!0,[`${p}.networkLogs`]:!0};switch(s){case"ios":return{...h,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...e&&{bundleId:di(e)},...t&&{app:t}};case"android":return{...h,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:r,...e&&{appPackage:di(e),appActivity:e.activity},...t&&{app:t}};default:throw Error(`unsupported mobile project ${s}`)}}function sg(s){return U.TESTIM_HEADSPIN===s.gridInfo.type?tg(s):U.TESTIM_TDC===s.gridInfo.type?rg(s):Kv(s)}function ng(s){return nu(s),sg(s)}function Jv(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,c={};return n==="dynamic"&&(!o&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!i&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function og(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);nu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=pt.getGridConnection(e),c=sg(s);if(e.type===U.TESTIM_HEADSPIN||e.type===U.TESTIM_TDC){let l=e.type===U.TESTIM_HEADSPIN?"headspin":"tdc",m=Jv(r,o==null?void 0:o.mobile);if(!dt.isEmpty(m)){let d=Object.entries(m).map(([p,g])=>g.split(",").map(f=>f===".*"||f==="="?"":`${p}:${f}`).join(",")).join(" ").trim();c[`${l}:selector`]=d}}return{...a,desiredCapabilities:c,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ig(s){var v,S;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,isHSAppIdExists:c,isTdcAppIdExists:l,testRunConfig:m}=s,{deviceUdid:d}=n;nu({nativeAppMetadata:r,appPath:o,gridInfo:t}),Vv({deviceUdid:d,gridInfo:t,testRunConfig:m});let p=d||((S=(v=m.mobile)==null?void 0:v.staticAllocation)==null?void 0:S.deviceUdid),g=await pt.getGridDirectConnection(t,p),f=t.type===U.TESTIM_TDC,h={projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,...!f&&{isHSAppIdExists:c},...f&&{isTdcAppIdExists:l},testRunConfig:m},y=f?rg(h):tg(h);return p&&(y["appium:udid"]=p),{...g,desiredCapabilities:y,capabilities:y,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function ag(s){let e=Object.assign({},s);return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],delete e.capabilities.key,delete e.capabilities.user,e}var zf,tu,Kf,dt,Jf,ns,Hf,Zl,Yf,ru,eu,Dv,Uv,qf,gn=w(()=>{"use strict";zf=E(require("fs")),tu=E(require("path")),Kf=E(require("crypto")),dt=E(require("lodash"));j();le();B();Te();ce();Wo();pi();Jf=require("lodash"),ns=x("testim-desired-capabilities-builder"),Hf=qn?"debug":"silent",Zl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Yf=["--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"],ru=(...s)=>Kf.createHash("sha256").update(s.join("")).digest("hex"),eu=s=>s.type===U.DEVICE_FARM||s.type===U.HYBRID&&s.provider==="devicefarm",Dv=s=>{var r;let{desiredCapabilities:e}=s;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.prototype.hasOwnProperty.call(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=N.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ns.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Uv=dt.memoize(Nv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(dt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return ru(i,a,c,r,l,o)}),qf=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Me(s){var e,t,r,n,o,i,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/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function cg(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 ou=w(()=>{"use strict"});function iu(s){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?r(p.parentNode,e):null}function r(p,g){for(let f=p;f&&f!==p.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(p,g){for(let f=p;f&&f!==p.ownerDocument;f=t(f))if(g(f))return f;return null}function o(p,g){if(!p||!g)return null;p instanceof DocumentFragment&&(p=p.host);let h=window.getComputedStyle(p).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(p);return o(y,g)}function i(p){let g=p.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(p,"stroke-width");return!!h&&parseInt(h,10)>0}return o(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(p){return o(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(p){var g;return p?(g=p.parentNode)!=null&&g.host?!0:l(p.parentNode):!1}if(!s||!l(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,f=>f.tagName.toUpperCase()==="SELECT");return iu(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let m=!!n(s,p=>Number(o(p,"opacity"))===0),d=!!n(s,p=>o(p,"display")==="none");return!(m||d||!i(s)||c(s))}var lg=w(()=>{"use strict"});var ug,pg,tr,Yv,Xv,gi,dg=w(()=>{"use strict";ug=E(require("promise-queue")),pg=E(require("webdriverio"));le();Be();j();B();kr();lg();ou();ss();tr=x("WebDriverApi"),Yv=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},Xv={implicit:0,pageLoad:1,script:2},gi=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,o=t?t.toString().substr(0,2e3):"";throw tr.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof xa<"u"&&(e=xa);let t=1/0;this.queue=new ug.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(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),L("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{tr.info("requesting browser",{testResultId:r,testName:t}),L("before this.client.init"),this.client=await pg.remote(e),this.logGridStatus(r)}),L("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){tr.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),tr.info("grid status",{gridStatusMsg:o.message,ready:o.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},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){tr.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 i()}catch(a){if(Me(a))return this.unsupportedActions.add("execute"),o();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),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Me(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}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 o;return(o=this.client)==null?void 0:o.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(Oe(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(iu,{ELEMENT:e,[Wt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Me(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(cg(e,this.isSafari(),tr))})}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 o=[];return o[Xv[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Me(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Oe(e)),await this.elementIdValue(Oe(e),t)}async getViewportSize(e){let t=await this.execute(Yv);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 keys(e){let t=i=>wa.hasOwnProperty(i)?[wa[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Me(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.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(Oe(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(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 o;return(o=this.client)==null?void 0:o.$(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)})}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.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(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 o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Me(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,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{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){tr.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 tr.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 mg={};G(mg,{doubleClick:()=>Qv});var Qv,fg=w(()=>{"use strict";Qv=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(p){function g(S,b,T){return T>S&&T<b}let f=p.pointerPosition||{},h=r.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,v=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:v}},a=function(p,g){return{screenX:0,screenY:0,clientX:p,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(p,h)},l=function(p,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(p,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},m=function(){var g;let p=document.activeElement;for(;(g=p.shadowRoot)!=null&&g.activeElement;)p=p.shadowRoot.activeElement;return p},d=function(p){let g=i(p),f=p.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let p=m();dispatchFocus(s.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var hn={};G(hn,{dispatchFocus:()=>Zv});function Zv(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var yn=w(()=>{"use strict"});var Tg={};G(Tg,{WebDriver:()=>Rr});async function sE(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 tE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var os,yg,bg,Ue,rr,eE,gg,tE,sr,rE,hg,Sr,Rr,bn=w(()=>{"use strict";os=E(require("lodash"));j();Be();gn();yg=E(require("p-retry")),bg=E(require("ua-parser-js"));kr();B();ou();dg();z();Te();ss();Ue=x("webdriver"),[rr,eE]=[0,2],{extractElementId:gg,getCdpAddressForHost:tE}=K,sr=()=>(be(),fe(Yt)).getSessionPlayer().codeSnippets,rE=()=>(be(),fe(Yt)).getSessionPlayer().locatorBuilderUtils,hg=()=>(be(),fe(Yt)).getSessionPlayer().utils,Sr=()=>(be(),fe(Yt)).getSessionPlayer().positionUtils;Rr=class extends gi{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,r,n,o,i,a,c,l=new Bt,m=!1,d=void 0){var h,y,v,S,b,T,I,C;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let p=mi(t,r,n,o,i,a,c,d);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=m?0:1500,f=m?()=>null:()=>this.executeJS("window.focus()");try{L("before initClient in webdriver.js init");let k=await this.initClient(p,r,c);L("after initResult before getCdpAddress in init"),this.cdpUrl=await sE(k),L("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${r}`,{sessionId:this.getSessionId(),testResultId:c}),await oe(g),N.flags.dontFocusOnInit.isEnabled()||await f(),L("after focus and delay in webdriver.js init")}catch(k){let R=JSON.stringify(os.omit(p,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:k,capabilitiesAsString:R});let M=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(T=k.stack)!=null&&T.includes("at startWebDriverSession")&&((I=k.message)!=null&&I.startsWith("Failed to create session"))&&((C=k.message)!=null&&C.includes("Timeout awaiting 'request'"))&&M?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new Dr(k.message):k.message.match(/capabilit(y|ies)/)?new Kn(k.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>os.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].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,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=te();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(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=gg(r.value);return await this.switchToFrame({ELEMENT:n,[Wt]: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 Jn:r}}async getElement(t){var o;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(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||N.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
20
|
+
`))},gl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:hl,argv:bl,exit:dl,cwd:It}=global.process,ww=["trace","debug","info","warn","error","silent"];Qa(bl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));yl.description("Testim.io CLI").option("-h --help","output usage information",Em).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",yw).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("--is-regression-baseline-run","save doms and run results as regression baseline data").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",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).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("--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("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).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("--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(hl.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,ml.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,ml.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: ${gl.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").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("--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").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",Le,[]).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)",Le,[]).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)",Le,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).parse(bl);u=yl.opts(),vw=()=>{u.grid||u.gridId||(u.host||(u.host="ondemand.saucelabs.com"),u.port||(u.port=80))},Ew=()=>{u.grid||u.gridId||(u.host||(u.host="hub-cloud.browserstack.com"),u.port||(u.port=80))},Sw=async()=>{var y,v,S,b,T,I,C,k;u.inspect&&require("inspector").open(u.inspect);let s={},e={},t=[],r={};if(!bl.slice(2).length)throw Em(),new Lr;if(u.requireCredentials){let R=await Promise.resolve().then(()=>(Qr(),sn)),N=await R.getProjectId(),O=await R.getToken();(!N||!O)&&await R.doLogin()}if(u.login)return await(await Promise.resolve().then(()=>(Qr(),sn))).doLogin(),{loginMode:!0};if(u.version){let R="Testim CLI Version: ";hl.npm_package_version&&(console.log(R,hl.npm_package_version),dl(0));let N=it();N&&(console.log(R,N),dl(0)),console.log("Could not find version, please check the package.json manually"),dl(0)}if(u.installLazyDeps)return{installLazyDepsMode:!0};u.disableFileCache&&Ed();let n=u.fileCacheLocation||u.usePrefechedData||u.createPrefechedData;if(n){let R=De.resolve(n);wd(R)}if(u.usePrefechedData&&Sd(),u.playerRequirePath){let R=De.resolve(u.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let N=De.join(R,"tsconfig.node.json"),D=require("ts-node").register({project:N,ignore:[/node_modules/,new RegExp(`^${Ft.escapeRegExp(De.relative(It(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:D.config.options.paths,baseUrl:D.config.options.baseUrl}),(be(),fe(Yt)).options.playerPath=R;let H=require("module"),J=H.prototype.require;H.prototype.require=function(de){return de==="rox-alias"?J.call(this,"rox-node"):J.apply(this,arguments)}}if(u.caFile&&(global.caFileContent=fl.readFileSync(u.caFile)),u.proxy&&(global.proxyUri=u.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),u.proxyForGrid&&!u.proxy)throw new P("missing --proxy option");if(dm(u))return mm(u);try{let R={};u.configFile?R=require(De.join(It(),u.configFile)).config:u.optionsFile&&(R=require(De.join(It(),u.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(N=>{let O=hw(N);u[O]=bw(u[O],R[N])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}if(u.tunneld)return{tunnel:!0,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:u.token,project:u.project};let o=((y=u.testConfig)==null?void 0:y.length)||((v=u.testConfigId)==null?void 0:v.length),i=((S=u.testPlan)==null?void 0:S.length)||((b=u.testPlanId)==null?void 0:b.length),a=((T=u.suite)==null?void 0:T.length)||((I=u.suiteId)==null?void 0:I.length);if(u.seleniumCapsFile)try{r=require(De.join(It(),u.seleniumCapsFile))}catch(R){throw new P(`Failed to parse selenium caps file file error: ${R.message}`)}if((C=u.reporters)!=null&&C.includes("junit")&&!u.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!u.tunnel&&u.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!u.tunnel&&u.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!u.tunnel&&[u.tunnelPort,u.tunnelHostHeader,u.tunnelRegion,u.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(u.chromeExtraPrefs)try{e=require(De.join(It(),u.chromeExtraPrefs))}catch(R){throw new P(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(u.chromeExtraArgs){let R=u.chromeExtraArgs.split(",");for(let N of R){let[O]=N.split("=");bm.includes(O)||u.useLocalChromeDriver||u.useChromeLauncher?(t.push(N),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(bm)}`)}}if(u.paramsFile)try{s=Object.assign({},s,require(De.join(It(),u.paramsFile)))}catch(R){throw new P(`Failed to read/open params file error: ${R.message}`)}if(u.params)try{s=Object.assign({},s,JSON.parse(u.params))}catch(R){throw new P(`Failed to parse params string error: ${R.message}`)}if(u.sauceUser&&!u.sauceKey||!u.sauceUser&&u.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(u.sauceUser&&u.sauceKey&&(vw(),u.saucelabs={},u.saucelabs.username=u.sauceUser,u.saucelabs.accessKey=u.sauceKey),u.sauceOptions)try{let R=require(De.join(It(),u.sauceOptions)),N=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let D=R.browserName.toLowerCase();switch(D){case"microsoftedge":u.browser="edge";break;default:u.browser=D}}u.browser==="edge"&&parseFloat(R.version)>=va&&(u.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!N&&u.browser==="chrome"&&O)throw new P("The minimum chrome supported version is 50.0");u.saucelabs=Object.assign({},u.saucelabs,R)}catch(R){throw new P(`Failed to parse saucelabs options file error: ${R.message}`)}if(u.browserstackUser&&!u.browserstackKey||!u.browserstackUser&&u.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(u.browserstackUser&&u.browserstackKey&&(Ew(),u.browserstack={},u.browserstack["browserstack.user"]=u.browserstackUser,u.browserstack["browserstack.key"]=u.browserstackKey),u.browserstackOptions)try{let R=require(De.join(It(),u.browserstackOptions)),N=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(u.browser=R.browserName.toLowerCase()),u.browser==="edge"&&parseFloat(R.browser_version)>=va&&(u.browser="edge-chromium"),!N&&parseFloat(R.browser_version)<50&&u.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");u.browserstack=Object.assign({},u.browserstack,R)}catch(R){throw new P(`Failed to parse browserstack options file error: ${R.message}`)}if(u.perfecto={},u.perfectoToken&&(u.perfecto.securityToken=u.perfectoToken),u.perfectoOptions)try{let R=require(De.join(It(),u.perfectoOptions)),N={location:"US East",securityToken:u.perfectoToken};u.perfecto=Object.assign({},N,R)}catch(R){throw new P(`Failed to parse perfecto options file error: ${R.message}`)}if(u.testobjectSauce={},u.testobjectKey&&(u.testobjectSauce.testobjectApiKey=u.testobjectKey),u.testobjectOptions)try{let R=require(De.join(It(),u.testobjectOptions)),N={testobjectApiKey:u.testobjectKey};u.testobjectSauce=Object.assign({},N,R)}catch(R){throw new P(`Failed to parse test object options file error: ${R.message}`)}if(!u.project){let N=await(await Promise.resolve().then(()=>(Qr(),sn))).getProjectId();if(N)u.project=N;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}u.testConfig&&(u.testConfig=[u.testConfig].flat()),u.testConfigId&&(u.testConfigId=[u.testConfigId].flat()),u.mode??="extension",u.retries=!u.retries||typeof u.retries=="boolean"?1:Number(u.retries)+1,u.browserTimeout=!u.browserTimeout||typeof u.browserTimeout=="boolean"?60*1e3:u.browserTimeout,u.newBrowserWaitTimeout=!u.newBrowserWaitTimeout||typeof u.newBrowserWaitTimeout=="boolean"?10*60*1e3:u.newBrowserWaitTimeout*60*1e3,u.getBrowserTimeout||(u.getBrowserTimeout=u.browserTimeout),u.getBrowserRetries||(u.getBrowserRetries=u.mode===Y.APPIUM?1:Math.round(u.newBrowserWaitTimeout/u.browserTimeout)),u.getSessionTimeout=u.browserTimeout<u.getSessionTimeout?u.getSessionTimeout:u.browserTimeout,u.driverRequestTimeout=u.browserTimeout<u.driverRequestTimeout?u.driverRequestTimeout:u.browserTimeout;let c=Boolean(u.timeout);if(u.timeout=!u.timeout||typeof u.timeout=="boolean"?10*60*1e3:u.timeout,u.beforeParallel=!u.beforeParallel||typeof u.beforeParallel=="boolean"?1:Number(u.beforeParallel),u.parallel=!u.parallel||typeof u.parallel=="boolean"?1:Number(u.parallel),u.afterParallel=!u.afterParallel||typeof u.afterParallel=="boolean"?1:Number(u.afterParallel),u.tunnelPort=!u.tunnelPort||typeof u.tunnelPort=="boolean"?"80":u.tunnelPort,u.port&&=Number(u.port),!u.token){let N=await(await Promise.resolve().then(()=>(Qr(),sn))).getToken();if(N)u.token=N;else throw new P("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 l=R=>R<=0||!Number.isInteger(R);if(l(u.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(u.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(u.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(u.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(u.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(u.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(u.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(u.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(u.mode))throw new P(`runner mode <${u.mode}> is not supported`);if(u.mode!==Y.SELENIUM&&u.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!u.browser&&!o&&!i&&(u.browser="chrome"),u.appiumLogLevel||(u.appiumLogLevel="silent"),!ww.includes(u.appiumLogLevel))throw new P(`runner appium-log-level <${u.appiumLogLevel}> is not supported`);if(u.testPlan&&u.testPlan.length===0&&u.testPlanId&&u.testPlanId.length===0){if(typeof u.host!="string"&&typeof u.grid!="string"&&typeof u.gridId!="string"&&!u.localTmaUrl&&!u.useLocalChromeDriver&&!u.useChromeLauncher&&!u.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(u.testId.length||u.label.length||u.name.length||o||u.browser||a||u.localTmaUrl||u.useLocalChromeDriver||u.useChromeLauncher)throw new P("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(!i&&(u.beforeParallel!==1||u.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([u.host,u.grid,u.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((k=u.host)!=null&&k.includes("/")&&(/^(f|ht)tps?:\/\//i.test(u.host)||(u.host=`http://${u.host}`),u.host=wm.parse(u.host).hostname),u.resultLabel.length){u.resultLabel=u.resultLabel.map(N=>N.trim()).filter(Boolean);let R=u.resultLabel.filter(N=>N.length>=250).filter(Boolean);if(u.branch==="auto-detect"&&u.resultLabel.includes("auto-detect-branch")&&mr()&&u.resultLabel.unshift(mr()),R.length)throw new P("A result label cannot exceed 250 characters")}let d=im(u),p=Oo(u);if(!u.w3cCapabilities&&!u.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(u.protocol||=u.port===443?"https":"http",!["http","https"].includes(u.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(u.rerunFailedByRunId&&u.branch)throw new P("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(u.rerunFailedByRunId&&(a||u.name.length||u.testId.length||u.label.length||i))throw new P("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(u.setRetention&&!Ft.inRange(Ft.parseInt(u.setRetention),1,11))throw new P("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)");u.setRetention&&=Number(u.setRetention);let g="is no longer supported, please use --override-mapping-file";if(u.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(u.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(u.disableMockNetwork&&u.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!u.collectCodeCoverage&&u.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!u.collectCodeCoverage&&u.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(u.collectCodeCoverage&&u.codeCoverageReporter&&Ft.difference(u.codeCoverageReporter,gl).length){let R=Ft.difference(u.codeCoverageReporter,gl);throw new P(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}u.codeCoverageReporter=u.codeCoverageReporter.length===0?["html","text"]:u.codeCoverageReporter,u.codeCoverageInclude=u.codeCoverageInclude.length===0?["src/**"]:u.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"},h=Object.keys(f).filter(R=>Boolean(u[R]));if(u.mode!==Y.EXTENSION&&h.length){let R=h.length>1?"are":"is";throw new P(`${h.map(N=>f[N]).join(" and ")} ${R} only applicable in extension mode`)}if(u.tmsFieldFile)try{let R=fl.readFileSync(u.tmsFieldFile);u.tmsCustomFields=JSON.parse(R)}catch(R){throw new P(`failed to parse field file error: ${R.message}`)}if(u.highSpeed&&(Tw("--high-speed","--turbo-mode"),u.turboMode=!0),u.skipLoadBalancer&&!u.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(u.deviceUdid&&(u.deviceName||u.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(u.setNoReset&&u.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(u.resetOnSessionStartOnly&&!u.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),u.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"},N=typeof u.lightweightMode=="string"?JSON.parse(u.lightweightMode):{};u.lightweightMode=Object.assign({},R,N)}catch(R){throw new P(`failed to parse lightweightMode settings error: ${R.message}`)}else u.turboMode&&u.mode===Y.EXTENSION&&(u.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"});if(typeof u.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[u.testId].flat(),name:[u.name].flat(),label:[u.label].flat(),suites:[u.suite].flat(),suiteIds:[u.suiteId].flat(),testPlan:[u.testPlan].flat(),testPlanIds:[u.testPlanId].flat(),webpackConfig:u.webpackConfig,reportFile:u.reportFile,urls:u.urls,reportFileClassname:u.overrideReportFileClassname,reporters:u.reporters,project:u.project,host:u.host,headless:u.headless,localTmaUrl:u.localTmaUrl,useLocalChromeDriver:u.useLocalChromeDriver,chromeBinaryLocation:u.chromeBinaryLocation,useChromeLauncher:u.useChromeLauncher,port:u.port,grid:u.grid,gridId:u.gridId,disableNativeEvents:u.disableNativeEvents,saucelabs:u.saucelabs,browserstack:u.browserstack,baseUrl:u.baseUrl,branch:(u.branch==="auto-detect"?mr():u.branch)||"master",autoDetect:u.branch==="auto-detect",token:u.token,userParamsData:s,mode:u.mode,isRegressionBaselineRun:u.isRegressionBaselineRun,browser:u.browser,beforeParallel:u.beforeParallel,parallel:u.parallel,afterParallel:u.afterParallel,canary:u.canary,rerunFailedByRunId:u.rerunFailedByRunId,disableGridCheck:u.disableGridCheck,disableTimeoutRetry:u.disableTimeoutRetry,resultLabels:u.resultLabel,path:u.path,protocol:u.protocol,perfecto:u.perfecto,experitestToken:u.experitestToken,testobjectSauce:u.testobjectSauce,gridUsername:u.gridUsername,gridPassword:u.gridPassword,overrideExecutionName:u.overrideExecutionName,tmsSuppressReporting:Boolean(u.suppressTmsReporting)||Boolean(u.tmsSuppressReporting),tmsRunId:u.tmsRunId,tmsCustomFields:u.tmsCustomFields,proxyForGrid:u.proxyForGrid,retentionDays:u.setRetention,passZeroTests:Boolean(u.passZeroTests),runQuarantinedTests:Boolean(u.runQuarantinedTests),deviceName:u.deviceName,deviceUdid:u.deviceUdid,customTag:u.customTag,osVersion:u.osVersion,skipLoadBalancer:u.skipLoadBalancer,lockDevice:u.lockDevice,appId:u.appId,appiumLogLevel:u.appiumLogLevel,setNoReset:u.setNoReset,fullReset:u.fullReset,resetOnSessionStartOnly:u.resetOnSessionStartOnly,ext:u.ext,extensionLocation:[u.extensionPath||d].flat(),extensionPath:u.extensionPath,playerLocation:u.playerPath||p,playerPath:u.playerPath,playerRequirePath:u.playerRequirePath,tunnel:u.tunnel,tunnelPort:u.tunnelPort,tunnelRoutes:u.tunnelRoutes,tunnelRoutesOutput:u.tunnelRoutesOutput,tunnelHostHeader:u.tunnelHostHeader,tunnelRegion:u.tunnelRegion,tunnelDiagnostics:u.tunnelDiagnostics,tunnelUseHttpAddress:u.tunnelUseHttpAddress,externalLambdatestTunnelId:u.externalLambdatestTunnelId,externalLambdatestUseWss:u.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(u.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(u.externalLambdatestMitm),beforeTest:u.beforeTest,afterTest:u.afterTest,beforeSuite:u.beforeSuite,afterSuite:u.afterSuite,timeout:u.timeout,timeoutWasGiven:c,browserTimeout:u.browserTimeout,newBrowserWaitTimeout:u.newBrowserWaitTimeout,getBrowserTimeout:u.getBrowserTimeout,getBrowserRetries:u.getBrowserRetries,getSessionTimeout:u.getSessionTimeout,getSessionRetries:u.getSessionRetries,driverRequestTimeout:u.driverRequestTimeout,driverRequestRetries:u.driverRequestRetries,testStartTimeout:u.testStartTimeout,testConfigNames:u.testConfig,testConfigIds:u.testConfigId,overrideMappingFile:u.overrideMappingFile,disableMockNetwork:u.disableMockNetwork,codeCoverageUrlFilter:u.codeCoverageUrlFilter,collectCodeCoverage:u.collectCodeCoverage,codeCoverageReportPath:u.codeCoverageReportPath,codeCoverageSourceMapPath:u.codeCoverageSourceMapPath,codeCoverageReporter:u.codeCoverageReporter,codeCoverageInclude:u.codeCoverageInclude,executionId:u.executionId,remoteRunId:u.remoteRunId,schedulerId:u.schedulerId,source:u.source,resultId:u.resultId,installCustomExtension:u.installCustomExtension,w3cCapabilities:u.w3cCapabilities,oldCapabilities:u.oldCapabilities,chromeBlockLocation:u.chromeBlockLocation,chromeUserDataDir:u.chromeUserDataDir,retries:u.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:u.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:u.monitorPerformance,user:u.user,lightweightMode:u.lightweightMode,createPrefechedData:u.createPrefechedData,saveRCALocally:u.saveRcaLocally,exitCodeIgnoreFailingTests:u.exitCodeIgnoreFailingTests,disableSockets:u.disableSockets,intersections:{labels:u.intersectWithLabel.length?[u.intersectWithLabel].flat():void 0,suiteNames:u.intersectWithSuite.length?[u.intersectWithSuite].flat():void 0,suiteIds:u.intersectWithSuiteId.length?[u.intersectWithSuiteId].flat():void 0},downloadBrowser:u.downloadBrowser}}});var Pm={};G(Pm,{installAllLazyDependencies:()=>xw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=ac(s);if(t)return t;let r;e.silent||(r=(0,Im.default)(`Installing ${s} before first usage...`).start());try{let n=await Iw(s);return r&&r.succeed(),n}catch(n){Rw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Am(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`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 ${c}${i}`;throw r&&r.fail(l),n}}async function Iw(s){return Zr.has(s)||(Zr.set(s,xm(s)),Zr.get(s).catch(()=>{Zr.delete(s)})),Zr.get(s)}async function xm(s){let e=ac(s);if(e)return e;let t=Am(s),r=`${s}@${t}`;return await go(at(),r),zt(s)}async function xw(){let s=Object.keys(Ia);for(let e of s)await xm(e)}function Am(s){let e=Object.entries(Ia).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Im,Rw,Zr,wr=w(()=>{"use strict";Im=E(require("ora"));Vs();B();j();Gn();Gs();Rw=x("lazy-require"),Zr=new Map});var km={};G(km,{preloadTests:()=>nn});async function nn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ct(async()=>{let t=await ie(s.testId,r=>Rc({...e,testId:r}),{concurrency:2});return Cm.keyBy(t,"testData.id")},"loadTests",Aw,[e,s.testId])()}var Cm,Aw,No=w(()=>{"use strict";Cm=E(require("lodash"));qt();ye();j();Aw=1e3*60*60*10});function Tl(){return it()}async function Lm(){if(!Ce)try{let s=await ae(Cw(),5e3,"The API call to NPM timed out"),e=Tl();e&&_m.lt(e,s)&&console.log(Om.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){Pw.warn("Failed to get NPM version",{err:s})}}var Om,_m,Pw,Cw,wl=w(()=>{"use strict";Om=E(require("chalk")),_m=E(require("semver"));j();le();Vs();qt();B();Pw=x("npm-driver"),Cw=ct(()=>Ad("@testim/testim-cli"),"getNpmVersion")});var vl,Ow,es,Dm,Mm,El,Nm,Um=w(()=>{"use strict";j();z();B();wr();vl=x("testimNgrok"),Ow=".whitelisted-ngrok.testim.io",es="",Mm=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${s.projectData.projectId}${Ow}`);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 o=await(await Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(vl.info("replace https to http"),es=o.replace("https://","http://")):es=o,s.tunnelDiagnostics&&El(),s.baseUrl=es},El=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===es);console.log("ngrok stats",n),vl.info("ngrok stats",{tunnel:n})}catch(e){vl.error("error collecting ngrok stats",{err:e})}s&&(Dm=setTimeout(()=>El(),1e4))},Nm=async s=>{if(!es)return;clearTimeout(Dm),s.tunnelDiagnostics&&await El(!1),await(await Ee("ngrok")).disconnect(es)}});var Xt,Rl,Fm,Lw,Dw,Sl,Uo,Bo,Fo,Mw,Bm,jm,$m=w(()=>{"use strict";Xt=E(require("os")),Rl=E(require("fs")),Fm=E(require("child_process"));j();ye();Lw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Dw={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"}},Sl=Xt.tmpdir(),Uo=`${Sl}/cloudflared`,Bo=null,Fo=null,Mw=async()=>{if(await ge(Uo))return;let e=Dw[Xt.platform()+Xt.arch()];if(!e)throw new Error(`tunnel on ${Xt.platform()+Xt.arch()} platform is not supported.`);let t=e.extract?Sl+e.path:Uo;await He(`${Lw}/${e.path}`,t),e.extract&&await Ze(t,Sl),await Rl.promises.chmod(Uo,"755")},Bm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([zc(s.company.companyId,t),Mw()]);Bo=r._id,Fo=Fm.spawn(Uo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Kc(s.company.companyId,Bo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Rl.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},jm=async s=>{let e=[];return Bo&&e.push(Jc(s.company.companyId,Bo)),Fo&&e.push(new Promise((t,r)=>{Fo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Fo.kill()})),await Promise.all(e)}});var V,Gm,Uw,Fw,Bw,Wm,jo,Il,M,Te=w(()=>{"use strict";V=E(require("rox-node"));B();j();le();Gm=x("FeatureFlagsService"),Uw=!Ce&&!0&&!Ap,Fw=2e4,Bw=60*60*24,Wm=["labs","disabled","enabled"],jo=class extends V.default.Variant{constructor(e="disabled"){super(e,Wm)}getValue(){let e=super.getValue();return Wm.includes(e)?e:(Gm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Il=class{constructor(){this.flags={useNewWSCLI:new V.default.Flag,useSafariWebdriverVisibilityChecks:new V.default.Flag,useClickimVisibilityChecks:new V.default.Flag,runGetElementCodeInAut:new V.default.Flag,enableFrameSwitchOptimization:new V.default.Flag,maximumJsResultSize:new V.default.Configuration(2e3*1024),skipFileInputClicks:new V.default.Flag,errorMessageOnBadNetwork:new V.default.Flag(!0),warnOnBadNetwork:new V.default.Flag(!1),overrideAzureStorageUrl:new V.default.Flag,useJsInputCodeInSafari:new V.default.Flag,useJsInputCodeInFirefox:new V.default.Flag,useJsInputCodeInEdgeChromium:new V.default.Flag,autoSaveDownloadFileFireFox:new V.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new V.default.Flag(!0),experimentalPreCodeCompilation:new V.default.Flag(!0),experimentalAsyncCustomCode:new V.default.Flag,useSameBrowserForMultiTests:new jo("labs"),highSpeedMode:new jo,usePortedHtml5DragDrop:new V.default.Flag,testNamesToBeforeSuiteHook:new V.default.Flag,addCustomCapabilities:new V.default.Variant("{}"),LTNetworkCapabilities:new V.default.Flag,downloadToBase64:new V.default.Flag,publicGridURL:new V.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new V.default.Flag(!0),unsupportedCapsFields:new V.default.Variant("[]"),useLinkedomToParseHtml:new V.default.Flag,dontFocusOnInit:new V.default.Flag,retryOnSeleniumHubError:new V.default.Flag,removeEdgeChromeDefaultVersion:new V.default.Flag,enableLambdaTestTunnelNTLM:new V.default.Flag,enableLambdaTestTunnelSkipUpgrade:new V.default.Flag,tdcHsPreventNetworkCapture:new V.default.Flag,headSpinTdcEnableFlagCapability:new V.default.Flag},V.default.register("default",this.flags)}setProjectId(e){V.default.setCustomStringProperty("projectId",e)}setProjectType(e){V.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){V.default.setCustomStringProperty("productType",e)}setCompanyId(e){V.default.setCustomStringProperty("companyId",e)}setPlanType(e){V.default.setCustomStringProperty("planType",e)}setIsPOC(e){V.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){V.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){V.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Uw)return;let e={fetchIntervalInSec:Bw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ae(V.default.setup(Ip,e),Fw).catch(t=>Gm.error("failed to get feature flag status",t))}},M=new Il});var Hm,qm,Qt,zm,Km,Vm,jw,$w,$o,Ww,Gw,ne,Wo=w(()=>{"use strict";Hm=E(require("ms")),qm=E(require("p-retry")),Qt=E(require("os")),zm=E(require("portfinder")),Km=E(require("child_process"));j();Ve();ye();z();B();_o();ce();Te();Vm=x("lambdatestService"),jw="https://downloads.lambdatest.com/tunnel/v3",$w={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"},$o=`${Qt.tmpdir()}/LT`,Ww=`${$o}/LT`,Gw=(0,Hm.default)("15m"),ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===U.LAMBDATEST||e.type===U.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Bc(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?Gw:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Ww))return;let t=$w[Qt.platform()+Qt.arch()];if(!t)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let r=`${$o}.zip`;await He(`${jw}/${t}`,r),await Ze(r,$o)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await zm.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o}=e,i=global.proxyUri;ne.tunnelName=te();let a=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled()&&(a=[...a,"--ntlm"]),M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(a=[...a,"--skip-upgrade"]),e.externalLambdatestUseWss&&(a=[...a,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(a=[...a,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)a=[...a,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)a=[...a,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(i)try{let m=new URL(i);a=[...a,"--proxy-host",m.hostname],m.port&&(a=[...a,"--proxy-port",m.port]),m.username&&m.password&&(a=[...a,"--proxy-user",m.username,"--proxy-pass",m.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(a=[...a,"--mitm"]),ne.tunnel=Km.spawn("./LT",a,{cwd:$o});let c="",l="";ne.tunnel.stdout.on("data",m=>{c+=m.toString()}),ne.tunnel.stderr.on("data",m=>{l+=m.toString()});try{let m=await(0,qm.default)(()=>Ne(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});Vm.info("LT tunnel info",m)}catch(m){throw Vm.error("Failed to start LT tunnel",{err:m,stdoutResult:c,stderrResult:l}),m}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=ne.lambdatestConfig.CAPABILITIES[t]||{},a={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},c=[],{mode:l,canary:m,ext:d,extensionPath:p,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!d){let f=il({canary:m},!0);!p&&f[t]&&(c=[...c,f[t]]),p&&je(p)&&(c=[...c,p])}return g&&je(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:ne.lambdatestConfig.PLATFORM,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,resolution:ne.lambdatestConfig.RESOLUTION,timezone:ne.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var xl={};G(xl,{connect:()=>Vo,disconnect:()=>Ho,serveTunneling:()=>Hw});var Go,Jm,Ym,Vw,Vo,Ho,Hw,Al=w(()=>{"use strict";Um();en();$m();Rt();Go=E(require("ora"));B();ce();Wo();Jm=x("tunnel"),Ym=s=>{var e;return[U.LAMBDATEST,U.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Vw=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===U.HYBRID&&s.gridData.tunnel==="cloudflare"},Vo=async s=>{if(!s.tunnel)return;let e=Mt(),t;try{Ym(s)?(t=(0,Go.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):Vw(s)?(t=(0,Go.default)("Starting testim cloudflare tunnel...").start(),await Bm(s)):(t=(0,Go.default)("Starting testim ngrok tunnel...").start(),await Mm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Jm.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Ho=async s=>{if(s.tunnel)try{Ym(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await jm(s):await Nm(s)}catch(e){let t="catch error - failed to close tunnel";throw Jm.error(t,{err:e}),new Error(t)}},Hw=async(s,e=new Promise(()=>{}))=>(await Vo(s),Yr(()=>Ho(s)),await e)});function qw(s){if(s.protocol)return s.protocol;if([U.TESTIM,U.BROWSERSTACK,U.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([U.TESTIM_ENTERPRISE,U.LAMBDATEST,U.DEVICE_FARM].includes(s.type)){let e=Xm.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zw(s){let e=Xm.exec(s);return e==null?void 0:e[3]}function zo(s){var y,v,S,b,T,I,C,k,R;let e=s&&zw(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&qw(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(v=s==null?void 0:s.external)==null?void 0:v.user,l=(S=s==null?void 0:s.external)==null?void 0:S.key,m=s==null?void 0:s.type,d=m===U.HYBRID?a&&((I=(T=(b=s.hybrid)==null?void 0:b.external)==null?void 0:T[s.hybrid.tunnel])==null?void 0:I.user):c,p=m===U.HYBRID?a&&((R=(k=(C=s.hybrid)==null?void 0:C.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:R.key):l,g=s==null?void 0:s.name,f=s&&(s._id||s.gridId),h=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:m,name:g,provider:h,tunnelUser:d,tunnelKey:p}}async function Zm(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Je.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(jr.UNKNOWN)}if(Je.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Je.error("invalid response - get grid",{res:o}),new Error(jr.UNKNOWN);if(o.status==="success"){let i=zo(o.grid);return Kw(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new Tt(jr.NOT_FOUND):o.code==="no-available-slot"?new Mr(`Failed to run test on ${r} - concurrency limit reached`):(Je.error("invalid code error response - get grid",{res:o}),new Tt(jr.UNKNOWN))}function Jw(s,e,t,r,n,o){return Zm(t,e,s,n,()=>Io(e,t,r,n,o))}function Yw(s,e,t,r,n,o,i){return Zm(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(m=>(m.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Io(e,t,c._id,n,o):Nc(e,t,r,n,o)})}function ef(s){return Fc(s)}async function tf(s,e,t){let n=(t||await ef(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return zo(n)}async function Xw(s,e,t){let n=(t||await ef(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return zo(n)}async function Pl(s,e){let t=on[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete on[s],!r){Je.warn("failed to find grid slot id",{projectId:e});return}Je.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Dc(i,e,r,n,o)}catch(a){Je.error("failed to release slot",{projectId:e,err:a})}}async function Qw(s){let e=Object.values(on).filter(Boolean);if(e.length!==0){Je.info("keep alive worker slots",{projectId:s,slots:e});try{await Lc(s,e)}catch(t){Je.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zw(s){Qm=global.setInterval(Qw,1e4,s)}async function ev(s){let e=Object.keys(on);if(e.length){Je.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>Pl(Number(t),s))}catch(t){Je.error("failed to release all slots",{err:t,projectId:s})}}}async function tv(s){await ev(s),clearInterval(Qm)}function rv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function rf(s){let t=(()=>qo.isEmpty(s.testobjectSauce)?qo.isEmpty(s.saucelabs)?qo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=rv(t,s),c=sv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function sf(s,e){let t=s.company.companyId;return await tf(t,e.gridId,s.allGrids)}async function nf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return rf(s);let l=t==null?void 0:t.companyId;if(a)return tf(l,a,e);if(c)return Xw(l,c,e);if(Us(s)||s.tunnelOnlyMode){Je.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new Tt("Missing host or grid configuration")}async function of(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:m,company:d}=t,p=d==null?void 0:d.companyId;if(l||m||c)return{mode:"local"};if(n)return rf(t);if(a)return Jw(r,p,o,a,s,e);if(i)return Yw(r,p,o,i,s,e,t);throw new Tt("Missing host or grid configuration")}var qo,Je,on,Xm,Qm,Kw,an,af,ts=w(()=>{"use strict";qo=E(require("lodash"));ye();B();j();ce();z();Je=x("grid-service"),on={},Xm=/(^(https?):\/{2})?(.*)/,Qm=null;Kw=(s,e,t,r,n)=>{on[s]={gridId:t,companyId:e,slotId:r,browser:n}};an={start:Zw,end:tv};af=async(s={},e={},t={},r={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:m,currentRetry:d}=n;if(!i||!a||(a===U.LAMBDATEST&&await((f=r.enableIfNeeded)==null?void 0:f.call(r,e)),a!==U.HYBRID||!o||!c||!m||!d))return e;let p=await Mc({companyId:o,gridId:i,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Je.info("handling hybrid grid",{response:p,companyId:o});let g=zo({...e,...p.connectionDetails,provider:p.provider});return p.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),p.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});function ln(){return Ko||"master"}function cf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Ko="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){Ko=s.branch||s;return}Ko=e?"master":void 0}var Ko,Cl=w(()=>{"use strict";z()});var un,kl,nv,Ol,ov,Jo,Yo,Xo,Qo,Zo,ei=w(()=>{"use strict";j();ce();un=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},kl=s=>{let{status:e}=s;return e===pe.ABORTED},nv=s=>{let{status:e}=s;return e===pe.PASSED},Ol=s=>s.runnerStatus===za.SKIPPED,ov=s=>s.testStatus===qe.EVALUATING,Jo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(ze(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Yo=s=>Object.values(s).filter(e=>un(e)&&ov(e)).length,Xo=s=>Object.values(s).filter(un),Qo=s=>Object.values(s).filter(nv),Zo=s=>Object.values(s).filter(kl)});function av(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var _l,ti,iv,ri,uf=w(()=>{"use strict";_l=E(require("lodash"));B();ei();ti=x("debug-reporter"),iv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ri=class{constructor(e){this.options=e}onTestStarted(e,t){ti.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,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;ti.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:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{..._l.default.omit(this.options,iv),company:_l.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=av(process.argv);ti.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=Qo(e).length,a=Object.keys(e).length-i;ti.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ll,xt,pn=w(()=>{"use strict";ce();Ll=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===U.DEVICE_FARM}},xt=new Ll});var Ml={};G(Ml,{Reporter:()=>cv});var Zt,dn,vr,si,pf,Dl,cv,Nl=w(()=>{"use strict";Zt=E(require("chalk")),dn=E(require("lodash"));j();ce();pn();ei();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:si}=Lt,pf="device",Dl=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: ${Zt.default.underline(ot(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?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${to(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ot(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
|
|
21
|
+
\r`)))}onTestPlanFinished(e,t,r,n,o){let i=Xo(e),a=Qo(e),c=Zo(e),l=a.length,m=c.length,d=i.length,p="",g="";if(xt.isTestStatusEnabled){let S=Yo(e);p=` FAILED-EVALUATING: ${S}`,d-=S,g=` SKIPPED: ${Jo(e,this.options)}`}let f=this.buildTestPlanName(o,t),h,y=vr[d?"error":"success"],v=`PASSED: ${l} FAILED: ${d}${p} ABORTED: ${m}${g} Duration: ${to(r)}`;f.trim()===""||f.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${f} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=dn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=dn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=dn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=dn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=p=>{p.forEach((g,f)=>{var v;let h=(v=g.testData)!=null&&v.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${ze(g,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${d} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===si.APPIUM?pf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===si.APPIUM?pf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.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,o=this.options.mode===si.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===si.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},cv=Dl});var Bl={};G(Bl,{Reporter:()=>fv});function lv(s){let e=s.testData||{},t=typeof e.total=="number"?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function uv(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 pv(s){return`${s.visitedUrlsJson||""}`}async function dv(s,e,t,r,n,o){function i(p){let g=ot(s,t,p.testId,p.resultId,r),f={$:{name:lv(p),classname:n,time:Za(p.duration),ownedBy:p.testOwnerName,ownerEmail:p.testOwnerEmail},"system-out":g};if(un(p)||kl(p)){let h=`Step Failed: ${p.failureReason||p.reason}`,y=un(p)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Ol(p)&&ze(p,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=uv(p),f["visited-urls-json"]=pv(p)),f}function a(p){let{results:g,testPlanName:f,configName:h}=p,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:m(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=Jo(y,o);let b=Yo(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(p){let g=Object.keys(p).map(h=>p[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(p){return Object.keys(p).length}function m(p){return Xo(p).length+Zo(p).length}let d={testsuites:{testsuite:e.map(p=>a(p))}};try{return new Fl.Builder().buildObject(d)}catch(p){return mv(p)}}function mv(s){let e=new Fl.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 Fl,df,Ul,fv,jl=w(()=>{"use strict";Fl=E(require("xml2js"));j();df=require("fs");pn();ei();Ul=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 dv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await df.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};fv=Ul});var mf={};G(mf,{Reporter:()=>gv});function rs(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 $l,Wl,gv,ff=w(()=>{"use strict";B();$l=x("team-city-reporter");Wl=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 rs(n)}onTestStarted(e,t,r,n){if(r){$l.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){$l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${rs(t)}' details='${rs(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){$l.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='${rs(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${rs(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${rs(t)}']`)}},gv=Wl});var gf={};G(gf,{Reporter:()=>hv});var Gl,hv,hf=w(()=>{"use strict";Gl=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,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},hv=Gl});var yf={};G(yf,{Reporter:()=>yv});var Vl,yv,bf=w(()=>{"use strict";j();al();Vl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ot(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Do(t)}},yv=Vl});var mx,Hl,X,At=w(()=>{"use strict";uf();B();mx=x("reporter"),Hl=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 ri(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Nl(),Ml));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(jl(),Bl));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(ff(),mf)),r.includes("console")&&Promise.resolve().then(()=>(Nl(),Ml)),r.includes("junit")&&Promise.resolve().then(()=>(jl(),Bl)),r.includes("json")&&Promise.resolve().then(()=>(hf(),gf)),r.includes("chrome")&&Promise.resolve().then(()=>(bf(),yf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},X=new Hl});function wf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function vf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:p,projectType:g,appSource:f,gridType:h}){let y=wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Tf(l,m),isStartUp:p,projectType:g,gridType:h,...["android","ios"].includes(g)&&f&&{appSource:f}},d);lt("test-run-ci",y)}function Ef({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:p,logger:g,isStartUp:f,projectType:h,appSource:y,gridType:v}){try{let S=wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Tf(m,d),isStartUp:f,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},p);if(n.success){lt("test-run-ci-success",S);return}lt("test-run-ci-fail",Object.assign({},S,{failureReason:n.failureReason}))}catch(S){g.error("failed to update test end analytics",{err:S})}}function Sf(s){lt("batch-run-ci",s)}var Tf,ql=w(()=>{"use strict";Xr();Eo();Tf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Kr&&e?"ci-with-user":Kr?"ci":e?"cli-with-user":s});var If,ni,xf=w(()=>{"use strict";If=require("istanbul-lib-report"),ni=class extends If.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 Af,Pf,Cf,mn,ut,kf,oi,zl,Of,bv,_f,Lf,Tv,wv,Df,vv,Ev,Sv,Rv,Iv,Mf,Nf=w(()=>{"use strict";Af=E(require("ora")),Pf=E(require("dayjs")),Cf=E(require("test-exclude")),mn=E(require("fs")),ut=E(require("path")),kf=E(require("istanbul-reports")),oi=E(require("istanbul-lib-report"));ye();z();j();B();wr();xf();zl=x("test-run-status"),Of=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},bv=s=>!!Of(s).search,_f=s=>s?Of(s).pathname.substring(1):"",Lf=(s,e)=>{let t=_f(e);return!new Cf.default({relativePath:!1,include:s}).shouldInstrument(t)},Tv=s=>s.substring(0,s.indexOf("?")),wv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Df=(s,e)=>`${ut.resolve(s,_f(e))}.js`,vv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ie(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ie(o.sources,async(i,a)=>{if(Lf(r,i))return;let c=Df(e,i);await mn.promises.mkdir(ut.parse(c).dir,{recursive:!0}),await mn.promises.writeFile(c,o.sourcesContent[a])})})},Ev={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(bv(e)&&(e=Tv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=ut.dirname(this.getPath(s));return ut.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Sv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=oi.createContext({dir:t,coverageMap:e,watermarks:oi.getDefaultWatermarks(),sourceFinder:a=>{try{let c=Df(r,a);return mn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ni({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Ev}),kf.create(a,c).execute(i)}),o},Rv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Lf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Iv=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await $c(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Xs(c,9e4);await ie(l,async m=>{if(!o.has(m.url)){let d=m.text;m.sourceUrl&&(o.set(m.url,"TEMP"),d=await Ec(m.sourceUrl)),o.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Mf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;zl.info("start js coverage process");let n=(0,Af.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=ut.resolve(s.codeCoverageReportPath||"./coverage"),i=ut.resolve(o,`.js/${(0,Pf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?ut.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([Ee("istanbul-lib-coverage"),Iv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}zl.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),p={};await ie(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:v}=m.get(f),S=await wv({sourceMapType:v,source:y,sourceMapDir:a});p[f]=S;let b=await Rv(s,{source:y,sourceMap:S,functions:h});d.merge(b)}),await vv(s,i,p);let g=await Sv(s,d,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof P?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),zl.error(l,{err:c})}}});var Uf={};G(Uf,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Bt});var xe,xv,Bt,ss=w(()=>{"use strict";j();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},xv=["ALL",...Object.values(xe)],Bt=class{constructor(){this.marks=Object.fromEntries(xv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=te();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`,no(r,50)],[`${t}_P95`,no(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var $f={};G($f,{initServer:()=>Cv,mapFilesToLocalDrive:()=>Jl});function Jl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ii[t.id]?{screenshot:ii[t.id]}:{})),Object.keys(ai).forEach(t=>{s.assets||={},s.assets[jf[t]]=ai[t]}),s.assets||={},s.assets.screenshots=Object.values(ii)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Cv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Av;await Kl.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let p=fn.join(n,d.testResultId);try{await Kl.promises.mkdir(p,{recursive:!0})}catch(g){return m(g,"")}return m(null,p)},filename(c,l,m){let{fileName:d}=c.body,p=JSON.parse(c.body.metadata||"{}");if(!p.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(p.stepId){let g=fn.extname(d);return m(null,`step_${p.stepId}_${p.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),i=(0,Bf.default)();i.post("/",o.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(ii[m.stepId]=c.file.path),m.testResultId&&Pv.includes(m.subType)&&(ai[m.subType]||=[],ai[m.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(i);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(p){if(p.syscall!=="listen")return l(p);switch(p.code){case"EACCES":case"EPERM":return l(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new P(`Port ${s} is already in use`));default:return l(p)}}})}var Kl,Ff,fn,Bf,Av,ii,ai,jf,Pv,Yl=w(()=>{"use strict";Kl=E(require("fs")),Ff=E(require("os")),fn=E(require("path")),Bf=E(require("express"));z();wr();Av=fn.join(Ff.tmpdir(),"testim/rca/"),ii={},ai={},jf={"test-log":"consoleLogs","har-file":"networkLogs"},Pv=Object.keys(jf)});var er,Xl,ci,Wf=w(()=>{"use strict";er=E(require("lodash"));j();B();Xl=x("override-test-data-builder"),ci=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&typeof e.overrideTestData<"u"&&(this.isObjectNotArray(e.overrideTestData)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Xl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&typeof e.overrideAllTestsData<"u"&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Xl.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}Xl.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 er.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 o=r.map(m=>this.generateTestUniqId(m)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=te();return Object.assign({},e,{resultId:o,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 li(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ye.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Er,Ye,kv,Ov,_v,Lv,ui,Gf=w(()=>{"use strict";Er=E(require("lodash"));j();ce();ts();ye();z();B();At();en();Nf();ss();Yl();le();Te();Wf();pn();Ye=x("test-run-status"),kv=mr(),Ov=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,_v=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Lv=it();ui=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 Bt;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ns(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:zn||t.parallel||1,browser:o,gitBranch:kv,gitCommit:Ov,gitRepoUrl:_v,runnerVersion:Lv,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(d=>d.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:i,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(m=t.gridData)==null?void 0:m.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:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:i,testStatus:d};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:p,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}),Hc({projectId:n,runId:o,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,X.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ao(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(m){Ye.error("failed to upload test data artifact (runner)",{err:m})}let c=Er.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(ze(e,this.options))return;let n=this.exportsGlobal;try{let o=await li(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ye.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Ye.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===qe.EVALUATING&&xt.isTestStatusEnabled){X.onTestIgnored(e,r,`test in ${qe.EVALUATING} status`);return}if(l){X.onTestPassed(o);return}X.onTestFailed(r,r.failureReason,ot(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);X.onTestIgnored(e,r,`test in ${qe.QUARANTINE}`)}monitorMemoryUsage(e){let t=ec();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Ye.info(`using ${r} to parse html`,{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,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Jl(i,Ye),i.resultUrl=ot(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),X.onTestFinished(i,e,o);let c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await li(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Ye.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await br(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 Ye.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t){let r="",{APP_FROM_DEVICE:n,VIRTUAL_BUILD:o}=Ya;return e&&(r=n),$r(t)&&(r=o),r}calcTestRunStatus(){let{options:e,testInfoList:t}=this,r=e.company.companyId,n=t.map(o=>{var d,p,g;let i=e.browser?$s(e.browser,e.saucelabs,e.browserstack):o.runConfig,a=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Fs(o.nativeApp),c=Bs(e)&&($r(o.nativeApp)||a),l=ze(o,e)||c,m={testId:o.testId,status:l?pe.SKIPPED:pe.QUEUED,name:o.name,resultId:o.resultId,testStatus:o.testStatus||qe.DRAFT,testCreatorName:o.creatorName,testCreatorEmail:o.creatorEmail,testOwnerName:o.testOwnerName,testOwnerEmail:o.testOwnerEmail,testLabels:o.testLabels,testSuites:o.testSuites,allLabels:o.allLabels,...c&&{reason:this.getMobileRunSkippedReason(a,o.nativeApp)},config:Object.assign({},this.execConfig,{companyId:r,testData:((d=o.testData)==null?void 0:d.value)||null,isBeforeTestPlan:o.isBeforeTestPlan,isAfterTestPlan:o.isAfterTestPlan,testDataTotal:((p=o.testData)==null?void 0:p.total)||null,testDataIndex:((g=o.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||o.baseUrl||o.testConfig.baseUrl,testConfig:o.overrideTestConfig||o.testConfig,browser:i.browserValue.toLowerCase()})};return[o.resultId,m]});return Object.fromEntries(n)}async executionStart(e,t,r,n,o){Ye.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Yr(()=>Promise.all([an.end(t),Ro("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},m=await li(i.beforeSuite,l),d=new ci(m,Er.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=m;let{testInfoList:p}=this,g=[],f=[],h=[];for(let v of p){if(v.isBeforeTestPlan){g.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}f.push(v)}let y=async()=>{let v=Er.cloneDeep(this.testRunStatus);await ie(Object.keys(v),async I=>{var O;let C=v[I],k=(O=C.config)==null?void 0:O.testData,R=C.testId,N=await Ao(t,R,I,k,c.defaults);N&&(delete C.config.testData,C.config.testDataUrl=N)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},T=Ac(b);return this.executionStartedPromise=T,T.catch(I=>Ye.error(I)),T};try{await y()}catch(v){Ye.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){Er.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 m;let t=rc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:p}of t)d===pe.PASSED&&n++,d===pe.SKIPPED&&o++,d===pe.FAILED&&p===qe.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await li(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ye.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await Mf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Ro("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Ye.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await xc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});var Vf,Pt,Ql,pt,pi=w(()=>{"use strict";B();ce();le();ye();Ve();Vf=E(require("ora")),Pt=x("mobile-grid-service"),Ql=class{constructor(){this.gridsAppIdGetter={[U.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getTdcAppPath(t),[U.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getHeadspinAppPath(t),[U.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getBrowserStackAppPath(t),[U.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===U.TESTIM_TDC||e===U.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e)?`${t}/lock`:""}getBaseApiUrl(e){return e===U.TESTIM_HEADSPIN?`${Dp}/devices`:e===U.TESTIM_TDC?`${Mp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await $e({url:r,headers:n,body:o})}catch(i){throw Pt.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Ne(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Pt.error("error while getting automation config for device",{error:o,deviceId:t}),o}}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if([U.BROWSERSTACK,U.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,c;if(t===U.TESTIM_HEADSPIN||t===U.TESTIM_TDC){let l=await Xc({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}return t===U.BROWSERSTACK?(c=e.mobile)==null?void 0:c.version.split("-")[0]:t===U.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r){var y;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:m="",type:d=""}={}}=r,p=t.capabilities,g=await this.getDeviceNameFromSessionCaps({capabilities:p,gridType:d,projectId:a,projectType:c,companyId:l,gridId:m}),f=p.platformVersion;!f&&d===U.BROWSERSTACK&&(f=(y=p.mobile)==null?void 0:y.version.split("-")[1]);let h={name:g,model:p.deviceModel,osVersion:f,udid:p.udid,osType:p.platformName,scaleFactor:p.pixelRatio,isVirtual:!1};return await br(a,n,o,i,"RUNNING",{device:h}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h}),h}async getTmaDeviceDetails(e){let t=await Ne(`${Np}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);return r?{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}:{}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Pt.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await kc({appId:e,projectId:t});if(!i)throw Pt.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Pt.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Lp*60))+1)*60*1e3,Math.max(_p,t)}async getAppInfoForRemoteRun({testRunHandler:e,options:t}){let r="",n,{executionId:o,testResultId:i}=e,{appId:a,project:c,authData:{token:l=""}={},gridData:{gridId:m="",type:d="",host:p=""}={}}=t;if(a){Pt.info("getting appData by appId",{appId:a,projectId:c,testResultId:i,executionId:o});let y=await this.getMobileAppDataByAppId({appId:a,projectId:c,token:l,executionId:o,testResultId:i});r=y.appUrl,n=y.mobileApp,e.nativeApp=n}else Pt.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:i,executionId:o}),r=e.downloadableAppPublicLink||"";let g=this.gridsAppIdGetter[d]({testRunHandler:e,mobileApp:n,gridHost:p}),f=!!g&&d===U.TESTIM_TDC,h=!!g&&d===U.TESTIM_HEADSPIN;if(g&&(r=g),!g&&U.BROWSERSTACK===d){if(e.isAppFromDevice)throw new Error("The selected application from your device is not supported by the BrowserStack grid. Please choose a compatible application for testing.");let y=n||e.mobileApp,v=(0,Vf.default)("uploading app to browserstack please wait..").start();try{Pt.info("uploading app to browserstack",{appId:a,projectId:c,testResultId:e.testResultId,executionId:e.executionId});let S=await Qc({projectId:c,gridId:m,app:y,timeout:this.calculateUploadRequestTimeOut(y.fileSize)});v.succeed("app uploaded successfully to browserstack"),r=S.browserStackAppId}catch(S){throw v.fail("failed to upload app to browserstack"),Pt.error("failed to upload app to browserstack",{error:S}),new Error("failed to upload app to browserstack")}}return{appPath:r,isTdcAppIdExists:f,isHSAppIdExists:h}}},pt=new Ql});function Mv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function su(s){return zf.readFileSync(s,{encoding:"base64"})}function Xf(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=su(s);ns.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${ru(r)} current extension count: ${e.length}`),e.push(r)}}function Qf(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,m=`--load-extension=${l}`;ns.info(`adding extension: testim unpacked , path: ${l}`),t.push(m);return}let o=s.canary?"-master.zip":".zip",i=tu.join(process.cwd(),`testim-headless${o}`),a=su(i);ns.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${ru(a)} current extension count: ${e.length}`),e.push(a)}function Nv(s,e,t,r,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...Yf];e.headless&&l.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Zl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Zl.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},w3c:!0};eu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),eu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Zl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function d(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Ka.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}d(),Xf(r,c,i),e.mode===Y.EXTENSION&&Qf(e,c,l,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=l;let p={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[p]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${g}:${p}`]=m),s}function Fv(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":qf.join(","),"browser.helperApps.neverAsk.openFile":qf.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.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=tu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=su(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Bv(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let o=(0,Jf.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),Object.assign({},o,r,n)}return Object.assign({},r,n)}return{}}function jv(s,e,t){return dt.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}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function $v(s){return s.perfecto?s.perfecto:{}}function Wv(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 Gv(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=Ea(o,i)),a}function mi(s,e,t,r,n,o,i,a=null){var h,y;if(r.mode==="local"){let v=[],S=[...Yf],b={};return s.headless&&S.push("--headless"),s.silentDebuggerExtensionApi&&S.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&S.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(T=>S.push(`--${T}`)),s.chromeBinaryLocation&&(b.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&Qf(s,v,S,null,a),Xf(n,v,a),{logLevel:Hf,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:S,extensions:v,...b},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,m=Gv(s,r),d={hostname:r.host,host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:Hf,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!dt.isEmpty(m)&&{headers:m},...s.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};eu(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs||={},s.saucelabs.username||=r.user,s.saucelabs.accessKey||=r.key),r.type==="browserstack"&&(s.browserstack||={},s.browserstack["browserstack.user"]||=r.user,s.browserstack["browserstack.key"]||=r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let p=Number(s.browserTimeout/1e3),g=s.browser||(t==null?void 0:t.browserValue);dt.merge(d.desiredCapabilities,Bv(s,e,t),jv(s,e,t),$v(s),Wv(s,g,p),a==null?void 0:a.getCapabilities(s,g,o,i,e));let f=null;switch(!s.ext&&!s.extensionPath&&((h=r.host)!=null&&h.endsWith(".testim.io"))&&!s.canary&&s.mode===Y.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&M.flags.removeEdgeChromeDefaultVersion.isEnabled()?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),!M.flags.removeEdgeChromeDefaultVersion.isEnabled()&&((y=r.host)!=null&&y.endsWith(".testim.io"))&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=Uv(d,s,t,n,r,f,a);break;case"firefox":d=Fv(d,s,a);break;case"safari":case"safari technology preview":d=Mv(d,g);break;default:break}dt.merge(d.desiredCapabilities,s.seleniumCapsFileContent);try{let v={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},S=C=>C[r.provider]||C[d.host]||C[v[d.host]],b=C=>{var k,R;return S(C)||C[(k=d.desiredCapabilities)==null?void 0:k.browserName]||C[(R=d.desiredCapabilities)==null?void 0:R.version]||C||{}},T=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),I=b(b(T));Object.keys(I).length&&(ns.info(`Adding custom capabilities: ${JSON.stringify(I)}`),Object.assign(d.desiredCapabilities,I))}catch(v){ns.error("Failed to load custom capabilities",{error:v,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(Dv(d),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}function nu({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let r=[U.BROWSERSTACK,U.SAUCELABS,U.TESTIM_HEADSPIN,U.TESTIM_TDC];if(t.mode!=="local"&&!r.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function Vv({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==U.TESTIM_TDC&&e.type!==U.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function Hv(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function Zf(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===U.TESTIM_TDC?"tdc":"headspin";return{[`${i}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${i}:capture.network`]:!1},...o&&{[`${i}:controlLock`]:!0},[`${i}:retryNewSessionFailure`]:!1,[`${i}:sessionTags`]:Hv(t),[`${i}:enableBatch`]:M.flags.headSpinTdcEnableFlagCapability.isEnabled(),...!r&&{"appium:noReset":n}}}function di(s){return"id"in s?s.id:s.packageName}function eg({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o,isHSAppIdExists:i,isTdcAppIdExists:a}){let{fullReset:c,setNoReset:l,resetOnSessionStartOnly:m}=t,d={"appium:app":n};switch(i&&(d={"headspin:app.id":n}),a&&(d={"tdc:app.id":n}),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest",...c&&{"appium:fullReset":c,"appium:resetOnSessionStartOnly":m},...r&&{"appium:bundleId":di(r)},...n&&d};case"android":return{...e,platformName:"Android","appium:fullReset":!!c,"appium:autoGrantPermissions":!l,"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...r&&{"appium:appPackage":di(r),"appium:appActivity":r.activity},...n&&d};default:throw Error(`unsupported mobile project ${s}`)}}function tg({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isHSAppIdExists:i}){let a=Zf(U.TESTIM_HEADSPIN,o,n);return a=eg({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isHSAppIdExists:i}),a}function rg({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,isTdcAppIdExists:i}){let a=Zf(U.TESTIM_TDC,o,n);return a=eg({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r,isTdcAppIdExists:i}),a}function qv({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function zv({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o,selectedGrid:i}=e;return s||(n!=null&&n.deviceName?n.deviceName:o!=null&&o.deviceNameRegex?o.deviceNameRegex:((i==null?void 0:i.type)===U.BROWSERSTACK||r===U.BROWSERSTACK)&&t==="ios"?"iPhone.*":".*")}function Kv({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,p=d===U.BROWSERSTACK?"browserstack":"saucelabs",g=qv({osVersion:c,mobileConfig:m}),f=zv({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h={...d===U.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===U.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${p}.user`]:o.user,[`${p}.key`]:o.key,[`${p}.debug`]:!0,[`${p}.networkLogs`]:!0};switch(s){case"ios":return{...h,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...e&&{bundleId:di(e)},...t&&{app:t}};case"android":return{...h,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:r,...e&&{appPackage:di(e),appActivity:e.activity},...t&&{app:t}};default:throw Error(`unsupported mobile project ${s}`)}}function sg(s){return U.TESTIM_HEADSPIN===s.gridInfo.type?tg(s):U.TESTIM_TDC===s.gridInfo.type?rg(s):Kv(s)}function ng(s){return nu(s),sg(s)}function Jv(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,c={};return n==="dynamic"&&(!o&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!i&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function og(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);nu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=pt.getGridConnection(e),c=sg(s);if(e.type===U.TESTIM_HEADSPIN||e.type===U.TESTIM_TDC){let l=e.type===U.TESTIM_HEADSPIN?"headspin":"tdc",m=Jv(r,o==null?void 0:o.mobile);if(!dt.isEmpty(m)){let d=Object.entries(m).map(([p,g])=>g.split(",").map(f=>f===".*"||f==="="?"":`${p}:${f}`).join(",")).join(" ").trim();c[`${l}:selector`]=d}}return{...a,desiredCapabilities:c,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ig(s){var v,S;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,isHSAppIdExists:c,isTdcAppIdExists:l,testRunConfig:m}=s,{deviceUdid:d}=n;nu({nativeAppMetadata:r,appPath:o,gridInfo:t}),Vv({deviceUdid:d,gridInfo:t,testRunConfig:m});let p=d||((S=(v=m.mobile)==null?void 0:v.staticAllocation)==null?void 0:S.deviceUdid),g=await pt.getGridDirectConnection(t,p),f=t.type===U.TESTIM_TDC,h={projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,...!f&&{isHSAppIdExists:c},...f&&{isTdcAppIdExists:l},testRunConfig:m},y=f?rg(h):tg(h);return p&&(y["appium:udid"]=p),{...g,desiredCapabilities:y,capabilities:y,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function ag(s){let e=Object.assign({},s);return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],delete e.capabilities.key,delete e.capabilities.user,e}var zf,tu,Kf,dt,Jf,ns,Hf,Zl,Yf,ru,eu,Dv,Uv,qf,gn=w(()=>{"use strict";zf=E(require("fs")),tu=E(require("path")),Kf=E(require("crypto")),dt=E(require("lodash"));j();le();B();Te();ce();Wo();pi();Jf=require("lodash"),ns=x("testim-desired-capabilities-builder"),Hf=qn?"debug":"silent",Zl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Yf=["--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"],ru=(...s)=>Kf.createHash("sha256").update(s.join("")).digest("hex"),eu=s=>s.type===U.DEVICE_FARM||s.type===U.HYBRID&&s.provider==="devicefarm",Dv=s=>{var r;let{desiredCapabilities:e}=s;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.prototype.hasOwnProperty.call(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=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ns.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Uv=dt.memoize(Nv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(dt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return ru(i,a,c,r,l,o)}),qf=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Me(s){var e,t,r,n,o,i,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/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function cg(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 ou=w(()=>{"use strict"});function iu(s){function e(p){return p?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(p.nodeType):!1}function t(p){return p?r(p.parentNode,e):null}function r(p,g){for(let f=p;f&&f!==p.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(p,g){for(let f=p;f&&f!==p.ownerDocument;f=t(f))if(g(f))return f;return null}function o(p,g){if(!p||!g)return null;p instanceof DocumentFragment&&(p=p.host);let h=window.getComputedStyle(p).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(p);return o(y,g)}function i(p){let g=p.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(p.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(p,"stroke-width");return!!h&&parseInt(h,10)>0}return o(p,"overflow")==="hidden"?!1:Array.from(p.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(p){return o(p,"overflow")==="hidden"}function c(p){return!p||!a(p)||!p.childNodes.length?!1:Array.from(p.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(p){var g;return p?(g=p.parentNode)!=null&&g.host?!0:l(p.parentNode):!1}if(!s||!l(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,f=>f.tagName.toUpperCase()==="SELECT");return iu(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let m=!!n(s,p=>Number(o(p,"opacity"))===0),d=!!n(s,p=>o(p,"display")==="none");return!(m||d||!i(s)||c(s))}var lg=w(()=>{"use strict"});var ug,pg,tr,Yv,Xv,gi,dg=w(()=>{"use strict";ug=E(require("promise-queue")),pg=E(require("webdriverio"));le();Be();j();B();kr();lg();ou();ss();tr=x("WebDriverApi"),Yv=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},Xv={implicit:0,pageLoad:1,script:2},gi=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,o=t?t.toString().substr(0,2e3):"";throw tr.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),typeof xa<"u"&&(e=xa);let t=1/0;this.queue=new ug.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(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),L("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{tr.info("requesting browser",{testResultId:r,testName:t}),L("before this.client.init"),this.client=await pg.remote(e),this.logGridStatus(r)}),L("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){tr.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),tr.info("grid status",{gridStatusMsg:o.message,ready:o.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},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){tr.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 i()}catch(a){if(Me(a))return this.unsupportedActions.add("execute"),o();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),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Me(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}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 o;return(o=this.client)==null?void 0:o.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(Oe(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(iu,{ELEMENT:e,[Wt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Me(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(cg(e,this.isSafari(),tr))})}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 o=[];return o[Xv[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Me(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(Oe(e)),await this.elementIdValue(Oe(e),t)}async getViewportSize(e){let t=await this.execute(Yv);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 keys(e){let t=i=>wa.hasOwnProperty(i)?[wa[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Me(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.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(Oe(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(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 o;return(o=this.client)==null?void 0:o.$(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)})}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.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(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 o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Me(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,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{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){tr.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 tr.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 mg={};G(mg,{doubleClick:()=>Qv});var Qv,fg=w(()=>{"use strict";Qv=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(p){function g(S,b,T){return T>S&&T<b}let f=p.pointerPosition||{},h=r.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,v=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:v}},a=function(p,g){return{screenX:0,screenY:0,clientX:p,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(p,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(p,h)},l=function(p,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(p,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},m=function(){var g;let p=document.activeElement;for(;(g=p.shadowRoot)!=null&&g.activeElement;)p=p.shadowRoot.activeElement;return p},d=function(p){let g=i(p),f=p.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let p=m();dispatchFocus(s.elementToFocusLocatedElement,p),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(p){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:p.toString(),success:!1})}}});var hn={};G(hn,{dispatchFocus:()=>Zv});function Zv(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var yn=w(()=>{"use strict"});var Tg={};G(Tg,{WebDriver:()=>Rr});async function sE(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 tE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var os,yg,bg,Ue,rr,eE,gg,tE,sr,rE,hg,Sr,Rr,bn=w(()=>{"use strict";os=E(require("lodash"));j();Be();gn();yg=E(require("p-retry")),bg=E(require("ua-parser-js"));kr();B();ou();dg();z();Te();ss();Ue=x("webdriver"),[rr,eE]=[0,2],{extractElementId:gg,getCdpAddressForHost:tE}=K,sr=()=>(be(),fe(Yt)).getSessionPlayer().codeSnippets,rE=()=>(be(),fe(Yt)).getSessionPlayer().locatorBuilderUtils,hg=()=>(be(),fe(Yt)).getSessionPlayer().utils,Sr=()=>(be(),fe(Yt)).getSessionPlayer().positionUtils;Rr=class extends gi{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,r,n,o,i,a,c,l=new Bt,m=!1,d=void 0){var h,y,v,S,b,T,I,C;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let p=mi(t,r,n,o,i,a,c,d);p.desiredCapabilities&&delete p.desiredCapabilities.marionette,p.capabilities&&delete p.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=m?0:1500,f=m?()=>null:()=>this.executeJS("window.focus()");try{L("before initClient in webdriver.js init");let k=await this.initClient(p,r,c);L("after initResult before getCdpAddress in init"),this.cdpUrl=await sE(k),L("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${r}`,{sessionId:this.getSessionId(),testResultId:c}),await oe(g),M.flags.dontFocusOnInit.isEnabled()||await f(),L("after focus and delay in webdriver.js init")}catch(k){let R=JSON.stringify(os.omit(p,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:k,capabilitiesAsString:R});let N=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(T=k.stack)!=null&&T.includes("at startWebDriverSession")&&((I=k.message)!=null&&I.startsWith("Failed to create session"))&&((C=k.message)!=null&&C.includes("Timeout awaiting 'request'"))&&N?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new Dr(k.message):k.message.match(/capabilit(y|ies)/)?new Kn(k.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>os.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].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,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=te();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(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=gg(r.value);return await this.switchToFrame({ELEMENT:n,[Wt]: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 Jn:r}}async getElement(t){var o;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(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
|
|
22
22
|
var fn = ${sr().getLocatedElementCode};
|
|
23
23
|
return fn.apply(null, arguments);
|
|
24
24
|
`,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:o,attributeValue:i,locatedElement:a}){let c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(o,i)}await this.executeJS(`
|
|
@@ -44,7 +44,7 @@ WARNING: ${s} is deprecated. ${t}
|
|
|
44
44
|
var eventData = arguments[0];
|
|
45
45
|
var done = arguments[1];
|
|
46
46
|
return doubleClick.call(null, eventData, done);
|
|
47
|
-
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,eE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Me(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Me(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Ue.warn(`could not find element for locatedElement ${t}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:c}=n.value;return{x:r.left+o+a/2,y:r.top+i+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:o}=r.clickOffset;try{return await this.moveTo(t,n,o)}catch(i){if(Me(i))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw i}}getMoveActions(t=1,r=1,n="viewport",o=0){return[{type:"pointerMove",duration:o,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Ue.error("tried to use element origin but failed because of visibility, trying location",n);let o=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(o)}}getDragCoordinates(t){let r=t.filter(i=>i.event==="mousemove"||i.event==="pointermove"),n=r[0].pointerPosition,o=r.at(-1).pointerPosition;return{xDiff:o.screenX-n.screenX,yDiff:o.screenY-n.screenY}}async dragWithMoveTo(t,r,n,o,i){return await this.moveTo(t,o,i),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,o,i){let a=this.getMoveActions(o,i,t,1),c=this.getClickActions(["pointerDown"],rr),l=this.getMoveActions(r,n,"pointer",1),m=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(m)}])}async drag(t,r,n,o,i){let{width:a,height:c}=r,l=n-a/2+1,m=o-c/2,d=this.getDragCoordinates(i),{xDiff:p,yDiff:g}=d;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,p,g,l,m);try{return await this.dragWithMoveTo(t,p,g,l,m)}catch(f){if(Me(f))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,p,g,l,m);throw f}}getMoveRelativeSequence(t,r,n,o){let i=(p,g)=>Math.hypot(p.x-g.x,p.y-g.y),a={x:t,y:r},c={x:n,y:o},l=10,m=Math.round(i(a,c)/l),d=Array.from({length:m},()=>({x:Math.round((c.x-a.x)/m),y:Math.round((c.y-a.y)/m)}));return[{x:1,y:1}].concat(d)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:c,toX:l,toY:m}=n,d=Sr().calculateElementMiddlePoint(o),p=Sr().calculateElementMiddlePoint(c),g=this.getMoveRelativeSequence(d.x+i,d.y+a,p.x+l,p.y+m);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let f of g)await this.moveTo(null,f.x,f.y);return await this.moveTo(r,Math.round(l),Math.round(m)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Sr().calculateElementMiddlePoint(r),m=Sr().calculateElementMiddlePoint(i),d=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(m.x+a),f=Math.floor(m.y+c),h=this.getMoveAbsoluteSequence(d,p,g,f),y=this.getMoveActions(d,p),v=this.getClickActions(["pointerDown"],rr),S=os.flatMap(h,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(g,f),T=this.getClickActions(["pointerUp"],rr),I=y.concat(v).concat(S).concat(b).concat(T);return this.actions([{type:"pointer",id:"mouse",actions:I}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw o}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw o}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw o}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Sr().calculateElementMiddlePoint(r),m=Sr().calculateElementMiddlePoint(i),d=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(m.x+a),f=Math.floor(m.y+c);await this.moveWithActionsAPI({x:d,y:p});let h=this.getClickActionList(["pointerDown"],rr);await this.actions(h),await this.moveWithActionsAPI({x:g,y:f});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(gg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(o){Ue.error("error getting element location",{err:o})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Ue.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Ue.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Me(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var au,cu,hi,lu=w(()=>{"use strict";B();Te();ye();au=x("lab-features-service"),cu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(au.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await jc(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){au.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=
|
|
47
|
+
`,t.timeout,t)}getClickActions(t=[],r=void 0){return t.map(n=>({type:n,button:r}))}getClickActionList(t=[],r=void 0){return[{type:"pointer",id:"mouse",actions:this.getClickActions(t,r)}]}leftClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,rr,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,eE,t,["pointerDown","pointerUp"])}async rightClick(t,r){if(this.unsupportedActions.has("move"))return this.rightClickWithActionsAPI(t,r);try{return await super._rightClick(t,r)}catch(n){if(Me(n))return this.unsupportedActions.add("move"),this.rightClickWithActionsAPI(t,r);throw n}}async leftClick(t,r){if(this.unsupportedActions.has("move"))return this.leftClickWithActionsAPI(t,r);try{return await super._leftClick(t,r)}catch(n){if(Me(n))return this.unsupportedActions.add("move"),this.leftClickWithActionsAPI(t,r);throw n}}async dragAndDropOldAPI(t,r){return await this.moveTo(t),await this.buttonDown(),await this.moveTo(r),await this.buttonUp()}async calculateElementMiddlePoint(t,r={top:0,left:0}){let n=await this.getLocatedElementRect(t);if(!(n!=null&&n.value))throw Ue.warn(`could not find element for locatedElement ${t}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:c}=n.value;return{x:r.left+o+a/2,y:r.top+i+c/2}}async hover(t,r){if(this.unsupportedActions.has("move"))return this.moveToElementWithActionsAPI(t,r);let{x:n,y:o}=r.clickOffset;try{return await this.moveTo(t,n,o)}catch(i){if(Me(i))return this.unsupportedActions.add("move"),this.moveToElementWithActionsAPI(t,r);throw i}}getMoveActions(t=1,r=1,n="viewport",o=0){return[{type:"pointerMove",duration:o,x:Math.floor(t)||1,y:Math.floor(r)||1,origin:n}]}moveWithActionsAPI(t){let r=this.getMoveActions(t.x,t.y);return this.actions([{type:"pointer",id:"mouse",actions:r}])}async moveToElementWithActionsAPI(t,r){try{return await this.actions([{type:"pointer",id:"mouse",actions:this.getRelativeMoveActions(r,t)}])}catch(n){Ue.error("tried to use element origin but failed because of visibility, trying location",n);let o=this.computeAbsoluteMovement(r);return await this.moveWithActionsAPI(o)}}getDragCoordinates(t){let r=t.filter(i=>i.event==="mousemove"||i.event==="pointermove"),n=r[0].pointerPosition,o=r.at(-1).pointerPosition;return{xDiff:o.screenX-n.screenX,yDiff:o.screenY-n.screenY}}async dragWithMoveTo(t,r,n,o,i){return await this.moveTo(t,o,i),await this.buttonDown(),await this.moveTo(t,r,n),await this.buttonUp()}dragWithActionsAPI(t,r,n,o,i){let a=this.getMoveActions(o,i,t,1),c=this.getClickActions(["pointerDown"],rr),l=this.getMoveActions(r,n,"pointer",1),m=this.getClickActions(["pointerUp"],rr);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(c).concat(l).concat(m)}])}async drag(t,r,n,o,i){let{width:a,height:c}=r,l=n-a/2+1,m=o-c/2,d=this.getDragCoordinates(i),{xDiff:p,yDiff:g}=d;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,p,g,l,m);try{return await this.dragWithMoveTo(t,p,g,l,m)}catch(f){if(Me(f))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,p,g,l,m);throw f}}getMoveRelativeSequence(t,r,n,o){let i=(p,g)=>Math.hypot(p.x-g.x,p.y-g.y),a={x:t,y:r},c={x:n,y:o},l=10,m=Math.round(i(a,c)/l),d=Array.from({length:m},()=>({x:Math.round((c.x-a.x)/m),y:Math.round((c.y-a.y)/m)}));return[{x:1,y:1}].concat(d)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,c)=>{let l=a.at(-1);return a.concat({x:Math.round(l.x+c.x),y:Math.round(l.y+c.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:c,toX:l,toY:m}=n,d=Sr().calculateElementMiddlePoint(o),p=Sr().calculateElementMiddlePoint(c),g=this.getMoveRelativeSequence(d.x+i,d.y+a,p.x+l,p.y+m);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let f of g)await this.moveTo(null,f.x,f.y);return await this.moveTo(r,Math.round(l),Math.round(m)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Sr().calculateElementMiddlePoint(r),m=Sr().calculateElementMiddlePoint(i),d=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(m.x+a),f=Math.floor(m.y+c),h=this.getMoveAbsoluteSequence(d,p,g,f),y=this.getMoveActions(d,p),v=this.getClickActions(["pointerDown"],rr),S=os.flatMap(h,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(g,f),T=this.getClickActions(["pointerUp"],rr),I=y.concat(v).concat(S).concat(b).concat(T);return this.actions([{type:"pointer",id:"mouse",actions:I}])}async dragAndDrop(t,r,n){if(this.isSafari()){if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPIWithGeneratedMoves(n);try{return await this.dragAndDropWithGeneratedMoves(t,r,n)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPIWithGeneratedMoves(n);throw o}}if(this.unsupportedActions.has("move"))return this.dragAndDropWithActionsAPI(n);try{return await this.dragAndDropOldAPI(t,r)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.dragAndDropWithActionsAPI(n);throw o}}doubleClickFallback(t,r,n){return this.isSafari()?this.doubleClickWithJS(r):this.doubleClickWithActionsAPI(t,n)}async doubleClick(t,r,n){if(this.unsupportedActions.has("move")||this.isSafari())return this.doubleClickFallback(t,r,n);try{return await this.doDoubleClick(t)}catch(o){if(Me(o))return this.unsupportedActions.add("move"),this.doubleClickFallback(t,r,n);throw o}}async dragAndDropWithActionsAPI(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:c}=t,l=Sr().calculateElementMiddlePoint(r),m=Sr().calculateElementMiddlePoint(i),d=Math.floor(l.x+n),p=Math.floor(l.y+o),g=Math.floor(m.x+a),f=Math.floor(m.y+c);await this.moveWithActionsAPI({x:d,y:p});let h=this.getClickActionList(["pointerDown"],rr);await this.actions(h),await this.moveWithActionsAPI({x:g,y:f});let y=this.getClickActionList(["pointerUp"],rr);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(gg(t));return r}getSource(){return this.source()}async getElementRect(t){let r={width:0,height:0,top:0,left:0},n;try{n=await this.getElementLocation(t)}catch(o){Ue.error("error getting element location",{err:o})}return n!=null&&n.value?{top:n.value.y,left:n.value.x,width:n.value.width,height:n.value.height}:r}async end(){Ue.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Ue.warn("failed to close session because session is undefined"),this.stopKeepAliveInterval();try{return await super.end()}catch{return}}async submit(t){if(this.unsupportedActions.has("submit"))return await super.submitFormManually(t);try{return await super.submitForm(t)}catch(r){if(Me(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var au,cu,hi,lu=w(()=>{"use strict";B();Te();ye();au=x("lab-features-service"),cu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(au.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await jc(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){au.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=M.flags[e];this.validateAsLabFeatureFlag(t);let r=t.getValue();if(r==="disabled")return!1;if(r==="enabled")return!0;let{featuresForProject:n,labBatman:o}=this,i=n.find(c=>c.featureFlagName===e),a=i==null?void 0:i.enabled;return Boolean(o&&a)}isLabsEnabledForCompany(e){var t;return Boolean((t=e==null?void 0:e.premiumFeatures)==null?void 0:t.enableLabFeatures)}validateAsLabFeatureFlag(e){if("getValue"in e)return;let t=`Attempted querying a lab feature flag which isn't a variant. This means that a wrong configuration is being used in FeatureFlagsService (for feature flag: ${e.name}`;throw au.error(t,{featureFlagName:e.name}),new Error(t)}},hi=new cu});function nE(s){let e=/^\\\\\?\\/.test(s),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function oE(s){try{return{sync:!0,lib:globalThis.require(s)}}catch(e){if(e.code!=="ERR_REQUIRE_ESM")throw e;let{sep:t,join:r}=globalThis.require("path"),{promises:n}=globalThis.require("fs");return{sync:!1,lib:n.readFile(`${s}${t}package.json`).then(i=>{let a=JSON.parse(i);return import(r(s,a.main||`${t}index.js`))})}}}function iE(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function aE(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).map(f=>`
|
|
48
48
|
var res = requireOrImportMethod('${nE(n[f])}');
|
|
49
49
|
if (res.sync) {
|
|
50
50
|
var ${f} = res.lib;
|
|
@@ -212,17 +212,17 @@ WARNING: ${s} is deprecated. ${t}
|
|
|
212
212
|
injectCode(params, args, incomingParams, context, code);
|
|
213
213
|
});
|
|
214
214
|
})();
|
|
215
|
-
`,p=[],g=new Sg.Worker(d,{eval:!0});try{return await ae(new Promise(f=>{g.on("message",h=>{if(h.action==="finish"){let{data:y}=h,v=Object.assign({},y,{tstConsoleLogs:p});mt.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),f(v)}else h.action==="progress"&&p.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?mt.error("Run code worker error",{err:h,transactionId:s,fileDataUrl:i}):mt.error("Run code worker error",{err:h,transactionId:s}),f({tstConsoleLogs:p,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{mt.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(f){if(!(f instanceof re))throw f;return mt.warn("timeout to run code",{transactionId:s,err:f}),{tstConsoleLogs:p,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function cE(s){try{await wg.promises.rm(s,{recursive:!0,force:!0})}catch(e){mt.warn("failed to remove install npm packages folder",{err:e})}}function Rg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function is(s,e,t,r,n,o){let i=Rg(n,e,s,t),{data:a}=await lE(i,r,o);return a}async function as(s,e,t,r,n,o,i,a,c,l){var f;let m=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),d=Rg(i,n,e,o);if(l){let h=await Xs(l);h&&(c=h)}Buffer.isBuffer(c)&&(mt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let p="data:,";c==="data:"&&(mt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=p);let g=await aE(d,t,r,s,m,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function lE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ig(),o=Tn.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Cd(o,r,i,t),mt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let d=Pd(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${d}`,packageLocalLocation:Tn.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(l){throw mt.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ae(a(),t)}catch(c){throw c instanceof re&&mt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ig(){return Tn.join(vg.tmpdir(),"/testim_local_packages")}function xg(){let s=Ig();return cE(s)}var wg,vg,Tn,Eg,Sg,mt,Ir=w(()=>{"use strict";wg=E(require("fs")),vg=E(require("os")),Tn=E(require("path"));j();Vs();Eg=E(require("data-uri-to-buffer")),Sg=require("worker_threads");z();B();ye();mt=x("cli-service")});var nr={};G(nr,{run:()=>pE});function uE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=
|
|
216
|
-
Action required: Please allow opening a websockets connection to ${me} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Ti.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Dg,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${me}/${t}`,this._socket=mu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Dg,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${me}/${t}`,this._socket=mu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Mg.default)(()=>ae(n(),TE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Ti.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Ng={};G(Ng,{remoteStepServiceSocketIO:()=>wE});var gu,wE,Ug=w(()=>{"use strict";fu();gu=class extends ls{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},wE=new gu});var Fg={};G(Fg,{remoteStepService:()=>us});var hu,wn,yu,us,wi=w(()=>{"use strict";bi();ce();Te();({REMOTE_STEP_SAVED:hu}=St),yu=class{async init(e){N.flags.useNewWSCLI.isEnabled()||(wn=(await Promise.resolve().then(()=>(Ug(),Ng))).remoteStepServiceSocketIO,wn.init(e))}joinToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:remoteStep`,{resultId:e},[hu]):wn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(N.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:remoteStep`,[hu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}wn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return N.flags.useNewWSCLI.isEnabled()?(ft.removeFilter(`${e}:remoteStep`,[hu]),Promise.resolve()):wn.unlistenToRemoteStep(e)}},us=new yu});var bu,Ar,Bg=w(()=>{"use strict";fu();bu=class extends ls{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,r,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Ar=new bu});var $g={};G($g,{testResultService:()=>Ct});var jg,Tu,Ct,vi=w(()=>{"use strict";jg=require("events");bi();ce();Te();Bg();Tu=class extends jg.EventEmitter{init(e,t){if(N.flags.useNewWSCLI.isEnabled()){ft.onConnect=()=>this.emit("socket-connected");return}t>this.getMaxListeners()&&this.setMaxListeners(t),Ar.init(e),Ar.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return N.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:testResult`,{resultId:e,testId:t},[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]):Ar.joinToTestResult(e,t)}async leaveTestResult(e,t){if(N.flags.useNewWSCLI.isEnabled()){ft.removeFilter(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]);return}await Ar.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(N.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Ar.listenToTestResult(e,t,r)}getSocket(){if(!N.flags.useNewWSCLI.isEnabled())return Ar.getSocket()}},Ct=new Tu});var Gg,Vg,Hg,we,vE,qg,Wg,Ei,zg=w(()=>{"use strict";Gg=E(require("lodash"));j();le();Be();Xr();Rt();ye();_g();Vg=E(require("p-retry")),Hg=require("url");B();No();ss();ce();wi();vi();Te();we=x("test-run-handler"),vE=3,qg=20*1e3,Wg=s=>JSON.stringify(s).length<qg,Ei=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Bt;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?$s(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isFFAllowAppFromDeviceEnabled(){return N.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Fs(this._nativeApp)}get isAppForIosVirtualDevice(){return $r(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Zn.FROM_DEVICE:Zn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Kt(),refreshToken:vo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Pp,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential}};if(this._options.disableMockNetwork&<("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Wg(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${qg} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await nn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Wg(e))return;let r=async()=>{try{return await Vc(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Wc(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){L("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{L("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};L("before Runtime.evaluate"),await(0,Vg.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),L("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return L("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Hg.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Tr(a,c,m,l);n(d),r||setTimeout(i,3e3)}catch(d){we.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ct.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Tr(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ct.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ct.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Gg.debounce(async()=>{try{let i=await Tr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ct.on("socket-connected",async()=>{try{await Ct.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await _c(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ct.off("socket-connected",e)}}listenToRemoteStep(e){us.listenToRemoteStep(this.testResultId,t=>{Og(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:vE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=te(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Si,Kg=w(()=>{"use strict";zg();Si=class{constructor(e,t,r,n,o,i){this._waitingTests=r.map(a=>new Ei(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var EE,SE,vn,wu=w(()=>{"use strict";ts();B();EE=x("worker-utils"),SE=async(s,e,t)=>{e&&await Pl(s,t)},vn=async(s,e,t,r)=>{EE.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await SE(s,e,t)}}});function CE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ii,Qg,Eu,Su,Zg,gt,Jg,Yg,Xg,En,RE,vu,IE,or,xE,Ri,AE,PE,kE,tt,Sn=w(()=>{"use strict";Ii=E(require("ms")),Qg=E(require("lodash")),Eu=E(require("p-retry")),Su=E(require("dayjs")),Zg=E(require("dayjs/plugin/duration"));j();Be();ts();ye();B();wu();At();Wo();Te();wi();vi();Ve();ce();z();Su.default.extend(Zg.default);gt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Jg,TEST_START_TIMEOUT_MSG:Yg,TEST_COMPLETE_TIMEOUT_MSG:Xg}=We,{SETUP_TIMEOUT:En,NETWORK_ERROR:RE,GRID_ERROR:vu,BROWSER_CLOSED:IE,SELENIUM_ERROR:or,UNKNOWN_ERROR:xE,MOBILE_SESSION_ERROR:Ri}=Ms,AE=(0,Ii.default)("1s"),PE=1;kE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],tt=class{constructor(e,t,r,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=tt.getWorkerId();this.lambdatestService=new ne;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return PE++}async getGridSlot(e,t){let r=await of(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return X.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Cs(!0)}async getBrowserOnce(e,t,r,n){throw new Cs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),gt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===U.BROWSERSTACK?Math.max((0,Ii.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ii.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{L("before getSlotOnce retries");let i=0,a=await(0,Eu.default)(async()=>{let m=Date.now();try{return await ae(this.getSlotOnce(e),this.options.getBrowserTimeout,We.GET_BROWSER_TIMEOUT_MSG)}catch(d){let p={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Mr?gt.info("could not get grid slot due to concurrency issue",p):gt.error("error getting grid slot",{error:d,...p}),i++,await oe(this.options.getBrowserTimeout-(Date.now()-m)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});L("after getSlotOnce retries"),L("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Eu.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{a=await af(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let p=this.setSessionTimeout();L("before getBrowserOnce");let g=await ae(this.getBrowserOnce(e,t,d,a),p,We.GET_BROWSER_TIMEOUT_MSG);return L("after getBrowserOnce"),X.onGetBrowserSuccess(this.id,r),d||g}catch(p){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw gt.error(`error getting ${f} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),X.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(p instanceof bt)&&this.options.mode!==Y.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-m)),p}},{retries:c-1,minTimeout:0,factor:1}),L("after getBrowserOnce retries")}catch(i){throw await vn(this.id,this.releaseSlotOnTestFinished,r,n),[bt,Dr].some(a=>i instanceof a)?i:i instanceof Tt?new ur(i,vu):new ur(i,or)}return n}async runTest(e,t,r){var m;L("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Bs(this.options)&&this.handleMobileTest(e);if(i)return i;L("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await vn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var D,$;if(ze(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,S=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof ur,T=y&&(S(Yg)||S(Xg)),k=N.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,R=T&&h.hasMoreTimeoutRetries(),M=h.hasMoreRetries()&&!b&&!T,O=!f.success&&(M||R||k);try{let H=h.retryKey;f.testRetryKey=H;let J=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,v,O,J),this.executionQueue.hasMoreTests()&&!((D=this.options.lightweightMode)!=null&&D.general)&&await oe(AE),await this.runTestCleanup(),O){if(R&&await h.startNewTimeoutRetry(),k){gt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let Q=($=this.options.projectData)==null?void 0:$.projectId,de=h.testResultId,$t=h.testId;await xo(Q,de,$t,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return M&&!k&&!R&&await h.startNewRetry(),gt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:H,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await m(h,O)}return await e()}catch(H){if(H instanceof Gt)return;gt.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
217
|
-
Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:v,TIMEOUT_ERROR:S,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Xa,T=f instanceof Error?f.message:f;return T.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),T.includes(Jg)||T.includes(S)?{errorType:En,reason:"timeout while getting device"}:T.includes(y)||T.includes(b)?{errorType:Ri,reason:"app doesn't exist on device"}:T.includes(v)?{errorType:Ri,reason:"app never started, check app permission or app activity"}:T.includes(h)?{errorType:Ri,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ri,reason:T}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&
|
|
218
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:or,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:or,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:xE,reason:v}},i=async(f,h)=>{var T;let y=await Ga();!y&&N.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),gt.warn("error on run",{err:f});let v=(T=this.userData)==null?void 0:T.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);xo(v,this.testResultId,this.testId,{status:Ds.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ds.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(CE(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var T;let y=this.testId,v=this.testResultId,S=(T=this.userData)==null?void 0:T.projectId,b=this.branch;if(!y||!v||!S||!b)return gt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await Tr(y,v,S,b);if(gt.warn("Test failed. Got results via API",{err:f,testResult:Qg.default.omit(I,kE)}),I&&I.status===Ds.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&>.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),m=async(f,h)=>{try{await Promise.all([!l&&us.joinToRemoteStep(this.testResultId),!c&&Ct.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),v=await t(y,f);return L("After onRunComplete"),v}catch(y){return a(y,f)}finally{l||us.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,m(d)):this.onQueueCompleted()}}});var Ru,eh,ps,Iu=w(()=>{"use strict";j();Ru=E(require("p-retry"));j();B();z();eh=x("window-utils"),ps=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return eh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&eh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&typeof window.location<"u")r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new bt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Ru.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Ru.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var xu,ds,Au=w(()=>{"use strict";B();xu=x("cookies-utils"),ds=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw xu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw xu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw xu.error("failed to remove cookie",{err:t}),t}}}});var Pu,xi,th=w(()=>{"use strict";Pu=E(require("p-retry")),xi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,Pu.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,Pu.default)(o,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function rh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return OE.warn("missing elementRect",nh.omit(s,"image")),{};let{elementRect:i}=s,a=await ms.default.read(Buffer.from(n[1],"base64")),c=i.left*r+o.left*r,l=i.top*r+o.top*r,m=i.width*r,d=i.height*r;c<0&&(m+=c,m=m<0?0:m,c=0),l<0&&(d+=l,d=d<0?0:d,l=0);let p=a.bitmap.width,g=a.bitmap.height;if(c+m>p&&(m=p-c),l+d>g&&(d=g-l),d<=0||m<=0)throw new Cu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,m,d).getBase64Async(ms.default.MIME_PNG)}}async function _E(s,e){let t=await ms.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await ms.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(ms.default.MIME_PNG)}function LE(s,e){return _E(s,e)}async function DE(){}async function ME(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await DE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function sh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var nh,ms,OE,Cu,Ai,oh=w(()=>{"use strict";nh=E(require("lodash"));j();ms=E(require("jimp"));B();OE=x("image-capture-utils"),Cu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Ai=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await rh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:sh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return ME({screenImage:t.image,absoluteScreenHighlight:sh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>oe(250),o=Boolean(e);async function i(p,g){o?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await n();let f=await r.takeScreenshot(),h=await rh({elementRect:g},f);return{position:{left:p.x+g.left,top:p.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(p){let g=[];for(let f of p){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(p,g){let f=Math.max(p.width,g.width),h=g.width,y=Math.max(p.height,g.height),v=g.height,S=Array.from({length:Math.ceil(f/h)},(T,I)=>({scrollX:Math.min(I*h,f-h),cropX:I*h-Math.min(I*h,f-h),cropW:h-(I*h-Math.min(I*h,f-h))})),b=Array.from({length:Math.ceil(y/v)},(T,I)=>({scrollY:Math.min(I*v,y-v),cropY:I*v-Math.min(I*v,y-v),cropH:v-(I*v-Math.min(I*v,y-v))}));return S.flatMap(T=>b.map(I=>({scrollPos:{x:T.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:T.cropX,width:T.cropW,height:I.cropH}})))}async function l(p,g){let f=await t.getCurrentScrollPosition(),h=c(p,g),y=await a(h);return await t.scrollToPosition(f),LE(p,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var ih,ah,Pi,Ci,ch=w(()=>{"use strict";ih=E(require("p-retry")),ah=E(require("semver"));j();B();Iu();th();oh();be();Pi=x("tab-service"),Ci=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Pi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=te();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ps(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Ai(t,a,new xi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=ee(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),m=r.map(d=>o.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,r,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,i,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Pi.error("failed to get url or title",{err:o})}}catch(n){Pi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await oe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Pi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ih.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=ah.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:r,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(r){let l=this.getAllTabIds(e).map(m=>Object.assign({},this.getTabInfo(e,m),{tabId:m})).filter(m=>!m.isClosed);i=r.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(m=>{let d=this.getTabInfo(e,m);return this.isSameTab(e,d,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let m=["no such window","no window found","the window could not be found"];if(l.message&&m.some(d=>l.message.toLowerCase().includes(d)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var ku,ki,Ou=w(()=>{"use strict";ku=class{select(){return console.log(`
|
|
215
|
+
`,p=[],g=new Sg.Worker(d,{eval:!0});try{return await ae(new Promise(f=>{g.on("message",h=>{if(h.action==="finish"){let{data:y}=h,v=Object.assign({},y,{tstConsoleLogs:p});mt.debug("Run code worker response",{messageWithLogs:v,transactionId:s}),f(v)}else h.action==="progress"&&p.push(h.data)}).on("error",h=>{h.message==="malformed data: URI"?mt.error("Run code worker error",{err:h,transactionId:s,fileDataUrl:i}):mt.error("Run code worker error",{err:h,transactionId:s}),f({tstConsoleLogs:p,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{mt.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(f){if(!(f instanceof re))throw f;return mt.warn("timeout to run code",{transactionId:s,err:f}),{tstConsoleLogs:p,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function cE(s){try{await wg.promises.rm(s,{recursive:!0,force:!0})}catch(e){mt.warn("failed to remove install npm packages folder",{err:e})}}function Rg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function is(s,e,t,r,n,o){let i=Rg(n,e,s,t),{data:a}=await lE(i,r,o);return a}async function as(s,e,t,r,n,o,i,a,c,l){var f;let m=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(h=>[h.paramName,h.testimPackageLocalLocation]))||[]),d=Rg(i,n,e,o);if(l){let h=await Xs(l);h&&(c=h)}Buffer.isBuffer(c)&&(mt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let p="data:,";c==="data:"&&(mt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=p);let g=await aE(d,t,r,s,m,a,c);return Object.assign({},g,{nodeVersion:process.version})}async function lE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ig(),o=Tn.join(n,`/${s}`),i=global.proxyUri;async function a(){let c="";try{if(c=await Cd(o,r,i,t),mt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let d=Pd(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${d}`,packageLocalLocation:Tn.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(l){throw mt.warn("npm package install failed",{transactionId:s,err:l}),l}}try{return await ae(a(),t)}catch(c){throw c instanceof re&&mt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ig(){return Tn.join(vg.tmpdir(),"/testim_local_packages")}function xg(){let s=Ig();return cE(s)}var wg,vg,Tn,Eg,Sg,mt,Ir=w(()=>{"use strict";wg=E(require("fs")),vg=E(require("os")),Tn=E(require("path"));j();Vs();Eg=E(require("data-uri-to-buffer")),Sg=require("worker_threads");z();B();ye();mt=x("cli-service")});var nr={};G(nr,{run:()=>pE});function uE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=M.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var pE,Ag=w(()=>{"use strict";Ir();z();Te();pE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:p}=e.data;try{let g=await as(r,n,o,i,a,c,l,m,d,p);return g&&uE({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof re?new Error("Timeout while running action"):g}}});var uu={};G(uu,{run:()=>dE});var dE,Pg=w(()=>{"use strict";Ir();z();dE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await is(t,r,n,i,o,a),success:!0}}catch(c){if(c instanceof wt)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof re)return{success:!1,code:"timeout"};throw c}}});async function kg(s,e,t,r){try{return await Gc(s,e,t,r)}catch{yi.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function fE(s,e,t,r,n){return yi.info("finished to run remote step",{stepId:t,sessionId:n}),await kg(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Cg(s,e,t,r,n){return yi.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await kg(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Og(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o}=s,i=t.type,a=e.getSessionId(),c=t.id;yi.info("start play remote step",{stepType:i,stepId:c,sessionId:a});let l=mE[i];if(!l)return await Cg(n,r,c,`Failed to find step type ${i}`,a);try{let m=await l.run(e,t,o);return await fE(n,r,c,m,a)}catch(m){return await Cg(n,r,c,m.message,a)}}var yi,mE,_g=w(()=>{"use strict";Ag();ye();Pg();B();yi=x("step-playback"),mE={"cli-validation-code-step":nr,"cli-wait-for-code-step":nr,"cli-action-code-step":nr,"cli-api-code-step":nr,"cli-condition-step":nr,"cli-download-code-step":nr,"node-package":uu}});var pu,Lg,xr,hE,du,ft,bi=w(()=>{"use strict";j();Rt();pu=E(require("ws")),Lg=require("events");B();le();xr=x("socket-ng-service"),hE=5e3,du=class extends Lg.EventEmitter{constructor(){super(...arguments);this.clientId=te();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){xr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),hE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){xr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(vp);return Kt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new pu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return xr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{xr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===pu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{xr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){xr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){xr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let o=i=>{r(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,r,n,o){function i(c){n(c)&&o(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=i.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,o=!1){return new Promise(i=>{let a=te(),c={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",l=>l.id===a,i),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(r)?r:[r];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},ft=new du});var Mg,mu,yE,bE,TE,Dg,Ti,ls,fu=w(()=>{"use strict";Mg=E(require("p-retry")),mu=E(require("socket.io-client"));le();j();B();yE=50,bE=10,TE=5e3,Dg=10*1e3,Ti=x("base socket service"),ls=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Ti.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Ti.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===bE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=yE)throw new Error(`Can't connect to Testim Servers.
|
|
216
|
+
Action required: Please allow opening a websockets connection to ${me} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Ti.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Dg,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${me}/${t}`,this._socket=mu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Dg,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${me}/${t}`,this._socket=mu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Mg.default)(()=>ae(n(),TE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Ti.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Ng={};G(Ng,{remoteStepServiceSocketIO:()=>wE});var gu,wE,Ug=w(()=>{"use strict";fu();gu=class extends ls{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"remoteStep"),this.listerers={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listerers[t]&&(this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listerers[t])}async unlistenToRemoteStep(t){this.listerers[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listerers[t]),delete this.listerers[t],await this.emitLeaveRoom(t))}},wE=new gu});var Fg={};G(Fg,{remoteStepService:()=>us});var hu,wn,yu,us,wi=w(()=>{"use strict";bi();ce();Te();({REMOTE_STEP_SAVED:hu}=St),yu=class{async init(e){M.flags.useNewWSCLI.isEnabled()||(wn=(await Promise.resolve().then(()=>(Ug(),Ng))).remoteStepServiceSocketIO,wn.init(e))}joinToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:remoteStep`,{resultId:e},[hu]):wn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(M.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:remoteStep`,[hu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}wn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return M.flags.useNewWSCLI.isEnabled()?(ft.removeFilter(`${e}:remoteStep`,[hu]),Promise.resolve()):wn.unlistenToRemoteStep(e)}},us=new yu});var bu,Ar,Bg=w(()=>{"use strict";fu();bu=class extends ls{constructor(){super(...arguments);this.listerers={}}init(t){super.init(t,"testResult"),this.listerers={}}listenToTestResult(t,r,n){this.listerers[t]&&(this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t]),this.listerers[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listerers[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listerers[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listerers[t]),delete this.listerers[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Ar=new bu});var $g={};G($g,{testResultService:()=>Ct});var jg,Tu,Ct,vi=w(()=>{"use strict";jg=require("events");bi();ce();Te();Bg();Tu=class extends jg.EventEmitter{init(e,t){if(M.flags.useNewWSCLI.isEnabled()){ft.onConnect=()=>this.emit("socket-connected");return}t>this.getMaxListeners()&&this.setMaxListeners(t),Ar.init(e),Ar.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return M.flags.useNewWSCLI.isEnabled()?ft.addFilter(`${e}:testResult`,{resultId:e,testId:t},[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]):Ar.joinToTestResult(e,t)}async leaveTestResult(e,t){if(M.flags.useNewWSCLI.isEnabled()){ft.removeFilter(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED]);return}await Ar.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(M.flags.useNewWSCLI.isEnabled()){ft.listenTo(`${e}:testResult`,[St.TEST_RESULT_UPDATED,St.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Ar.listenToTestResult(e,t,r)}getSocket(){if(!M.flags.useNewWSCLI.isEnabled())return Ar.getSocket()}},Ct=new Tu});var Gg,Vg,Hg,we,vE,qg,Wg,Ei,zg=w(()=>{"use strict";Gg=E(require("lodash"));j();le();Be();Xr();Rt();ye();_g();Vg=E(require("p-retry")),Hg=require("url");B();No();ss();ce();wi();vi();Te();we=x("test-run-handler"),vE=3,qg=20*1e3,Wg=s=>JSON.stringify(s).length<qg,Ei=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Bt;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?$s(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getBrowserStackAppPath(e){var t;return this.isAppFromDevice?null:e?e.browserStackAppId:(t=this._nativeApp)==null?void 0:t.browserStackAppId}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getHeadspinAppPath(e){var t;return this.isAppFromDevice?null:e?e.headSpinAppId:(t=this._nativeApp)==null?void 0:t.headSpinAppId}getTdcAppPath(e){var t;return this.isAppFromDevice?null:e?e.testimTdcAppId:(t=this._nativeApp)==null?void 0:t.testimTdcAppId}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isFFAllowAppFromDeviceEnabled(){return M.flags.allowAppFromDeviceRuns.isEnabled()}get isAppFromDevice(){return Fs(this._nativeApp)}get isAppForIosVirtualDevice(){return $r(this._nativeApp)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Zn.FROM_DEVICE:Zn.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${me}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Kt(),refreshToken:vo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Pp,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,onprem:this._options.company.onprem,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential}};if(this._options.disableMockNetwork&<("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Wg(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,c=this.testId;i?(Object.assign(t,{runData:o}),we.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):we.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${qg} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await nn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return we.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Wg(e))return;let r=async()=>{try{return await Vc(this._options.project,this._testId,this._testResultId,e)}catch(i){return we.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Wc(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){L("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{L("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=i||{};L("before Runtime.evaluate"),await(0,Vg.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),L("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return L("after Runtime.evaluate"),l.value}catch(i){throw we.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Hg.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){we.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(we.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Tr(a,c,m,l);n(d),r||setTimeout(i,3e3)}catch(d){we.error("failed to check if done",{err:d}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ct.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Tr(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return we.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw we.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}catch(o){throw we.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(We.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ct.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){we.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ct.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){we.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Gg.debounce(async()=>{try{let i=await Tr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(we.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(we.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return we.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ct.on("socket-connected",async()=>{try{await Ct.joinToTestResult(this._testResultId,this.testId)}catch(i){we.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await _c(this._testResultId,this._options.project,this.retryKey);a?await e()||(we.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){we.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ct.off("socket-connected",e)}}listenToRemoteStep(e){us.listenToRemoteStep(this.testResultId,t=>{Og(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:vE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=te(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Si,Kg=w(()=>{"use strict";zg();Si=class{constructor(e,t,r,n,o,i){this._waitingTests=r.map(a=>new Ei(e,t,a,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var EE,SE,vn,wu=w(()=>{"use strict";ts();B();EE=x("worker-utils"),SE=async(s,e,t)=>{e&&await Pl(s,t)},vn=async(s,e,t,r)=>{EE.info("releasing player",{hasPlayer:Boolean(r)});try{await(r==null?void 0:r.onDone())}finally{await SE(s,e,t)}}});function CE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Ii,Qg,Eu,Su,Zg,gt,Jg,Yg,Xg,En,RE,vu,IE,or,xE,Ri,AE,PE,kE,tt,Sn=w(()=>{"use strict";Ii=E(require("ms")),Qg=E(require("lodash")),Eu=E(require("p-retry")),Su=E(require("dayjs")),Zg=E(require("dayjs/plugin/duration"));j();Be();ts();ye();B();wu();At();Wo();Te();wi();vi();Ve();ce();z();Su.default.extend(Zg.default);gt=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Jg,TEST_START_TIMEOUT_MSG:Yg,TEST_COMPLETE_TIMEOUT_MSG:Xg}=We,{SETUP_TIMEOUT:En,NETWORK_ERROR:RE,GRID_ERROR:vu,BROWSER_CLOSED:IE,SELENIUM_ERROR:or,UNKNOWN_ERROR:xE,MOBILE_SESSION_ERROR:Ri}=Ms,AE=(0,Ii.default)("1s"),PE=1;kE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],tt=class{constructor(e,t,r,n,o,i,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.id=tt.getWorkerId();this.lambdatestService=new ne;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.isRegressionBaselineRun=t.isRegressionBaselineRun,this.userData=t.userData}static getWorkerId(){return PE++}async getGridSlot(e,t){let r=await of(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return X.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Cs(!0)}async getBrowserOnce(e,t,r,n){throw new Cs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),gt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!ze({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=!e.isFFAllowAppFromDeviceEnabled&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:pe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}setSessionTimeout(){var e;return this.options.mode===Y.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===U.BROWSERSTACK?Math.max((0,Ii.default)("600s"),this.options.getSessionTimeout):Math.max((0,Ii.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{L("before getSlotOnce retries");let i=0,a=await(0,Eu.default)(async()=>{let m=Date.now();try{return await ae(this.getSlotOnce(e),this.options.getBrowserTimeout,We.GET_BROWSER_TIMEOUT_MSG)}catch(d){let p={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw d instanceof Mr?gt.info("could not get grid slot due to concurrency issue",p):gt.error("error getting grid slot",{error:d,...p}),i++,await oe(this.options.getBrowserTimeout-(Date.now()-m)),d}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1});L("after getSlotOnce retries"),L("before getBrowserOnce retries");let c=this.options.getBrowserRetries-i;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Eu.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{a=await af(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1}),this.options.gridData.provider=a.provider,this.options.gridData.host=a.host,this.options.gridData.failedGetBrowserAttempts=l;let p=this.setSessionTimeout();L("before getBrowserOnce");let g=await ae(this.getBrowserOnce(e,t,d,a),p,We.GET_BROWSER_TIMEOUT_MSG);return L("after getBrowserOnce"),X.onGetBrowserSuccess(this.id,r),d||g}catch(p){let g={provider:a.provider,host:a.host,failedGetBrowserAttempts:l,id:this.options.gridData.gridId,type:a.type},f=this.options.mode===Y.APPIUM?"device":"browser";throw gt.error(`error getting ${f} from grid`,{error:p,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g}),X.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(p instanceof bt)&&this.options.mode!==Y.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-m)),p}},{retries:c-1,minTimeout:0,factor:1}),L("after getBrowserOnce retries")}catch(i){throw await vn(this.id,this.releaseSlotOnTestFinished,r,n),[bt,Dr].some(a=>i instanceof a)?i:i instanceof Tt?new ur(i,vu):new ur(i,or)}return n}async runTest(e,t,r){var m;L("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Bs(this.options)&&this.handleMobileTest(e);if(i)return i;L("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,l)}finally{await vn(this.id,this.releaseSlotOnTestFinished,n,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var p,g;let e=()=>process.nextTick(()=>this.run()),t=async(f,h,y)=>{var D,$;if(ze(f,this.options)||!h.isFFAllowAppFromDeviceEnabled&&h.isAppFromDevice||h.isAppForIosVirtualDevice)return e();let v=h.sessionId,S=H=>y==null?void 0:y.message.includes(H),b=y&&y instanceof ur,T=y&&(S(Yg)||S(Xg)),k=M.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&h.isSeleniumHubNoMatchSessionError(f.reason)&&!h.ignoreSeleniumHubError,R=T&&h.hasMoreTimeoutRetries(),N=h.hasMoreRetries()&&!b&&!T,O=!f.success&&(N||R||k);try{let H=h.retryKey;f.testRetryKey=H;let J=h.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,v,O,J),this.executionQueue.hasMoreTests()&&!((D=this.options.lightweightMode)!=null&&D.general)&&await oe(AE),await this.runTestCleanup(),O){if(R&&await h.startNewTimeoutRetry(),k){gt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:h.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let Q=($=this.options.projectData)==null?void 0:$.projectId,de=h.testResultId,$t=h.testId;await xo(Q,de,$t,{show:!1}),h.decreaseSeleniumHubRetry(),h.decreaseRetryCount(),await h.startNewRetry()}return N&&!k&&!R&&await h.startNewRetry(),gt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:T,testRetryKey:H,totalRetries:h._totalRetryCount}),this.testResultId=h.testResultId,await m(h,O)}return await e()}catch(H){if(H instanceof Gt)return;gt.error("failed to process test result",{error:H}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
217
|
+
Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: network connectivity test failed)":""}`,n=f=>{let{DEVICE_OS_VERSION_TOO_LOW:h,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:v,TIMEOUT_ERROR:S,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Xa,T=f instanceof Error?f.message:f;return T.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),T.includes(Jg)||T.includes(S)?{errorType:En,reason:"timeout while getting device"}:T.includes(y)||T.includes(b)?{errorType:Ri,reason:"app doesn't exist on device"}:T.includes(v)?{errorType:Ri,reason:"app never started, check app permission or app activity"}:T.includes(h)?{errorType:Ri,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ri,reason:T}},o=(f,h)=>{let y=this.options.mode===Y.APPIUM?"device":"browser";if(!h&&M.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:RE,reason:r()};let v=f instanceof Error?f.message:f;if(v.includes(Jg))return{errorType:En,reason:`Test couldn't get ${y}`};if(v.includes(Yg))return{errorType:En,reason:"Test couldn't be started"};if(v.includes(Xg)){if(!this.testRunTimeout)return{errorType:En,reason:"Test timeout reached: test is too long"};let S=Su.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(S.asMinutes()),T=S.asSeconds(),I=b>0?` ${b} min`:"",C=T>0?` ${T} sec`:"";return{errorType:En,reason:`Test timeout reached (timeout:${I}${C}): test is too long`}}if(f instanceof ur&&f.type){if(f.type===vu)return{errorType:vu,reason:`Test couldn't get ${y} from grid - ${f.message}`};if(f.type===or)return{errorType:or,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===IE?{errorType:or,reason:`Session terminated, this is often caused to connection
|
|
218
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:or,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:or,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:or,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:xE,reason:v}},i=async(f,h)=>{var T;let y=await Ga();!y&&M.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),gt.warn("error on run",{err:f});let v=(T=this.userData)==null?void 0:T.projectId,{errorType:S,reason:b}=this.options.mode===Y.APPIUM?n(f):o(f,y);xo(v,this.testResultId,this.testId,{status:Ds.COMPLETED,success:!1,reason:b,errorType:S,testRetryKey:h.retryKey,setupStepResult:{status:Ds.COMPLETED,success:!1,reason:b,errorType:S}},h.remoteRunId),await t(CE(this.testId,this.testName,this.testResultId,b),h,f)},a=async(f,h)=>{var T;let y=this.testId,v=this.testResultId,S=(T=this.userData)==null?void 0:T.projectId,b=this.branch;if(!y||!v||!S||!b)return gt.warn("Test failed. Not enough data to recover results via API",{err:f}),i(f,h);try{let I=await Tr(y,v,S,b);if(gt.warn("Test failed. Got results via API",{err:f,testResult:Qg.default.omit(I,kE)}),I&&I.status===Ds.COMPLETED)return await t(I,h);throw f}catch(I){return I!==f&>.error("Failed to fetch test results from server",{testId:y,resultId:v,projectId:S,branch:b,err:I}),i(f,h)}},c=this.options.disableSockets||((p=this.options.lightweightMode)==null?void 0:p.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),l=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep),m=async(f,h)=>{try{await Promise.all([!l&&us.joinToRemoteStep(this.testResultId),!c&&Ct.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Y.APPIUM&&f.validateRunConfig();let y=await this.runTest(f,this.customExtensionLocalLocation,h),v=await t(y,f);return L("After onRunComplete"),v}catch(y){return a(y,f)}finally{l||us.unlistenToRemoteStep(this.testResultId)}},d=this.executionQueue.getNext();return d?(this.testId=d.testId,this.testName=d.testName,this.testResultId=d.testResultId,this.overrideTestConfigId=d.overrideTestConfigId,this.testRunConfig=d.runConfig,this.branch=d.branch,m(d)):this.onQueueCompleted()}}});var Ru,eh,ps,Iu=w(()=>{"use strict";j();Ru=E(require("p-retry"));j();B();z();eh=x("window-utils"),ps=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return eh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&eh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&typeof window.location<"u")r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new bt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Ru.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,Ru.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var xu,ds,Au=w(()=>{"use strict";B();xu=x("cookies-utils"),ds=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw xu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw xu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw xu.error("failed to remove cookie",{err:t}),t}}}});var Pu,xi,th=w(()=>{"use strict";Pu=E(require("p-retry")),xi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,Pu.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,Pu.default)(o,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function rh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return OE.warn("missing elementRect",nh.omit(s,"image")),{};let{elementRect:i}=s,a=await ms.default.read(Buffer.from(n[1],"base64")),c=i.left*r+o.left*r,l=i.top*r+o.top*r,m=i.width*r,d=i.height*r;c<0&&(m+=c,m=m<0?0:m,c=0),l<0&&(d+=l,d=d<0?0:d,l=0);let p=a.bitmap.width,g=a.bitmap.height;if(c+m>p&&(m=p-c),l+d>g&&(d=g-l),d<=0||m<=0)throw new Cu("height or width is equal or lower than zero");return{elementImage:await a.crop(c,l,m,d).getBase64Async(ms.default.MIME_PNG)}}async function _E(s,e){let t=await ms.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await ms.default.read(Buffer.from(o[1],"base64"));await new Promise((a,c)=>{t.composite(i,n.position.left,n.position.top,l=>{if(l){c(l);return}a()})})}return await t.getBase64Async(ms.default.MIME_PNG)}function LE(s,e){return _E(s,e)}async function DE(){}async function ME(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await DE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function sh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var nh,ms,OE,Cu,Ai,oh=w(()=>{"use strict";nh=E(require("lodash"));j();ms=E(require("jimp"));B();OE=x("image-capture-utils"),Cu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Ai=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await rh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:sh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return ME({screenImage:t.image,absoluteScreenHighlight:sh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>oe(250),o=Boolean(e);async function i(p,g){o?await t.scrollToPositionWithoutAnimation(p):await t.scrollToPosition(p),await n();let f=await r.takeScreenshot(),h=await rh({elementRect:g},f);return{position:{left:p.x+g.left,top:p.y+g.top},size:{width:g.width,height:g.height},image:h.elementImage}}async function a(p){let g=[];for(let f of p){let h=await i(f.scrollPos,f.cropData);g.push(h)}return g}function c(p,g){let f=Math.max(p.width,g.width),h=g.width,y=Math.max(p.height,g.height),v=g.height,S=Array.from({length:Math.ceil(f/h)},(T,I)=>({scrollX:Math.min(I*h,f-h),cropX:I*h-Math.min(I*h,f-h),cropW:h-(I*h-Math.min(I*h,f-h))})),b=Array.from({length:Math.ceil(y/v)},(T,I)=>({scrollY:Math.min(I*v,y-v),cropY:I*v-Math.min(I*v,y-v),cropH:v-(I*v-Math.min(I*v,y-v))}));return S.flatMap(T=>b.map(I=>({scrollPos:{x:T.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:T.cropX,width:T.cropW,height:I.cropH}})))}async function l(p,g){let f=await t.getCurrentScrollPosition(),h=c(p,g),y=await a(h);return await t.scrollToPosition(f),LE(p,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var ih,ah,Pi,Ci,ch=w(()=>{"use strict";ih=E(require("p-retry")),ah=E(require("semver"));j();B();Iu();th();oh();be();Pi=x("tab-service"),Ci=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Pi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=te();function c(l){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!l.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ps(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Ai(t,a,new xi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=ee(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),c=n(i),l=n(a),m=r.map(d=>o.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,r){let{tabMatcher:n}=ee();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(l=>o[l].url);if(this.exactUrlMatch(t,r,i))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,i,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Pi.error("failed to get url or title",{err:o})}}catch(n){Pi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await oe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Pi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ih.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=ah.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var a,c;let{tabMatcher:r,commonConstants:n}=ee();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((a=t.useCurrentTab)!=null&&a.call(t)){let l=await this.driver.getCurrentTabId();if(l)return l;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i;if(r){let l=this.getAllTabIds(e).map(m=>Object.assign({},this.getTabInfo(e,m),{tabId:m})).filter(m=>!m.isClosed);i=r.matchTabs(t,l)}else{let l=t.tabInfo;l?i=this.getAllTabIds(e).find(m=>{let d=this.getTabInfo(e,m);return this.isSameTab(e,d,l)}):i=this.getMainTabId(e)}if(!i)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===i)return i;try{return await this.switchTab(i,e),Object.assign(this.sessionTabs[e],{currentTab:i}),i}catch(l){let m=["no such window","no window found","the window could not be found"];if(l.message&&m.some(d=>l.message.toLowerCase().includes(d)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[i].isClosed=!0,this.getTabIdByTabInfo(e,t);throw l}}}});var ku,ki,Ou=w(()=>{"use strict";ku=class{select(){return console.log(`
|
|
219
219
|
internal error - cant use port selector in selenium!!!!
|
|
220
|
-
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},ki=new ku});var fs,_u=w(()=>{"use strict";Au();be();fs=class{constructor(e,t){this.driver=e;this._abortedSteps=[];this.cookieUtils=t||new ds(this.driver)}get sessionPlayerInit(){return ee()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,r=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(r)}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-o.x,y:e.y-o.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`,{value:n}=await this.driver.executeJS(r);return n}}});function uh(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=lh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let p="got empty result in frame result, not rejected from locate element player";throw NE.error(p),new Error(p)}let l=await s.switchToLocatedFrame(a),m=lh(l.value),d=this.getResultsFromCache(m);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:l.value,frameLocateResultUrl:d}}async locate(r,n,o,i,a,c){let l=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let m=await l.locate(r,o,r.targetId);m.isVisible=!0;let d=await l.handleLocateResult(m,c,r).catch(()=>{throw new Error("")}),{locatedElement:p}=i.data[r.targetId],f=(await s.getElementLocationWithPadding(p)).value||{top:0,left:0};d.frameOffset={top:o.frameOffset.top+f.top,left:o.frameOffset.left+f.left},l.addFrameDataToContext&&l.addFrameDataToContext(d.targetId,d.locateResult);let h=await this.foundFrameCallback(d,a,r.testimFrameId);return this.currentFrameHandler=h,h}async findFrame(r,n,o,i){let a=
|
|
220
|
+
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},ki=new ku});var fs,_u=w(()=>{"use strict";Au();be();fs=class{constructor(e,t){this.driver=e;this._abortedSteps=[];this.cookieUtils=t||new ds(this.driver)}get sessionPlayerInit(){return ee()}getTimeStamp(){return Date.now()}getTestimId(e){if(!e)return;let{locatorBuilderUtils:t}=this.sessionPlayerInit,r=t.TESTIM_ID_FIELD_NAME;return t.isEmptyResult(e)?t.EMPTY_RESULT_ID:e.getAttribute(r)}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async restoreNativeAlerts(){}executeOverloadNativeAlertsInFrame(){}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-o.x,y:e.y-o.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=`return ${this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t)}`,{value:n}=await this.driver.executeJS(r);return n}}});function uh(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=lh(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:c}=ee();if(c.isEmptyResult(a)){let p="got empty result in frame result, not rejected from locate element player";throw NE.error(p),new Error(p)}let l=await s.switchToLocatedFrame(a),m=lh(l.value),d=this.getResultsFromCache(m);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:l.value,frameLocateResultUrl:d}}async locate(r,n,o,i,a,c){let l=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let m=await l.locate(r,o,r.targetId);m.isVisible=!0;let d=await l.handleLocateResult(m,c,r).catch(()=>{throw new Error("")}),{locatedElement:p}=i.data[r.targetId],f=(await s.getElementLocationWithPadding(p)).value||{top:0,left:0};d.frameOffset={top:o.frameOffset.top+f.top,left:o.frameOffset.left+f.left},l.addFrameDataToContext&&l.addFrameDataToContext(d.targetId,d.locateResult);let h=await this.foundFrameCallback(d,a,r.testimFrameId);return this.currentFrameHandler=h,h}async findFrame(r,n,o,i){let a=M.flags.enableFrameSwitchOptimization.isEnabled(),l=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),m=1,d=l&&l.stepId===r.id&&l.results.length>m;if(a&&!d&&this.currentFrameHandler){let y=n.findIndex(v=>v.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let v=n.slice(y+1),S=0;for(let b of v)S++,this.currentFrameHandler=await this.locate(b,S,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let p=await i.getTopFrameHandler();p.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===p?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=p;let f=0,h=p;for(let y of n)f++,h=await this.locate(y,f,h,o,i,r);return h}}return e}var NE,UE,lh,ph=w(()=>{"use strict";B();Te();be();kr();NE=x("frame-locator"),UE="ELEMENT",lh=s=>s?s[UE]||s[Wt]:null});var Oi,Lu=w(()=>{"use strict";le();Oi=()=>{try{if(wp)return!1;if(require("inspector").url())return!0}catch{}return!1}});var W,ue=w(()=>{"use strict";be();W=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=o;this.locateElementPlayer=i;this.exportsTest=a;this.frameId=0}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return ee()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function BE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:M.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?M.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function jE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new dh.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,o,i,a){let{locatorBuilderUtils:c,codeSnippets:l,visibilityUtils:m,positionUtils:d}=ee();if(BE(n,m,d,s))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||c.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let f=[d.calculateElementMiddlePoint(r),d.calculateClickPoint(n.clickOffset,r)].filter(Boolean),h=l.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,f,!1,n),y;try{y=await s.execute(`return ${h}`)}catch(I){throw Pr.error("failed to execute getVisibilityCode",{err:I}),I}let{value:v}=y||{},S=v.elementVisibilityInfo||FE,[b,T]=v.elementsFromPointResults||[null,null];return m.checkElementVisibility(S,n,T,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=ee();await s.execute(r(t))}}}var dh,Pr,FE,Rn,mh=w(()=>{"use strict";ue();B();Te();be();dh=require("linkedom"),Pr=x("locate-step-action"),FE={opacity:1,clientRects:{}};Rn=class extends W{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return jE(e)}static getFrameIdByTestimFrameId(){throw Pr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw Pr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw Pr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw Pr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw Pr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw Pr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var fh={};G(fh,{scroll:()=>$E});var $E,gh=w(()=>{"use strict";$E=function(s,e,t,r,n,o,i,a){function c(S,b){if(!b)return{success:!1};elementScrollTo(b,S.x,S.y);let T=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-S.y)<1&&Math.abs(T-S.x)<1,actualX:T,actualY:I}}function l(S,b){if(!t)return{x:n,y:o};let T=getLocatedElement(b);if(r&&!T)return{x:S.scrollWidth,y:S.scrollHeight};if(!T)throw new Error("could not find target element");let I=T.getBoundingClientRect(),C=0,k=0,R=Math.max(window.innerHeight-(I.height+10),0),N=Math.max(window.innerWidth-(I.width+10),0);return C=a?S.scrollTop+I.top-Math.min(o,R):S.scrollTop,k=i?S.scrollLeft+I.left-Math.min(n,N):S.scrollLeft,{x:Math.round(k),y:Math.round(C)}}let m=!s,d=m?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!d)throw new Error("could not find target to scroll on");let p={top:d.scrollTop,left:d.scrollLeft},g=l(d,e),f=c(g,d);m&&!document.scrollingElement&&!f.success&&p.top===d.scrollTop&&p.left===d.scrollLeft&&(d=document.body,g=l(d,e),f=c(g,d));let h=f.actualX,y=f.actualY,v=getLocatedElement(e);if(t&&r&&!v)return{success:!1,expectedPosition:g};if(t){if(!v)throw new Error("could not find target to scroll to");let S=v.getBoundingClientRect();h=S.left,y=S.top}return{success:f.success,actualX:h,actualY:y}}});var _i,hh=w(()=>{"use strict";ue();_i=class extends W{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),c=this.driver.isFirefox()?function(d,p,g){d.scrollTo(p,g)}:function(d,p,g){d.scrollTop=g,d.scrollLeft=p},{scroll:l}=await Promise.resolve().then(()=>(gh(),fh)),m=`
|
|
221
221
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
222
222
|
const elementScrollTo = ${c.toString()};
|
|
223
223
|
const scroll = ${l.toString()};
|
|
224
224
|
return scroll.apply(null, arguments)
|
|
225
|
-
`;try{let d=await this.driver.executeJS(m,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:g,actualY:f}=d.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var yh,bh=w(()=>{"use strict";yh=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Th,wh=w(()=>{"use strict";Th=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(O){e({status:"done",result:O,success:!0})}function a(O){O||={},e({status:"failed",result:O,success:!1,keep:!0})}function c(O){return O!=null&&O.toLowerCase?(O=O.toLowerCase(),O==="text"?"text/plain":O==="url"?"text/uri-list":O):O}function l(){try{return new DataTransfer}catch{return{data:{},setData(D,$){o[c(D)]=$},getData(D){return o[c(D)]}}}}let m=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],p=m.concat(["drop","dragenter","dragover"]);function g(O){let D=O;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function f(O,D,$){let H=D.element,{dispatchDragEventsOnClosestDraggable:J}=$;if(m.includes(O.type)&&J){if(!H&&D.lastDraggedElement)return D.lastDraggedElement;let Q=g(H);if(Q)return D.lastDraggedElement=Q,Q}return H}function h(O,D,$){function H(ht,Cr,A){return A>ht&&A<Cr}let J=O.pointerPosition||{};if(D)return{x:J.originX||0,y:J.originY||0};let Q=$.getBoundingClientRect(),de=J.originX&&H(Q.left,Q.left+Q.width,J.originX)?J.originX:Q.left+Q.width/2,$t=J.originY&&H(Q.top,Q.top+Q.height,J.originY)?J.originY:Q.top+Q.height/2;return{x:de,y:$t}}function y(O,D,$){let H=(D==null?void 0:D.modifiers)||{},J=h(O,$.isDrag,$.element),Q=(D==null?void 0:D.button)||0,de=O.event;return d.includes(de)?S(de,H,J.x,J.y,Q):p.includes(de)?T(de,H,J.x,J.y):b(de,H,J.x,J.y,Q)}function v(O,D,$){return{screenX:0,screenY:0,clientX:D,clientY:$,ctrlKey:Boolean(O.ctrl),altKey:Boolean(O.alt),shiftKey:Boolean(O.shift),metaKey:Boolean(O.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(O,D,$,H,J){if(n){let de=v(D,$,H);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(O,de)}let Q=document.createEvent("PointerEvent");return Q.initPointerEvent(O,!0,!0,document.defaultView,1,0,0,$,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Q}function b(O,D,$,H,J){let Q=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Q.initMouseEvent(O,!0,!0,document.defaultView,1,0,0,$,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement),Q}function T(O,D,$,H){if(O==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(O,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let J=v(D,$,H),Q=new window.DragEvent(O,J);return Object.defineProperties(Q,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Q}function I(O,D,$){let H=f(O,D,$);H==null||H.dispatchEvent(O)}function C(O,D){function $(){return O.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return $()}function k(O,D,$){if($){let H=Math.min($.timeStamp-D.timeStamp,40);setTimeout(()=>{R(O)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function R(O){let D,$=O.events[O.eventIndex],H=O.events[++O.eventIndex];try{O.element=getLocatedElement($.locatedElement),D=y($,s,O)}catch(J){return a(`exception in get event in drag step:${J.message}`)}if(C($,O))return k(O,$,H);if(D)try{I(D,O,$)}catch(J){return a(`exception in executeEvent in drag step:${J.message}`)}else return a(`cannot execute event ${$.event}`);k(O,$,H)}let M={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{R(M)}catch(O){a(O)}},0)}});var vh={};G(vh,{doClick:()=>WE});var WE,Eh=w(()=>{"use strict";WE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,T){var k;function I(R){function M(){return o(R).find($=>[...$.classList||[]].includes("Select-control"))}function O(){let $=M();return $?$.querySelector("input"):null}let D=O();D==null||D.focus()}let C=(k=b.quirks)==null?void 0:k.isReactSelect;T.type==="mousedown"&&C&&I(b.element)}function n(b,T){var C;let I=(C=b.quirks)==null?void 0:C.isCKEditorFrame;T.type==="click"&&I&&document.body.focus()}function o(b){let T=[];for(;b!=null&&b.parentNode;)T.push(b),b=b.parentNode;return T}function i(b){let T={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(T)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function l(b){let T={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=g("mousemove",T,C,k,0);b.dispatchEvent(O)}function m(b,T){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{},k=T.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,M=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:M}}function d(b,T,I){return{screenX:0,screenY:0,clientX:T,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(b,T,I,C){if(!window.PointerEvent)return;let k=d(T,I,C);return k.pointerType="mouse",k.isPrimary=!0,new window.PointerEvent(b,k)}function g(b,T,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement),R}function f(b,T){let I=["pointerup","pointerdown","pointermove"],C=T.modifiers||{},k=m(b,T.element),R=T.button||0,M=b.event;return I.includes(M)?p(M,C,k.x,k.y):g(M,C,k.x,k.y,R)}function h(){var T;let b=document.activeElement;for(;(T=b.shadowRoot)!=null&&T.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(T=>{try{return f(T,b)}catch{return}}).filter(Boolean).forEach(T=>{b.element.dispatchEvent(T),r(b,T),n(b,T)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),T=S.quirks,I=T==null?void 0:T.isReactSelect,C=T==null?void 0:T.isCKEditorFrame;!I&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Sh={};G(Sh,{doDragPath:()=>GE});var GE,Rh=w(()=>{"use strict";GE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function c(b){let T={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=p("mousemove",T,C,k,0);b.dispatchEvent(O)}function l(b,T){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{};if(S.isDrag)return{x:C.originX||0,y:C.originY||0};let k=T.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,M=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:M}}function m(b,T,I){return{screenX:0,screenY:0,clientX:T,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,T,I,C,k){if(r){let M=m(T,I,C);return M.pointerType="mouse",M.isPrimary=!0,new window.PointerEvent(b,M)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function p(b,T,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement),R}function g(b,T){let I=["pointerup","pointerdown","pointermove"],C=T.modifiers||{},k=l(b,T.element),R=T.button||0,M=b.event;return I.includes(M)?d(M,C,k.x,k.y,R):p(M,C,k.x,k.y,R)}function f(b,T){function I(){return b.event==="click"&&T.isDrag&&!T.allEventsOnSameElement}return I()}function h(b,T,I){try{let C=g(T.events[b],T);f(C,T)||T.element.dispatchEvent(C)}catch{}if(b+1===T.events.length)I();else{let C=Math.min(T.events[b+1].timeStamp-T.events[b].timeStamp,n);setTimeout(()=>{h(b+1,T,I)},C)}}function y(b,T){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T()})}let S={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var In,Li,Ih=w(()=>{"use strict";In=E(require("lodash"));ue();bh();Te();wh();Li=class extends W{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Eh(),vh)),Promise.resolve().then(()=>(yn(),hn))]),l=`
|
|
225
|
+
`;try{let d=await this.driver.executeJS(m,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(d!=null&&d.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:p,actualX:g,actualY:f}=d.value;return p?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,g,f)}}}catch{return{errorType:o.SCROLL_ACTION_FAILURE,success:!1}}}scrollOnDocument(e,t){return this.scroll(t,e)}scrollOnElement(e,t){return this.scroll(t,e,this.getTarget().locatedElement)}execute(){let{context:e,step:t}=this,r=t.isScrollToElement?e.data.scrollToElement.locatedElement:null;return t.element.isDocument?this.scrollOnDocument(t,r):this.scrollOnElement(t,r)}}});var yh,bh=w(()=>{"use strict";yh=function(s){let e={};function t(a){return a!=null&&a.toLowerCase?(a=a.toLowerCase(),a==="text"?"text/plain":a==="url"?"text/uri-list":a):a}let r={data:{},setData(a,c){e[t(a)]=c},getData(a){return e[t(a)]}},n=getLocatedElement(s.fromLocatedElement),o=getLocatedElement(s.toLocatedElement);if(!n)throw new Error("from element not found");if(!o)throw new Error("to element not found");let i=function(a,c){let l=document.createEvent("CustomEvent");l.initCustomEvent(c,!0,!0,null),Object.assign(l,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(l):a.fireEvent&&a.fireEvent(`on${c}`,l)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var Th,wh=w(()=>{"use strict";Th=function(s,e){let t=typeof MouseEvent=="function",r=typeof DragEvent=="function",n=typeof PointerEvent=="function",o={};window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function i(O){e({status:"done",result:O,success:!0})}function a(O){O||={},e({status:"failed",result:O,success:!1,keep:!0})}function c(O){return O!=null&&O.toLowerCase?(O=O.toLowerCase(),O==="text"?"text/plain":O==="url"?"text/uri-list":O):O}function l(){try{return new DataTransfer}catch{return{data:{},setData(D,$){o[c(D)]=$},getData(D){return o[c(D)]}}}}let m=["drag","dragstart","dragend"],d=["pointerup","pointerdown","pointermove"],p=m.concat(["drop","dragenter","dragover"]);function g(O){let D=O;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function f(O,D,$){let H=D.element,{dispatchDragEventsOnClosestDraggable:J}=$;if(m.includes(O.type)&&J){if(!H&&D.lastDraggedElement)return D.lastDraggedElement;let Q=g(H);if(Q)return D.lastDraggedElement=Q,Q}return H}function h(O,D,$){function H(ht,Cr,A){return A>ht&&A<Cr}let J=O.pointerPosition||{};if(D)return{x:J.originX||0,y:J.originY||0};let Q=$.getBoundingClientRect(),de=J.originX&&H(Q.left,Q.left+Q.width,J.originX)?J.originX:Q.left+Q.width/2,$t=J.originY&&H(Q.top,Q.top+Q.height,J.originY)?J.originY:Q.top+Q.height/2;return{x:de,y:$t}}function y(O,D,$){let H=(D==null?void 0:D.modifiers)||{},J=h(O,$.isDrag,$.element),Q=(D==null?void 0:D.button)||0,de=O.event;return d.includes(de)?S(de,H,J.x,J.y,Q):p.includes(de)?T(de,H,J.x,J.y):b(de,H,J.x,J.y,Q)}function v(O,D,$){return{screenX:0,screenY:0,clientX:D,clientY:$,ctrlKey:Boolean(O.ctrl),altKey:Boolean(O.alt),shiftKey:Boolean(O.shift),metaKey:Boolean(O.meta),bubbles:!0,cancelable:!0,composed:!0}}function S(O,D,$,H,J){if(n){let de=v(D,$,H);return de.pointerType="mouse",de.isPrimary=!0,new window.PointerEvent(O,de)}let Q=document.createEvent("PointerEvent");return Q.initPointerEvent(O,!0,!0,document.defaultView,1,0,0,$,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Q}function b(O,D,$,H,J){let Q=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Q.initMouseEvent(O,!0,!0,document.defaultView,1,0,0,$,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),J,document.body?document.body.parentNode:document.documentElement),Q}function T(O,D,$,H){if(O==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=l()),!r){let de=document.createEvent("CustomEvent");return de.initCustomEvent(O,!0,!0,null),Object.assign(de,{dataTransfer:window.TSTA.dataTransfer}),de}let J=v(D,$,H),Q=new window.DragEvent(O,J);return Object.defineProperties(Q,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Q}function I(O,D,$){let H=f(O,D,$);H==null||H.dispatchEvent(O)}function C(O,D){function $(){return O.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return $()}function k(O,D,$){if($){let H=Math.min($.timeStamp-D.timeStamp,40);setTimeout(()=>{R(O)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function R(O){let D,$=O.events[O.eventIndex],H=O.events[++O.eventIndex];try{O.element=getLocatedElement($.locatedElement),D=y($,s,O)}catch(J){return a(`exception in get event in drag step:${J.message}`)}if(C($,O))return k(O,$,H);if(D)try{I(D,O,$)}catch(J){return a(`exception in executeEvent in drag step:${J.message}`)}else return a(`cannot execute event ${$.event}`);k(O,$,H)}let N={eventIndex:0,allEventsOnSameElement:s.allEventsOnSameElement,events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement};setTimeout(()=>{try{R(N)}catch(O){a(O)}},0)}});var vh={};G(vh,{doClick:()=>WE});var WE,Eh=w(()=>{"use strict";WE=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,T){var k;function I(R){function N(){return o(R).find($=>[...$.classList||[]].includes("Select-control"))}function O(){let $=N();return $?$.querySelector("input"):null}let D=O();D==null||D.focus()}let C=(k=b.quirks)==null?void 0:k.isReactSelect;T.type==="mousedown"&&C&&I(b.element)}function n(b,T){var C;let I=(C=b.quirks)==null?void 0:C.isCKEditorFrame;T.type==="click"&&I&&document.body.focus()}function o(b){let T=[];for(;b!=null&&b.parentNode;)T.push(b),b=b.parentNode;return T}function i(b){let T={status:"done",result:b,success:!0,...S.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(T)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function c(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function l(b){let T={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=g("mousemove",T,C,k,0);b.dispatchEvent(O)}function m(b,T){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{},k=T.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,N=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:N}}function d(b,T,I){return{screenX:0,screenY:0,clientX:T,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function p(b,T,I,C){if(!window.PointerEvent)return;let k=d(T,I,C);return k.pointerType="mouse",k.isPrimary=!0,new window.PointerEvent(b,k)}function g(b,T,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement),R}function f(b,T){let I=["pointerup","pointerdown","pointermove"],C=T.modifiers||{},k=m(b,T.element),R=T.button||0,N=b.event;return I.includes(N)?p(N,C,k.x,k.y):g(N,C,k.x,k.y,R)}function h(){var T;let b=document.activeElement;for(;(T=b.shadowRoot)!=null&&T.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(T=>{try{return f(T,b)}catch{return}}).filter(Boolean).forEach(T=>{b.element.dispatchEvent(T),r(b,T),n(b,T)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let S={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!S.element){a("element not found");return}c(S.element),l(S.element);try{y(S);let b=h(),T=S.quirks,I=T==null?void 0:T.isReactSelect,C=T==null?void 0:T.isCKEditorFrame;!I&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var Sh={};G(Sh,{doDragPath:()=>GE});var GE,Rh=w(()=>{"use strict";GE=function(s,e){let t=typeof Event=="function",r=typeof PointerEvent=="function",n=40;window.__unloadNavigator=o,window.addEventListener("unload",window.__unloadNavigator);function o(b){e({status:"done",result:b,success:!0})}function i(b){b||="",e({status:"failed",result:b,success:!1})}function a(b){let T=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");T.initEvent("mouseover",!0,!0),b.dispatchEvent(T)}function c(b){let T={},I=b.getBoundingClientRect(),C=I.left+I.width/2,k=I.top+I.height/2,O=p("mousemove",T,C,k,0);b.dispatchEvent(O)}function l(b,T){function I(O,D,$){return $>O&&$<D}let C=b.pointerPosition||{};if(S.isDrag)return{x:C.originX||0,y:C.originY||0};let k=T.getBoundingClientRect(),R=C.originX&&I(k.left,k.left+k.width,C.originX)?C.originX:k.left+k.width/2,N=C.originY&&I(k.top,k.top+k.height,C.originY)?C.originY:k.top+k.height/2;return{x:R,y:N}}function m(b,T,I){return{screenX:0,screenY:0,clientX:T,clientY:I,ctrlKey:Boolean(b.ctrl),altKey:Boolean(b.alt),shiftKey:Boolean(b.shift),metaKey:Boolean(b.meta),bubbles:!0,cancelable:!0,composed:!0}}function d(b,T,I,C,k){if(r){let N=m(T,I,C);return N.pointerType="mouse",N.isPrimary=!0,new window.PointerEvent(b,N)}let R=document.createEvent("PointerEvent");return R.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),R}function p(b,T,I,C,k){let R=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return R.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(T.ctrl),Boolean(T.alt),Boolean(T.shift),Boolean(T.meta),k,document.body?document.body.parentNode:document.documentElement),R}function g(b,T){let I=["pointerup","pointerdown","pointermove"],C=T.modifiers||{},k=l(b,T.element),R=T.button||0,N=b.event;return I.includes(N)?d(N,C,k.x,k.y,R):p(N,C,k.x,k.y,R)}function f(b,T){function I(){return b.event==="click"&&T.isDrag&&!T.allEventsOnSameElement}return I()}function h(b,T,I){try{let C=g(T.events[b],T);f(C,T)||T.element.dispatchEvent(C)}catch{}if(b+1===T.events.length)I();else{let C=Math.min(T.events[b+1].timeStamp-T.events[b].timeStamp,n);setTimeout(()=>{h(b+1,T,I)},C)}}function y(b,T){h(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T()})}let S={eventIndex:0,element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,eventType:s.eventType,eventData:s.eventData,stepId:s.id,testResultId:s.testResultId,quirks:s.quirks,isDoubleClick:s.isDoubleClick,isDrag:s.isDrag,useRecordedMousedown:s.useRecordedMousedown,trackActiveElement:s.trackActiveElement,allEventsOnSameElement:s.allEventsOnSameElement};if(!S.element){i("element not found");return}a(S.element),c(S.element),y(S,()=>{o()})}});var In,Li,Ih=w(()=>{"use strict";In=E(require("lodash"));ue();bh();Te();wh();Li=class extends W{getDnDRectsAndOffsets(e,t,r,n){let o=this.stepActionUtils.getClickOffset(r,e.rectWithoutFrameOffset),i=this.stepActionUtils.getClickOffset(n,t.rectWithoutFrameOffset);return{fromRect:e.rectWithoutFrameOffset,fromX:o.x,fromY:o.y,toRect:t.rectWithoutFrameOffset,toX:i.x,toY:i.y}}async clickJs(){var m;let{step:e,context:t}=this,r=this.getTarget(),n=t.data.timeToPlayStep+3e3,o=e.events;if(!(o!=null&&o.length))return{success:!1,reason:"Malformed step: missing recorded events"};let i={isRoot:r.isRoot,locatedElement:r.locatedElement,events:o,quirks:e.quirks,modifiers:e.modifiers,button:e.button},[{doClick:a},{dispatchFocus:c}]=await Promise.all([Promise.resolve().then(()=>(Eh(),vh)),Promise.resolve().then(()=>(yn(),hn))]),l=`
|
|
226
226
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
227
227
|
var dispatchFocus = ${c.toString()};
|
|
228
228
|
var doClick = ${a.toString()};
|
|
@@ -234,7 +234,7 @@ Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: n
|
|
|
234
234
|
var dispatchFocus = ${c.toString()};
|
|
235
235
|
var doDragPath = ${a.toString()};
|
|
236
236
|
return doDragPath.apply(null, arguments);
|
|
237
|
-
`;try{return(d=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(p){return{success:!1,reason:p.message,exception:p}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:o}=e,i={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(
|
|
237
|
+
`;try{return(d=(await this.driver.executeCodeAsync(l,n,i)).value)!=null&&d.success?{success:!0}:{success:!1}}catch(p){return{success:!1,reason:p.message,exception:p}}}async chooseAndRunAction(){let e=this.getTarget(),{locatedElement:t,seleniumElement:r,rectWithoutFrameOffset:n,rect:o}=e,i={frameOffset:{x:o.left-n.left,y:o.top-n.top},rect:n,clickOffset:this.stepActionUtils.getClickOffset(this.step.element.clickOffset,n)};if(M.flags.skipFileInputClicks.isEnabled()&&e.tagName==="INPUT"&&(e.elementSymbol.includes('type="file"')||e.elementSymbol.includes("type='file'")||e.elementSymbol.includes("type=file")))return{keep:!0,success:"skipped",reason:"Clicking on input type=file is disabled"};if(this.step.isDoubleClick){let m={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,m,i)}if(this.step.isDrag){if(this.step.toElement){let m=this.context.data.toElement;if(this.step.isHTML5Drag){if(M.flags.usePortedHtml5DragDrop.isEnabled()){let f=this.generateHTML5DragEventSequence(),h=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),v={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:f,eventData:{modifiers:this.step.modifiers,button:this.step.button},quirks:this.step.quirks,isDrag:this.step.isDrag,useRecordedMousedown:this.step.useRecordedMousedown,allEventsOnSameElement:this.step.allEventsOnSameElement,elementToFocusLocatedElement:y.elementToFocusLocatedElement,trackActiveElement:this.step.trackActiveElement,locatedElement:y.locatedElement,isRoot:y.isRoot},S=`
|
|
238
238
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
239
239
|
var dnd = ${Th.toString()};
|
|
240
240
|
var eventData = arguments[0];
|
|
@@ -245,14 +245,14 @@ Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: n
|
|
|
245
245
|
var dnd = ${yh.toString()};
|
|
246
246
|
var eventData = arguments[0];
|
|
247
247
|
return dnd.call(null, eventData);
|
|
248
|
-
`,g={fromLocatedElement:t,toLocatedElement:m.locatedElement};return this.driver.executeJS(p,g)}let d=this.getDnDRectsAndOffsets(e,m,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,m.seleniumElement,d)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,i):this.driver.leftClick(r,i)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var xn,xh=w(()=>{"use strict";ue();xn=class extends W{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:o}}=this,i=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(i),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ah,VE,Di,Ph=w(()=>{"use strict";Ah=E(require("lodash"));ue();B();VE=x("evaluate-expression-step-action"),Di=class extends W{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{VE.info("runner running incoming params evaluation");let o=t.incomingParams||{};Ah.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),d=Function.apply(Function,i.concat([l]))(...a);return t.data[e.targetName]=d,t.data[e.targetId]=d,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:d,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var Ch={};G(Ch,{setText:()=>HE});var HE,kh=w(()=>{"use strict";HE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){$t()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(A){try{if(!t)return;let _=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return A.eventData&&(_.data=A.eventData.data),_}catch{}}function c(A){try{let _=document.createEvent("TextEvent");_.data=A.eventData.data;let F=1,q=A.eventData.locale||"en-US";return _.initTextEvent("textInput",!0,!0,window,A.eventData.data,F,q),_}catch{}}function l(A){return a(A)||c(A)}function m(A,_,F){try{return new KeyboardEvent(A,{bubbles:!0,cancelable:!0,location:_.location||0,key:_.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function d(A,_,F){try{let q=document.createEvent("KeyboardEvent");return q.initKeyEvent(A,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),_.key||"",0),q}catch{}}function p(A,_,F){try{let q=document.createEvent("Events");return q.initEvent(A,!0,!0),Object.assign(q,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:_.key||""}),q}catch{}}function g(A,_,F){return m(A,_,F)||d(A,_,F)||p(A,_,F)}function f(A){if(!o.has(A.event))return null;let _=A.eventData,F=_.modifiers||{},q=g(A.event,_,F);return Object.defineProperties(q,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(q,{_keyCode_:_.keyCode,_charCode_:_.charCode||0}),q}function h(A){return A.event==="textInput"?l(A):f(A)}function y(A,_){return(()=>{var q;return A.event==="textInput"&&!((q=_.quirks)!=null&&q.isAuth0Form)})()}function v(A,_){return A.event==="keyup"&&_.event==="keydown"?i:0}function S(A,_){let F=v(A,_);return Math.min(_.timeStamp-A.timeStamp,F)}function b(A){let _=Object.getOwnPropertyDescriptor(A,"value");if(!_)return;let F=A.value;A.value=`${F}#`,_.configurable&&delete A.value,A.value=F;let q=document.createEvent("HTMLEvents");q.initEvent("input",!0,!1),A.dispatchEvent(q),Object.defineProperty(A,"value",_)}function T(A){if(H(A.element))try{if(b(A.element),t)A.element.dispatchEvent(new Event("change"));else{let _=document.createEvent("HTMLEvents");_.initEvent("change",!1,!0),A.element.dispatchEvent(_)}}catch{}}function I(A,_,F){F?setTimeout(()=>{$(A)},S(_,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T(A),$t())}function C(A,_){return(A==="change"||A==="blur")&&_.element.tagName==="OPTION"}function k(A,_,F){return C(A.type,_)?_.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):_.element}function R(A,_){let F=A.firstChild,q;for(;F;){if(F.nodeType===3){if(_.offset--<=0)return F}else if(F.nodeType===1&&(q=R(F,_),q))return q;F=F.nextSibling}return null}function
|
|
248
|
+
`,g={fromLocatedElement:t,toLocatedElement:m.locatedElement};return this.driver.executeJS(p,g)}let d=this.getDnDRectsAndOffsets(e,m,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,m.seleniumElement,d)}return this.dragPathJs()}let c=this.driver.isSafari()&&this.step.button===2,l=this.driver.isSafari()&&e.tagName==="SELECT";return l?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!l&&(!this.step.nativeEvents||c)?this.clickJs():this.step.button===2?this.driver.rightClick(r,i):this.driver.leftClick(r,i)}async performAction(){let e=await this.chooseAndRunAction();if(!e.status&&e.value&&e.value.keep&&(e=e.value),e.keep)return delete e.keep,e}addDragendIfNeeded(e){if(e.some(r=>r.event==="dragend"))return e;let t={event:"dragend",eventInfo:{detail:0},pointerPosition:this.getToElementPosition()};return e.concat(t)}getToElementPosition(){var t,r;if(!((r=(t=this.context.data)==null?void 0:t.toElement)!=null&&r.rect))return;let{rect:e}=this.context.data.toElement;return{originX:e.left+e.width/2,originY:e.top+e.height/2}}addDragOverBeforeDragEnd(e){let t=e.findIndex(n=>["dragend","drop"].includes(n.event)),r=e[t-1];if(!r||r.event!=="dragover"){let n={event:"dragover",eventInfo:{detail:0},pointerPosition:this.getToElementPosition(),fireOnTarget:!0};e.splice(t,0,n)}else Object.assign(r,{fireOnTarget:!0});return e}fixEventSequence(e){let t=this.addDragendIfNeeded(e);return this.addDragOverBeforeDragEnd(t)}addElementLocatedElementToDragEvents(e,t,r){let n=o=>o.fireOnTarget||["drop","dragenter"].includes(o.event);return e.forEach(o=>Object.assign(o,{locatedElement:n(o)?r:t})),e}generateHTML5DragEventSequence(){let e=this.context.data.targetId,t=this.context.data.toElement,r=this.step.events.filter(n=>n.event!=="mousemove"&&n.event!=="pointermove");return r=this.fixEventSequence(r),r=this.addElementLocatedElementToDragEvents(r,e.locatedElement,t.locatedElement),this.step.dispatchDragEventsOnClosestDraggable&&r.forEach(n=>Object.assign(n,{dispatchDragEventsOnClosestDraggable:!0})),r}}});var xn,xh=w(()=>{"use strict";ue();xn=class extends W{async performAction(){let{step:e,context:t,sessionPlayerInit:{stepParamExpressionEvaluator:r,utils:n,commonConstants:o}}=this,i=this.getTarget();try{let a=await this.stepActionUtils.extractTargetText(i),{evaluatedText:c}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(c,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(c),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:c.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ah,VE,Di,Ph=w(()=>{"use strict";Ah=E(require("lodash"));ue();B();VE=x("evaluate-expression-step-action"),Di=class extends W{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{VE.info("runner running incoming params evaluation");let o=t.incomingParams||{};Ah.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],l=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),d=Function.apply(Function,i.concat([l]))(...a);return t.data[e.targetName]=d,t.data[e.targetId]=d,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:d,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var Ch={};G(Ch,{setText:()=>HE});var HE,kh=w(()=>{"use strict";HE=function(s,e){let t=typeof Event=="function",r=s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),n={eventIndex:0,element:r,events:s.events,eventType:s.eventType,quirks:s.quirks};if(!r)throw new Error("element not found");window.__unloadNavigator=function(){$t()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(A){try{if(!t)return;let _=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return A.eventData&&(_.data=A.eventData.data),_}catch{}}function c(A){try{let _=document.createEvent("TextEvent");_.data=A.eventData.data;let F=1,q=A.eventData.locale||"en-US";return _.initTextEvent("textInput",!0,!0,window,A.eventData.data,F,q),_}catch{}}function l(A){return a(A)||c(A)}function m(A,_,F){try{return new KeyboardEvent(A,{bubbles:!0,cancelable:!0,location:_.location||0,key:_.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function d(A,_,F){try{let q=document.createEvent("KeyboardEvent");return q.initKeyEvent(A,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),_.key||"",0),q}catch{}}function p(A,_,F){try{let q=document.createEvent("Events");return q.initEvent(A,!0,!0),Object.assign(q,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:_.key||""}),q}catch{}}function g(A,_,F){return m(A,_,F)||d(A,_,F)||p(A,_,F)}function f(A){if(!o.has(A.event))return null;let _=A.eventData,F=_.modifiers||{},q=g(A.event,_,F);return Object.defineProperties(q,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(q,{_keyCode_:_.keyCode,_charCode_:_.charCode||0}),q}function h(A){return A.event==="textInput"?l(A):f(A)}function y(A,_){return(()=>{var q;return A.event==="textInput"&&!((q=_.quirks)!=null&&q.isAuth0Form)})()}function v(A,_){return A.event==="keyup"&&_.event==="keydown"?i:0}function S(A,_){let F=v(A,_);return Math.min(_.timeStamp-A.timeStamp,F)}function b(A){let _=Object.getOwnPropertyDescriptor(A,"value");if(!_)return;let F=A.value;A.value=`${F}#`,_.configurable&&delete A.value,A.value=F;let q=document.createEvent("HTMLEvents");q.initEvent("input",!0,!1),A.dispatchEvent(q),Object.defineProperty(A,"value",_)}function T(A){if(H(A.element))try{if(b(A.element),t)A.element.dispatchEvent(new Event("change"));else{let _=document.createEvent("HTMLEvents");_.initEvent("change",!1,!0),A.element.dispatchEvent(_)}}catch{}}function I(A,_,F){F?setTimeout(()=>{$(A)},S(_,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),T(A),$t())}function C(A,_){return(A==="change"||A==="blur")&&_.element.tagName==="OPTION"}function k(A,_,F){return C(A.type,_)?_.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):_.element}function R(A,_){let F=A.firstChild,q;for(;F;){if(F.nodeType===3){if(_.offset--<=0)return F}else if(F.nodeType===1&&(q=R(F,_),q))return q;F=F.nextSibling}return null}function N(A,_){if(!(!A||!_)){if(!isNaN(_.start))Object.assign(A,{selectionStart:_.start,selectionEnd:_.end});else if(!isNaN(_.nodeOffset)){let F;if(A.firstChild?F=R(A,{offset:_.nodeOffset}):F=A,F){let q=window.getSelection(),st=document.createRange();try{q.removeAllRanges(),st.setStart(F,_.textOffset),st.setEnd(F,_.textOffset),q.addRange(st)}catch{}}}}}function O(A,_){return A==="submit"&&Boolean(_.action)}function D(A,_,F){if(_.isFocusable&&_.isSelectable(A)&&A.type!=="submit")try{N(_.element,F.eventData.selection)}catch{}let q=k(A,_,F);if(!q)throw new Error("could not find element");O(A.type,q)?q.submit():q.dispatchEvent(A)}function $(A){let _,F=A.events[A.eventIndex],q=A.events[++A.eventIndex];try{_=h(F)}catch(st){return ht(`exception in get event in text step:${st.message}`)}if(y(F,A))return I(A,F,q);if(_)try{D(_,A,F)}catch(st){return ht(`exception in executeEvent in text step:${st.message}`)}else if(A.noEventExecuter)A.noEventExecuter(A,F);else return ht(`cannot execute event ${F.event}`);I(A,F,q)}function H(A){let _=A.tagName;return _==="INPUT"||_==="TEXTAREA"}function J(A){return A.getAttribute?Boolean(A.getAttribute("contenteditable")==="true"):!1}function Q(A,_){if(H(A.element)){A.element.value=_.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),A.element.dispatchEvent(F)}else A.isContentEditable&&(A.element.innerHTML=_.eventData.text)}function de(){var _;let A=document.activeElement;for(;(_=A.shadowRoot)!=null&&_.activeElement;)A=A.shadowRoot.activeElement;return A}function $t(A){let _={status:"done",result:A,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(_)}function ht(A){A||="";let _={status:"failed",result:A,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(_)}try{let A=H(n.element);n.isContentEditable=J(n.element),!A&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=A||n.isContentEditable,n.isSelectable=_=>_.type!=="keyup",n.noEventExecuter=Q}catch(A){ht(`exception in set text step:${A.message}`);return}let Cr=de();dispatchFocus(s.elementToFocusLocatedElement,Cr),$(n)}});var Mi,Oh=w(()=>{"use strict";ue();j();Mi=class extends W{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(Oe(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var f;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:c}=o.codeSnippets;if(i.isDraftEditor&&c)return this.driver.executeJS(c(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let l={eventType:t,events:e,quirks:r,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:m},{dispatchFocus:d}]=await Promise.all([Promise.resolve().then(()=>(kh(),Ch)),Promise.resolve().then(()=>(yn(),hn))]),p=`
|
|
249
249
|
var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
|
|
250
250
|
var dispatchFocus = ${d};
|
|
251
251
|
var setText = ${m.toString()};
|
|
252
252
|
var eventData = arguments[0];
|
|
253
253
|
var done = arguments[1];
|
|
254
254
|
return setText.call(null, eventData, done);
|
|
255
|
-
`,g=await this.driver.executeCodeAsync(p,a,l);return{success:Boolean((f=g.value)==null?void 0:f.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Oe(t.seleniumElement),e[r]),r<e.length-1&&await oe(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Oe(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var _h={};G(_h,{runCode:()=>qE});var qE,Lh=w(()=>{"use strict";qE=function(s,e){var m;function t(d,p){let g=`data-testim-${d}`,f="Native sessionStorage is not available";function h(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(h))throw new Error(f);let y=JSON.parse(window.sessionStorage.getItem(g)||"{}"),v=Object.assign({},y,p);window.sessionStorage.setItem(g,JSON.stringify(v))}catch(y){let v=y.message.toLowerCase().includes("quota"),S=y.message===f;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||v||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let T=JSON.parse(b.getAttribute(g)||"{}"),I=Object.assign({},T,p);if(b.setAttribute(g,JSON.stringify(I)),v||S)try{window.sessionStorage.removeItem(g)}catch{}return}throw y}}function r(d){return d.function?d.function.args.map(p=>p!=null&&p.locatedElement?getLocatedElement(p.locatedElement):p):d.directParams.map(p=>p.selector?document.querySelector(p.selector):p.value).concat(d.otherParams)}function n(d,p){function g(){return d.apply(null,p)}return g.prototype=d.prototype,new g}let o={},i={},a={},c=s.functionParams,l=s.transactionId;try{let d=r(s);d.push(o,i,a);let p=((m=s.function)==null?void 0:m.params)||c,f=(e||n(Function,p)).apply(null,d);typeof Promise<"u"&&f instanceof Promise?(t(l,{type:"promise"}),f.then(h=>{t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})},h=>{t(l,{status:"failed",success:!1,result:{resultValue:h.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:f,exports:o,exportsTest:i,exportsGlobal:a}})}catch(d){t(l,{status:"failed",success:!1,result:{resultValue:d.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Ni,Du,ir,Ui=w(()=>{"use strict";Ni=E(require("lodash"));j();ue();B();Te();Du=x("base-js-step-action"),ir=class extends W{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=
|
|
255
|
+
`,g=await this.driver.executeCodeAsync(p,a,l);return{success:Boolean((f=g.value)==null?void 0:f.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(Oe(t.seleniumElement),e[r]),r<e.length-1&&await oe(this.step.delayBetweenChars||0)}async setValueAppendNative(){let e=[],t=this.context,r=this.getTarget();if(r!=null&&r.seleniumElement)return this.step.delayBetweenChars?this.setTextDelayed():(e.push(Array.from(t.stepText)),this.driver.elementIdValue(Oe(r.seleniumElement),e));throw new Error("missing selenium element")}async performAction(){let e=this.getTarget(),t=this.driver.isSafari()&&e.locatedElement&&e.locatedElement.shadowPath&&Array.isArray(e.locatedElement.shadowPath)&&e.locatedElement.shadowPath.length>1;return this.step.nativeEvents&&!t?this.setValueNative():this.setValueJS()}}});var _h={};G(_h,{runCode:()=>qE});var qE,Lh=w(()=>{"use strict";qE=function(s,e){var m;function t(d,p){let g=`data-testim-${d}`,f="Native sessionStorage is not available";function h(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(h))throw new Error(f);let y=JSON.parse(window.sessionStorage.getItem(g)||"{}"),v=Object.assign({},y,p);window.sessionStorage.setItem(g,JSON.stringify(v))}catch(y){let v=y.message.toLowerCase().includes("quota"),S=y.message===f;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||v||S){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let T=JSON.parse(b.getAttribute(g)||"{}"),I=Object.assign({},T,p);if(b.setAttribute(g,JSON.stringify(I)),v||S)try{window.sessionStorage.removeItem(g)}catch{}return}throw y}}function r(d){return d.function?d.function.args.map(p=>p!=null&&p.locatedElement?getLocatedElement(p.locatedElement):p):d.directParams.map(p=>p.selector?document.querySelector(p.selector):p.value).concat(d.otherParams)}function n(d,p){function g(){return d.apply(null,p)}return g.prototype=d.prototype,new g}let o={},i={},a={},c=s.functionParams,l=s.transactionId;try{let d=r(s);d.push(o,i,a);let p=((m=s.function)==null?void 0:m.params)||c,f=(e||n(Function,p)).apply(null,d);typeof Promise<"u"&&f instanceof Promise?(t(l,{type:"promise"}),f.then(h=>{t(l,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})},h=>{t(l,{status:"failed",success:!1,result:{resultValue:h.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(l,{status:"done",success:!0,result:{resultValue:f,exports:o,exportsTest:i,exportsGlobal:a}})}catch(d){t(l,{status:"failed",success:!1,result:{resultValue:d.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Ni,Du,ir,Ui=w(()=>{"use strict";Ni=E(require("lodash"));j();ue();B();Te();Du=x("base-js-step-action"),ir=class extends W{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=M.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&Du.warn(`js result size exceeded ${i}, stepId: ${this.step.id}`),!1)}catch{return!1}}executeGetStatus(t){return this.driver.executeJS(r=>{let n=`data-testim-${r}`;try{return window.sessionStorage.getItem(n)}catch(o){if(o.message.includes("sessionStorage")||o.message.includes("The operation is insecure")){let i=document.head.querySelector("#testim-storage-backup");return i?i.getAttribute(n):"{}"}throw o}},t)}constructJSFunParams(t){let r=t.incomingParams,n=["context",...r.as.functionParameters,"exports","exportsTest","exportsGlobal"],o=[t.context,...r.as.functionArguments];return n.push(t.code),o.forEach(i=>{Ni.isObject(i)&&ro(i,"seleniumElement",Ni.isEqual)}),{function:{params:n,args:o},transactionId:t.transactionId,browser:t.browser,browserMajor:t.browserMajor}}checkStatus(t){let{context:r,stepActionUtils:n,step:{id:o=""}}=this,i=r.config.retryTimeout,a=r.data.timeToPlayStep-i,c=async()=>{let l;try{l=await this.executeGetStatus(t)}catch(p){Du.warn("failed to get js status",{err:p}),l={value:'{ "status": "exception" }'}}let m;try{m=JSON.parse((l==null?void 0:l.value)||"{}")}catch{Du.warn("non object value",{selRes:l}),m={status:"exception"}}let d=n.abortedSteps.find(p=>p.id===o);return d||(m?m.status==="done"?m:m.status==="failed"?{success:!1,shouldRetry:!0,result:m.result}:a-i<=0?Object.assign(m,{success:!1,shouldRetry:!0}):(a-=i,await oe(i),c()):{success:!0})};return c()}async executeInAut(t){let r=M.flags.experimentalPreCodeCompilation.isEnabled(),n=M.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(d=>Boolean(d==null?void 0:d.locatedElement)),a="undefined";if(r){let d=o.function.params.slice(0,-1);a=n?`async function(${d.join(",")}) {
|
|
256
256
|
${t.code}
|
|
257
257
|
};`:`function(${d.join(",")}) {
|
|
258
258
|
${t.code}
|
|
@@ -262,7 +262,7 @@ Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: n
|
|
|
262
262
|
var eventData = arguments[0];
|
|
263
263
|
var funcToRun = ${a};
|
|
264
264
|
return runCode.call(null, eventData, funcToRun);
|
|
265
|
-
`;if(!r)return this.driver.executeJS(m,o);try{return await this.driver.executeJS(m,o)}catch(d){return this.handleExecutionError(d)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:c}=t;o.exports&&(n.data.exports=o.exports);let l={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return Object.assign({},t,{errorType:r.STOPPED});let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${r.testResultId}:${t.id}`,id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var jt,Dh=w(()=>{"use strict";Ui();jt=class extends ir{isFailedResult(e){return e===!1}}});var gs,Mh=w(()=>{"use strict";Ui();gs=class extends ir{isFailedResult(e){return!e}}});var zE,Fi,Nh=w(()=>{"use strict";ue();j();zE={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},Fi=class extends W{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Oe(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(zE[t]),this.setWithValueApi(e)}}});var Uh={};G(Uh,{selectOption:()=>KE});function KE(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Fh=w(()=>{"use strict"});var Bi,Bh=w(()=>{"use strict";ue();j();Te();Bi=class extends W{async performAction(){var p,g;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Oe(t))}catch(f){if(!f.message.includes("Cannot check the displayedness of a non-Element argument"))throw f}let{selectOption:c}=await Promise.resolve().then(()=>(Fh(),Uh)),l=
|
|
265
|
+
`;if(!r)return this.driver.executeJS(m,o);try{return await this.driver.executeJS(m,o)}catch(d){return this.handleExecutionError(d)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:c}=t;o.exports&&(n.data.exports=o.exports);let l={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...l,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...l,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...l,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...c&&{navigateToDifferentDomain:c}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return Object.assign({},t,{errorType:r.STOPPED});let{result:o={},tstConsoleLogs:i}=t;return{tstConsoleLogs:i,data:n.data,exportsGlobal:o.exportsGlobal,exportsTest:o.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:o.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),o={transactionId:`${r.testResultId}:${t.id}`,id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(o);let i=await this.checkStatus(o.transactionId);return this.checkCodeResponse(i)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var jt,Dh=w(()=>{"use strict";Ui();jt=class extends ir{isFailedResult(e){return e===!1}}});var gs,Mh=w(()=>{"use strict";Ui();gs=class extends ir{isFailedResult(e){return!e}}});var zE,Fi,Nh=w(()=>{"use strict";ue();j();zE={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},Fi=class extends W{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(Oe(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(zE[t]),this.setWithValueApi(e)}}});var Uh={};G(Uh,{selectOption:()=>KE});function KE(s,e){function t(r,n){let o=Element.prototype.matches,i=o&&isNativeFunction(o)?o:document.createElement(r.tagName).__proto__.matches;do{if(i.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(i=>{let a=document.createEvent("HTMLEvents");return a.initEvent(i,!0,!1),a}).forEach(i=>{if(e){n.dispatchEvent(i);return}r.dispatchEvent(i)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var Fh=w(()=>{"use strict"});var Bi,Bh=w(()=>{"use strict";ue();j();Te();Bi=class extends W{async performAction(){var p,g;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((p=this.step.element)==null?void 0:p.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(Oe(t))}catch(f){if(!f.message.includes("Cannot check the displayedness of a non-Element argument"))throw f}let{selectOption:c}=await Promise.resolve().then(()=>(Fh(),Uh)),l=M.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),m=`
|
|
266
266
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
267
267
|
const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
|
|
268
268
|
const selectOption = ${c.toString()};
|
|
@@ -273,7 +273,7 @@ Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: n
|
|
|
273
273
|
var eventData = arguments[0];
|
|
274
274
|
var done = arguments[1];
|
|
275
275
|
return wheel.call(null, eventData, done);
|
|
276
|
-
`;return{success:((d=(await this.driver.executeCodeAsync(l,a,i)).value)==null?void 0:d.state)==="success"}}}});var Hh={};G(Hh,{downloadFileAndFireDropEvent:()=>XE});var XE,qh=w(()=>{"use strict";XE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let m=++i;return function(d){m in c||(c[m]=d,a++,e.length===a&&l.endWithCallback(c))}},endWith(m){l.endWithCallback=m}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var QE,Gi,zh=w(()=>{"use strict";ue();B();Te();QE=x("drop-file-step-action"),Gi=class extends W{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=
|
|
276
|
+
`;return{success:((d=(await this.driver.executeCodeAsync(l,a,i)).value)==null?void 0:d.state)==="success"}}}});var Hh={};G(Hh,{downloadFileAndFireDropEvent:()=>XE});var XE,qh=w(()=>{"use strict";XE=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,c=[],l={endWithCallback:void 0,waitOn(){let m=++i;return function(d){m in c||(c[m]=d,a++,e.length===a&&l.endWithCallback(c))}},endWith(m){l.endWithCallback=m}};return l}function n(i,a,c){let l=new XMLHttpRequest;l.open("GET",i),l.responseType="blob",l.onload=function(){if(this.status>=200&&this.status<300)c({blob:l.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},l.onerror=function(){throw new Error("Failed to load blob")},l.send()}let o=r();e.forEach(i=>{n(i.url,i.name,o.waitOn())}),o.endWith(i=>{let a=createDropEvent(i);t.dispatchEvent(a)})}});var QE,Gi,zh=w(()=>{"use strict";ue();B();Te();QE=x("drop-file-step-action"),Gi=class extends W{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=M.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrl(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,QE),{downloadFileAndFireDropEvent:c}=await Promise.resolve().then(()=>(qh(),Hh)),l=`
|
|
277
277
|
const getLocatedElement = ${e.getLocatedElementCode};
|
|
278
278
|
const createDropEvent = ${e.createDropEvent.toString()};
|
|
279
279
|
const downloadFileAndFireDropEvent = ${c.toString()};
|
|
@@ -401,14 +401,14 @@ Please make sure the CLI has stable access to the internet. ${Va()?"(Internal: n
|
|
|
401
401
|
var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
402
402
|
var getVisibleElement = ${Yh(r)};
|
|
403
403
|
return getVisibleElement.apply(null, arguments);
|
|
404
|
-
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw Vi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",g=n?n.message:"";if(g===m||g.startsWith(d)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(p)||g.includes(c)||g.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Vi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Oe(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=
|
|
404
|
+
`;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw Vi.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",p="is not reachable by keyboard",g=n?n.message:"";if(g===m||g.startsWith(d)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(p)||g.includes(c)||g.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Vi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Oe(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.useJsInputCodeInSafari.isEnabled(),o=M.flags.useJsInputCodeInFirefox.isEnabled(),i=M.flags.useJsInputCodeInEdgeChromium.isEnabled(),a=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:c,context:l,step:m,stepActionUtils:d,driver:p}=this,g=await c.utils.addTokenToFileUrl(l.project.id,m.fileUrls,d.testimServicesApi,r,Vi),f=p.isSafari()&&(n||g.length>1),h=p.isFirefox()&&(o||g.length>1),y=p.isEdgeChromium()&&(i||g.length>1);if(a&&(g=await Promise.all(g.map(async({name:S,url:b})=>{let T=await _t(b);return{name:S,url:`data:${T.type};base64,${Buffer.from(T.body).toString("base64")}`}}))),f||h||y){await this.driver.executeJS(`
|
|
405
405
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
406
406
|
const downloadAndUploadFile = ${nS()};
|
|
407
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,g);return}let v=await Xh(g,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var qi,zi,ey=w(()=>{"use strict";qi=require("url");ue();zi=class extends W{async updateBaseUrl(e){let t=new qi.URL(e),r=new qi.URL(this.context.recordedBaseUrl),n=new qi.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ki,ty=w(()=>{"use strict";ue();j();Ki=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var Ji,ry=w(()=>{"use strict";ue();Ji=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var An,sy=w(()=>{"use strict";ue();An=class extends W{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Yi,ny=w(()=>{"use strict";ue();Yi=class extends W{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var oy,Mu,Nu,iy=w(()=>{"use strict";oy=E(require("@applitools/spec-driver-webdriverio"));Gn();be();Mu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=hp["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:oy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Nu=new Mu});var cy,ay,Pn,ly=w(()=>{"use strict";cy=E(require("lodash"));ue();B();iy();ay=x("pixel-validation-step-action"),Pn=class extends W{async performAction(){var d,p;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((p=r.batch)==null?void 0:p.id)||o,c=await Nu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let g=await c.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};cy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),ay.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){ay.error("Applitools SDK step failed",{err:g,info:g.info}),m={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Nu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var hs,Uu=w(()=>{"use strict";Ir();z();Ui();hs=class extends ir{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},p=t.data.timeToPlayStep,g=await as(o,i,a,d,c,l,m,p);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,uy=w(()=>{"use strict";Uu();ar=class extends hs{isFailedResult(e){return e===!1}}});var Xi,py=w(()=>{"use strict";Uu();Xi=class extends hs{isFailedResult(e){return!e}}});var Qi,dy=w(()=>{"use strict";Ir();ue();z();Qi=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await is(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof wt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var ys,my=w(()=>{"use strict";ue();ys=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var ve,fy=w(()=>{"use strict";ue();ve=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Zi,gy=w(()=>{"use strict";ue();Zi=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ea,hy=w(()=>{"use strict";ue();ea=class extends W{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function oS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ta(s,e){oS(iS,e),e.registerLocateStepActionUtils(Rn.getUtils(s))}var iS,Fu=w(()=>{"use strict";mh();hh();Ih();xh();Ph();Oh();Dh();Mh();Nh();Bh();jh();$h();Vh();zh();Zh();ey();ty();ry();sy();ny();ly();uy();py();dy();my();fy();gy();hy();iS={locate:Rn,scroll:_i,mouse:Li,submit:ji,text:Mi,"special-key":Fi,"user-code":jt,"validation-code-step":jt,"wait-for-code-step":jt,"action-code-step":jt,"condition-step":gs,"skip-code-step":gs,"element-code-step":gs,"evaluate-expression":Di,"text-validation":xn,"wait-for-text-validation":xn,"select-option":Bi,"drop-file":Gi,"input-file":Hi,hover:$i,navigation:zi,wheel:Wi,sleep:Ki,refresh:Ji,"api-validation":An,"api-action":An,"api-code-step":jt,"extract-text":Yi,"simple-ui-verification":Pn,"wait-for-simple-ui-verification":Pn,"cli-validation-download-file":ys,"cli-wait-for-download-file":ys,"network-validation-step":ys,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Xi,"node-package":Qi,"email-code-step":jt,"cli-email-code-step":ar,"sfdc-internal-test-step":ea,"sfdc-recorded-step":Zi,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve}});var yy,aS,bs,Bu=w(()=>{"use strict";yy=["simple-ui-verification","wait-for-simple-ui-verification"],aS=[...yy,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor"],bs=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=aS.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return yy.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Ty={};G(Ty,{SeleniumTestPlayer:()=>Cn});var by,Cn,ju=w(()=>{"use strict";j();by=require("@applitools/eyes-sdk-core");bn();z();Au();ch();Ou();_u();ph();Lu();be();Fu();Bu();Cn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new bs(Oi());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Rr;let m=new fs(this.driver);this.stepActionFactory=new l(m),ta(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=uh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ds(this.driver),FrameLocator:d,portSelector:ki,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:by.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ae((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var wy={};G(wy,{WorkerSelenium:()=>$u});function lS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>L(`Got event ${t}`))}var ra,cS,$u,vy=w(()=>{"use strict";j();Be();Sn();B();At();No();ce();Iu();z();ju();be();ra=x("worker-selenium"),cS=1e9,$u=class extends tt{initPlayer(t){return new Cn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){L("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ps(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),L("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),L("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,cS),await this.windowUtils.validatePageIsAvailable(),L("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof bt||m||d?new bt(`Page '${c}' is not available`):(ra.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),lS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await nn(this.options))[this.testId]);let m=async()=>ae(new Promise((p,g)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:p,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(g)}),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG).catch(p=>{var g;throw p instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),p}).then(async p=>{await o.drain(),p.stepsResults=null,p.resultId=this.testResultId,i.isAlive()||(ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.keepAliveIssue=g);let h={...p,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),L("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),L("right after super.runTestOnce in workerSelenium");let p=await m();return L("right after runSeleniumTest"),p}catch(p){throw ra.error("failed to run test once",{err:p}),p}}}});var sa,Ey=w(()=>{"use strict";sa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Wu,na,Sy=w(()=>{"use strict";B();Wu=x("mobile-frame-locator-mock"),na=class{foundFrameCallback(){return Wu.info("foundFrameCallback-mock invoked"),{}}locate(){return Wu.info("locate-mock invoked"),{}}async findFrame(){return Wu.info("findFrame-mock invoked"),{}}}});var uS,Iy,Ry,Ts,Gu=w(()=>{"use strict";uS=E(require("webdriverio")),Iy=require("@applitools/eyes-sdk-core");Ey();Ou();B();_u();Lu();be();Fu();Sy();Bu();Ry=x("appium-test-player"),Ts=class{constructor(e,t,r,n=uS,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=ee(),d=new fs(this.driver);this.stepActionFactory=new l(d),ta(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new bs(Oi()),this.sessionPlayer=new a(e,{tabService:new sa,cookieUtils:void 0,FrameLocator:na,portSelector:ki,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Iy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{await(n==null?void 0:n.endSession()),Ry.info("appium session deleted",o)}catch(i){Ry.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=ee();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function pS(s){return await Ne(`${s}/api/status`)}async function xy(s,e){return await Ne(`${s}/api/devices/${e}/status`)}async function Ay(s){let e="";try{(await pS(s)).fsmState!=="Ready"&&(e="TMA is not ready")}catch{e="It seems that the TMA agent is offline."}if(e)throw new Error(e)}var Py=w(()=>{"use strict";Ve()});var ky={};G(ky,{WorkerLocalTma:()=>zu});var Cy,kn,oa,Vu,Hu,qu,zu,Oy=w(()=>{"use strict";Cy=E(require("jsdom"));Ve();kn=E(require("semver"));gn();Sn();j();B();At();Gu();be();Py();pi();oa=x("worker-appium"),Vu=class extends Error{},Hu=class extends Error{},qu=class extends Error{},zu=class extends tt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),n=new Cy.JSDOM("").window.DOMParser,o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}checkIfUpgradeIsNeeded(t,r,n){if(n)return!1;let[o,i]=[kn.coerce(t),kn.coerce(r)];return!o||!i?!1:kn.cmp(o,"!==",i)}async getBrowserOnce(t,r,n,o){var C;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await Ay(i);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,p=c.type,g=!1,f=this.options.appId;if(f){let{executionId:k,testResultId:R}=t,{mobileApp:M}=await pt.getMobileAppDataByAppId({appId:f,projectId:l,token:m,executionId:k,testResultId:R});t.nativeApp=M}let h=p==="android"?t.androidActivityWait:null,y=t.nativeAppMetadata,v=t.downloadableAppPublicLink,S=t.appPackageNameOrBundleId;if(!y)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!S)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:T},I]=await Promise.all([this.getAppStateFromDevice(i,a,S),xy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&v&&await this.installApp(i,a,v),b&&(!t.isAppFromDevice||f)&&(g=this.checkIfUpgradeIsNeeded(T,y.version,I.isVirtual));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(C=this.options.projectData)==null?void 0:C.name}-${this.options.project}`},R=ng({projectType:p,nativeAppMetadata:y,appPath:v,androidActivityWait:h,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),M={capabilities:{udid:a,...R}},O=await this.requestNewAppiumSessionFromTma(i,M,y);if(this.sessionData=O,g){let $=this.initAndGetAppiumAPI(n);await $.removeApp(S),await this.installApp(i,a,v),await $.activateApp({[p==="ios"?"appId":"bundleId"]:S})}let D=await d.attach({sessionId:O.sessionId,capabilities:R});this.device=await pt.updateTmaDeviceDetails(a,this.options,t),oa.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:D.sessionId,testResultId:this.testResultId,nativeAppMetadata:y,sessionCaps:D.capabilities})}catch(k){throw oa.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await $e({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new qu(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Ne(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await _t(n);await Ls(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Hu(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Vu(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,p)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(p)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw oa.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw oa.error("failed to run test once",{err:l}),l}}}});var Ly={};G(Ly,{WorkerAppium:()=>Ku});var _y,On,Ku,Dy=w(()=>{"use strict";gn();_y=require("linkedom");Sn();B();At();Gu();be();pi();ce();On=x("worker-appium"),Ku=class extends tt{initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,{appPath:c,isTdcAppIdExists:l,isHSAppIdExists:m}=await pt.getAppInfoForRemoteRun({testRunHandler:t,options:this.options}),d=a==="android"?t.androidActivityWait:null,p=t.nativeAppMetadata;if(!p)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag}},f={projectType:a,nativeAppMetadata:p,appPath:c,androidActivityWait:d,sessionTags:g,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:m,isTdcAppIdExists:l},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await pt.lockDevice(o,this.options.deviceUdid),h=await ig(f)):h=og(f),On.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:g,nativeAppMetadata:p,capabilities:ag(h)}),this.activeSession=await i.remote(h),this.device=await pt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),On.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(g){throw On.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===U.TESTIM_HEADSPIN||o===U.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var p,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((p=this.testRunConfig.mobile)==null?void 0:p.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:S}=await pt.getHeadSpinDeviceConnection(this.options.gridData,f);l=`${h}://${y}:${v}${S}`}else l=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(l,this.activeSession.sessionId,_y.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let d=async()=>{try{let f=await new Promise((y,v)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(v)});return await i.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw On.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),f}};try{return await super.runTestOnce(t,r),await d()}catch(f){throw On.error("failed to run test once",{err:f}),f}}}});var ia,My=w(()=>{"use strict";j();bn();z();ia=class{constructor(e){this.id=e;this.driver=new Rr}async onDone(){try{await ae(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Ny,aa,Uy=w(()=>{"use strict";Ny=E(require("ws"));j();aa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Ny.default(this._cdpUrl,{timeout:e}),r=Vt(o=>{t.once("open",o)}),n=Vt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var la,Ju,ca,Fy=w(()=>{"use strict";j();la=E(require("chrome-launcher"));gn();Uy();en();Ju=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new aa}async init(e,t,r,n,o,i,a,c,l,m){var f,h,y,v;let d=mi(e,t,r,n,o,i,a),p=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...la.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await la.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Yr(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},ca=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new Ju(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var jy={};G(jy,{WorkerExtension:()=>_n});function dS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function By(s){return dS(s)?s:new Error(s)}var rt,_n,Yu=w(()=>{"use strict";Be();z();Sn();j();B();At();ce();My();Fy();rt=x("worker-ext"),_n=class extends tt{initPlayer(){return this.options.useChromeLauncher?new ca(this.id):new ia(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw rt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;L("WorkerExtension runTestOnce");let i=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ae(e.runTestUsingCDP(m.cdpTestRunner),d,We.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof re))throw p;return rt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,p)=>{try{let g=await m.url(d);return p.driverUrlFinished=!0,g}catch(g){throw rt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(L("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw rt.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ae(Promise.all([a(t.driver,f,p),c(p)]),this.options.testStartTimeout,We.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;rt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...p}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),rt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),v.type=Ms.BROWSER_CLOSED,h.abort(v)};d.registerToClosedBrowser(y);try{let v=ae(e.onCompleted(),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG),S=await Na(v,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(I){rt.error("Could not update the grid about the test status",{err:I})}d.isAlive()||(rt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(rt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw rt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),By(v)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw rt.warn("failed to start url",{err:f}),By(f)}};t.driver.start();try{return await super.runTestOnce(e,t),L("WorkerExtension super.runTestOnce"),await l()}catch(m){throw rt.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var $y={};G($y,{WorkerExtensionSingleBrowser:()=>Xu});var mS,fS,Xu,Wy=w(()=>{"use strict";Be();j();B();wu();At();Yu();mS=x("base-worker"),fS=500,Xu=class extends _n{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await vn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(mS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;L("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await oe(fS)}}});function gS(s,e){e===0?s():setTimeout(s,e*xp)}var Qu,ua,Gy=w(()=>{"use strict";bn();le();Be();ql();Rt();lu();z();B();ce();Kg();Qu=x("parallel-worker-manager"),ua=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(vy(),fe(wy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Oy(),fe(ky)).WorkerLocalTma:(Dy(),fe(Ly)).WorkerAppium;default:return hi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Wy(),fe($y)).WorkerExtensionSingleBrowser:(Yu(),fe(jy)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return L("before new Worker",n.mode),new o(t,...r)}finally{L("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let m=!1,d=0,p=g=>new Promise(f=>{var ht,Cr,A,_,F,q,st,ha;let h=o.project,y=new Si(r,n,e,o,i,t),v={},S=e.length,b=((ht=o.company)==null?void 0:ht.ucid)||"",T=(Cr=o.company)==null?void 0:Cr.companyId,I=(A=o.company)==null?void 0:A.name,C=o.source||"cli",k=o.user,R=(_=o.company)==null?void 0:_.planType,M=(F=o.company)==null?void 0:F.isStartUp,O=(q=o.projectData)==null?void 0:q.name,D=(st=o.projectData)==null?void 0:st.type,$=o.lightweightMode,H=(ha=o.gridData)==null?void 0:ha.type,J=(kt,nt,he,ya,Dn,ba)=>(d++,vf({executionId:r,projectId:h,testId:nt,resultId:he,ucid:b,companyId:T,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,isStartUp:M,projectType:D,appSource:ba,gridType:H}),t.testStartAndReport(kt,r,he,ya,Dn)),Q=async(kt,nt,he,ya,Dn,ba)=>{var lp,up,pp;d--;let Xe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...he.seleniumStats&&{seleniumStats:he.seleniumStats},...he.gridIssues&&{gridIssues:he.gridIssues},...he.keepAliveIssue&&{keepAliveIssue:he.keepAliveIssue},...o.host&&{gridHost:o.host}};if(he.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(he.seleniumPerfMarks),delete he.seleniumPerfMarks),o.grid||o.gridId?(Xe.gridName=o.grid||((lp=o.gridData)==null?void 0:lp.name),Xe.gridType=(up=o.gridData)==null?void 0:up.type,Xe.gridProvider=(pp=o.gridData)==null?void 0:pp.provider):o.localTmaUrl?(Xe.gridName="local-tma-from-options",Xe.gridType="local-tma"):o.useLocalChromeDriver?(Xe.gridName="local-chrome-driver-from-options",Xe.gridType="local-chrome"):o.useChromeLauncher?(Xe.gridName="chrome-launcher-from-options",Xe.gridType="local-chrome"):o.browserstack?Xe.gridName="browserstack-from-options":o.saucelabs&&(Xe.gridName="saucelabs-from-options"),await t.testEndAndReport(kt,he,r,ya,Dn,Xe).catch(Nb=>Qu.error("testEndAndReport threw an error",{err:Nb})),Dn)return;v[he.resultId]=he,Ef({executionId:r,projectId:h,testId:nt,resultId:he.resultId,result:he,ucid:b,companyId:T,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,logger:Qu,isStartUp:M,projectType:D,appSource:ba}),l&&!he.success&&(y.stop(),m=!0),(Object.keys(v).length===S||m&&d===0)&&f(v)},de=(kt,nt)=>{v[nt.resultId]=nt,t.onTestIgnored(kt,nt.resultId),d--,(Object.keys(v).length===S||m&&d===0)&&f(v)},$t=(kt,nt)=>t.onGridSlot(kt,nt);o.userData={loginData:Object.assign({},Mt(),{refreshToken:vo(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},L("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,J,Q,$t,de).forEach((kt,nt)=>{L("before schedule worker.run after createWorkers"),gS(()=>{L("right before worker.run"),kt.run()},nt)})});try{let g=await Kt(),f=await p(g);if(m)throw new Gt;return f}catch(g){throw Qu.error("failed running parallel workers",{executionId:r,err:g}),g}}}});async function Hy(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Cc({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Zu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function ep(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Vy.difference(Ns(s,e),t);if(r.length>0)throw lt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Vy,qy=w(()=>{"use strict";Vy=E(require("lodash"));j();Xr();ye();z()});var Ln,v_,tp,rp,pa,zy=w(()=>{"use strict";Ln=E(require("lodash"));j();B();le();ce();Be();ts();Cl();ql();ye();Rt();At();Gf();z();Gy();qy();({testRunStatus:v_,CLI_MODE:tp}=Lt),rp=x("test-plan-runner"),pa=class{constructor(e){this.startTime=Date.now();this.workerManager=new ua(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},m=Mt(),d=async()=>{let h=o.beforeParallel||1,y=!0,v=await this.workerManager.runTests(e,c,i,a,o,n,m,h,y);Object.assign(l,v)},p=async()=>{let h=zn||o.parallel,y=!1;L("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,m,h,y);L("right after this.workerManager.runTests"),Object.assign(l,v)},g=async()=>{let h=o.afterParallel||1,y=!1,v=await this.workerManager.runTests(r,c,i,a,o,n,m,h,y);Object.assign(l,v)};Sf({executionId:i,projectId:o.project}),L("right before runBeforeTests");try{return await d(),L("right before runTestPlanTests"),await p(),L("right after runTestPlanTests"),await g(),l}catch(h){if(rp.error("error running test plan",{err:h}),h instanceof Gt)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await f()}async function f(){var y,v,S,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===tp.SELENIUM){let[{getSessionPlayer:T},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(be(),Yt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=T();await C.closeBatch(i,I);return}let h;try{if(!((b=(S=(v=o.company)==null?void 0:v.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(h=await qc(o.project),Ln.default.isEmpty(h)||!i))return;let{runKey:T,url:I}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:T}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,T,I;let l=te(),m=n.project;Oa(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let d=[...e,...t,...r],p=new ui(d,n,i,a),g=Ln.default.chain(d).map(C=>{var k;return((k=C.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(C=>C.name),y=(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:p.executionStart(l,m,this.startTime,o,h);L("before testListInfoPromise");let v=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||X.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,f),L("before runTestAllPhases");let S=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",p);return L("before executionEnd"),await p.executionEnd(l),L("after executionEnd"),{results:S,executionId:l,testPlanName:o,configName:f}}async runTestPlans(e,t){rp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(m){return Ln.default.flattenDeep(Object.values(m)).reduce((d,p)=>d.concat(p.beforeTests,p.tests,p.afterTests),[])}let n={},o={},i=e.project,a=await Pc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==tp.APPIUM&&await ep(e,r(l)),await ie(c,async m=>{var f;let d=m.testPlanId;n[d]={};let p=Object.assign({},e);p.baseUrl||=m.startUrl,p.appId||=((f=m.mobileApp)==null?void 0:f.appId)||void 0,p.gridId||=m.gridId,e.grid&&delete p.gridId,p.gridData=await sf(e,m);let g=p.overrideExecutionName||m.name;return await ie(l[d],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,p,g,d,t);X.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let v=Object.keys(n[d]).map(I=>({executionId:I,status:Zu(n[d][I])})),S=Object.keys(n[d]).map(I=>n[d][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Zu(S);Object.assign(o,S);let T=b?v[0].executionId:v.find(I=>!I.status).executionId;return await Ic(i,d,{success:b,executions:v,executionId:T}),y})})}async runAnonymousTestPlan(e,t){var a;rp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),L("before getSuite");let r=await Hy(e,t);if(L("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return L("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async c=>{if(e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==tp.APPIUM&&await ep(e,c),L("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return L("right after runTestPlan"),await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=ln(),r=[];Us(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Ln.default.flattenDeep(r);return L("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),L("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Xy={};G(Xy,{init:()=>DS,run:()=>_S});async function yS(s){let e=s.project,t=await Oc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),tn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function bS(s,e){var i,a,c,l,m,d;let t=so(e.activePlan),r=s.parallel;if(t==="free"&&r>Jy)throw new P(`The free plan allows only ${Jy} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let p=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!p)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
408
|
-
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}let n=s.retentionDays;if(!n)return;let o=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function TS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await yS(s)}catch(t){if([P,Ps].some(r=>t instanceof r))throw t;hS.error("could not validate cli account",{err:t})}}function wS(s){let e=Mt();return pm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function vS(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(
|
|
407
|
+
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,g);return}let v=await Xh(g,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var qi,zi,ey=w(()=>{"use strict";qi=require("url");ue();zi=class extends W{async updateBaseUrl(e){let t=new qi.URL(e),r=new qi.URL(this.context.recordedBaseUrl),n=new qi.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var Ki,ty=w(()=>{"use strict";ue();j();Ki=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var Ji,ry=w(()=>{"use strict";ue();Ji=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var An,sy=w(()=>{"use strict";ue();An=class extends W{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Yi,ny=w(()=>{"use strict";ue();Yi=class extends W{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var oy,Mu,Nu,iy=w(()=>{"use strict";oy=E(require("@applitools/spec-driver-webdriverio"));Gn();be();Mu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=hp["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:oy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Nu=new Mu});var cy,ay,Pn,ly=w(()=>{"use strict";cy=E(require("lodash"));ue();B();iy();ay=x("pixel-validation-step-action"),Pn=class extends W{async performAction(){var d,p;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((p=r.batch)==null?void 0:p.id)||o,c=await Nu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let g=await c.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};cy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),ay.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){ay.error("Applitools SDK step failed",{err:g,info:g.info}),m={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Nu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var hs,Uu=w(()=>{"use strict";Ir();z();Ui();hs=class extends ir{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},p=t.data.timeToPlayStep,g=await as(o,i,a,d,c,l,m,p);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,uy=w(()=>{"use strict";Uu();ar=class extends hs{isFailedResult(e){return e===!1}}});var Xi,py=w(()=>{"use strict";Uu();Xi=class extends hs{isFailedResult(e){return!e}}});var Qi,dy=w(()=>{"use strict";Ir();ue();z();Qi=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await is(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof wt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var ys,my=w(()=>{"use strict";ue();ys=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only on Chrome"}}}});var ve,fy=w(()=>{"use strict";ue();ve=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Zi,gy=w(()=>{"use strict";ue();Zi=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ea,hy=w(()=>{"use strict";ue();ea=class extends W{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function oS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ta(s,e){oS(iS,e),e.registerLocateStepActionUtils(Rn.getUtils(s))}var iS,Fu=w(()=>{"use strict";mh();hh();Ih();xh();Ph();Oh();Dh();Mh();Nh();Bh();jh();$h();Vh();zh();Zh();ey();ty();ry();sy();ny();ly();uy();py();dy();my();fy();gy();hy();iS={locate:Rn,scroll:_i,mouse:Li,submit:ji,text:Mi,"special-key":Fi,"user-code":jt,"validation-code-step":jt,"wait-for-code-step":jt,"action-code-step":jt,"condition-step":gs,"skip-code-step":gs,"element-code-step":gs,"evaluate-expression":Di,"text-validation":xn,"wait-for-text-validation":xn,"select-option":Bi,"drop-file":Gi,"input-file":Hi,hover:$i,navigation:zi,wheel:Wi,sleep:Ki,refresh:Ji,"api-validation":An,"api-action":An,"api-code-step":jt,"extract-text":Yi,"simple-ui-verification":Pn,"wait-for-simple-ui-verification":Pn,"cli-validation-download-file":ys,"cli-wait-for-download-file":ys,"network-validation-step":ys,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Xi,"node-package":Qi,"email-code-step":jt,"cli-email-code-step":ar,"sfdc-internal-test-step":ea,"sfdc-recorded-step":Zi,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve}});var yy,aS,bs,Bu=w(()=>{"use strict";yy=["simple-ui-verification","wait-for-simple-ui-verification"],aS=[...yy,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor"],bs=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=aS.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return yy.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var Ty={};G(Ty,{SeleniumTestPlayer:()=>Cn});var by,Cn,ju=w(()=>{"use strict";j();by=require("@applitools/eyes-sdk-core");bn();z();Au();ch();Ou();_u();ph();Lu();be();Fu();Bu();Cn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new bs(Oi());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Rr;let m=new fs(this.driver);this.stepActionFactory=new l(m),ta(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ci(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=uh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ds(this.driver),FrameLocator:d,portSelector:ki,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:by.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ae((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var wy={};G(wy,{WorkerSelenium:()=>$u});function lS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>L(`Got event ${t}`))}var ra,cS,$u,vy=w(()=>{"use strict";j();Be();Sn();B();At();No();ce();Iu();z();ju();be();ra=x("worker-selenium"),cS=1e9,$u=class extends tt{initPlayer(t){return new Cn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){L("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ps(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),L("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),L("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,cS),await this.windowUtils.validatePageIsAvailable(),L("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof bt||m||d?new bt(`Page '${c}' is not available`):(ra.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),lS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await nn(this.options))[this.testId]);let m=async()=>ae(new Promise((p,g)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:p,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(g)}),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG).catch(p=>{var g;throw p instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),p}).then(async p=>{await o.drain(),p.stepsResults=null,p.resultId=this.testResultId,i.isAlive()||(ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),p.keepAliveIssue=g);let h={...p,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),L("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),L("right after super.runTestOnce in workerSelenium");let p=await m();return L("right after runSeleniumTest"),p}catch(p){throw ra.error("failed to run test once",{err:p}),p}}}});var sa,Ey=w(()=>{"use strict";sa=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Wu,na,Sy=w(()=>{"use strict";B();Wu=x("mobile-frame-locator-mock"),na=class{foundFrameCallback(){return Wu.info("foundFrameCallback-mock invoked"),{}}locate(){return Wu.info("locate-mock invoked"),{}}async findFrame(){return Wu.info("findFrame-mock invoked"),{}}}});var uS,Iy,Ry,Ts,Gu=w(()=>{"use strict";uS=E(require("webdriverio")),Iy=require("@applitools/eyes-sdk-core");Ey();Ou();B();_u();Lu();be();Fu();Sy();Bu();Ry=x("appium-test-player"),Ts=class{constructor(e,t,r,n=uS,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=ee(),d=new fs(this.driver);this.stepActionFactory=new l(d),ta(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new bs(Oi()),this.sessionPlayer=new a(e,{tabService:new sa,cookieUtils:void 0,FrameLocator:na,portSelector:ki,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Iy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{await(n==null?void 0:n.endSession()),Ry.info("appium session deleted",o)}catch(i){Ry.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=ee();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function pS(s){return await Ne(`${s}/api/status`)}async function xy(s,e){return await Ne(`${s}/api/devices/${e}/status`)}async function Ay(s){let e="";try{(await pS(s)).fsmState!=="Ready"&&(e="TMA is not ready")}catch{e="It seems that the TMA agent is offline."}if(e)throw new Error(e)}var Py=w(()=>{"use strict";Ve()});var ky={};G(ky,{WorkerLocalTma:()=>zu});var Cy,kn,oa,Vu,Hu,qu,zu,Oy=w(()=>{"use strict";Cy=E(require("jsdom"));Ve();kn=E(require("semver"));gn();Sn();j();B();At();Gu();be();Py();pi();oa=x("worker-appium"),Vu=class extends Error{},Hu=class extends Error{},qu=class extends Error{},zu=class extends tt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),n=new Cy.JSDOM("").window.DOMParser,o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}checkIfUpgradeIsNeeded(t,r,n){if(n)return!1;let[o,i]=[kn.coerce(t),kn.coerce(r)];return!o||!i?!1:kn.cmp(o,"!==",i)}async getBrowserOnce(t,r,n,o){var C;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await Ay(i);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,p=c.type,g=!1,f=this.options.appId;if(f){let{executionId:k,testResultId:R}=t,{mobileApp:N}=await pt.getMobileAppDataByAppId({appId:f,projectId:l,token:m,executionId:k,testResultId:R});t.nativeApp=N}let h=p==="android"?t.androidActivityWait:null,y=t.nativeAppMetadata,v=t.downloadableAppPublicLink,S=t.appPackageNameOrBundleId;if(!y)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!S)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:T},I]=await Promise.all([this.getAppStateFromDevice(i,a,S),xy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&v&&await this.installApp(i,a,v),b&&(!t.isAppFromDevice||f)&&(g=this.checkIfUpgradeIsNeeded(T,y.version,I.isVirtual));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(C=this.options.projectData)==null?void 0:C.name}-${this.options.project}`},R=ng({projectType:p,nativeAppMetadata:y,appPath:v,androidActivityWait:h,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),N={capabilities:{udid:a,...R}},O=await this.requestNewAppiumSessionFromTma(i,N,y);if(this.sessionData=O,g){let $=this.initAndGetAppiumAPI(n);await $.removeApp(S),await this.installApp(i,a,v),await $.activateApp({[p==="ios"?"appId":"bundleId"]:S})}let D=await d.attach({sessionId:O.sessionId,capabilities:R});this.device=await pt.updateTmaDeviceDetails(a,this.options,t),oa.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:D.sessionId,testResultId:this.testResultId,nativeAppMetadata:y,sessionCaps:D.capabilities})}catch(k){throw oa.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await $e({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new qu(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Ne(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await _t(n);await Ls(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Hu(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Vu(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,p)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(p)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw oa.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw oa.error("failed to run test once",{err:l}),l}}}});var Ly={};G(Ly,{WorkerAppium:()=>Ku});var _y,On,Ku,Dy=w(()=>{"use strict";gn();_y=require("linkedom");Sn();B();At();Gu();be();pi();ce();On=x("worker-appium"),Ku=class extends tt{initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,{appPath:c,isTdcAppIdExists:l,isHSAppIdExists:m}=await pt.getAppInfoForRemoteRun({testRunHandler:t,options:this.options}),d=a==="android"?t.androidActivityWait:null,p=t.nativeAppMetadata;if(!p)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let g={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag}},f={projectType:a,nativeAppMetadata:p,appPath:c,androidActivityWait:d,sessionTags:g,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig,isHSAppIdExists:m,isTdcAppIdExists:l},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await pt.lockDevice(o,this.options.deviceUdid),h=await ig(f)):h=og(f),On.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:g,nativeAppMetadata:p,capabilities:ag(h)}),this.activeSession=await i.remote(h),this.device=await pt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),On.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(g){throw On.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===U.TESTIM_HEADSPIN||o===U.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var p,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((p=this.testRunConfig.mobile)==null?void 0:p.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:S}=await pt.getHeadSpinDeviceConnection(this.options.gridData,f);l=`${h}://${y}:${v}${S}`}else l=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(l,this.activeSession.sessionId,_y.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let d=async()=>{try{let f=await new Promise((y,v)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(v)});return await i.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw On.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),f}};try{return await super.runTestOnce(t,r),await d()}catch(f){throw On.error("failed to run test once",{err:f}),f}}}});var ia,My=w(()=>{"use strict";j();bn();z();ia=class{constructor(e){this.id=e;this.driver=new Rr}async onDone(){try{await ae(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Ny,aa,Uy=w(()=>{"use strict";Ny=E(require("ws"));j();aa=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Ny.default(this._cdpUrl,{timeout:e}),r=Vt(o=>{t.once("open",o)}),n=Vt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var la,Ju,ca,Fy=w(()=>{"use strict";j();la=E(require("chrome-launcher"));gn();Uy();en();Ju=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new aa}async init(e,t,r,n,o,i,a,c,l,m){var f,h,y,v;let d=mi(e,t,r,n,o,i,a),p=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...la.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await la.launch({chromeFlags:p,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Yr(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},ca=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new Ju(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var jy={};G(jy,{WorkerExtension:()=>_n});function dS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function By(s){return dS(s)?s:new Error(s)}var rt,_n,Yu=w(()=>{"use strict";Be();z();Sn();j();B();At();ce();My();Fy();rt=x("worker-ext"),_n=class extends tt{initPlayer(){return this.options.useChromeLauncher?new ca(this.id):new ia(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw rt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;L("WorkerExtension runTestOnce");let i=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ae(e.runTestUsingCDP(m.cdpTestRunner),d,We.TEST_START_TIMEOUT_MSG)}catch(p){if(!(p instanceof re))throw p;return rt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,p)=>{try{let g=await m.url(d);return p.driverUrlFinished=!0,g}catch(g){throw rt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(L("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw rt.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,p={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ae(Promise.all([a(t.driver,f,p),c(p)]),this.options.testStartTimeout,We.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;rt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...p}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),rt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),v.type=Ms.BROWSER_CLOSED,h.abort(v)};d.registerToClosedBrowser(y);try{let v=ae(e.onCompleted(),this.testRunTimeout,We.TEST_COMPLETE_TIMEOUT_MSG),S=await Na(v,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(I){rt.error("Could not update the grid about the test status",{err:I})}d.isAlive()||(rt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(rt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw rt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),By(v)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw rt.warn("failed to start url",{err:f}),By(f)}};t.driver.start();try{return await super.runTestOnce(e,t),L("WorkerExtension super.runTestOnce"),await l()}catch(m){throw rt.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var $y={};G($y,{WorkerExtensionSingleBrowser:()=>Xu});var mS,fS,Xu,Wy=w(()=>{"use strict";Be();j();B();wu();At();Yu();mS=x("base-worker"),fS=500,Xu=class extends _n{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await vn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(mS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;L("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await oe(fS)}}});function gS(s,e){e===0?s():setTimeout(s,e*xp)}var Qu,ua,Gy=w(()=>{"use strict";bn();le();Be();ql();Rt();lu();z();B();ce();Kg();Qu=x("parallel-worker-manager"),ua=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(vy(),fe(wy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Oy(),fe(ky)).WorkerLocalTma:(Dy(),fe(Ly)).WorkerAppium;default:return hi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Wy(),fe($y)).WorkerExtensionSingleBrowser:(Yu(),fe(jy)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return L("before new Worker",n.mode),new o(t,...r)}finally{L("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let m=!1,d=0,p=g=>new Promise(f=>{var ht,Cr,A,_,F,q,st,ha;let h=o.project,y=new Si(r,n,e,o,i,t),v={},S=e.length,b=((ht=o.company)==null?void 0:ht.ucid)||"",T=(Cr=o.company)==null?void 0:Cr.companyId,I=(A=o.company)==null?void 0:A.name,C=o.source||"cli",k=o.user,R=(_=o.company)==null?void 0:_.planType,N=(F=o.company)==null?void 0:F.isStartUp,O=(q=o.projectData)==null?void 0:q.name,D=(st=o.projectData)==null?void 0:st.type,$=o.lightweightMode,H=(ha=o.gridData)==null?void 0:ha.type,J=(kt,nt,he,ya,Dn,ba)=>(d++,vf({executionId:r,projectId:h,testId:nt,resultId:he,ucid:b,companyId:T,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,isStartUp:N,projectType:D,appSource:ba,gridType:H}),t.testStartAndReport(kt,r,he,ya,Dn)),Q=async(kt,nt,he,ya,Dn,ba)=>{var lp,up,pp;d--;let Xe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...he.seleniumStats&&{seleniumStats:he.seleniumStats},...he.gridIssues&&{gridIssues:he.gridIssues},...he.keepAliveIssue&&{keepAliveIssue:he.keepAliveIssue},...o.host&&{gridHost:o.host}};if(he.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(he.seleniumPerfMarks),delete he.seleniumPerfMarks),o.grid||o.gridId?(Xe.gridName=o.grid||((lp=o.gridData)==null?void 0:lp.name),Xe.gridType=(up=o.gridData)==null?void 0:up.type,Xe.gridProvider=(pp=o.gridData)==null?void 0:pp.provider):o.localTmaUrl?(Xe.gridName="local-tma-from-options",Xe.gridType="local-tma"):o.useLocalChromeDriver?(Xe.gridName="local-chrome-driver-from-options",Xe.gridType="local-chrome"):o.useChromeLauncher?(Xe.gridName="chrome-launcher-from-options",Xe.gridType="local-chrome"):o.browserstack?Xe.gridName="browserstack-from-options":o.saucelabs&&(Xe.gridName="saucelabs-from-options"),await t.testEndAndReport(kt,he,r,ya,Dn,Xe).catch(Nb=>Qu.error("testEndAndReport threw an error",{err:Nb})),Dn)return;v[he.resultId]=he,Ef({executionId:r,projectId:h,testId:nt,resultId:he.resultId,result:he,ucid:b,companyId:T,companyName:I,projectName:O,companyPlan:R,source:C,user:k,lightweightMode:$,logger:Qu,isStartUp:N,projectType:D,appSource:ba}),l&&!he.success&&(y.stop(),m=!0),(Object.keys(v).length===S||m&&d===0)&&f(v)},de=(kt,nt)=>{v[nt.resultId]=nt,t.onTestIgnored(kt,nt.resultId),d--,(Object.keys(v).length===S||m&&d===0)&&f(v)},$t=(kt,nt)=>t.onGridSlot(kt,nt);o.userData={loginData:Object.assign({},Mt(),{refreshToken:vo(),authData:Mt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},L("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,J,Q,$t,de).forEach((kt,nt)=>{L("before schedule worker.run after createWorkers"),gS(()=>{L("right before worker.run"),kt.run()},nt)})});try{let g=await Kt(),f=await p(g);if(m)throw new Gt;return f}catch(g){throw Qu.error("failed running parallel workers",{executionId:r,err:g}),g}}}});async function Hy(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Cc({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Zu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function ep(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Vy.difference(Ns(s,e),t);if(r.length>0)throw lt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Vy,qy=w(()=>{"use strict";Vy=E(require("lodash"));j();Xr();ye();z()});var Ln,v_,tp,rp,pa,zy=w(()=>{"use strict";Ln=E(require("lodash"));j();B();le();ce();Be();ts();Cl();ql();ye();Rt();At();Gf();z();Gy();qy();({testRunStatus:v_,CLI_MODE:tp}=Lt),rp=x("test-plan-runner"),pa=class{constructor(e){this.startTime=Date.now();this.workerManager=new ua(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},m=Mt(),d=async()=>{let h=o.beforeParallel||1,y=!0,v=await this.workerManager.runTests(e,c,i,a,o,n,m,h,y);Object.assign(l,v)},p=async()=>{let h=zn||o.parallel,y=!1;L("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,m,h,y);L("right after this.workerManager.runTests"),Object.assign(l,v)},g=async()=>{let h=o.afterParallel||1,y=!1,v=await this.workerManager.runTests(r,c,i,a,o,n,m,h,y);Object.assign(l,v)};Sf({executionId:i,projectId:o.project}),L("right before runBeforeTests");try{return await d(),L("right before runTestPlanTests"),await p(),L("right after runTestPlanTests"),await g(),l}catch(h){if(rp.error("error running test plan",{err:h}),h instanceof Gt)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await f()}async function f(){var y,v,S,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===tp.SELENIUM){let[{getSessionPlayer:T},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(be(),Yt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=T();await C.closeBatch(i,I);return}let h;try{if(!((b=(S=(v=o.company)==null?void 0:v.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(h=await qc(o.project),Ln.default.isEmpty(h)||!i))return;let{runKey:T,url:I}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:T}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,T,I;let l=te(),m=n.project;Oa(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let d=[...e,...t,...r],p=new ui(d,n,i,a),g=Ln.default.chain(d).map(C=>{var k;return((k=C.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(C=>C.name),y=(T=n.lightweightMode)!=null&&T.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:p.executionStart(l,m,this.startTime,o,h);L("before testListInfoPromise");let v=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||X.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,f),L("before runTestAllPhases");let S=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",p);return L("before executionEnd"),await p.executionEnd(l),L("after executionEnd"),{results:S,executionId:l,testPlanName:o,configName:f}}async runTestPlans(e,t){rp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(m){return Ln.default.flattenDeep(Object.values(m)).reduce((d,p)=>d.concat(p.beforeTests,p.tests,p.afterTests),[])}let n={},o={},i=e.project,a=await Pc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==tp.APPIUM&&await ep(e,r(l)),await ie(c,async m=>{var f;let d=m.testPlanId;n[d]={};let p=Object.assign({},e);p.baseUrl||=m.startUrl,p.appId||=((f=m.mobileApp)==null?void 0:f.appId)||void 0,p.gridId||=m.gridId,e.grid&&delete p.gridId,p.gridData=await sf(e,m);let g=p.overrideExecutionName||m.name;return await ie(l[d],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,p,g,d,t);X.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let v=Object.keys(n[d]).map(I=>({executionId:I,status:Zu(n[d][I])})),S=Object.keys(n[d]).map(I=>n[d][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Zu(S);Object.assign(o,S);let T=b?v[0].executionId:v.find(I=>!I.status).executionId;return await Ic(i,d,{success:b,executions:v,executionId:T}),y})})}async runAnonymousTestPlan(e,t){var a;rp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),L("before getSuite");let r=await Hy(e,t);if(L("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return L("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async c=>{if(e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==tp.APPIUM&&await ep(e,c),L("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return L("right after runTestPlan"),await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=ln(),r=[];Us(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Ln.default.flattenDeep(r);return L("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),L("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var Xy={};G(Xy,{init:()=>DS,run:()=>_S});async function yS(s){let e=s.project,t=await Oc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),tn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function bS(s,e){var i,a,c,l,m,d;let t=so(e.activePlan),r=s.parallel;if(t==="free"&&r>Jy)throw new P(`The free plan allows only ${Jy} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let p=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!p)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
|
|
408
|
+
Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}let n=s.retentionDays;if(!n)return;let o=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function TS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await yS(s)}catch(t){if([P,Ps].some(r=>t instanceof r))throw t;hS.error("could not validate cli account",{err:t})}}function wS(s){let e=Mt();return pm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function vS(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return ft.connect(s);if(!t){let{remoteStepService:n}=await Promise.resolve().then(()=>(wi(),Fg));await n.init(s)}if(!e){let{testResultService:n}=await Promise.resolve().then(()=>(vi(),$g));n.init(s,r)}}function ES(s,e){let{branch:t,autoDetect:r}=s;if(cf(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function SS(s){let{project:e}=s,t=ln();Yy.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await Sc({projectId:e,branch:t}))}function RS(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:p,ext:g,playerPath:f}=s;if([Y.SELENIUM].includes(d)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!p&&!g)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),m=so(a);m==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Ky?Ky:s.newBrowserWaitTimeout),M.setCompanyId(r),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(m),xt.setPlanType(m),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:m,isPOC:c,isStartUp:l,activePlan:a}}function IS(s,e){s.editorUrl=As||e.editorUrl}function xS(s,e){s.allGrids=e}function AS(s,e){s.authData=e}function PS(s,e){let{id:t,name:r,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function CS(s){s.gridData=await nf(s)}async function kS(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(lt("user-override-file",t),s.mockNetworkRules=await Zd(s.overrideMappingFile))}async function OS(s,e){L("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Lm(),L("in runner.js after checkNpmVersion"),await TS(s),L("in runRunner before tunnel.connect"),await Vo(s),L("in runRunner after tunnel.connect");let a=await new pa(e).run(s);return L("before tunnel.disconnect"),await Ho(s),await an.end(t),L("after tunnel.disconnect and gridService.keepAlive.end"),a}function LS(s){var e;xt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
|
|
409
409
|
\x1B[4m\x1B[36mOur Free grid offers basic service performance.
|
|
410
410
|
If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
|
|
411
|
-
`)}async function DS(s){var y,v,S;L("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o,parallel:i}=s,a=
|
|
411
|
+
`)}async function DS(s){var y,v,S;L("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o,parallel:i}=s,a=M.fetch(),c=vS(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep),maxNumberOfListeners:i||1});a.catch(()=>{}),c.catch(()=>{});let{authData:l,editorConfig:m,companyByProjectId:d,projectById:p,branchName:g,allGrids:f}=await Qs(s);bS(s,d),await Promise.all([a,c]),L("after featureFlagsReady and socketConnected"),IS(s,m),RS(s,d),PS(s,p),ES(s,g),xS(s,f),AS(s,l),await SS(s),(y=s.lightweightMode)!=null&&y.disableLabs||await hi.loadLabFeatures(p.id,d.activePlan),((v=s.lightweightMode)==null?void 0:v.type)==="turboMode"&&(M.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((S=s.lightweightMode)==null?void 0:S.type)==="turboMode"&&console.log(`
|
|
412
412
|
Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),an.start(e),wS(e),await kS(s),await CS(s),LS(s);let h=ln();await X.setOptions(s,h)}var Yy,Ky,Jy,hS,_S,Qy=w(()=>{"use strict";Yy=E(require("lodash"));j();wl();Al();Be();ts();Xr();Cl();ye();Rt();B();At();le();ce();z();zy();bi();lu();Te();pn();rl();Ky=30*60*1e3,Jy=1,hS=x("runner");_S=OS});function Zy(s){s.get("/",(e,t)=>{let r=sp();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Tl()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());pl({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var eb=w(()=>{"use strict";Qr();np();wl()});var op,tb,ws,da,rb=w(()=>{"use strict";op=E(require("chalk"));Ir();tb=require("express");B();z();ws=x("cli-router"),da=(0,tb.Router)();da.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let d=await as(t,r,n,o,i,a,c,l,m);d.success||(console.log(op.default.red(d.result.resultValue)),ws.error("CLI Action Failure",{message:d.result.resultValue})),e.status(200).json({success:!0,data:d})}catch(d){ws.error("failed to run cli code",{err:d}),console.log(op.default.red("failed to run cli code",d)),e.status(500).json({success:!1,code:"internal-error"})}});da.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:o,stepResultId:i,timeout:a}=s.body;if(!t||typeof o!="object"||!r||typeof n!="number"||!i||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}try{let c=await is(t,r,n,o,i,a);ws.info("installed packages successfully"),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof wt){ws.error("failed to install node packages",{err:c}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof re){ws.error("timeout installing node package"),e.status(200).json({success:!1,code:"timeout"});return}ws.error("failed to install node packages",{err:c}),e.status(500).json({success:!1,code:"internal-error"})}})});var MS,sb=w(()=>{"use strict";Ir();B();rb();MS=x("cli-service");xg().catch(s=>MS.warn("failed to clean local package folder",{err:s}))});async function NS(s,e,t="utf8"){let r=ib.join(ob.tmpdir(),s);return await nb.promises.writeFile(r,e,t),r}async function FS(s){var t;let e=Date.now();try{let r=`
|
|
413
413
|
module.paths = ${JSON.stringify(module.paths)};
|
|
414
414
|
process.on('unhandledRejection', (error) => {
|