@testim/testim-cli 4.96.0 → 4.97.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 CHANGED
@@ -7,19 +7,19 @@ This is probably due to an installation of @testim/testim-cli with sudo, and run
7
7
  Testim had missing write access to ${r||e}
8
8
 
9
9
  `),!0):!1}async function gm(s){return(await dm(`npm view ${s} version`)).stdout.trim()}function Uc(s){try{return Qt(s)}catch{return!1}}function hm(s,e){return require(br.join(s,`./node_modules/${e}/package.json`)).version}function ym(s){if(typeof s=="string"&&s.endsWith(".cjs"))return s;if(typeof s=="object"&&s!==null)for(let e of Object.keys(s).filter(t=>t!=="browser")){let t=ym(s[e]);if(t)return t}}function bm(s){let e=require(br.join(s,"package.json"));if(!("exports"in e))return"";let t=ym(e);if(!t)throw new ao(e.name);return t}async function xo(s,e,t){let r=br.join(s,"npm-shrinkwrap.json"),n=br.join(s,"npm-shrinkwrap-dummy.json"),o=!1;try{try{await ge(r)&&(await Mc.promises.rename(r,n),o=!0)}catch{}return await dm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(i=>{throw fm(i.stderr,s,e)?new jr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):i})}finally{if(o)try{await Mc.promises.rename(n,r)}catch{}}}function Tm(s,e,t,r){return new Promise((n,o)=>{let i=t?["--proxy",t]:[],a=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",c="",d="--no-save --no-package-lock --no-prune --prefer-offline --no-audit --progress=false".split(" "),m=(0,Ao.spawn)("node",[Nc,"i","--prefix",s,...d,...e,...i],a);m.stderr.pipe(process.stderr),m.stdout.pipe(process.stdout),m.stdout.on("data",u=>{l+=u}),m.stderr.on("data",u=>{c+=u}),m.on("close",u=>{var f,h;if(u){let g;try{let y=(f=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(c))==null?void 0:f[1],T=(h=/No matching version found for (\S+)@/gm.exec(c))==null?void 0:h[1];y||T?g=`404 Not Found - GET https://registry.npmjs.org/${T??y} - Not found`:fm(c,Nc)?g=`insufficient write access in location ${Nc}`:g=`Npm Installation closed with exit code ${u} with error: ${c}`}catch{g=`Npm Install closed with exit code ${u}
10
- stdout: ${l} stderr: ${c}`}mm.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),o(new At(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{o(new ne)}},r)})}var Mc,br,pm,Ao,dm,mm,Nc,Yr=w(()=>{"use strict";Mc=E(require("fs")),br=E(require("path"));B();pm=require("util"),Ao=require("child_process");j();Dc();Ks();K();dm=(0,pm.promisify)(Ao.exec),mm=x("cli-service");Nc=br.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var W,vm,_w,Ow,Lw,wm,Po,Fc,D,pe=w(()=>{"use strict";W=E(require("rox-node"));j();B();ue();vm=x("FeatureFlagsService"),_w=!Oe&&!0&&!pd,Ow=2e4,Lw=60*60*24,wm=["labs","disabled","enabled"],Po=class extends W.default.Variant{constructor(e="disabled"){super(e,wm)}getValue(){let e=super.getValue();return wm.includes(e)?e:(vm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Fc=class{constructor(){this.flags={useNewWSCLI:new W.default.Flag,useSafariWebdriverVisibilityChecks:new W.default.Flag,useClickimVisibilityChecks:new W.default.Flag,runGetElementCodeInAut:new W.default.Flag,enableFrameSwitchOptimization:new W.default.Flag,maximumJsResultSize:new W.default.Configuration(2e3*1024),skipFileInputClicks:new W.default.Flag,errorMessageOnBadNetwork:new W.default.Flag(!0),warnOnBadNetwork:new W.default.Flag(!1),overrideAzureStorageUrl:new W.default.Flag,autoSaveDownloadFileFireFox:new W.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new W.default.Flag(!0),experimentalPreCodeCompilation:new W.default.Flag(!0),experimentalAsyncCustomCode:new W.default.Flag,useSameBrowserForMultiTests:new Po("labs"),highSpeedMode:new Po,usePortedHtml5DragDrop:new W.default.Flag,testNamesToBeforeSuiteHook:new W.default.Flag,addCustomCapabilities:new W.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new W.default.Variant("{}"),LTNetworkCapabilities:new W.default.Flag,downloadToBase64:new W.default.Flag,publicGridURL:new W.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new W.default.Flag(!0),unsupportedCapsFields:new W.default.Variant("[]"),dontFocusOnInit:new W.default.Flag,retryOnSeleniumHubError:new W.default.Flag,enableLambdaTestTunnelNTLM:new W.default.Flag,enableLambdaTestTunnelSkipUpgrade:new W.default.Flag,tdcHsPreventNetworkCapture:new W.default.Flag,headSpinTdcEnableFlagCapability:new W.default.Flag,enableBatchTDC:new W.default.Flag,enableBatchHeadSpin:new W.default.Flag,clearRunnerFileCache:new W.default.Flag,forceTurboModeIfNeeded:new W.default.Flag,redisSlotManager:new W.default.Flag,tunnelBinaryNewVersion:new W.default.Flag(!1),encryptedCredentials:new W.default.Flag,computePackagePathFromPackageJsonExports:new W.default.Flag,sendExtensionOnEdgeNonLinux:new W.default.Flag,enableAppium2pCloudy:new W.default.Flag,reuseCliPkgInstallFolder:new W.default.Flag,getPublicIpFrom3rdPartyServices:new W.default.Flag,chromedriverCdnBinariesUrl:new W.default.Variant(""),sfdcHybridCompany:new W.default.Flag,allowFixingAppIdStructure:new W.default.Flag},W.default.register("default",this.flags)}setProjectId(e){W.default.setCustomStringProperty("projectId",e)}setProjectType(e){W.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){W.default.setCustomStringProperty("productType",e)}setCompanyId(e){W.default.setCustomStringProperty("companyId",e)}setPlanType(e){W.default.setCustomStringProperty("planType",e)}setIsPOC(e){W.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){W.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){W.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!_w)return;let e={fetchIntervalInSec:Lw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(W.default.setup(ld,e),Ow).catch(t=>vm.error("failed to get feature flag status",t))}},D=new Fc});var Am={};V(Am,{install:()=>Nw,isReady:()=>Uw,start:()=>Mw});var Em,Sm,Im,Rm,Bc,Dw,Nw,Mw,Uw,xm=w(()=>{"use strict";Em=E(require("fkill")),Sm=E(require("p-retry"));Yr();Ve();B();Ks();pe();Im="chromedriver",Rm=9515,Bc=`http://localhost:${Rm}/wd/hub`,Dw=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Nw=async()=>{let s=D.flags.chromedriverCdnBinariesUrl.getValue(),e=_e(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await xo(ht(),`${Im} --detect_chromedriver_version ${e}`)},Mw=async()=>{process.env.NODE_OPTIONS="",await(0,Em.default)(`:${Rm}`,{silent:!0}),await Qt(Im).start(Dw,!0)},Uw=async({chromeBinaryLocation:s})=>{await(0,Sm.default)(async()=>{var n;let e=await Te(`${Bc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ge({url:`${Bc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Us(`${Bc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Ys={};V(Ys,{getSessionPlayerFolder:()=>Gc,prepareChromeDriver:()=>Js,prepareCustomExtension:()=>$c,prepareExtension:()=>Wc,preparePlayer:()=>Tr});async function $c(s,e=!1){if(!s)return;if(_e(s)){let n=Xr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Fw(s)>jc&&!e)throw new P(Cm);return await Je(s,n),n}let t=Xr.resolve(s);if(!km.existsSync(t))throw new P(`Failed to find custom extension in location: ${t}`);if(wc(t)>jc&&!e)throw new P(Cm);return t}async function Fw(s){let e=(Ve(),be(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw ko.warn("failed to download custom extension",{err:t}),new P(`Failed to download custom extension from location: ${s}`)}}function Wc(s){ko.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:lo(t)}));return bt(()=>ie(e,({location:t,path:r})=>uo(t,r)),"prepareExtension",Om,e)()}async function Js(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(xm(),Am));try{await o.install(),await o.start(),t||await o.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(i){let a="Failed to initiate Chrome Driver";throw i instanceof jr||(ko.error(a,{...s,...Io(),error:(0,_m.serializeError)(i)}),console.log(`
10
+ stdout: ${l} stderr: ${c}`}mm.info(`Npm Install closed with exit code ${u}`,{message:g,stderr:c}),o(new At(g))}else n(l)}),setTimeout(()=>{try{m.kill()}finally{o(new ne)}},r)})}var Mc,br,pm,Ao,dm,mm,Nc,Yr=w(()=>{"use strict";Mc=E(require("fs")),br=E(require("path"));B();pm=require("util"),Ao=require("child_process");j();Dc();Ks();K();dm=(0,pm.promisify)(Ao.exec),mm=x("cli-service");Nc=br.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var W,vm,_w,Ow,Lw,wm,Po,Fc,L,pe=w(()=>{"use strict";W=E(require("rox-node"));j();B();ue();vm=x("FeatureFlagsService"),_w=!Oe&&!0&&!pd,Ow=2e4,Lw=60*60*24,wm=["labs","disabled","enabled"],Po=class extends W.default.Variant{constructor(e="disabled"){super(e,wm)}getValue(){let e=super.getValue();return wm.includes(e)?e:(vm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},Fc=class{constructor(){this.flags={useNewWSCLI:new W.default.Flag,useSafariWebdriverVisibilityChecks:new W.default.Flag,useClickimVisibilityChecks:new W.default.Flag,runGetElementCodeInAut:new W.default.Flag,enableFrameSwitchOptimization:new W.default.Flag,maximumJsResultSize:new W.default.Configuration(2e3*1024),skipFileInputClicks:new W.default.Flag,errorMessageOnBadNetwork:new W.default.Flag(!0),warnOnBadNetwork:new W.default.Flag(!1),overrideAzureStorageUrl:new W.default.Flag,autoSaveDownloadFileFireFox:new W.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new W.default.Flag(!0),experimentalPreCodeCompilation:new W.default.Flag(!0),experimentalAsyncCustomCode:new W.default.Flag,useSameBrowserForMultiTests:new Po("labs"),highSpeedMode:new Po,usePortedHtml5DragDrop:new W.default.Flag,testNamesToBeforeSuiteHook:new W.default.Flag,addCustomCapabilities:new W.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new W.default.Variant("{}"),LTNetworkCapabilities:new W.default.Flag,downloadToBase64:new W.default.Flag,publicGridURL:new W.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new W.default.Flag(!0),unsupportedCapsFields:new W.default.Variant("[]"),dontFocusOnInit:new W.default.Flag,retryOnSeleniumHubError:new W.default.Flag,enableLambdaTestTunnelNTLM:new W.default.Flag,enableLambdaTestTunnelSkipUpgrade:new W.default.Flag,tdcHsPreventNetworkCapture:new W.default.Flag,headSpinTdcEnableFlagCapability:new W.default.Flag,enableBatchTDC:new W.default.Flag,enableBatchHeadSpin:new W.default.Flag,clearRunnerFileCache:new W.default.Flag,forceTurboModeIfNeeded:new W.default.Flag,redisSlotManager:new W.default.Flag,tunnelBinaryNewVersion:new W.default.Flag(!1),encryptedCredentials:new W.default.Flag,computePackagePathFromPackageJsonExports:new W.default.Flag,sendExtensionOnEdgeNonLinux:new W.default.Flag,enableAppium2pCloudy:new W.default.Flag,reuseCliPkgInstallFolder:new W.default.Flag,getPublicIpFrom3rdPartyServices:new W.default.Flag,chromedriverCdnBinariesUrl:new W.default.Variant(""),sfdcHybridCompany:new W.default.Flag,allowFixingAppIdStructure:new W.default.Flag,enableAppium2BrowserStack:new W.default.Flag},W.default.register("default",this.flags)}setProjectId(e){W.default.setCustomStringProperty("projectId",e)}setProjectType(e){W.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){W.default.setCustomStringProperty("productType",e)}setCompanyId(e){W.default.setCustomStringProperty("companyId",e)}setPlanType(e){W.default.setCustomStringProperty("planType",e)}setIsPOC(e){W.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){W.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){W.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!_w)return;let e={fetchIntervalInSec:Lw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(W.default.setup(ld,e),Ow).catch(t=>vm.error("failed to get feature flag status",t))}},L=new Fc});var Am={};V(Am,{install:()=>Nw,isReady:()=>Uw,start:()=>Mw});var Em,Sm,Im,Rm,Bc,Dw,Nw,Mw,Uw,xm=w(()=>{"use strict";Em=E(require("fkill")),Sm=E(require("p-retry"));Yr();Ve();B();Ks();pe();Im="chromedriver",Rm=9515,Bc=`http://localhost:${Rm}/wd/hub`,Dw=["--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],Nw=async()=>{let s=L.flags.chromedriverCdnBinariesUrl.getValue(),e=_e(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await xo(ht(),`${Im} --detect_chromedriver_version ${e}`)},Mw=async()=>{process.env.NODE_OPTIONS="",await(0,Em.default)(`:${Rm}`,{silent:!0}),await Qt(Im).start(Dw,!0)},Uw=async({chromeBinaryLocation:s})=>{await(0,Sm.default)(async()=>{var n;let e=await Te(`${Bc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ge({url:`${Bc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Us(`${Bc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var Ys={};V(Ys,{getSessionPlayerFolder:()=>Gc,prepareChromeDriver:()=>Js,prepareCustomExtension:()=>$c,prepareExtension:()=>Wc,preparePlayer:()=>Tr});async function $c(s,e=!1){if(!s)return;if(_e(s)){let n=Xr.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Fw(s)>jc&&!e)throw new P(Cm);return await Je(s,n),n}let t=Xr.resolve(s);if(!km.existsSync(t))throw new P(`Failed to find custom extension in location: ${t}`);if(wc(t)>jc&&!e)throw new P(Cm);return t}async function Fw(s){let e=(Ve(),be(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw ko.warn("failed to download custom extension",{err:t}),new P(`Failed to download custom extension from location: ${s}`)}}function Wc(s){ko.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:lo(t)}));return bt(()=>ie(e,({location:t,path:r})=>uo(t,r)),"prepareExtension",Om,e)()}async function Js(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),o=await Promise.resolve().then(()=>(xm(),Am));try{await o.install(),await o.start(),t||await o.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(i){let a="Failed to initiate Chrome Driver";throw i instanceof jr||(ko.error(a,{...s,...Io(),error:(0,_m.serializeError)(i)}),console.log(`
11
11
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
12
12
  2. If Chrome is installed, please verify it's binary directory:
13
13
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
14
14
  - exists in your PATH environment variables.
15
15
  3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
16
- 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function Bw(){let s=`${Mr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}async function jw(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await Bw();return`${s}-${t}`}function Gc(){let s=ht();return Xr.resolve(s,"testim-bin")}function $w(){let s=Gc();return Xr.resolve(s,"sessionPlayer.zip")}async function Lm(s,e,t=!1){try{return await uo(s,e),await rt(e,Gc())}catch(r){if(t)throw r;return await Lm(s,e,!0)}}async function Tr(s,e){ko.info("prepare player",{location:s,canary:e});let t=$w();return bt(async()=>{let r=await jw(s,e);return await Lm(r,t),{}},"preparePlayer",Om,[s,e,t])()}var Pm,km,Xr,_m,ko,Om,jc,Cm,Xs=w(()=>{"use strict";Pm=E(require("ms")),km=E(require("fs")),Xr=E(require("path"));ue();Bt();_m=require("serialize-error");j();Dc();K();B();ko=x("prepare runner and testim start"),Om=(0,Pm.default)("0.5 day"),jc=16,Cm=`The size of the custom extension is more than ${jc}MB`});function Ww(){let s=Qs.type().toLowerCase();return s==="darwin"?Qs.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Qs.arch()==="x64"?"win64":"win32":"linux"}async function Oo(){let s=Ww(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new P(`Unsupported platform: ${s}`);let r=parseInt(Zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${Zs}/${n[s]}.zip`,a=_o.join(Vc,n[s]),l=`${a}.zip`,c=_o.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Hc.default)("Downloading Chromium").start();try{await Dm.promises.mkdir(Vc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Hc.default)("Extracting Chromium").start();try{await rt(l,Vc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Dm,Qs,_o,Hc,Zs,Vc,qc=w(()=>{"use strict";Dm=E(require("fs")),Qs=E(require("os")),_o=E(require("path")),Hc=E(require("ora"));K();B();Zs="1000968",Vc=_o.join(Ft,`chrome-${Zs}`)});async function Fm(s,e){return wr=s,Yc=e,await zc()}function Bm(s,e){wr=e.projectId,Yc=e.token,en=e.userAccessKey,st=s.token,rn=Xc(st),sn=s.refreshToken,Kc=s.ngrokToken,Jc=s.isNgrokWhitelisted,Nm=e.publicIp,Mm=e.initializedFromCache}function Gw(s=wr,e=Yc){return bt(()=>(tn.info("request to get cli token from server"),Ge({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Um*10,{projectId:s,token:e})()}async function Vw(){tn.info("request to refresh JWT cli token from server");let s=await Ge({url:`${fe}/auth/refreshToken`,body:{token:st,refreshToken:sn}});return st=s.token,rn=Xc(st),s.refreshToken&&(sn=s.refreshToken),st}async function zc(){try{let s=await Gw();return tn.info("successfully get cli token from server"),st=s.token,rn=Xc(st),sn=s.refreshToken,Kc=s.ngrokToken,Jc=s.isNgrokWhitelisted,st}catch(s){throw s.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(tn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:wr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function Xc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!rn)return zc();if(rn<Date.now()+4*Um)try{return await Vw()}catch(s){return tn.error("failed to refresh token, executing fallback",s),zc()}return st}function Lo(){return sn}function jt(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Kc,isNgrokWhitelisted:Jc}:{}}async function Do(){if(!en||!wr)return;if(await Qc({userAccessKey:en,projectId:wr}))return en;let e=`user access key "${en}" is invalid for project "${wr}"`;throw new P(e)}function No(){return Nm}function Mo(){return Mm}var tn,st,rn,sn,Kc,Jc,wr,Yc,en,Nm,Mm,Um,nt=w(()=>{"use strict";ue();Ve();Bt();K();j();he();tn=x("testim-custom-token"),wr=null,Yc=null,Um=5*60*1e3});var jm={};V(jm,{isCi:()=>Qr});var Qr,Uo=w(()=>{"use strict";Qr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var xe={};V(xe,{addTestRetry:()=>El,clearTestResult:()=>Tl,deleteCloudflareTunnel:()=>Al,fetchLambdatestConfig:()=>hl,fixGridAppIDStructure:()=>kl,forceUpdateCloudflareTunnelRoutes:()=>Rl,getAllGrids:()=>gl,getAppDetails:()=>an,getApplitoolsIntegrationData:()=>Sl,getBrowserStackSessionMetaData:()=>ev,getCloudflareTunnel:()=>Il,getEditorUrl:()=>Xw,getGridById:()=>Bo,getGridByName:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>yl,getMobileDevicesFromGrid:()=>Cl,getRealData:()=>bl,getS3Artifact:()=>on,getS3ArtifactText:()=>el,getSuiteTestList:()=>al,getTestPlan:()=>Yw,getTestPlanTestList:()=>il,getTestResults:()=>Er,getUsageForCurrentBillingPeriod:()=>cl,initializeUserWithAuth:()=>fl,isTestResultCompleted:()=>ll,keepAliveCompanySlots:()=>Dl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>tl,loadTest:()=>rl,releaseCompanySlot:()=>Ol,releaseGridSlot:()=>pl,reportExecutionFinished:()=>Fo,reportExecutionStarted:()=>ol,requestCompanySlot:()=>_l,saveRemoteStep:()=>wl,saveTestPlanResult:()=>sl,updateCompanySlot:()=>Ll,updateExecutionTests:()=>nl,updateRemoteRunFailure:()=>xl,updateTestDataArtifact:()=>$o,updateTestResult:()=>jo,updateTestStatus:()=>vr,uploadAppToGrid:()=>Pl,uploadRunDataArtifact:()=>vl,validateUserAccessKey:()=>Qc});async function Zr(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ae({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Zr(),i={...t,...o};return Ge({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function zw(s,e,t,r={},n=void 0){let o=await Zr(),i={...r,...o};return await Fs(`${fe}${s||""}`,e,t,i,n)}async function nn(s,e){let t=await Zr();return await gc(`${fe}${s||""}`,e,t)}async function Kw(s,e){let t=await Zr();return await Us(`${fe}${s||""}`,e,t)}async function Jw(s,e){let t=await Zr();return await Bs(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await Zr();return await Te(`${fe}${s||""}`,e||void 0,n,r,t)}function on(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function el(s){return(0,X.default)(()=>Jw(`/storage${s}`))}async function Yw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function tl({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function rl({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function sl(s,e,t){return(0,X.default)(()=>Ae({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,o,i=ee){return(0,X.default)(()=>nn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Hw,...o}),{retries:i,factor:1})}function nl(s,e,t,r,n,o,i,a){return(0,X.default)(()=>nn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function ol({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Uo(),jm));return Ae({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Fo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,X.default)(()=>nn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function il(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function al({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Ae({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function an({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function cl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function ll(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Er(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function ul(s,e){return Ae({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ae({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ae({url:"/grid/hybrid/provider",body:s})}function ml(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Bo(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function fl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:o,gridId:i,grid:a}){var l,c;try{return await(0,X.default)(()=>Ge({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:o,gridId:i,gridName:a}}),{retries:ee,factor:1})}catch(d){throw Wt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Xw(){if(_s)return{editorUrl:_s};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function gl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function bl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function jo(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function Tl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function wl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Qw(s){return s.startsWith("/")?s:`/${s}`}function Zw(s,e,t){let r=Qw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Wm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=Zw(l,"test-result-artifacts",s),d=Buffer.from($m.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>zw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function El({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,X.default)(()=>Ae({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function Sl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Il(s,e){try{return await nn("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function Rl(s,e){try{return await Ae({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function Al(s,e){try{return await Kw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function xl(s){return Ge({url:`${fe}/result/remoteRunFailure`,body:s})}async function Cl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${qw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,X.default)(()=>Se(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Pl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Ae({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function kl(s){return(0,X.default)(()=>Ae({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function _l(s,e){return(0,X.default)(()=>Ae({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Ol(s,e,t){return(0,X.default)(()=>Ae({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function Ll(s,e,t){return(0,X.default)(()=>nn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function Dl(s,e,t){return Ae({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function ev(s,e){return await Te(`${Os}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Qc(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,$m,X,Zc,Hw,Wt,ee,qw,hl,yl,vl,$o,he=w(()=>{"use strict";er=E(require("lodash")),$m=E(require("pako"));B();ue();ae();Ve();nt();X=E(require("p-retry")),Zc=E(require("object-hash"));K();j();Hw=gt(),Wt=x("testim service api"),ee=3,qw="/grid";hl=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),yl=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});vl=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Wm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Zc.default)(r)}:${e}:${t}`),$o=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Wm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Sc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Zc.default)(r)}:${e}:${t}`)});async function Gm(){let s=await Promise.any(tv.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var tv,Vm=w(()=>{"use strict";Ve();tv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};V(tr,{getSessionPlayer:()=>te,options:()=>Ml});var Wo,Ml,Nl,te,we=w(()=>{"use strict";Wo=require("path");j();Ml={playerPath:void 0},te=()=>{if(Nl)return Nl;let s=($e(),be(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Xs(),be(Ys)),t=e(),r=Ml.playerPath?(0,Wo.resolve)(Ml.playerPath,"src/background/sessionPlayerInit.ts"):(0,Wo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Nl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(sc),n}});function nv(s){process.nextTick(()=>{if([Z.SELENIUM,Z.APPIUM].includes(s))try{(we(),be(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?sv:rv,f=null;if(D.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Gm()}catch(y){Hm.error("failed to get public ip",y)}let h=!0;M("before initializeUserWithAuth");let g=await bt(async()=>(nv(a),h=!1,await fl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],M("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(Hm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),Bm(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var Hm,rv,sv,qm=w(()=>{"use strict";$e();he();Bt();nt();Vm();ae();j();pe();Hm=x("initializeUserWithAuth"),rv=1e3*60*5,sv=1e3*60*60*10});async function Jm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Oo():s.chromeBinaryLocation,e=Js({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Z.EXTENSION&&await Tr(s.playerLocation,s.canary),s.mode===Z.EXTENSION&&!s.ext&&await Wc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await $c(s.installCustomExtension,n)}return await e,t}async function Ym(s){var i;ov.info("prepare MockNetwork",{location:s});let e=await Tc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>zm*1e6)throw new Error(`${Ul} exceeded ${zm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Ul} cannot be parsed.${Go.EOL}${a}`)}let n=new Km.default;if(!n.validate(Oc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Go.EOL);throw new Error(`${Ul} is malformed.${Go.EOL}${a}`)}return r.entries}var Go,Km,zm,Ul,ov,Fl=w(()=>{"use strict";Go=E(require("os"));B();Xd();Xs();Km=E(require("ajv"));ae();qc();qm();zm=1,Ul="JSON file supplied to --mock-network-pattern",ov=(j(),be(ac)).getLogger("prepare runner")});function Qm(s,e=process){async function t(r){await ce(ie(Xm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function es(s){Xm.push(s)}var ln,Xm,un=w(()=>{"use strict";j();B();ln=x("process-handler"),Xm=[]});function Wl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?fd:Mr}/extension/testim-firefox-profile${t}`,n=`${e?gd:Mr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function sf(s){let{chrome:e,firefox:t}=Wl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Ho(s){let e=`${Mr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var qo=w(()=>{"use strict";ue()});function lf(s){Oe||(s!=null&&s.userId||(s={anonymousId:cf}),af.identify(s))}function Tt(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:cf};af.track(Object.assign(r,{event:e,properties:t}))}var of,af,cf,ts=w(()=>{"use strict";ue();of=require("@segment/analytics-node"),af=new of.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),cf=require("crypto").randomBytes(20).toString("hex")});function uf(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function pf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Ho(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var df=w(()=>{"use strict";qo();ts();K()});var mf,dv,mv,Gl,ff=w(()=>{"use strict";mf="TST_CREDS",dv=["username","password"],mv="$encrypted",Gl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of dv)t[r]={[mv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(mf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[mf]:this.proxyPlaceholder})}}});function Ko(s){let{platform:e}=process;e==="win32"?(0,zo.exec)(`start chrome ${s}`):e==="darwin"?(0,zo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,zo.exec)(`google-chrome ${s}`)}var zo,Vl=w(()=>{"use strict";zo=require("child_process")});var Jl={};V(Jl,{doLogin:()=>Kl,getProjectId:()=>fv,getToken:()=>gv});async function fv(){return yf("projectId")}async function gv(){return yf("token")}function hf(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function hv(){let s=(await import("express")).default(),e=async function(){return hf(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),xe)),{editorUrl:n}=await r();Ko(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Kl({overwriteExisting:s=!0,projects:e=null}={}){let t=Hl.homedir(),r=ql.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await hf(hv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await gf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await gf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function gf(s,e){await zl.promises.writeFile(s,Jo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function yf(s){let e=Hl.homedir(),t=ql.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Jo.parse((await zl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Hl,ql,Jo,zl,Yo=w(()=>{"use strict";Hl=E(require("os")),ql=E(require("path")),Jo=E(require("yaml"));B();zl=require("fs");K();Vl()});var If={};V(If,{process:()=>Iv});var Xl,wf,Xo,vf,Gt,Me,Ef,yv,Ne,eu,bv,Tv,bf,Sf,wv,Ql,Zl,tu,Yl,Pt,vv,p,Ev,Sv,Tf,Iv,Rf=w(()=>{"use strict";Xl=E(require("ms")),wf=E(require("chalk")),Xo=E(require("fs")),vf=E(require("url")),Gt=E(require("lodash")),Me=E(require("path"));B();qo();df();Bt();Ef=require("commander");ae();K();Nr();B();pe();ff();yv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),eu=new Ef.Command,bv=s=>s.split(","),Tv=(s,e)=>!s||s.length===0?e:s,bf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Sf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}eu.help(g=>g.split(`
16
+ 4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),i}}async function Bw(){let s=`${Mr}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}async function jw(s,e){if(!_e(s)||_e(s)&&e||Oe)return s;let t=await Bw();return`${s}-${t}`}function Gc(){let s=ht();return Xr.resolve(s,"testim-bin")}function $w(){let s=Gc();return Xr.resolve(s,"sessionPlayer.zip")}async function Lm(s,e,t=!1){try{return await uo(s,e),await rt(e,Gc())}catch(r){if(t)throw r;return await Lm(s,e,!0)}}async function Tr(s,e){ko.info("prepare player",{location:s,canary:e});let t=$w();return bt(async()=>{let r=await jw(s,e);return await Lm(r,t),{}},"preparePlayer",Om,[s,e,t])()}var Pm,km,Xr,_m,ko,Om,jc,Cm,Xs=w(()=>{"use strict";Pm=E(require("ms")),km=E(require("fs")),Xr=E(require("path"));ue();Bt();_m=require("serialize-error");j();Dc();K();B();ko=x("prepare runner and testim start"),Om=(0,Pm.default)("0.5 day"),jc=16,Cm=`The size of the custom extension is more than ${jc}MB`});function Ww(){let s=Qs.type().toLowerCase();return s==="darwin"?Qs.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?Qs.arch()==="x64"?"win64":"win32":"linux"}async function Oo(){let s=Ww(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new P(`Unsupported platform: ${s}`);let r=parseInt(Zs,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},o={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},i=`${e}/${t[s]}/${Zs}/${n[s]}.zip`,a=_o.join(Vc,n[s]),l=`${a}.zip`,c=_o.join(a,o[s]);if(await ge(c))return c;if(!await ge(l)){let m=(0,Hc.default)("Downloading Chromium").start();try{await Dm.promises.mkdir(Vc),await Je(i,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,Hc.default)("Extracting Chromium").start();try{await rt(l,Vc)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Dm,Qs,_o,Hc,Zs,Vc,qc=w(()=>{"use strict";Dm=E(require("fs")),Qs=E(require("os")),_o=E(require("path")),Hc=E(require("ora"));K();B();Zs="1000968",Vc=_o.join(Ft,`chrome-${Zs}`)});async function Fm(s,e){return wr=s,Yc=e,await zc()}function Bm(s,e){wr=e.projectId,Yc=e.token,en=e.userAccessKey,st=s.token,rn=Xc(st),sn=s.refreshToken,Kc=s.ngrokToken,Jc=s.isNgrokWhitelisted,Nm=e.publicIp,Mm=e.initializedFromCache}function Gw(s=wr,e=Yc){return bt(()=>(tn.info("request to get cli token from server"),Ge({url:`${fe}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",Um*10,{projectId:s,token:e})()}async function Vw(){tn.info("request to refresh JWT cli token from server");let s=await Ge({url:`${fe}/auth/refreshToken`,body:{token:st,refreshToken:sn}});return st=s.token,rn=Xc(st),s.refreshToken&&(sn=s.refreshToken),st}async function zc(){try{let s=await Gw();return tn.info("successfully get cli token from server"),st=s.token,rn=Xc(st),sn=s.refreshToken,Kc=s.ngrokToken,Jc=s.isNgrokWhitelisted,st}catch(s){throw s.message.includes("Unauthorized")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(tn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:wr}),new P(`While trying to retrieve CLI token, caught error: ${s}`))}}function Xc(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Zt(){if(!rn)return zc();if(rn<Date.now()+4*Um)try{return await Vw()}catch(s){return tn.error("failed to refresh token, executing fallback",s),zc()}return st}function Lo(){return sn}function jt(){return st?{uid:require("jsonwebtoken").decode(st).id,ngrokToken:Kc,isNgrokWhitelisted:Jc}:{}}async function Do(){if(!en||!wr)return;if(await Qc({userAccessKey:en,projectId:wr}))return en;let e=`user access key "${en}" is invalid for project "${wr}"`;throw new P(e)}function No(){return Nm}function Mo(){return Mm}var tn,st,rn,sn,Kc,Jc,wr,Yc,en,Nm,Mm,Um,nt=w(()=>{"use strict";ue();Ve();Bt();K();j();he();tn=x("testim-custom-token"),wr=null,Yc=null,Um=5*60*1e3});var jm={};V(jm,{isCi:()=>Qr});var Qr,Uo=w(()=>{"use strict";Qr=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});var xe={};V(xe,{addTestRetry:()=>El,clearTestResult:()=>Tl,deleteCloudflareTunnel:()=>Al,fetchLambdatestConfig:()=>hl,fixGridAppIDStructure:()=>kl,forceUpdateCloudflareTunnelRoutes:()=>Rl,getAllGrids:()=>gl,getAppDetails:()=>an,getApplitoolsIntegrationData:()=>Sl,getBrowserStackSessionMetaData:()=>ev,getCloudflareTunnel:()=>Il,getEditorUrl:()=>Xw,getGridById:()=>Bo,getGridByName:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>yl,getMobileDevicesFromGrid:()=>Cl,getRealData:()=>bl,getS3Artifact:()=>on,getS3ArtifactText:()=>el,getSuiteTestList:()=>al,getTestPlan:()=>Yw,getTestPlanTestList:()=>il,getTestResults:()=>Er,getUsageForCurrentBillingPeriod:()=>cl,initializeUserWithAuth:()=>fl,isTestResultCompleted:()=>ll,keepAliveCompanySlots:()=>Dl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>tl,loadTest:()=>rl,releaseCompanySlot:()=>Ol,releaseGridSlot:()=>pl,reportExecutionFinished:()=>Fo,reportExecutionStarted:()=>ol,requestCompanySlot:()=>_l,saveRemoteStep:()=>wl,saveTestPlanResult:()=>sl,updateCompanySlot:()=>Ll,updateExecutionTests:()=>nl,updateRemoteRunFailure:()=>xl,updateTestDataArtifact:()=>$o,updateTestResult:()=>jo,updateTestStatus:()=>vr,uploadAppToGrid:()=>Pl,uploadRunDataArtifact:()=>vl,validateUserAccessKey:()=>Qc});async function Zr(){let s=await Zt();if(!s)throw new Error("Failed to get token from server");return{Authorization:`Bearer ${s}`}}async function Ae({url:s,body:e,headers:t={},timeout:r,retry:n}){let o=await Zr(),i={...t,...o};return Ge({url:`${fe}${s||""}`,body:e,headers:i,timeout:r,retry:n})}async function zw(s,e,t,r={},n=void 0){let o=await Zr(),i={...r,...o};return await Fs(`${fe}${s||""}`,e,t,i,n)}async function nn(s,e){let t=await Zr();return await gc(`${fe}${s||""}`,e,t)}async function Kw(s,e){let t=await Zr();return await Us(`${fe}${s||""}`,e,t)}async function Jw(s,e){let t=await Zr();return await Bs(`${fe}${s||""}`,e||void 0,t)}async function Se(s,e,t,r){let n=await Zr();return await Te(`${fe}${s||""}`,e||void 0,n,r,t)}function on(s,e){return(0,X.default)(()=>Se(`/storage${s}`,null,{isBinary:!0},e),{retries:ee,factor:1})}function el(s){return(0,X.default)(()=>Jw(`/storage${s}`))}async function Yw(s,e){let t=n=>n==null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,X.default)(()=>Se("/testPlan",{projectId:s,name:e.join(",")}),{retries:ee,factor:1})).map(({testConfigIds:n,beforeAllLabels:o,testLabels:i,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(o),testLabels:t(i),afterAllLabels:t(a)}))}async function tl({branch:s,projectId:e}){let t=await(0,X.default)(()=>Se(`/branch/branchData/${s}`,{projectId:e}),{retries:ee,factor:1});return t==null?void 0:t.sfdcCredential}function rl({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,X.default)(()=>Se(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:ee,factor:1})}function sl(s,e,t){return(0,X.default)(()=>Ae({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:ee,factor:1})}function vr(s,e,t,r,n,o,i=ee){return(0,X.default)(()=>nn("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:Hw,...o}),{retries:i,factor:1})}function nl(s,e,t,r,n,o,i,a){return(0,X.default)(()=>nn("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:o,endTime:i,projectId:a}),{retries:ee,factor:1})}async function ol({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:o,resultLabels:i,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Uo(),jm));return Ae({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:o,resultLabels:i,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function Fo(s,e,t,r,n={},o=void 0,i=void 0){let a=Date.now();return(0,X.default)(()=>nn("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:o,resultExtraData:i}),{retries:ee,factor:1})}async function il(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:ee,factor:1})}function al({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,X.default)(()=>Ae({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:o,suiteIds:i,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:ee,factor:1})}async function an({appId:s,projectId:e}){try{return await(0,X.default)(()=>Se(`/mobile-app/app/${s}?projectId=${e}`),{retries:ee,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function cl(s){try{return await(0,X.default)(()=>Se(`/plan/project/${s}/usage-current-billing-period`),{retries:ee,factor:1})}catch(e){Wt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function ll(s,e,t){return(0,X.default)(()=>Se(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:ee,factor:1})}function Er(s,e,t,r){return(0,X.default)(()=>Se(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:ee,factor:1})}function ul(s,e){return Ae({url:`/grid/keep-alive?reqId=${se()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ae({url:`/grid/release?reqId=${se()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ae({url:"/grid/hybrid/provider",body:s})}function ml(s,e,t,r,n){return(0,X.default)(()=>Se("/grid/name",{companyId:s,projectId:e,name:t,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}function Bo(s,e,t,r,n){return(0,X.default)(()=>Se(`/grid/${t}`,{companyId:s,projectId:e,browser:r,executionId:n,reqId:se()}),{retries:ee,factor:1})}async function fl({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:o,gridId:i,grid:a}){var l,c;try{return await(0,X.default)(()=>Ge({url:`${fe}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:o,gridId:i,gridName:a}}),{retries:ee,factor:1})}catch(d){throw Wt.error("error initializing info from server",d),(l=d==null?void 0:d.message)!=null&&l.includes("Bad Request")?new P("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(c=d==null?void 0:d.code)!=null&&c.includes("ENOTFOUND")?new P("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend."):d}}async function Xw(){if(_s)return{editorUrl:_s};try{return await(0,X.default)(()=>Se("/system-info/editor-url"),{retries:ee,onFailedAttempt:s=>{if(s.attemptNumber>=ee)throw s},factor:1})}catch{return Wt.error("cannot retrieve editor-url from server"),{editorUrl:"https://app.testim.io"}}}function gl(s){return(0,X.default)(()=>Se("/grid",{companyId:s}),{retries:ee,factor:1})}function bl(s,e,t){return(0,X.default)(()=>Se(`/real-data/${e}?${t}&projectId=${s}`),{retries:ee,factor:1})}function jo(s,e,t,r,n){return(0,X.default)(()=>Ae({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:ee,factor:1})}function Tl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:ee,factor:1})}function wl(s,e,t,r){return(0,X.default)(()=>Ae({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:ee,factor:1})}function Qw(s){return s.startsWith("/")?s:`/${s}`}function Zw(s,e,t){let r=Qw(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Wm(s,e,t,r,n,o="application/octet-stream"){let i=null;o==="application/json"&&(i=".json");let a=`${n}_${se()}${i||""}`,l=`${e}/${t}/${a}`,c=Zw(l,"test-result-artifacts",s),d=Buffer.from($m.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,X.default)(()=>zw(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:ee,factor:1}),c}function El({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:o,testResult:i}){return(0,X.default)(()=>Ae({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:o,testId:t,runId:e,testResult:i}}),{retries:ee,factor:1})}async function Sl(s){try{return await Se(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Wt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Il(s,e){try{return await nn("/tunnel",{companyId:s,routes:e})}catch(t){return Wt.warn("could'nt get tunnel.",{err:t}),{}}}async function Rl(s,e){try{return await Ae({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}async function Al(s,e){try{return await Kw(`/tunnel/${e}`,{companyId:s})}catch(t){Wt.warn("could'nt get tunnel.",{err:t});return}}function xl(s){return Ge({url:`${fe}/result/remoteRunFailure`,body:s})}async function Cl({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let o=`${qw}/mobileDevices/${t}/${r}?projectType=${e}`;o=n?`${o}&selectors=${encodeURIComponent(n)}`:o;try{return await(0,X.default)(()=>Se(o,{projectId:s}),{retries:ee,factor:1})}catch(i){return Wt.warn("could'nt get devices from headspin grid.",{err:i}),null}}async function Pl({projectId:s,gridId:e,app:t,timeout:r}){return(0,X.default)(()=>Ae({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:ee,factor:1})}async function kl(s){return(0,X.default)(()=>Ae({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:ee,factor:1})}async function _l(s,e){return(0,X.default)(()=>Ae({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:ee,factor:1})}async function Ol(s,e,t){return(0,X.default)(()=>Ae({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:ee,factor:1})}async function Ll(s,e,t){return(0,X.default)(()=>nn("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:ee,factor:1})}function Dl(s,e,t){return Ae({url:`/slot-management/keep-alive?reqId=${se()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function ev(s,e){return await Te(`${Os}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function Qc(s){try{return await Se("/v2/project/validateUserAccessKey",s),!0}catch(e){return Wt.error("error validating user access key",{error:e}),!1}}var er,$m,X,Zc,Hw,Wt,ee,qw,hl,yl,vl,$o,he=w(()=>{"use strict";er=E(require("lodash")),$m=E(require("pako"));B();ue();ae();Ve();nt();X=E(require("p-retry")),Zc=E(require("object-hash"));K();j();Hw=gt(),Wt=x("testim service api"),ee=3,qw="/grid";hl=async()=>(0,X.default)(()=>Se("/grid/lt/config"),{retries:ee,factor:1}),yl=async s=>(0,X.default)(()=>Se(`/labFeature/v2/project/${s}`),{retries:ee,factor:1});vl=er.memoize(async(s,e,t,r)=>{if(!er.isEmpty(r))return await Wm(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Zc.default)(r)}:${e}:${t}`),$o=er.memoize(async(s,e,t,r,n)=>!r||er.isEmpty(r)?void 0:await Wm(s,e,t,JSON.stringify((()=>{let i=er.clone(r);if(n!=null&&n.hiddenParams){let{hiddenParams:a}=n;(a||[]).forEach(l=>{i[l]&&Object.assign(i,{[l]:Sc.HIDDEN_PARAM})})}return i})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Zc.default)(r)}:${e}:${t}`)});async function Gm(){let s=await Promise.any(tv.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var tv,Vm=w(()=>{"use strict";Ve();tv=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});var tr={};V(tr,{getSessionPlayer:()=>te,options:()=>Ml});var Wo,Ml,Nl,te,we=w(()=>{"use strict";Wo=require("path");j();Ml={playerPath:void 0},te=()=>{if(Nl)return Nl;let s=($e(),be(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(Xs(),be(Ys)),t=e(),r=Ml.playerPath?(0,Wo.resolve)(Ml.playerPath,"src/background/sessionPlayerInit.ts"):(0,Wo.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),Nl=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(sc),n}});function nv(s){process.nextTick(()=>{if([Z.SELENIUM,Z.APPIUM].includes(s))try{(we(),be(tr)).getSessionPlayer()}catch{}})}async function cn(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:o,useChromeLauncher:i,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(o||i),u=d?sv:rv,f=null;if(L.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{f=await Gm()}catch(y){Hm.error("failed to get public ip",y)}let h=!0;M("before initializeUserWithAuth");let g=await bt(async()=>(nv(a),h=!1,await fl({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:f,gridId:l,grid:c})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:f})();return s.publicIps=[g.clientPublicIp],M("after initializeUserWithAuth"),f&&g.clientPublicIp&&g.clientPublicIp!==f&&(Hm.error("public ip mismatch",{publicIpFromExternalService:f,publicIpFromServices:g.clientPublicIp}),s.publicIps.push(f)),Bm(g.authData,{projectId:e,token:t,userAccessKey:r,publicIp:g.clientPublicIp,initializedFromCache:h}),g}var Hm,rv,sv,qm=w(()=>{"use strict";$e();he();Bt();nt();Vm();ae();j();pe();Hm=x("initializeUserWithAuth"),rv=1e3*60*5,sv=1e3*60*60*10});async function Jm(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Oo():s.chromeBinaryLocation,e=Js({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==Z.EXTENSION&&await Tr(s.playerLocation,s.canary),s.mode===Z.EXTENSION&&!s.ext&&await Wc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await $c(s.installCustomExtension,n)}return await e,t}async function Ym(s){var i;ov.info("prepare MockNetwork",{location:s});let e=await Tc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>zm*1e6)throw new Error(`${Ul} exceeded ${zm}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Ul} cannot be parsed.${Go.EOL}${a}`)}let n=new Km.default;if(!n.validate(Oc,r)){let a=(i=n.errors)==null?void 0:i.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Go.EOL);throw new Error(`${Ul} is malformed.${Go.EOL}${a}`)}return r.entries}var Go,Km,zm,Ul,ov,Fl=w(()=>{"use strict";Go=E(require("os"));B();Xd();Xs();Km=E(require("ajv"));ae();qc();qm();zm=1,Ul="JSON file supplied to --mock-network-pattern",ov=(j(),be(ac)).getLogger("prepare runner")});function Qm(s,e=process){async function t(r){await ce(ie(Xm,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{ln.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(ln.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{ln.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw ln.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function es(s){Xm.push(s)}var ln,Xm,un=w(()=>{"use strict";j();B();ln=x("process-handler"),Xm=[]});function Wl(s,e){let t=s.canary?"-master.zip":".zip",r=`${e?fd:Mr}/extension/testim-firefox-profile${t}`,n=`${e?gd:Mr}/extension/testim-headless${t}`;return{firefox:r,chrome:n,"edge-chromium":n}}function sf(s){let{chrome:e,firefox:t}=Wl(s,!1);return s.browser==="firefox"?t:s.browser==="chrome"?e:[e,t]}function Ho(s){let e=`${Mr}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var qo=w(()=>{"use strict";ue()});function lf(s){Oe||(s!=null&&s.userId||(s={anonymousId:cf}),af.identify(s))}function Tt(s,e){return pn("ci",s,e)}function pn(s,e,t){if(Oe)return;let r=s?{userId:s}:{anonymousId:cf};af.track(Object.assign(r,{event:e,properties:t}))}var of,af,cf,ts=w(()=>{"use strict";ue();of=require("@segment/analytics-node"),af=new of.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),cf=require("crypto").randomBytes(20).toString("hex")});function uf(s){return s.start&&pn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function pf(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new P("Agent port is not number");let t=Ho(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var df=w(()=>{"use strict";qo();ts();K()});var mf,dv,mv,Gl,ff=w(()=>{"use strict";mf="TST_CREDS",dv=["username","password"],mv="$encrypted",Gl={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of dv)t[r]={[mv]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(mf)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[mf]:this.proxyPlaceholder})}}});function Ko(s){let{platform:e}=process;e==="win32"?(0,zo.exec)(`start chrome ${s}`):e==="darwin"?(0,zo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,zo.exec)(`google-chrome ${s}`)}var zo,Vl=w(()=>{"use strict";zo=require("child_process")});var Jl={};V(Jl,{doLogin:()=>Kl,getProjectId:()=>fv,getToken:()=>gv});async function fv(){return yf("projectId")}async function gv(){return yf("token")}function hf(s,e){return Promise.race([s,oe(e).then(()=>{throw new ne("timeout")})])}async function hv(){let s=(await import("express")).default(),e=async function(){return hf(new Promise(n=>{s.get("/loginInfo",(o,i)=>{n(JSON.parse(Buffer.from(o.query.info,"base64").toString())),i.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let o=s.listen(42543,i=>{i&&n(i),r(o.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(he(),xe)),{editorUrl:n}=await r();Ko(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Kl({overwriteExisting:s=!0,projects:e=null}={}){let t=Hl.homedir(),r=ql.join(t,".testim");if(await ge(r)&&!s)return;let o={},[{default:i},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await hf(hv(),62e3).catch(()=>null)),e!=null&&e.token){o.token=e.token,o.projectId=e.projectId,l.succeed(),await gf(r,o);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await i({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});o.token=c.project.ci.token,o.projectId=c.project.id,await gf(r,o);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function gf(s,e){await zl.promises.writeFile(s,Jo.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function yf(s){let e=Hl.homedir(),t=ql.join(e,".testim"),r=await ge(t),n={};if(r)try{n=Jo.parse((await zl.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Hl,ql,Jo,zl,Yo=w(()=>{"use strict";Hl=E(require("os")),ql=E(require("path")),Jo=E(require("yaml"));B();zl=require("fs");K();Vl()});var If={};V(If,{process:()=>Iv});var Xl,wf,Xo,vf,Gt,Me,Ef,yv,Ne,eu,bv,Tv,bf,Sf,wv,Ql,Zl,tu,Yl,Pt,vv,p,Ev,Sv,Tf,Iv,Rf=w(()=>{"use strict";Xl=E(require("ms")),wf=E(require("chalk")),Xo=E(require("fs")),vf=E(require("url")),Gt=E(require("lodash")),Me=E(require("path"));B();qo();df();Bt();Ef=require("commander");ae();K();Nr();B();pe();ff();yv=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),eu=new Ef.Command,bv=s=>s.split(","),Tv=(s,e)=>!s||s.length===0?e:s,bf=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],Sf=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function o(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function i(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}eu.help(g=>g.split(`
17
17
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!i(T)&&!o(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
18
18
  `))},wv=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(wf.default.yellow(`
19
19
  WARNING: ${s} is deprecated. ${t}
20
- `))},Ql=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Zl,argv:tu,exit:Yl,cwd:Pt}=global.process,vv=["trace","debug","info","warn","error","silent"];Ac(tu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));eu.description("Testim.io CLI").option("-h --help","output usage information",Sf).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",Ne,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Ne,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Ne,[]).option("--test-id [test-id]","test ID to run",Ne,[]).option("-l, --label [label]","labels to search test by",Ne,[]).option("-n, --name [test-name]","test name to run",Ne,[]).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",bv).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Ne,[]).option("--test-plan-id [test-plan-id]","test plan to run",Ne,[]).option("--suite [suite-name]","suite to run",Ne,[]).option("--suite-id [suite-id]","suite ID to run",Ne,[]).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",Ne,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Zl.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,Xl.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,Xl.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: ${Ql.join("/")}`,Ne,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Ne,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Ne,[]).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)",Ne,[]).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)",Ne,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).parse(tu);p=eu.opts(),Ev=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Sv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Tf=s=>{var r;if(!D.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Xo.readFileSync(s);(r=Gl)!=null&&r.containsEncryptedCredentials(t.toString())&&Gl.injectProxyCredentialsStoreToGlobal()},Iv=async()=>{var T,R,b,v,I,C,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!tu.slice(2).length)throw Sf(),new Fr;if(p.version){let A="Testim CLI Version: ";Zl.npm_package_version&&(console.log(A,Zl.npm_package_version),Yl(0));let S=gt();S&&(console.log(A,S),Yl(0)),console.log("Could not find version, please check the package.json manually"),Yl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&lm(),p.clearFileCache&&Kr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let A=Me.resolve(n);am(A)}if(p.usePrefechedData&&um(),p.playerRequirePath){let A=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",A);let S=Me.join(A,"tsconfig.node.json"),U=require("ts-node").register({project:S,ignore:[/node_modules/,new RegExp(`^${Gt.escapeRegExp(Me.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(we(),be(tr)).options.playerPath=A;let q=require("module"),Y=q.prototype.require;q.prototype.require=function(pt){return pt==="rox-alias"?Y.call(this,"rox-node"):pt==="canvas"?{}:Y.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Xo.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(uf(p))return pf(p);try{let A={};p.configFile?(Tf(p.configFile),A=require(Me.join(Pt(),p.configFile)).config):p.optionsFile&&(A=require(Me.join(Pt(),p.optionsFile))),A&&typeof A.then=="function"&&(A=await A),Object.keys(A).forEach(S=>{let L=yv(S);p[L]=Tv(p[L],A[S])})}catch(A){throw A.message=`Unable to read options file: ${A.message}`,A}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((T=p.testConfig)==null?void 0:T.length)||((R=p.testConfigId)==null?void 0:R.length),i=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((I=p.suite)==null?void 0:I.length)||((C=p.suiteId)==null?void 0:C.length);if(p.seleniumCapsFile)try{r=require(Me.join(Pt(),p.seleniumCapsFile))}catch(A){throw new P(`Failed to parse selenium caps file file error: ${A.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(Pt(),p.chromeExtraPrefs))}catch(A){throw new P(`Failed to read/open chrome extra prefs file error: ${A.message}`)}if(p.chromeExtraArgs){let A=p.chromeExtraArgs.split(",");for(let S of A){let[L]=S.split("=");bf.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(S),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(bf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Tf(p.paramsFile),s={...s,...require(Me.join(Pt(),p.paramsFile))}}catch(A){throw new P(`Failed to read/open params file error: ${A.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(A){throw new P(`Failed to parse params string error: ${A.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Ev(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let A=require(Me.join(Pt(),p.sauceOptions)),S=A.platformName&&["ios","android"].includes(A.platformName.toLowerCase());if(A.browserName){let U=A.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(A.version)>=Wa&&(p.browser="edge-chromium");let L=parseFloat(A.version)<50&&!["dev","beta"].includes(A.version);if(!S&&p.browser==="chrome"&&L)throw new P("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...A}}catch(A){throw new P(`Failed to parse saucelabs options file error: ${A.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Sv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let A=require(Me.join(Pt(),p.browserstackOptions)),S=A.platform&&["mac","android"].includes(A.platform.toLowerCase());if(A.browserName&&(p.browser=A.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(A.browser_version)>=Wa&&(p.browser="edge-chromium"),!S&&parseFloat(A.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...A}}catch(A){throw new P(`Failed to parse browserstack options file error: ${A.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let A=require(Me.join(Pt(),p.perfectoOptions)),S={location:"US East",securityToken:p.perfectoToken};p.perfecto={...S,...A}}catch(A){throw new P(`Failed to parse perfecto options file error: ${A.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let A=require(Me.join(Pt(),p.testobjectOptions)),S={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...S,...A}}catch(A){throw new P(`Failed to parse test object options file error: ${A.message}`)}if(!p.project){let S=await(await Promise.resolve().then(()=>(Yo(),Jl))).getProjectId();if(S)p.project=S;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}D.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Z.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let S=await(await Promise.resolve().then(()=>(Yo(),Jl))).getToken();if(S)p.token=S;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 d=A=>A<=0||!Number.isInteger(A);if(d(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Z.EXTENSION,Z.SELENIUM,Z.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.mode!==Z.SELENIUM&&p.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!vv.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.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&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=vf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(S=>S.trim()).filter(Boolean);let A=p.resultLabel.filter(S=>S.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&hr()&&p.resultLabel.unshift(hr()),A.length)throw new P("A result label cannot exceed 250 characters")}let u=sf(p),f=Ho(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.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(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.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(p.setRetention&&!Gt.inRange(Gt.parseInt(p.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)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Gt.difference(p.codeCoverageReporter,Ql).length){let A=Gt.difference(p.codeCoverageReporter,Ql);throw new P(`invalid --code-coverage-reporter parameters ${A.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(A=>Boolean(p[A]));if(p.mode!==Z.EXTENSION&&y.length){let A=y.length>1?"are":"is";throw new P(`${y.map(S=>g[S]).join(" and ")} ${A} only applicable in extension mode`)}if(p.tmsFieldFile)try{let A=Xo.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(A)}catch(A){throw new P(`failed to parse field file error: ${A.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new P("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(wv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.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(p.setNoReset&&p.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(p.lightweightMode)try{let A={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"},S=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...A,...S}}catch(A){throw new P(`failed to parse lightweightMode settings error: ${A.message}`)}else p.turboMode&&p.mode===Z.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Z.SELENIUM&&console.warn(`
21
- When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?hr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Pf={};V(Pf,{installAllLazyDependencies:()=>xv,lazyRequire:()=>ot});async function ot(s,e={}){let t=Uc(s);if(t)return t;let r;e.silent||(r=(0,Af.default)(`Installing ${s} before first usage...`).start());try{let n=await Av(s);return r&&r.succeed(),n}catch(n){Rv.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Cf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function Av(s){return rs.has(s)||(rs.set(s,xf(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function xf(s){let e=Uc(s);if(e)return e;let t=Cf(s),r=`${s}@${t}`;return await xo(ht(),r),Qt(s)}async function xv(){let s=Object.keys(qa);for(let e of s)await xf(e)}function Cf(s){let e=Object.entries(qa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Af,Rv,rs,mn=w(()=>{"use strict";Af=E(require("ora"));Yr();j();B();Zn();Ks();Rv=x("lazy-require"),rs=new Map});var _f={};V(_f,{preloadTests:()=>fn});async function fn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await bt(async()=>{let t=await ie(s.testId,r=>rl({...e,testId:r}),{concurrency:2});return kf.keyBy(t,"testData.id")},"loadTests",Cv,[e,s.testId])()}var kf,Cv,Qo=w(()=>{"use strict";kf=E(require("lodash"));Bt();he();B();Cv=1e3*60*60*10});function ru(){return gt()}async function Df(){if(!Oe)try{let s=await ce(kv(),5e3,"The API call to NPM timed out"),e=ru();e&&Lf.lt(e,s)&&console.log(Of.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){Pv.warn("Failed to get NPM version",{err:s})}}var Of,Lf,Pv,kv,su=w(()=>{"use strict";Of=E(require("chalk")),Lf=E(require("semver"));B();ue();Yr();Bt();j();Pv=x("npm-driver"),kv=bt(()=>gm("@testim/testim-cli"),"getNpmVersion")});var nu,Ov,ss,Nf,Mf,ou,Uf,Ff=w(()=>{"use strict";B();K();j();mn();nu=x("testimNgrok"),Ov=".whitelisted-ngrok.testim.io",ss="",Mf=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=`${se()}-${s.projectData.projectId}${Ov}`);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 ot("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(nu.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&ou(),s.baseUrl=ss},ou=async(s=!0)=>{try{let t=(await ot("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),nu.info("ngrok stats",{tunnel:n})}catch(e){nu.error("error collecting ngrok stats",{err:e})}s&&(Nf=setTimeout(()=>ou(),1e4))},Uf=async s=>{if(!ss)return;clearTimeout(Nf),s.tunnelDiagnostics&&await ou(!1),await(await ot("ngrok")).disconnect(ss)}});var rr,au,Bf,Dv,Nv,iu,Zo,ti,ei,Mv,jf,$f,Wf=w(()=>{"use strict";rr=E(require("os")),au=E(require("fs")),Bf=E(require("child_process"));B();he();Dv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Nv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},iu=rr.tmpdir(),Zo=`${iu}/cloudflared`,ti=null,ei=null,Mv=async()=>{if(await ge(Zo))return;let e=Nv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?iu+e.path:Zo;await Je(`${Dv}/${e.path}`,t),e.extract&&await rt(t,iu),await au.promises.chmod(Zo,"755")},jf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Il(s.company.companyId,t),Mv()]);ti=r._id,ei=Bf.spawn(Zo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Rl(s.company.companyId,ti),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await au.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},$f=async s=>{let e=[];return ti&&e.push(Al(s.company.companyId,ti)),ei&&e.push(new Promise((t,r)=>{ei.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ei.kill()})),await Promise.all(e)}});function Gv(s){if(!(s!=null&&s.width)||!(s!=null&&s.height))return re.lambdatestConfig.RESOLUTION;let e=`${s.width}x${s.height}`;return Wv.includes(e)?e:(ri.warn("default resolution is used because the resolution is not supported by LT",{resolutionString:e}),re.lambdatestConfig.RESOLUTION)}var Gf,Vf,Vt,Hf,qf,zf,si,Kf,ri,Fv,Bv,gn,jv,$v,re,Wv,ni=w(()=>{"use strict";Gf=E(require("ms")),Vf=E(require("p-retry")),Vt=E(require("os")),Hf=E(require("portfinder")),qf=E(require("child_process"));B();Ve();he();zf=E(require("fs")),si=E(require("fs/promises")),Kf=require("path");K();j();qo();ae();pe();B();ri=x("lambdatestService"),Fv="https://downloads.lambdatest.com/tunnel/v3",Bv={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"},gn=`${Vt.tmpdir()}/LT`,jv=`${gn}/LT`,$v=(0,Gf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=hl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?$v:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(jv))return;let t=Bv[Vt.platform()+Vt.arch()];if(!t)throw new Error(`tunnel on ${Vt.platform()+Vt.arch()} platform is not supported.`);let r=`${gn}.zip`;await Je(`${Fv}/${t}`,r),await rt(r,gn)}static async chmodLtTunnel(e){if(!(Vt.platform()==="win32"||!await ge(e))){try{await si.access(e,zf.constants.X_OK);return}catch{}try{await si.chmod(e,"777")}catch(r){throw ri.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await oe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Hf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(D.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(D.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...xc(u)])}if(D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,Kf.join)(gn,"LT")),re.tunnel=qf.spawn("./LT",c,{cwd:gn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Vf.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});ri.info("LT tunnel info",u)}catch(u){throw ri.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,o,i){if(!this.isActive)return{};let a=re.lambdatestConfig.CAPABILITIES[t]||{},l={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},c=[],{mode:d,canary:m,ext:u,extensionPath:f,installCustomExtension:h}=e,g=(i==null?void 0:i.os)==="Windows 11"?i.os:re.lambdatestConfig.PLATFORM;if(d===Z.EXTENSION&&!u){let y=Wl({canary:m},!0);!f&&y[t]&&(c=[...c,y[t]]),f&&_e(f)&&(c=[...c,f])}return h&&_e(h)&&(c=[...c,h]),{build:r,name:`${n} - ${o}`,platform:g,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,resolution:Gv(i==null?void 0:i.resolution),timezone:re.lambdatestConfig.TIMEZONE,...a,loadExtension:c,...l,console:!0,queueTimeout:300,network:D.flags.LTNetworkCapabilities.isEnabled(),ntlm:D.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:D.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Wv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"]});var cu={};V(cu,{connect:()=>ii,disconnect:()=>ai,serveTunneling:()=>Hv});var oi,Jf,Yf,Vv,ii,ai,Hv,lu=w(()=>{"use strict";Ff();un();Wf();nt();oi=E(require("ora"));j();ae();ni();Jf=x("tunnel"),Yf=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Vv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},ii=async s=>{if(!s.tunnel)return;let e=jt(),t;try{Yf(s)?(t=(0,oi.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Vv(s)?(t=(0,oi.default)("Starting testim cloudflare tunnel...").start(),await jf(s)):(t=(0,oi.default)("Starting testim ngrok tunnel...").start(),await Mf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Jf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},ai=async s=>{if(s.tunnel)try{Yf(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await $f(s):await Uf(s)}catch(e){let t="catch error - failed to close tunnel";throw Jf.error(t,{err:e}),new Error(t)}},Hv=async(s,e=new Promise(()=>{}))=>(await ii(s),es(()=>ai(s)),await e)});function qv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=Xf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zv(s){let e=Xf.exec(s);return e==null?void 0:e[3]}function li(s){var b,v,I,C,_,$,A,S,L,U,H;let e=s&&zv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&qv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(I=s==null?void 0:s.external)==null?void 0:I.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&(($=(_=(C=s.hybrid)==null?void 0:C.external)==null?void 0:_[s.hybrid.tunnel])==null?void 0:$.user):l,u=d===O.HYBRID?a&&((L=(S=(A=s.hybrid)==null?void 0:A.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:L.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.androidToken,T=(H=s==null?void 0:s.mobileTokens)==null?void 0:H.iosToken,R=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:R}}async function Zf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(yt.UNKNOWN)}if(Qe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(yt.UNKNOWN);if(o.status==="success"){let i=li(o.grid);return Kv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(yt.NOT_FOUND):o.code==="no-available-slot"?new Jt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new ze(yt.UNKNOWN))}function Jv(s,e,t,r,n,o){return Zf(t,e,s,n,()=>Bo(e,t,r,n,o))}function Yv(s,e,t,r,n,o,i){return Zf(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Bo(e,t,l._id,n,o):ml(e,t,r,n,o)})}function eg(s){return gl(s)}async function tg(s,e,t){let n=(t||await eg(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return li(n)}async function Xv(s,e,t){let n=(t||await eg(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return li(n)}async function uu(s,e){let t=hn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete hn[s],!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await pl(i,e,r,n,o)}catch(a){Qe.error("failed to release slot",{projectId:e,err:a})}}async function Qv(s){let e=Object.values(hn).filter(Boolean);if(e.length!==0){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await ul(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zv(s){Qf=global.setInterval(Qv,1e4,s)}async function eE(s){let e=Object.keys(hn);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>uu(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function tE(s){await eE(s),clearInterval(Qf)}function rE(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sE(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function rg(s){let t=(()=>ci.isEmpty(s.testobjectSauce)?ci.isEmpty(s.saucelabs)?ci.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=rE(t,s),l=sE(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function sg(s,e){let t=s.company.companyId;return await tg(t,e.gridId,s.allGrids)}async function ng(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return rg(s);let c=t==null?void 0:t.companyId;if(a)return tg(c,a,e);if(l)return Xv(c,l,e);if(Gs(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function og(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return rg(t);if(a)return Jv(r,u,o,a,s,e);if(i)return Yv(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var ci,Qe,hn,Xf,Qf,Kv,yn,ig,ns=w(()=>{"use strict";ci=E(require("lodash"));he();j();B();ae();K();Qe=x("grid-service"),hn={},Xf=/(^(https?):\/{2})?(.*)/,Qf=null;Kv=(s,e,t,r,n)=>{hn[s]={gridId:t,companyId:e,slotId:r,browser:n}};yn={start:Zv,end:tE};ig=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||(a===O.LAMBDATEST&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await dl({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Qe.info("handling hybrid grid",{response:u,companyId:o});let f=li({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function pu(s,e,t){let r=os[s];if(!r)return;let{slotId:n}=r;if(delete os[s],!n){it.warn("failed to find slot slot id",{companyId:e,workerId:s});return}it.info("release slot id",{companyId:e,slotId:n});try{await Ol(e,t,n)}catch(o){it.error("failed to release slot",{companyId:e,err:o})}}async function nE(s,e){let t=Object.values(os).filter(Boolean);if(t.length!==0){it.info("keep alive worker slots",{companyId:s,slots:t});try{await Dl(s,e,t)}catch(r){it.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function oE(s,e){ag=global.setInterval(()=>nE(s,e),1e4)}async function iE(s,e){let t=Object.keys(os);if(t.length){it.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>pu(Number(r),s,e))}catch(r){it.error("failed to release all slots",{err:r,companyId:s})}}}async function aE(s,e){await iE(s,e),clearInterval(ag)}async function lg(s,e,t){let r;try{r=await _l(s,e)}catch(n){throw it.error("failed to get slot",{companyId:s,err:n}),new Error(yt.UNKNOWN)}if(it.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw it.error("invalid response - get slot",{res:r}),new Error(yt.UNKNOWN);if(r.status==="success")return cg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(yt.NOT_FOUND):r.code==="no-available-slot"?new Jt("Failed to run test - concurrency limit reached"):(it.error("invalid code error response - get slot",{res:r}),new ze(yt.UNKNOWN))}async function ug(s,e,t,r){let n=os[r];if(!n)throw new Error("slot not found");Object.assign(n,t),cg(r,n),await Ll(s,e,n),it.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var it,os,ag,cg,Tn,is=w(()=>{"use strict";he();j();B();ae();K();it=x("slot-service"),os={},ag=null,cg=(s,e)=>{os[s]=e};Tn={start:oE,end:aE}});function vn(){return ui||"master"}function pg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){ui="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){ui=s.branch||s;return}ui=e?"master":void 0}var ui,du=w(()=>{"use strict";K()});var En,mu,cE,fu,lE,pi,di,mi,fi,gi,hi=w(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},mu=s=>{let{status:e}=s;return e===de.ABORTED},cE=s=>{let{status:e}=s;return e===de.PASSED},fu=s=>s.runnerStatus===vc.SKIPPED,lE=s=>s.testStatus===Ye.EVALUATING,pi=(s,e)=>Object.values(s).filter(t=>{var r,n;return fu(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,di=s=>Object.values(s).filter(e=>En(e)&&lE(e)).length,mi=s=>Object.values(s).filter(En),fi=s=>Object.values(s).filter(cE),gi=s=>Object.values(s).filter(mu)});function pE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var gu,yi,uE,bi,mg=w(()=>{"use strict";gu=E(require("lodash"));j();hi();yi=x("debug-reporter"),uE=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],bi=class{constructor(e){this.options=e}onTestStarted(e,t){yi.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,l=r.failedGetBrowserAttempts;yi.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:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...gu.default.omit(this.options,uE),company:gu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=pE(process.argv);yi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=fi(e).length,a=Object.keys(e).length-i;yi.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var hu,kt,Sn=w(()=>{"use strict";ae();hu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},kt=new hu});var bu={};V(bu,{Reporter:()=>dE});var sr,In,Sr,Ti,fg,yu,dE,Tu=w(()=>{"use strict";sr=E(require("chalk")),In=E(require("lodash"));B();ae();Sn();hi();Sr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:Ti}=Ut,fg="device",yu=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: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,o=Sr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${fo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Sr.error("Failed runs are:")),console.log(Sr.error(t.join(`
22
- \r`)))}onTestPlanFinished(e,t,r,n,o){let i=mi(e),a=fi(e),l=gi(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let R=di(e);u=` FAILED-EVALUATING: ${R}`,m-=R,f=` SKIPPED: ${pi(e,this.options)}`}let h=this.buildTestPlanName(o,t),g,y=Sr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${fo(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.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 l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ti.APPIUM?fg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ti.APPIUM?fg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.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===Ti.APPIUM?"device":"browser";if(n)console.log(Sr.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(Sr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ti.APPIUM?"Appium":"Selenium";console.log(Sr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},dE=yu});var Eu={};V(Eu,{Reporter:()=>bE});function mE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function fE(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 gE(s){return`${s.visitedUrlsJson||""}`}async function hE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:mE(u),classname:n,time:Cc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||mu(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return fu(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=fE(u),h["visited-urls-json"]=gE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},R={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){R.skipped=pi(y,o);let b=di(y);R.failures-=b,R["failure-evaluating"]=b}return{$:R,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return mi(u).length+gi(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new vu.Builder().buildObject(m)}catch(u){return yE(u)}}function yE(s){let e=new vu.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 vu,gg,wu,bE,Su=w(()=>{"use strict";vu=E(require("xml2js"));B();gg=require("fs");Sn();hi();wu=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 hE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await gg.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)}};bE=wu});var hg={};V(hg,{Reporter:()=>TE});function as(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 Iu,Ru,TE,yg=w(()=>{"use strict";j();Iu=x("team-city-reporter");Ru=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 as(n)}onTestStarted(e,t,r,n){if(r){Iu.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){Iu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${as(t)}' details='${as(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){Iu.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='${as(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${as(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${as(t)}']`)}},TE=Ru});var bg={};V(bg,{Reporter:()=>wE});var Au,wE,Tg=w(()=>{"use strict";Au=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}}))}},wE=Au});var wg={};V(wg,{Reporter:()=>vE});var xu,vE,vg=w(()=>{"use strict";B();Vl();xu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Ko(t)}},vE=xu});var Wx,Cu,Q,_t=w(()=>{"use strict";mg();j();Wx=x("reporter"),Cu=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 bi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Tu(),bu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Su(),Eu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(yg(),hg)),r.includes("console")&&Promise.resolve().then(()=>(Tu(),bu)),r.includes("junit")&&Promise.resolve().then(()=>(Su(),Eu)),r.includes("json")&&Promise.resolve().then(()=>(Tg(),bg)),r.includes("chrome")&&Promise.resolve().then(()=>(vg(),wg))])).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))}}},Q=new Cu});function Sg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Sg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:Eg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);Tt("test-run-ci",y)}function Rg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let R=Sg({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Eg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",R);return}Tt("test-run-ci-fail",{...R,failureReason:n.failureReason})}catch(R){f.error("failed to update test end analytics",{err:R})}}function Ag(s){Tt("batch-run-ci",s)}var Eg,Pu=w(()=>{"use strict";ts();Uo();Eg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Qr&&e?"ci-with-user":Qr?"ci":e?"cli-with-user":s});var Cg,wi,Pg=w(()=>{"use strict";Cg=require("istanbul-lib-report"),wi=class extends Cg.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 kg,_g,Og,Rn,wt,Lg,vi,ku,Dg,EE,Ng,Mg,SE,IE,Ug,RE,AE,xE,CE,PE,Fg,Bg=w(()=>{"use strict";kg=E(require("ora")),_g=E(require("dayjs")),Og=E(require("test-exclude")),Rn=E(require("fs")),wt=E(require("path")),Lg=E(require("istanbul-reports")),vi=E(require("istanbul-lib-report"));he();K();B();j();mn();Pg();ku=x("test-run-status"),Dg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},EE=s=>!!Dg(s).search,Ng=s=>s?Dg(s).pathname.substring(1):"",Mg=(s,e)=>{let t=Ng(e);return!new Og.default({relativePath:!1,include:s}).shouldInstrument(t)},SE=s=>s.substring(0,s.indexOf("?")),IE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ot("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)},Ug=(s,e)=>`${wt.resolve(s,Ng(e))}.js`,RE=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(Mg(r,i))return;let l=Ug(e,i);await Rn.promises.mkdir(wt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},AE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(EE(e)&&(e=SE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},xE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=vi.createContext({dir:t,coverageMap:e,watermarks:vi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Ug(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new wi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:AE}),Lg.create(a,l).execute(i)}),o},CE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await ot("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Mg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},PE=async(s,e)=>{let{mergeProcessCovs:r}=await ot("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await bl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await on(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await el(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Fg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;ku.info("start js coverage process");let n=(0,kg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=wt.resolve(s.codeCoverageReportPath||"./coverage"),i=wt.resolve(o,`.js/${(0,_g.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([ot("istanbul-lib-coverage"),PE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}ku.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),R=await IE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=R;let b=await CE(s,{source:y,sourceMap:R,functions:g});m.merge(b)}),await RE(s,i,u);let f=await xE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),ku.error(c,{err:l})}}});var jg={};V(jg,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Ir});var Ce,kE,Ir,cs=w(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},kE=["ALL",...Object.values(Ce)],Ir=class{constructor(){this.marks=Object.fromEntries(kE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,yo(r,50)],[`${t}_P95`,yo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Vg={};V(Vg,{initServer:()=>LE,mapFilesToLocalDrive:()=>Ou});function Ou(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Ei[t.id]?{screenshot:Ei[t.id]}:{})),Object.keys(Si).forEach(t=>{s.assets||={},s.assets[Gg[t]]=Si[t]}),s.assets||={},s.assets.screenshots=Object.values(Ei)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function LE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ot("multer"),n=typeof t=="string"?t:_E;await _u.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await _u.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Wg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Ei[d.stepId]=l.file.path),d.testResultId&&OE.includes(d.subType)&&(Si[d.subType]||=[],Si[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var _u,$g,An,Wg,_E,Ei,Si,Gg,OE,Lu=w(()=>{"use strict";_u=E(require("fs")),$g=E(require("os")),An=E(require("path")),Wg=E(require("express"));K();mn();_E=An.join($g.tmpdir(),"testim/rca/"),Ei={},Si={},Gg={"test-log":"consoleLogs","har-file":"networkLogs"},OE=Object.keys(Gg)});var nr,Du,Ii,Hg=w(()=>{"use strict";nr=E(require("lodash"));B();j();Du=x("override-test-data-builder"),Ii=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Du.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Du.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}Du.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 nr.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(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...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 Ri(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Rr,Ze,DE,NE,ME,UE,Ai,qg=w(()=>{"use strict";Rr=E(require("lodash"));B();ae();ns();is();he();K();j();_t();un();Bg();cs();Lu();ue();pe();Hg();Sn();Ze=x("test-run-status"),DE=hr(),NE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,ME=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,UE=gt();Ai=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ws(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:ro||t.parallel||1,browser:o,gitBranch:DE,gitCommit:NE,gitRepoUrl:ME,runnerVersion:UE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R},El({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await $o(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Ri(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.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={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Pc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,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&&Ou(i,Ze),i.resultUrl=qe(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),Q.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Ri(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},this.options.userData.loginData.token)}catch(a){Ze.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 vr(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 Ze.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,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Ic;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,h,g;let l=e.browser?qs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Gr(D,n)&&Vs(a.nativeApp)&&!e.appId,d=Hs(e)&&(Wr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;es(()=>Promise.all([this.endKeepAlive(d,t,c),Fo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...D.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Ri(i.beforeSuite,m),f=new Ii(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let R=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async C=>{var L;let _=b[C],$=(L=_.config)==null?void 0:L.testData,A=_.testId,S=await $o(t,A,C,$,l.defaults);S&&(delete _.config.testData,_.config.testDataUrl=S)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),I=ol({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections});return this.executionStartedPromise=I,I.catch(C=>Ze.error(C)),I};try{await R()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=_c(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Ri(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Fg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await nl(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}}});function BE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Bu(s){return Jg.readFileSync(s,{encoding:"base64"})}function Zg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=Bu(s);ls.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Fu(r)} current extension count: ${e.length}`),e.push(r)}}function eh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ls.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Uu.join(process.cwd(),`testim-headless${o}`),a=Bu(i);ls.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Fu(a)} current extension count: ${e.length}`),e.push(a)}function jE(s,e,t,r,n,o,i){var h,g;let a=t.seleniumName||t.browserValue,l=[],c=[...Qg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":Nu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Nu.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};Mu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Mu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=Nu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(g=(h=e.projectData)==null?void 0:h.defaults)!=null&&g.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Ec.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Zg(r,l,i),e.mode===Z.EXTENSION&&eh(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return re.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function WE(s,e,t){let r={"pdfjs.disabled":!0};if(D.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Kg.join(","),"browser.helperApps.neverAsk.openFile":Kg.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===Z.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Uu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Bu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function GE(s){return`${s.width}x${s.height}`}function VE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Xg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=GE(r.resolution||t.sl.screenResolution),delete i.screenResolution),at.merge(i,o,n)}return at.merge(o,n)}return{}}function HE(s,e,t){return at.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function qE(s){return s.perfecto?s.perfecto:{}}function zE(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 KE(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=Ga(o,i)),a}function xi(s){var T,R,b,v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],C=[...Qg],_={};return t.headless&&C.push("--headless"),t.silentDebuggerExtensionApi&&C.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&C.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach($=>C.push(`--${$}`)),t.chromeBinaryLocation&&(_.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&eh(t,I,C,null,c),Zg(i,I,c),{logLevel:zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:C,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=KE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:zg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!at.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Mu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let h=Number(t.browserTimeout/1e3),g=t.browser||(n==null?void 0:n.browserValue);at.merge(f.desiredCapabilities,VE(t,r,n,e),HE(t,r,n),qE(t),zE(t,g,h),c==null?void 0:c.getCapabilities(t,g,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((T=o.host)!=null&&T.endsWith(".testim.io"))&&!t.canary&&t.mode===Z.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&D.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(y="/opt/testim-headless"),g){case"chrome":case"edge-chromium":f=$E(f,t,n,i,o,y,c);break;case"firefox":f=WE(f,t,c);break;case"safari":case"safari technology preview":f=BE(f,g);break;default:break}at.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[D.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},C=S=>S[o.provider]||S[f.host]||S[I[f.host]],_=S=>{var L,U;return C(S)||S[(L=f.desiredCapabilities)==null?void 0:L.browserName]||S[(U=f.desiredCapabilities)==null?void 0:U.version]||S||{}},$=JSON.parse(D.flags.addCustomCapabilities.getValue()||"{}"),A=_(_($));Object.keys(A).length&&(ls.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(f.desiredCapabilities,A))}catch(I){ls.error("Failed to load custom capabilities",{error:I,customCapabilities:D.flags.addCustomCapabilities.getValue()})}if(f.desiredCapabilities&&!f.capabilities&&(FE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,s.printFinalCaps){let I=(R=f.capabilities)==null?void 0:R.alwaysMatch,C=JSON.parse(JSON.stringify(f)),_=(b=C==null?void 0:C.capabilities)==null?void 0:b.alwaysMatch,$=S=>S.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(S=>{var L,U;_!=null&&_[S]&&(_[S].extensions=(U=(L=I==null?void 0:I[S])==null?void 0:L.extensions)==null?void 0:U.map($))}),_!=null&&_.loadExtension&&(_.loadExtension=(v=I==null?void 0:I.loadExtension)==null?void 0:v.map($));let A=require("util");console.log(A.inspect(C,{showHidden:!1,depth:null,colors:!0}))}return f}var Jg,Uu,Yg,at,Xg,ls,zg,Nu,Qg,Fu,Mu,FE,$E,Kg,ju=w(()=>{"use strict";Jg=E(require("fs")),Uu=E(require("path")),Yg=E(require("crypto")),at=E(require("lodash"));B();ue();j();pe();ae();ni();Xg=require("lodash"),ls=x("testim-desired-capabilities-builder"),zg=to?"debug":"silent",Nu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Qg=["--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"],Fu=(...s)=>Yg.createHash("sha256").update(s.join("")).digest("hex"),Mu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",FE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=D.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ls.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};$E=at.memoize(jE,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(at.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Fu(i,a,l,r,c,o)}),Kg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(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 rh(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 $u=w(()=>{"use strict"});function Wu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=o(u,"stroke-width");return!!g&&parseInt(g,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Wu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var sh=w(()=>{"use strict"});var nh,oh,Ht,JE,YE,Ci,ih=w(()=>{"use strict";nh=E(require("promise-queue")),oh=E(require("webdriverio"));ue();$e();B();j();Nr();sh();$u();cs();Ht=x("WebDriverApi"),JE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},YE={implicit:0,pageLoad:1,script:2},Ci=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 Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),za!==void 0&&(e=za);let t=1/0;this.queue=new nh.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(),M("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await oh.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.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 l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.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){Ht.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(Fe(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(Fe(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(Ce.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,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.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(Wu,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(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(rh(e,this.isSafari(),Ht))})}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[YE[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(Fe(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(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(JE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var 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(De(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)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var 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(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.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{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.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 Ht.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 ah={};V(ah,{doubleClick:()=>XE});var XE,ch=w(()=>{"use strict";XE=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(u){function f(R,b,v){return v>R&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var xn={};V(xn,{dispatchFocus:()=>QE});function QE(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 Cn=w(()=>{"use strict"});var mh={};V(mh,{WebDriver:()=>xr});async function rS(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 eS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var us,ph,dh,Be,or,ZE,lh,eS,ir,tS,uh,Ar,xr,Pn=w(()=>{"use strict";us=E(require("lodash"));B();$e();ju();ph=E(require("p-retry")),dh=E(require("ua-parser-js"));Nr();j();$u();ih();K();pe();cs();Be=x("webdriver"),[or,ZE]=[0,2],{extractElementId:lh,getCdpAddressForHost:eS}=J,ir=()=>(we(),be(tr)).getSessionPlayer().codeSnippets,tS=()=>(we(),be(tr)).getSessionPlayer().locatorBuilderUtils,uh=()=>(we(),be(tr)).getSessionPlayer().utils,Ar=()=>(we(),be(tr)).getSessionPlayer().positionUtils;xr=class extends Ci{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var R,b,v,I,C,_,$,A;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(b=(R=n==null?void 0:n.company)==null?void 0:R.activePlan)==null?void 0:b.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=xi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let y=u?0:1500,T=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await rS(S),M("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(y),D.flags.dontFocusOnInit.isEnabled()||await T(),M("after focus and delay in webdriver.js init")}catch(S){let L=JSON.stringify(us.omit(g,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:L});let U=((C=(I=n==null?void 0:n.company)==null?void 0:I.activePlan)==null?void 0:C.plan)==="free";throw(_=S.stack)!=null&&_.includes("at startWebDriverSession")&&(($=S.message)!=null&&$.startsWith("Failed to create session"))&&((A=S.message)!=null&&A.includes("Timeout awaiting 'request'"))&&U?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new oo(S.message):S.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):S.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${S.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>us.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","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();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,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=lh(r.value);return await this.switchToFrame({ELEMENT:n,[zt]: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 io:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||D.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
20
+ `))},Ql=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Zl,argv:tu,exit:Yl,cwd:Pt}=global.process,vv=["trace","debug","info","warn","error","silent"];Ac(tu,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));eu.description("Testim.io CLI").option("-h --help","output usage information",Sf).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",Ne,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Ne,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Ne,[]).option("--test-id [test-id]","test ID to run",Ne,[]).option("-l, --label [label]","labels to search test by",Ne,[]).option("-n, --name [test-name]","test name to run",Ne,[]).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",bv).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Ne,[]).option("--test-plan-id [test-plan-id]","test plan to run",Ne,[]).option("--suite [suite-name]","suite to run",Ne,[]).option("--suite-id [suite-id]","suite ID to run",Ne,[]).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",Ne,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Zl.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,Xl.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,Xl.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: ${Ql.join("/")}`,Ne,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Ne,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Ne,[]).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)",Ne,[]).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)",Ne,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).parse(tu);p=eu.opts(),Ev=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Sv=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Tf=s=>{var r;if(!L.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Xo.readFileSync(s);(r=Gl)!=null&&r.containsEncryptedCredentials(t.toString())&&Gl.injectProxyCredentialsStoreToGlobal()},Iv=async()=>{var T,R,b,v,I,C,_,$;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!tu.slice(2).length)throw Sf(),new Fr;if(p.version){let A="Testim CLI Version: ";Zl.npm_package_version&&(console.log(A,Zl.npm_package_version),Yl(0));let S=gt();S&&(console.log(A,S),Yl(0)),console.log("Could not find version, please check the package.json manually"),Yl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&lm(),p.clearFileCache&&Kr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let A=Me.resolve(n);am(A)}if(p.usePrefechedData&&um(),p.playerRequirePath){let A=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",A);let S=Me.join(A,"tsconfig.node.json"),U=require("ts-node").register({project:S,ignore:[/node_modules/,new RegExp(`^${Gt.escapeRegExp(Me.relative(Pt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:U.config.options.paths,baseUrl:U.config.options.baseUrl}),(we(),be(tr)).options.playerPath=A;let q=require("module"),Y=q.prototype.require;q.prototype.require=function(pt){return pt==="rox-alias"?Y.call(this,"rox-node"):pt==="canvas"?{}:Y.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Xo.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(uf(p))return pf(p);try{let A={};p.configFile?(Tf(p.configFile),A=require(Me.join(Pt(),p.configFile)).config):p.optionsFile&&(A=require(Me.join(Pt(),p.optionsFile))),A&&typeof A.then=="function"&&(A=await A),Object.keys(A).forEach(S=>{let D=yv(S);p[D]=Tv(p[D],A[S])})}catch(A){throw A.message=`Unable to read options file: ${A.message}`,A}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((T=p.testConfig)==null?void 0:T.length)||((R=p.testConfigId)==null?void 0:R.length),i=((b=p.testPlan)==null?void 0:b.length)||((v=p.testPlanId)==null?void 0:v.length),a=((I=p.suite)==null?void 0:I.length)||((C=p.suiteId)==null?void 0:C.length);if(p.seleniumCapsFile)try{r=require(Me.join(Pt(),p.seleniumCapsFile))}catch(A){throw new P(`Failed to parse selenium caps file file error: ${A.message}`)}if((_=p.reporters)!=null&&_.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(Pt(),p.chromeExtraPrefs))}catch(A){throw new P(`Failed to read/open chrome extra prefs file error: ${A.message}`)}if(p.chromeExtraArgs){let A=p.chromeExtraArgs.split(",");for(let S of A){let[D]=S.split("=");bf.includes(D)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(S),D==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${D}), allowed values: ${JSON.stringify(bf)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Tf(p.paramsFile),s={...s,...require(Me.join(Pt(),p.paramsFile))}}catch(A){throw new P(`Failed to read/open params file error: ${A.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(A){throw new P(`Failed to parse params string error: ${A.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(Ev(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let A=require(Me.join(Pt(),p.sauceOptions)),S=A.platformName&&["ios","android"].includes(A.platformName.toLowerCase());if(A.browserName){let U=A.browserName.toLowerCase();switch(U){case"microsoftedge":p.browser="edge";break;default:p.browser=U}}p.browser==="edge"&&parseFloat(A.version)>=Wa&&(p.browser="edge-chromium");let D=parseFloat(A.version)<50&&!["dev","beta"].includes(A.version);if(!S&&p.browser==="chrome"&&D)throw new P("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...A}}catch(A){throw new P(`Failed to parse saucelabs options file error: ${A.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Sv(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let A=require(Me.join(Pt(),p.browserstackOptions)),S=A.platform&&["mac","android"].includes(A.platform.toLowerCase());if(A.browserName&&(p.browser=A.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(A.browser_version)>=Wa&&(p.browser="edge-chromium"),!S&&parseFloat(A.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...A}}catch(A){throw new P(`Failed to parse browserstack options file error: ${A.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let A=require(Me.join(Pt(),p.perfectoOptions)),S={location:"US East",securityToken:p.perfectoToken};p.perfecto={...S,...A}}catch(A){throw new P(`Failed to parse perfecto options file error: ${A.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let A=require(Me.join(Pt(),p.testobjectOptions)),S={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...S,...A}}catch(A){throw new P(`Failed to parse test object options file error: ${A.message}`)}if(!p.project){let S=await(await Promise.resolve().then(()=>(Yo(),Jl))).getProjectId();if(S)p.project=S;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}L.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Z.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let S=await(await Promise.resolve().then(()=>(Yo(),Jl))).getToken();if(S)p.token=S;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 d=A=>A<=0||!Number.isInteger(A);if(d(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(d(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(d(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Z.EXTENSION,Z.SELENIUM,Z.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.mode!==Z.SELENIUM&&p.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!vv.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.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&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if(($=p.host)!=null&&$.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=vf.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(S=>S.trim()).filter(Boolean);let A=p.resultLabel.filter(S=>S.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&hr()&&p.resultLabel.unshift(hr()),A.length)throw new P("A result label cannot exceed 250 characters")}let u=sf(p),f=Ho(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.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(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.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(p.setRetention&&!Gt.inRange(Gt.parseInt(p.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)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Gt.difference(p.codeCoverageReporter,Ql).length){let A=Gt.difference(p.codeCoverageReporter,Ql);throw new P(`invalid --code-coverage-reporter parameters ${A.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(A=>Boolean(p[A]));if(p.mode!==Z.EXTENSION&&y.length){let A=y.length>1?"are":"is";throw new P(`${y.map(S=>g[S]).join(" and ")} ${A} only applicable in extension mode`)}if(p.tmsFieldFile)try{let A=Xo.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(A)}catch(A){throw new P(`failed to parse field file error: ${A.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new P("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(wv("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.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(p.setNoReset&&p.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(p.lightweightMode)try{let A={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"},S=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...A,...S}}catch(A){throw new P(`failed to parse lightweightMode settings error: ${A.message}`)}else p.turboMode&&p.mode===Z.EXTENSION?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&p.mode===Z.SELENIUM&&console.warn(`
21
+ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?hr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionLocation:[p.extensionPath||u].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Pf={};V(Pf,{installAllLazyDependencies:()=>xv,lazyRequire:()=>ot});async function ot(s,e={}){let t=Uc(s);if(t)return t;let r;e.silent||(r=(0,Af.default)(`Installing ${s} before first usage...`).start());try{let n=await Av(s);return r&&r.succeed(),n}catch(n){Rv.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Cf(s),i=`${s}@${o}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${i}`;throw r&&r.fail(c),n}}async function Av(s){return rs.has(s)||(rs.set(s,xf(s)),rs.get(s).catch(()=>{rs.delete(s)})),rs.get(s)}async function xf(s){let e=Uc(s);if(e)return e;let t=Cf(s),r=`${s}@${t}`;return await xo(ht(),r),Qt(s)}async function xv(){let s=Object.keys(qa);for(let e of s)await xf(e)}function Cf(s){let e=Object.entries(qa).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Af,Rv,rs,mn=w(()=>{"use strict";Af=E(require("ora"));Yr();j();B();Zn();Ks();Rv=x("lazy-require"),rs=new Map});var _f={};V(_f,{preloadTests:()=>fn});async function fn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await bt(async()=>{let t=await ie(s.testId,r=>rl({...e,testId:r}),{concurrency:2});return kf.keyBy(t,"testData.id")},"loadTests",Cv,[e,s.testId])()}var kf,Cv,Qo=w(()=>{"use strict";kf=E(require("lodash"));Bt();he();B();Cv=1e3*60*60*10});function ru(){return gt()}async function Df(){if(!Oe)try{let s=await ce(kv(),5e3,"The API call to NPM timed out"),e=ru();e&&Lf.lt(e,s)&&console.log(Of.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){Pv.warn("Failed to get NPM version",{err:s})}}var Of,Lf,Pv,kv,su=w(()=>{"use strict";Of=E(require("chalk")),Lf=E(require("semver"));B();ue();Yr();Bt();j();Pv=x("npm-driver"),kv=bt(()=>gm("@testim/testim-cli"),"getNpmVersion")});var nu,Ov,ss,Nf,Mf,ou,Uf,Ff=w(()=>{"use strict";B();K();j();mn();nu=x("testimNgrok"),Ov=".whitelisted-ngrok.testim.io",ss="",Mf=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=`${se()}-${s.projectData.projectId}${Ov}`);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 ot("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(nu.info("replace https to http"),ss=o.replace("https://","http://")):ss=o,s.tunnelDiagnostics&&ou(),s.baseUrl=ss},ou=async(s=!0)=>{try{let t=(await ot("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ss);console.log("ngrok stats",n),nu.info("ngrok stats",{tunnel:n})}catch(e){nu.error("error collecting ngrok stats",{err:e})}s&&(Nf=setTimeout(()=>ou(),1e4))},Uf=async s=>{if(!ss)return;clearTimeout(Nf),s.tunnelDiagnostics&&await ou(!1),await(await ot("ngrok")).disconnect(ss)}});var rr,au,Bf,Dv,Nv,iu,Zo,ti,ei,Mv,jf,$f,Wf=w(()=>{"use strict";rr=E(require("os")),au=E(require("fs")),Bf=E(require("child_process"));B();he();Dv="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",Nv={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},iu=rr.tmpdir(),Zo=`${iu}/cloudflared`,ti=null,ei=null,Mv=async()=>{if(await ge(Zo))return;let e=Nv[rr.platform()+rr.arch()];if(!e)throw new Error(`tunnel on ${rr.platform()+rr.arch()} platform is not supported.`);let t=e.extract?iu+e.path:Zo;await Je(`${Dv}/${e.path}`,t),e.extract&&await rt(t,iu),await au.promises.chmod(Zo,"755")},jf=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Il(s.company.companyId,t),Mv()]);ti=r._id,ei=Bf.spawn(Zo,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Rl(s.company.companyId,ti),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await au.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},$f=async s=>{let e=[];return ti&&e.push(Al(s.company.companyId,ti)),ei&&e.push(new Promise((t,r)=>{ei.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ei.kill()})),await Promise.all(e)}});function Gv(s){if(!(s!=null&&s.width)||!(s!=null&&s.height))return re.lambdatestConfig.RESOLUTION;let e=`${s.width}x${s.height}`;return Wv.includes(e)?e:(ri.warn("default resolution is used because the resolution is not supported by LT",{resolutionString:e}),re.lambdatestConfig.RESOLUTION)}var Gf,Vf,Vt,Hf,qf,zf,si,Kf,ri,Fv,Bv,gn,jv,$v,re,Wv,ni=w(()=>{"use strict";Gf=E(require("ms")),Vf=E(require("p-retry")),Vt=E(require("os")),Hf=E(require("portfinder")),qf=E(require("child_process"));B();Ve();he();zf=E(require("fs")),si=E(require("fs/promises")),Kf=require("path");K();j();qo();ae();pe();B();ri=x("lambdatestService"),Fv="https://downloads.lambdatest.com/tunnel/v3",Bv={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"},gn=`${Vt.tmpdir()}/LT`,jv=`${gn}/LT`,$v=(0,Gf.default)("15m"),re=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===O.LAMBDATEST||e.type===O.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){re.isLambdatestGrid(e)&&(re.lambdatestConfigPromise||=hl(),re.lambdatestConfig=await re.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?$v:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(jv))return;let t=Bv[Vt.platform()+Vt.arch()];if(!t)throw new Error(`tunnel on ${Vt.platform()+Vt.arch()} platform is not supported.`);let r=`${gn}.zip`;await Je(`${Fv}/${t}`,r),await rt(r,gn)}static async chmodLtTunnel(e){if(!(Vt.platform()==="win32"||!await ge(e))){try{await si.access(e,zf.constants.X_OK);return}catch{}try{await si.chmod(e,"777")}catch(r){throw ri.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await oe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){re.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Hf.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;re.tunnelName=se();let c=["--tunnelName",re.tunnelName,"--infoAPIPort",String(t)];if(L.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],i&&a)c=[...c,"--ntlm-username",i,"--ntlm-password",a];else{let u=JSON.parse(L.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...xc(u)])}if(L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)c=[...c,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await re.delay(3e3),await re.chmodLtTunnel((0,Kf.join)(gn,"LT")),re.tunnel=qf.spawn("./LT",c,{cwd:gn});let d="",m="";re.tunnel.stdout.on("data",u=>{d+=u.toString()}),re.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,Vf.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});ri.info("LT tunnel info",u)}catch(u){throw ri.error("Failed to start LT tunnel",{err:u,stdoutResult:d,stderrResult:m}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!re.tunnel))return new Promise((t,r)=>{re.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),re.tunnel.kill()})}getCapabilities(e,t,r,n,o,i){if(!this.isActive)return{};let a=re.lambdatestConfig.CAPABILITIES[t]||{},l={...re.tunnelName&&{tunnel:!0,tunnelName:re.tunnelName}},c=[],{mode:d,canary:m,ext:u,extensionPath:f,installCustomExtension:h}=e,g=(i==null?void 0:i.os)==="Windows 11"?i.os:re.lambdatestConfig.PLATFORM;if(d===Z.EXTENSION&&!u){let y=Wl({canary:m},!0);!f&&y[t]&&(c=[...c,y[t]]),f&&_e(f)&&(c=[...c,f])}return h&&_e(h)&&(c=[...c,h]),{build:r,name:`${n} - ${o}`,platform:g,selenium_version:re.lambdatestConfig.SELENIUM_VERSION,resolution:Gv(i==null?void 0:i.resolution),timezone:re.lambdatestConfig.TIMEZONE,...a,loadExtension:c,...l,console:!0,queueTimeout:300,network:L.flags.LTNetworkCapabilities.isEnabled(),ntlm:L.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:L.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},Wv=["1024x768","1280x800","1280x1024","1366x768","1440x900","1680x1050","1600x1200","1920x1200","1920x1080","2048x1536","2560x1440"]});var cu={};V(cu,{connect:()=>ii,disconnect:()=>ai,serveTunneling:()=>Hv});var oi,Jf,Yf,Vv,ii,ai,Hv,lu=w(()=>{"use strict";Ff();un();Wf();nt();oi=E(require("ora"));j();ae();ni();Jf=x("tunnel"),Yf=s=>{var e;return[O.LAMBDATEST,O.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},Vv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===O.HYBRID&&s.gridData.tunnel==="cloudflare"},ii=async s=>{if(!s.tunnel)return;let e=jt(),t;try{Yf(s)?(t=(0,oi.default)("Starting testim lambdatest tunnel...").start(),await re.connectTunnel(s)):Vv(s)?(t=(0,oi.default)("Starting testim cloudflare tunnel...").start(),await jf(s)):(t=(0,oi.default)("Starting testim ngrok tunnel...").start(),await Mf(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw Jf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},ai=async s=>{if(s.tunnel)try{Yf(s)?await re.disconnectTunnel(s):"tunnelRoutes"in s?await $f(s):await Uf(s)}catch(e){let t="catch error - failed to close tunnel";throw Jf.error(t,{err:e}),new Error(t)}},Hv=async(s,e=new Promise(()=>{}))=>(await ii(s),es(()=>ai(s)),await e)});function qv(s){if(s.protocol)return s.protocol;if([O.TESTIM,O.BROWSERSTACK,O.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([O.TESTIM_ENTERPRISE,O.LAMBDATEST,O.DEVICE_FARM].includes(s.type)){let e=Xf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function zv(s){let e=Xf.exec(s);return e==null?void 0:e[3]}function li(s){var b,v,I,C,_,$,A,S,D,U,H;let e=s&&zv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&qv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(b=s==null?void 0:s.hybrid)==null?void 0:b.tunnel,l=(v=s==null?void 0:s.external)==null?void 0:v.user,c=(I=s==null?void 0:s.external)==null?void 0:I.key,d=s==null?void 0:s.type,m=d===O.HYBRID?a&&(($=(_=(C=s.hybrid)==null?void 0:C.external)==null?void 0:_[s.hybrid.tunnel])==null?void 0:$.user):l,u=d===O.HYBRID?a&&((D=(S=(A=s.hybrid)==null?void 0:A.external)==null?void 0:S[s.hybrid.tunnel])==null?void 0:D.key):c,f=s==null?void 0:s.name,h=s&&(s._id||s.gridId),g=s==null?void 0:s.provider,y=(U=s==null?void 0:s.mobileTokens)==null?void 0:U.androidToken,T=(H=s==null?void 0:s.mobileTokens)==null?void 0:H.iosToken,R=s==null?void 0:s.apiUrl;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:R}}async function Zf(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error(yt.UNKNOWN)}if(Qe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(yt.UNKNOWN);if(o.status==="success"){let i=li(o.grid);return Kv(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new ze(yt.NOT_FOUND):o.code==="no-available-slot"?new Jt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new ze(yt.UNKNOWN))}function Jv(s,e,t,r,n,o){return Zf(t,e,s,n,()=>Bo(e,t,r,n,o))}function Yv(s,e,t,r,n,o,i){return Zf(t,e,s,n,()=>{var c;let l=(c=i.allGrids)==null?void 0:c.find(d=>(d.name||"").toLowerCase()===r.toLowerCase());return l!=null&&l._id?Bo(e,t,l._id,n,o):ml(e,t,r,n,o)})}function eg(s){return gl(s)}async function tg(s,e,t){let n=(t||await eg(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return li(n)}async function Xv(s,e,t){let n=(t||await eg(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return li(n)}async function uu(s,e){let t=hn[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete hn[s],!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await pl(i,e,r,n,o)}catch(a){Qe.error("failed to release slot",{projectId:e,err:a})}}async function Qv(s){let e=Object.values(hn).filter(Boolean);if(e.length!==0){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await ul(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function Zv(s){Qf=global.setInterval(Qv,1e4,s)}async function eE(s){let e=Object.keys(hn);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await ie(e,t=>uu(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function tE(s){await eE(s),clearInterval(Qf)}function rE(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function sE(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function rg(s){let t=(()=>ci.isEmpty(s.testobjectSauce)?ci.isEmpty(s.saucelabs)?ci.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=rE(t,s),l=sE(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:l,key:a}}async function sg(s,e){let t=s.company.companyId;return await tg(t,e.gridId,s.allGrids)}async function ng(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:l}=s;if(n||i||o)return{mode:"local"};if(r)return rg(s);let c=t==null?void 0:t.companyId;if(a)return tg(c,a,e);if(l)return Xv(c,l,e);if(Gs(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new ze("Missing host or grid configuration")}async function og(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:l,useLocalChromeDriver:c,useChromeLauncher:d,company:m}=t,u=m==null?void 0:m.companyId;if(c||d||l)return{mode:"local"};if(n)return rg(t);if(a)return Jv(r,u,o,a,s,e);if(i)return Yv(r,u,o,i,s,e,t);throw new ze("Missing host or grid configuration")}var ci,Qe,hn,Xf,Qf,Kv,yn,ig,ns=w(()=>{"use strict";ci=E(require("lodash"));he();j();B();ae();K();Qe=x("grid-service"),hn={},Xf=/(^(https?):\/{2})?(.*)/,Qf=null;Kv=(s,e,t,r,n)=>{hn[s]={gridId:t,companyId:e,slotId:r,browser:n}};yn={start:Zv,end:tE};ig=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!i||!a||(a===O.LAMBDATEST&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==O.HYBRID||!o||!l||!d||!m))return e;let u=await dl({companyId:o,gridId:i,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Qe.info("handling hybrid grid",{response:u,companyId:o});let f=li({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});async function pu(s,e,t){let r=os[s];if(!r)return;let{slotId:n}=r;if(delete os[s],!n){it.warn("failed to find slot slot id",{companyId:e,workerId:s});return}it.info("release slot id",{companyId:e,slotId:n});try{await Ol(e,t,n)}catch(o){it.error("failed to release slot",{companyId:e,err:o})}}async function nE(s,e){let t=Object.values(os).filter(Boolean);if(t.length!==0){it.info("keep alive worker slots",{companyId:s,slots:t});try{await Dl(s,e,t)}catch(r){it.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function oE(s,e){ag=global.setInterval(()=>nE(s,e),1e4)}async function iE(s,e){let t=Object.keys(os);if(t.length){it.warn("not all slots released before end runner flow",{companyId:s});try{await ie(t,r=>pu(Number(r),s,e))}catch(r){it.error("failed to release all slots",{err:r,companyId:s})}}}async function aE(s,e){await iE(s,e),clearInterval(ag)}async function lg(s,e,t){let r;try{r=await _l(s,e)}catch(n){throw it.error("failed to get slot",{companyId:s,err:n}),new Error(yt.UNKNOWN)}if(it.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw it.error("invalid response - get slot",{res:r}),new Error(yt.UNKNOWN);if(r.status==="success")return cg(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new ze(yt.NOT_FOUND):r.code==="no-available-slot"?new Jt("Failed to run test - concurrency limit reached"):(it.error("invalid code error response - get slot",{res:r}),new ze(yt.UNKNOWN))}async function ug(s,e,t,r){let n=os[r];if(!n)throw new Error("slot not found");Object.assign(n,t),cg(r,n),await Ll(s,e,n),it.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var it,os,ag,cg,Tn,is=w(()=>{"use strict";he();j();B();ae();K();it=x("slot-service"),os={},ag=null,cg=(s,e)=>{os[s]=e};Tn={start:oE,end:aE}});function vn(){return ui||"master"}function pg(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){ui="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){ui=s.branch||s;return}ui=e?"master":void 0}var ui,du=w(()=>{"use strict";K()});var En,mu,cE,fu,lE,pi,di,mi,fi,gi,hi=w(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===de.FAILED},mu=s=>{let{status:e}=s;return e===de.ABORTED},cE=s=>{let{status:e}=s;return e===de.PASSED},fu=s=>s.runnerStatus===vc.SKIPPED,lE=s=>s.testStatus===Ye.EVALUATING,pi=(s,e)=>Object.values(s).filter(t=>{var r,n;return fu(t)&&(Xe(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,di=s=>Object.values(s).filter(e=>En(e)&&lE(e)).length,mi=s=>Object.values(s).filter(En),fi=s=>Object.values(s).filter(cE),gi=s=>Object.values(s).filter(mu)});function pE(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var gu,yi,uE,bi,mg=w(()=>{"use strict";gu=E(require("lodash"));j();hi();yi=x("debug-reporter"),uE=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],bi=class{constructor(e){this.options=e}onTestStarted(e,t){yi.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,l=r.failedGetBrowserAttempts;yi.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:l,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...gu.default.omit(this.options,uE),company:gu.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let l=pE(process.argv);yi.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,o){let i=fi(e).length,a=Object.keys(e).length-i;yi.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var hu,kt,Sn=w(()=>{"use strict";ae();hu=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===O.DEVICE_FARM}},kt=new hu});var bu={};V(bu,{Reporter:()=>dE});var sr,In,Sr,Ti,fg,yu,dE,Tu=w(()=>{"use strict";sr=E(require("chalk")),In=E(require("lodash"));B();ae();Sn();hi();Sr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:Ti}=Ut,fg="device",yu=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: ${sr.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?de.PASSED:de.FAILED,n=`(${e.testId})`,o=Sr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${fo(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Sr.error("Failed runs are:")),console.log(Sr.error(t.join(`
22
+ \r`)))}onTestPlanFinished(e,t,r,n,o){let i=mi(e),a=fi(e),l=gi(e),c=a.length,d=l.length,m=i.length,u="",f="";if(kt.isTestStatusEnabled){let R=di(e);u=` FAILED-EVALUATING: ${R}`,m-=R,f=` SKIPPED: ${pi(e,this.options)}`}let h=this.buildTestPlanName(o,t),g,y=Sr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${fo(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=In.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=In.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=In.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=In.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 l=u=>{u.forEach((f,h)=>{var T;let g=(T=f.testData)!=null&&T.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`;console.log(" ",h+1,":",`${f.name}${Xe(f,this.options)?"-quarantine":""}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${m} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===Ti.APPIUM?fg:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===Ti.APPIUM?fg:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.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===Ti.APPIUM?"device":"browser";if(n)console.log(Sr.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(Sr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===Ti.APPIUM?"Appium":"Selenium";console.log(Sr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},dE=yu});var Eu={};V(Eu,{Reporter:()=>bE});function mE(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function fE(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 gE(s){return`${s.visitedUrlsJson||""}`}async function hE(s,e,t,r,n,o){function i(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:mE(u),classname:n,time:Cc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||mu(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return fu(u)&&Xe(u,o)&&kt.isTestStatusEnabled&&(h.skipped={}),o.urls&&(h["visited-urls-list"]=fE(u),h["visited-urls-json"]=gE(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},R={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(kt.isTestStatusEnabled){R.skipped=pi(y,o);let b=di(y);R.failures-=b,R["failure-evaluating"]=b}return{$:R,testcase:Object.keys(y).map(b=>i(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return mi(u).length+gi(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new vu.Builder().buildObject(m)}catch(u){return yE(u)}}function yE(s){let e=new vu.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 vu,gg,wu,bE,Su=w(()=>{"use strict";vu=E(require("xml2js"));B();gg=require("fs");Sn();hi();wu=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 hE(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await gg.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)}};bE=wu});var hg={};V(hg,{Reporter:()=>TE});function as(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 Iu,Ru,TE,yg=w(()=>{"use strict";j();Iu=x("team-city-reporter");Ru=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 as(n)}onTestStarted(e,t,r,n){if(r){Iu.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){Iu.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${as(t)}' details='${as(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){Iu.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='${as(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${as(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${as(t)}']`)}},TE=Ru});var bg={};V(bg,{Reporter:()=>wE});var Au,wE,Tg=w(()=>{"use strict";Au=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}}))}},wE=Au});var wg={};V(wg,{Reporter:()=>vE});var xu,vE,vg=w(()=>{"use strict";B();Vl();xu=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Ko(t)}},vE=xu});var Wx,Cu,Q,_t=w(()=>{"use strict";mg();j();Wx=x("reporter"),Cu=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 bi(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Tu(),bu));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Su(),Eu));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(yg(),hg)),r.includes("console")&&Promise.resolve().then(()=>(Tu(),bu)),r.includes("junit")&&Promise.resolve().then(()=>(Su(),Eu)),r.includes("json")&&Promise.resolve().then(()=>(Tg(),bg)),r.includes("chrome")&&Promise.resolve().then(()=>(vg(),wg))])).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))}}},Q=new Cu});function Sg(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Ig({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Sg({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:l,source:Eg(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);Tt("test-run-ci",y)}function Rg({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let R=Sg({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:Eg(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",R);return}Tt("test-run-ci-fail",{...R,failureReason:n.failureReason})}catch(R){f.error("failed to update test end analytics",{err:R})}}function Ag(s){Tt("batch-run-ci",s)}var Eg,Pu=w(()=>{"use strict";ts();Uo();Eg=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Qr&&e?"ci-with-user":Qr?"ci":e?"cli-with-user":s});var Cg,wi,Pg=w(()=>{"use strict";Cg=require("istanbul-lib-report"),wi=class extends Cg.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 kg,_g,Og,Rn,wt,Lg,vi,ku,Dg,EE,Ng,Mg,SE,IE,Ug,RE,AE,xE,CE,PE,Fg,Bg=w(()=>{"use strict";kg=E(require("ora")),_g=E(require("dayjs")),Og=E(require("test-exclude")),Rn=E(require("fs")),wt=E(require("path")),Lg=E(require("istanbul-reports")),vi=E(require("istanbul-lib-report"));he();K();B();j();mn();Pg();ku=x("test-run-status"),Dg=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},EE=s=>!!Dg(s).search,Ng=s=>s?Dg(s).pathname.substring(1):"",Mg=(s,e)=>{let t=Ng(e);return!new Og.default({relativePath:!1,include:s}).shouldInstrument(t)},SE=s=>s.substring(0,s.indexOf("?")),IE=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ot("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)},Ug=(s,e)=>`${wt.resolve(s,Ng(e))}.js`,RE=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(Mg(r,i))return;let l=Ug(e,i);await Rn.promises.mkdir(wt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,o.sourcesContent[a])})})},AE={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(EE(e)&&(e=SE(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},xE=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=vi.createContext({dir:t,coverageMap:e,watermarks:vi.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Ug(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new wi({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:AE}),Lg.create(a,l).execute(i)}),o},CE=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await ot("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Mg(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},PE=async(s,e)=>{let{mergeProcessCovs:r}=await ot("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await bl(s,"testResult",`runId=${e}`)).data.docs;return await ie(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await on(l,9e4);await ie(c,async d=>{if(!o.has(d.url)){let m=d.text;d.sourceUrl&&(o.set(d.url,"TEMP"),m=await el(d.sourceUrl)),o.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},Fg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;ku.info("start js coverage process");let n=(0,kg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=wt.resolve(s.codeCoverageReportPath||"./coverage"),i=wt.resolve(o,`.js/${(0,_g.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([ot("istanbul-lib-coverage"),PE(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}ku.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await ie(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),R=await IE({sourceMapType:T,source:y,sourceMapDir:a});u[h]=R;let b=await CE(s,{source:y,sourceMap:R,functions:g});m.merge(b)}),await RE(s,i,u);let f=await xE(s,m,o,i);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof P?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),ku.error(c,{err:l})}}});var jg={};V(jg,{SELENIUM_PERF_MARKS:()=>Ce,SeleniumPerfStats:()=>Ir});var Ce,kE,Ir,cs=w(()=>{"use strict";B();Ce={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},kE=["ALL",...Object.values(Ce)],Ir=class{constructor(){this.marks=Object.fromEntries(kE.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=se();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,yo(r,50)],[`${t}_P95`,yo(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Vg={};V(Vg,{initServer:()=>LE,mapFilesToLocalDrive:()=>Ou});function Ou(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,Ei[t.id]?{screenshot:Ei[t.id]}:{})),Object.keys(Si).forEach(t=>{s.assets||={},s.assets[Gg[t]]=Si[t]}),s.assets||={},s.assets.screenshots=Object.values(Ei)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function LE({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ot("multer"),n=typeof t=="string"?t:_E;await _u.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await _u.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),i=(0,Wg.default)();i.post("/",o.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(Ei[d.stepId]=l.file.path),d.testResultId&&OE.includes(d.subType)&&(Si[d.subType]||=[],Si[d.subType].push(l.file.path)),c.sendStatus(200)}),i.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(i);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new P(`Port ${s} is already in use`));default:return c(u)}}})}var _u,$g,An,Wg,_E,Ei,Si,Gg,OE,Lu=w(()=>{"use strict";_u=E(require("fs")),$g=E(require("os")),An=E(require("path")),Wg=E(require("express"));K();mn();_E=An.join($g.tmpdir(),"testim/rca/"),Ei={},Si={},Gg={"test-log":"consoleLogs","har-file":"networkLogs"},OE=Object.keys(Gg)});var nr,Du,Ii,Hg=w(()=>{"use strict";nr=E(require("lodash"));B();j();Du=x("override-test-data-builder"),Ii=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Du.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Du.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}Du.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 nr.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(d=>this.generateTestUniqId(d)),i=o.indexOf(n),a=o.lastIndexOf(n),l=r[i],c=this.createNewTestItems(l,t);return r.splice(i,a-i+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=se();return{...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 Ri(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Rr,Ze,DE,NE,ME,UE,Ai,qg=w(()=>{"use strict";Rr=E(require("lodash"));B();ae();ns();is();he();K();j();_t();un();Bg();cs();Lu();ue();pe();Hg();Sn();Ze=x("test-run-status"),DE=hr(),NE=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,ME=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,UE=gt();Ai=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new Ir;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Ws(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:ro||t.parallel||1,browser:o,gitBranch:DE,gitCommit:NE,gitRepoUrl:ME,runnerVersion:UE,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R}=a,b={originalTestResultId:t,previousTestResultId:r,config:Rr.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:i,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:R},El({projectId:n,runId:o,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,Q.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:o,projectData:i}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await $o(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(d){Ze.error("failed to upload test data artifact (runner)",{err:d})}let l=Rr.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,vr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Xe(e,this.options))return;let n=this.exportsGlobal;try{let o=await Ri(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...o},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Ze.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={...t,key:void 0,user:void 0},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Ye.EVALUATING&&kt.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Ye.EVALUATING} status`);return}if(c){Q.onTestPassed(o);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,i,l,this.branchToUse),i,n,l)}calcResultText(e){return e.success?de.PASSED:de.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Ye.QUARANTINE}`)}monitorMemoryUsage(e){let t=Pc();t.isOverThreshold&&Ze.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,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&&Ou(i,Ze),i.resultUrl=qe(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),Q.onTestFinished(i,e,o);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await Ri(this.options.afterTest,{...e,exportsGlobal:o,globalParameters:o},this.options.userData.loginData.token)}catch(a){Ze.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 vr(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 Ze.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,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Ic;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var f,h,g;let l=e.browser?qs(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=Gr(L,n)&&Vs(a.nativeApp)&&!e.appId,d=Hs(e)&&(Wr(a.nativeApp,n)||c),m=Xe(a,e)||d,u={testId:a.testId,status:m?de.SKIPPED:de.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Ye.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(o)}async endKeepAlive(e,t,r){e==="redis"&&await Tn.end(r,t),e==="mongo"&&await yn.end(t)}async executionStart(e,t,r,n,o){Ze.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=i;es(()=>Promise.all([this.endKeepAlive(d,t,c),Fo("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,...L.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},u=await Ri(i.beforeSuite,m),f=new Ii(u,Rr.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let R=async()=>{let b=Rr.cloneDeep(this.testRunStatus);await ie(Object.keys(b),async C=>{var D;let _=b[C],$=(D=_.config)==null?void 0:D.testData,A=_.testId,S=await $o(t,A,C,$,l.defaults);S&&(delete _.config.testData,_.config.testDataUrl=S)});let v=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),I=ol({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:v,intersections:i.intersections});return this.executionStartedPromise=I,I.catch(C=>Ze.error(C)),I};try{await R()}catch(b){Ze.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){Rr.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var d;let t=_c(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:m,testStatus:u}of t)m===de.PASSED&&n++,m===de.SKIPPED&&o++,m===de.FAILED&&u===Ye.EVALUATING&&i++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await Ri(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Fg(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await Fo("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Ze.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await nl(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}}});function BE(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Bu(s){return Jg.readFileSync(s,{encoding:"base64"})}function Zg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&_e(s))&&s){let r=Bu(s);ls.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Fu(r)} current extension count: ${e.length}`),e.push(r)}}function eh(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let l=typeof s.ext=="string"?s.ext:`${__dirname}/..`,c=r||l,d=`--load-extension=${c}`;ls.info(`adding extension: testim unpacked , path: ${c}`),t.push(d);return}let o=s.canary?"-master.zip":".zip",i=Uu.join(process.cwd(),`testim-headless${o}`),a=Bu(i);ls.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${Fu(a)} current extension count: ${e.length}`),e.push(a)}function jE(s,e,t,r,n,o,i){var h,g;let a=t.seleniumName||t.browserValue,l=[],c=[...Qg];e.headless&&c.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":Nu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Nu.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};Mu(n)&&(d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),Mu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>c.push(`--${y}`)),e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=Nu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&c.push(`--user-data-dir=${e.chromeUserDataDir}`),(g=(h=e.projectData)==null?void 0:h.defaults)!=null&&g.disableChromiumGpu&&c.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function m(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Ec.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}m(),Zg(r,l,i),e.mode===Z.EXTENSION&&eh(e,l,c,o,i),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=c;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],f={MicrosoftEdge:"ms",chrome:"goog"}[a];return re.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${f}:${u}`]=d),s}function WE(s,e,t){let r={"pdfjs.disabled":!0};if(L.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Kg.join(","),"browser.helperApps.neverAsk.openFile":Kg.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===Z.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=Uu.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=Bu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function GE(s){return`${s.width}x${s.height}`}function VE(s,e,t,r){let{saucelabs:n}=s;if(n!=null&&n.browserVersion&&(n.version=n.browserVersion),n!=null&&n.username&&n.accessKey){let o={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=n.appiumVersion||t.sl.appiumVersion;let i=(0,Xg.cloneDeep)(t.sl);return(r!=null&&r.resolution||t.sl.screenResolution)&&(o["sauce:options"].screenResolution=GE(r.resolution||t.sl.screenResolution),delete i.screenResolution),at.merge(i,o,n)}return at.merge(o,n)}return{}}function HE(s,e,t){return at.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function qE(s){return s.perfecto?s.perfecto:{}}function zE(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 KE(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=Ga(o,i)),a}function xi(s){var T,R,b,v;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,lambdatestService:c}=s;if(o.mode==="local"){let I=[],C=[...Qg],_={};return t.headless&&C.push("--headless"),t.silentDebuggerExtensionApi&&C.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&C.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach($=>C.push(`--${$}`)),t.chromeBinaryLocation&&(_.binary=t.chromeBinaryLocation),t.mode!=="selenium"&&eh(t,I,C,null,c),Zg(i,I,c),{logLevel:zg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:C,extensions:I,..._},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:d,driverRequestRetries:m}=t,u=KE(t,o),f={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:zg,connectionRetryTimeout:d,connectionRetryCount:m,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!at.isEmpty(u)&&{headers:u},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Mu(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,f.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(f.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let h=Number(t.browserTimeout/1e3),g=t.browser||(n==null?void 0:n.browserValue);at.merge(f.desiredCapabilities,VE(t,r,n,e),HE(t,r,n),qE(t),zE(t,g,h),c==null?void 0:c.getCapabilities(t,g,a,l,r,e));let y=null;switch(!t.ext&&!t.extensionPath&&((T=o.host)!=null&&T.endsWith(".testim.io"))&&!t.canary&&t.mode===Z.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&L.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(y="/opt/testim-headless"),g){case"chrome":case"edge-chromium":f=$E(f,t,n,i,o,y,c);break;case"firefox":f=WE(f,t,c);break;case"safari":case"safari technology preview":f=BE(f,g);break;default:break}at.merge(f.desiredCapabilities,t.seleniumCapsFileContent);try{let I={"hub.lambdatest.com":"lambdatest",[L.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},C=S=>S[o.provider]||S[f.host]||S[I[f.host]],_=S=>{var D,U;return C(S)||S[(D=f.desiredCapabilities)==null?void 0:D.browserName]||S[(U=f.desiredCapabilities)==null?void 0:U.version]||S||{}},$=JSON.parse(L.flags.addCustomCapabilities.getValue()||"{}"),A=_(_($));Object.keys(A).length&&(ls.info(`Adding custom capabilities: ${JSON.stringify(A)}`),Object.assign(f.desiredCapabilities,A))}catch(I){ls.error("Failed to load custom capabilities",{error:I,customCapabilities:L.flags.addCustomCapabilities.getValue()})}if(f.desiredCapabilities&&!f.capabilities&&(FE(f),f.capabilities={alwaysMatch:f.desiredCapabilities,firstMatch:[{}]},delete f.desiredCapabilities),f.hostname=f.host,s.printFinalCaps){let I=(R=f.capabilities)==null?void 0:R.alwaysMatch,C=JSON.parse(JSON.stringify(f)),_=(b=C==null?void 0:C.capabilities)==null?void 0:b.alwaysMatch,$=S=>S.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(S=>{var D,U;_!=null&&_[S]&&(_[S].extensions=(U=(D=I==null?void 0:I[S])==null?void 0:D.extensions)==null?void 0:U.map($))}),_!=null&&_.loadExtension&&(_.loadExtension=(v=I==null?void 0:I.loadExtension)==null?void 0:v.map($));let A=require("util");console.log(A.inspect(C,{showHidden:!1,depth:null,colors:!0}))}return f}var Jg,Uu,Yg,at,Xg,ls,zg,Nu,Qg,Fu,Mu,FE,$E,Kg,ju=w(()=>{"use strict";Jg=E(require("fs")),Uu=E(require("path")),Yg=E(require("crypto")),at=E(require("lodash"));B();ue();j();pe();ae();ni();Xg=require("lodash"),ls=x("testim-desired-capabilities-builder"),zg=to?"debug":"silent",Nu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Qg=["--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"],Fu=(...s)=>Yg.createHash("sha256").update(s.join("")).digest("hex"),Mu=s=>s.type===O.DEVICE_FARM||s.type===O.HYBRID&&s.provider==="devicefarm",FE=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=L.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{ls.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};$E=at.memoize(jE,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(at.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Fu(i,a,l,r,c,o)}),Kg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Fe(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 rh(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 $u=w(()=>{"use strict"});function Wu(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function o(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return o(y,f)}function i(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=o(u,"stroke-width");return!!g&&parseInt(g,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?i(g):!1)}function a(u){return o(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!i(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return Wu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(o(u,"opacity"))===0),m=!!n(s,u=>o(u,"display")==="none");return!(d||m||!i(s)||l(s))}var sh=w(()=>{"use strict"});var nh,oh,Ht,JE,YE,Ci,ih=w(()=>{"use strict";nh=E(require("promise-queue")),oh=E(require("webdriverio"));ue();$e();B();j();Nr();sh();$u();cs();Ht=x("WebDriverApi"),JE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},YE={implicit:0,pageLoad:1,script:2},Ci=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 Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),za!==void 0&&(e=za);let t=1/0;this.queue=new nh.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(),M("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(Ce.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await oh.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,Ce.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 l of a.slots||[])if(((i=l==null?void 0:l.session)==null?void 0:i.sessionId)===t){r=a,n=l;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.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){Ht.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(Fe(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(Fe(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(Ce.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,Ce.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Ce.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(De(e)))}finally{this.seleniumPerfStats.markEnd(t,Ce.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(Wu,{ELEMENT:e,[zt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Fe(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(rh(e,this.isSafari(),Ht))})}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[YE[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(Fe(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(De(e)),await this.elementIdValue(De(e),t)}async getViewportSize(e){let t=await this.execute(JE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var 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(De(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)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var 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(Fe(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.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{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){Ht.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 Ht.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 ah={};V(ah,{doubleClick:()=>XE});var XE,ch=w(()=>{"use strict";XE=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(u){function f(R,b,v){return v>R&&v<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=i(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var xn={};V(xn,{dispatchFocus:()=>QE});function QE(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 Cn=w(()=>{"use strict"});var mh={};V(mh,{WebDriver:()=>xr});async function rS(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 eS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var us,ph,dh,Be,or,ZE,lh,eS,ir,tS,uh,Ar,xr,Pn=w(()=>{"use strict";us=E(require("lodash"));B();$e();ju();ph=E(require("p-retry")),dh=E(require("ua-parser-js"));Nr();j();$u();ih();K();pe();cs();Be=x("webdriver"),[or,ZE]=[0,2],{extractElementId:lh,getCdpAddressForHost:eS}=J,ir=()=>(we(),be(tr)).getSessionPlayer().codeSnippets,tS=()=>(we(),be(tr)).getSessionPlayer().locatorBuilderUtils,uh=()=>(we(),be(tr)).getSessionPlayer().utils,Ar=()=>(we(),be(tr)).getSessionPlayer().positionUtils;xr=class extends Ci{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var R,b,v,I,C,_,$,A;let{overrideConfiguration:r,browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(b=(R=n==null?void 0:n.company)==null?void 0:R.activePlan)==null?void 0:b.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let g=xi({browserOptions:n,testName:o,testRunConfig:i,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h});g.desiredCapabilities&&delete g.desiredCapabilities.marionette,g.capabilities&&delete g.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let y=u?0:1500,T=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let S=await this.initClient(g,o,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await rS(S),M("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${o}`,{sessionId:this.getSessionId(),testResultId:d}),await oe(y),L.flags.dontFocusOnInit.isEnabled()||await T(),M("after focus and delay in webdriver.js init")}catch(S){let D=JSON.stringify(us.omit(g,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:S,capabilitiesAsString:D});let U=((C=(I=n==null?void 0:n.company)==null?void 0:I.activePlan)==null?void 0:C.plan)==="free";throw(_=S.stack)!=null&&_.includes("at startWebDriverSession")&&(($=S.message)!=null&&$.startsWith("Failed to create session"))&&((A=S.message)!=null&&A.includes("Timeout awaiting 'request'"))&&U?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):S.message.match(/Invalid username or password/)?new Br(S.message):S.message.match(/capabilit(y|ies)/)?new oo(S.message):S.message.match(/403 Forbidden/)?new Error("Grid Access Denied"):S.message.match(/Browser_Version not supported/)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${S.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>us.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","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=se();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,Be.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Be.warn("failed to click on alert",{err:l}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=lh(r.value);return await this.switchToFrame({ELEMENT:n,[zt]: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 io:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(Ce.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||L.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
23
23
  var fn = ${ir().getLocatedElementCode};
24
24
  return fn.apply(null, arguments);
25
25
  `,t)}finally{this.seleniumPerfStats.markEnd(r,Ce.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Ce.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 l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(o,i)}await this.executeJS(`
@@ -45,7 +45,7 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
45
45
  var eventData = arguments[0];
46
46
  var done = arguments[1];
47
47
  return doubleClick.call(null, eventData, done);
48
- `,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,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,ZE,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(Fe(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(Fe(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 Be.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:l}=n.value;return{x:r.left+o+a/2,y:r.top+i+l/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(Fe(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){Be.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),l=this.getClickActions(["pointerDown"],or),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],or);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,o,i){let{width:a,height:l}=r,c=n-a/2+1,d=o-l/2,m=this.getDragCoordinates(i),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Fe(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,o){let i=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:o},c=10,d=Math.round(i(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:l,toX:c,toY:d}=n,m=Ar().calculateElementMiddlePoint(o),u=Ar().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+i,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],or),R=us.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],or),I=y.concat(T).concat(R).concat(b).concat(v);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(Fe(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(Fe(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(Fe(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:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],or);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],or);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(lh(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){Be.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(){Be.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Be.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(Fe(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Gu,Vu,Pi,Hu=w(()=>{"use strict";j();pe();he();Gu=x("lab-features-service"),Vu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Gu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await yl(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Gu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=D.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(l=>l.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 Gu.error(t,{featureFlagName:e.name}),new Error(t)}},Pi=new Vu});function sS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function nS(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 oS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function iS(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).map(h=>`
48
+ `,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,or,t,["pointerDown","pointerUp"])}rightClickWithActionsAPI(t,r){return this.actWithActionsAPI(r,ZE,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(Fe(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(Fe(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 Be.warn(`could not find element for locatedElement ${t==null?void 0:t.testimId}`),new Error("could not calculate rect");let{x:o,y:i,width:a,height:l}=n.value;return{x:r.left+o+a/2,y:r.top+i+l/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(Fe(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){Be.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),l=this.getClickActions(["pointerDown"],or),c=this.getMoveActions(r,n,"pointer",1),d=this.getClickActions(["pointerUp"],or);return this.actions([{type:"pointer",id:"mouse",actions:a.concat(l).concat(c).concat(d)}])}async drag(t,r,n,o,i){let{width:a,height:l}=r,c=n-a/2+1,d=o-l/2,m=this.getDragCoordinates(i),{xDiff:u,yDiff:f}=m;if(this.unsupportedActions.has("move"))return this.dragWithActionsAPI(t,u,f,c,d);try{return await this.dragWithMoveTo(t,u,f,c,d)}catch(h){if(Fe(h))return this.unsupportedActions.add("move"),this.dragWithActionsAPI(t,u,f,c,d);throw h}}getMoveRelativeSequence(t,r,n,o){let i=(u,f)=>Math.hypot(u.x-f.x,u.y-f.y),a={x:t,y:r},l={x:n,y:o},c=10,d=Math.round(i(a,l)/c),m=Array.from({length:d},()=>({x:Math.round((l.x-a.x)/d),y:Math.round((l.y-a.y)/d)}));return[{x:1,y:1}].concat(m)}getMoveAbsoluteSequence(t,r,n,o){return this.getMoveRelativeSequence(t,r,n,o).reduce((a,l)=>{let c=a.at(-1);return a.concat({x:Math.round(c.x+l.x),y:Math.round(c.y+l.y)})},[{x:Math.round(t),y:Math.round(r)}])}async dragAndDropWithGeneratedMoves(t,r,n){let{fromRect:o,fromX:i,fromY:a,toRect:l,toX:c,toY:d}=n,m=Ar().calculateElementMiddlePoint(o),u=Ar().calculateElementMiddlePoint(l),f=this.getMoveRelativeSequence(m.x+i,m.y+a,u.x+c,u.y+d);await this.moveTo(t,Math.floor(i),Math.floor(a)),await this.buttonDown();for(let h of f)await this.moveTo(null,h.x,h.y);return await this.moveTo(r,Math.round(c),Math.round(d)),await this.buttonUp()}dragAndDropWithActionsAPIWithGeneratedMoves(t){let{fromRect:r,fromX:n,fromY:o,toRect:i,toX:a,toY:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l),g=this.getMoveAbsoluteSequence(m,u,f,h),y=this.getMoveActions(m,u),T=this.getClickActions(["pointerDown"],or),R=us.flatMap(g,C=>this.getMoveActions(C.x,C.y)),b=this.getMoveActions(f,h),v=this.getClickActions(["pointerUp"],or),I=y.concat(T).concat(R).concat(b).concat(v);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(Fe(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(Fe(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(Fe(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:l}=t,c=Ar().calculateElementMiddlePoint(r),d=Ar().calculateElementMiddlePoint(i),m=Math.floor(c.x+n),u=Math.floor(c.y+o),f=Math.floor(d.x+a),h=Math.floor(d.y+l);await this.moveWithActionsAPI({x:m,y:u});let g=this.getClickActionList(["pointerDown"],or);await this.actions(g),await this.moveWithActionsAPI({x:f,y:h});let y=this.getClickActionList(["pointerUp"],or);return this.actions(y)}async getTabIds(){let{value:t}=await this.windowHandles();return t}async isVisible(t){let{value:r}=await this.elementIdDisplayed(lh(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){Be.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(){Be.info("delete session",{sessionId:this.getSessionId()}),this.getSessionId()||Be.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(Fe(r))return this.unsupportedActions.add("submit"),super.submitFormManually(t);throw r}}}});var Gu,Vu,Pi,Hu=w(()=>{"use strict";j();pe();he();Gu=x("lab-features-service"),Vu=class{constructor(){this.featuresForProject=[];this.labBatman=!1}async loadLabFeatures(e,t){(!t||!e)&&(Gu.error("missing companyPlan or projectId when loading lab features",{companyPlan:t,projectId:e}),this.featuresForProject=[]);try{let r=this.isLabsEnabledForCompany(t),n=r?await yl(e):[];this.featuresForProject=n,this.labBatman=r}catch(r){Gu.error("failed loading lab features",{err:r,companyPlan:t,projectId:e}),this.featuresForProject=[]}}isFeatureAvailableForProject(e){let t=L.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(l=>l.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 Gu.error(t,{featureFlagName:e.name}),new Error(t)}},Pi=new Vu});function sS(s){let e=s.startsWith("\\\\?\\"),t=/[^\u0000-\u0080]+/.test(s);return e||t?s:s.replace(/\\/g,"/")}function nS(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 oS(s){let e=Object.getPrototypeOf(async()=>null).constructor;function t(){return e.apply(null,s)}return t.prototype=e.prototype,new t}async function iS(s,e,t,r,n={},o=void 0,i=void 0){let a=Object.keys(n).map(h=>`
49
49
  var res = requireOrImportMethod('${sS(n[h])}');
50
50
  if (res.sync) {
51
51
  var ${h} = res.lib;
@@ -213,17 +213,17 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
213
213
  injectCode(params, args, incomingParams, context, code);
214
214
  });
215
215
  })();
216
- `,u=[],f=new yh.Worker(m,{eval:!0});try{return await ce(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ct.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ct.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:i}):ct.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{ct.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(h){if(!(h instanceof ne))throw h;return ct.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function aS(s){try{await fh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ct.warn("failed to remove install npm packages folder",{err:e})}}function bh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ds(s,e,t,r,n,o){let i=bh(n,e,s,t),{data:a}=await cS(i,r,o);return a}async function ms(s,e,t,r,n,o,i,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||D.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=bm(y.testimPackageLocalLocation);return[y.paramName,ps.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=bh(i,n,e,o);if(c){let y=await on(c);y&&(l=y)}Buffer.isBuffer(l)&&(ct.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ct.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await iS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function cS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Th(),i=D.flags.reuseCliPkgInstallFolder.isEnabled()?n:ps.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Tm(i,r,a,t),ct.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 u=hm(i,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ps.resolve(i,"node_modules",m.packageName)}}),installFolder:i}}catch(d){throw ct.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ce(l(),t)}catch(c){throw c instanceof ne&&ct.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Th(){return ps.join(gh.tmpdir(),"/testim_local_packages")}function lS(){let s=Th();return aS(s)}var fh,gh,ps,hh,yh,ct,fs=w(()=>{"use strict";fh=E(require("fs")),gh=E(require("os")),ps=E(require("path"));B();Yr();hh=E(require("data-uri-to-buffer")),yh=require("worker_threads");K();j();he();Yr();pe();ct=x("cli-service");lS().catch(s=>ct.warn("failed to clean local package folder",{err:s}))});var ar={};V(ar,{run:()=>pS});function uS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=D.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var pS,wh=w(()=>{"use strict";fs();K();pe();pS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await ms(r,n,o,i,a,l,c,d,m,u);return f&&uS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ne?new Error("Timeout while running action"):f}}});var qu={};V(qu,{run:()=>dS});var dS,vh=w(()=>{"use strict";fs();K();dS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ds(t,r,n,i,o,a),success:!0}}catch(l){if(l instanceof At)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ne)return{success:!1,code:"timeout"};throw l}}});async function Sh(s,e,t,r){try{return await wl(s,e,t,r)}catch{ki.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function fS(s,e,t,r,n){return ki.info("finished to run remote step",{stepId:t,sessionId:n}),await Sh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Eh(s,e,t,r,n){return ki.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Sh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Ih(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(),l=t.id;ki.info("start play remote step",{stepType:i,stepId:l,sessionId:a});let c=mS[i];if(!c)return await Eh(n,r,l,`Failed to find step type ${i}`,a);try{let d=await c.run(e,t,o);return await fS(n,r,l,d,a)}catch(d){return await Eh(n,r,l,d.message,a)}}var ki,mS,Rh=w(()=>{"use strict";wh();he();vh();j();ki=x("step-playback"),mS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":qu}});var zu,Ah,Cr,hS,Ku,vt,_i=w(()=>{"use strict";B();nt();zu=E(require("ws")),Ah=require("events");j();ue();Cr=x("socket-service"),hS=5e3,Ku=class extends Ah.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),hS)}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){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(od);return Zt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new zu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===zu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.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(l){n(l)&&o(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=i.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}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=se(),l={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",c=>c.id===a,i),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}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})}},vt=new Ku});var Ch,Ju,yS,bS,TS,xh,Oi,gs,Yu=w(()=>{"use strict";Ch=E(require("p-retry")),Ju=E(require("socket.io-client"));ue();B();j();yS=50,bS=10,TS=5e3,xh=10*1e3,Oi=x("base socket service"),gs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Oi.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{}Oi.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===bS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=yS)throw new Error(`Can't connect to Testim Servers.
217
- Action required: Please allow opening a websockets connection to ${fe} 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",()=>{Oi.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:xh,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=`${fe}/${t}`,this._socket=Ju.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:xh,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=`${fe}/${t}`,this._socket=Ju.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,Ch.default)(()=>ce(n(),TS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Ph={};V(Ph,{remoteStepServiceSocketIO:()=>wS});var Xu,wS,kh=w(()=>{"use strict";Yu();Xu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}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.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},wS=new Xu});var _h={};V(_h,{remoteStepService:()=>hs});var Qu,_n,Zu,hs,Li=w(()=>{"use strict";_i();ae();pe();({REMOTE_STEP_SAVED:Qu}=Ct),Zu=class{async init(e){D.flags.useNewWSCLI.isEnabled()||(_n=(await Promise.resolve().then(()=>(kh(),Ph))).remoteStepServiceSocketIO,_n.init(e))}joinToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Qu]):_n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Qu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}_n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return D.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Qu]),Promise.resolve()):_n.unlistenToRemoteStep(e)}},hs=new Zu});var ep,Pr,Oh=w(()=>{"use strict";Yu();ep=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[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.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new ep});var Dh={};V(Dh,{testResultService:()=>Ot});var Lh,tp,Ot,Di=w(()=>{"use strict";Lh=require("events");_i();ae();pe();Oh();tp=class extends Lh.EventEmitter{init(e){if(D.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return D.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(D.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(D.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!D.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},Ot=new tp});var Mh,Uh,Fh,Ee,vS,Bh,Nh,Ni,jh=w(()=>{"use strict";Mh=E(require("lodash"));B();ue();$e();ts();nt();he();Rh();Uh=E(require("p-retry")),Fh=require("url");j();Qo();cs();ae();Li();Di();Ee=x("test-run-handler"),vS=3,Bh=20*1e3,Nh=s=>JSON.stringify(s).length<Bh,Ni=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 Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;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._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?qs(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}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}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[e])==null?void 0:a[t]:null}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 isAppFromDevice(){return Vs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/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 overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Zt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:dd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,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},userAccessKey:await Do()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Nh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),Ee.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Bh} 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 fn(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 Ee.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&&Nh(e))return;let r=async()=>{try{return await vl(this._options.project,this._testId,this._testResultId,e)}catch(i){return Ee.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Tl(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){M("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{M("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};M("before Runtime.evaluate"),await(0,Uh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(i){throw Ee.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 Fh.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)){Ee.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)&&(Ee.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:l,branch:c,_options:{project:d}}=this;try{let m=await Er(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){Ee.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ot.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Er(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return Ee.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Ee.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw Ee.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ot.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ot.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Ee.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=Mh.debounce(async()=>{try{let i=await Er(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Ee.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"?(Ee.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 Ee.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ot.on("socket-connected",async()=>{try{await Ot.joinToTestResult(this._testResultId,this.testId)}catch(i){Ee.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 ll(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Ee.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ot.off("socket-connected",e)}}listenToRemoteStep(e){hs.listenToRemoteStep(this.testResultId,t=>{Ih(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:vS;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=se(),!((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 Mi,$h=w(()=>{"use strict";jh();Mi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Ni(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var ES,SS,IS,On,rp=w(()=>{"use strict";ns();is();j();ES=x("worker-utils"),SS=async(s,e,t)=>{e&&await uu(s,t)},IS=async(s,e,t)=>{await pu(s,e,t)},On=async(s,e,t,r,n,o)=>{ES.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await SS(s,e,t),n==="redis"&&await IS(s,r,t)}}});function kS(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Bi,Vh,Fi,op,Hh,Et,Wh,Gh,sp,Ln,RS,np,AS,cr,xS,Ui,CS,PS,_S,lt,Dn=w(()=>{"use strict";Bi=E(require("ms")),Vh=E(require("lodash")),Fi=E(require("p-retry")),op=E(require("dayjs")),Hh=E(require("dayjs/plugin/duration"));B();$e();ns();is();he();j();rp();_t();ni();pe();Li();Di();Ve();ae();K();op.default.extend(Hh.default);Et=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Wh,TEST_START_TIMEOUT_MSG:Gh,TEST_COMPLETE_TIMEOUT_MSG:sp}=Ue,{SETUP_TIMEOUT:Ln,NETWORK_ERROR:RS,GRID_ERROR:np,BROWSER_CLOSED:AS,SELENIUM_ERROR:cr,UNKNOWN_ERROR:xS,MOBILE_SESSION_ERROR:Ui}=$s,CS=(0,Bi.default)("1s"),PS=1;_S=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],lt=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.id=lt.getWorkerId();this.lambdatestService=new re;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}static getWorkerId(){return PS++}async getGridSlot(e,t){let r=await og(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ds(!0)}async getBrowserOnce(e,t,r,n){throw new Ds(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Et.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Gr(D,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;return this.options.mode===Z.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Bi.default)("600s"),this.options.getSessionTimeout):Math.max((0,Bi.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Fi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Fi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(lg(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Jt?Et.info("could not get grid slot due to concurrency issue",r):Et.error("error getting grid slot",{error:e,...r}),await oe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Fi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await ig(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();M("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===Z.APPIUM?"device":"browser";throw Et.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Rt)&&this.options.mode!==Z.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(i){throw await On(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Rt,Br].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,np):new fr(i,cr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Hs(this.options)&&this.handleMobileTest(e);if(i)return i;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,c)}finally{await On(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(h,g,y)=>{var L,U,H;if(Xe(h,this.options)||Gr(D,(L=this.options.gridData)==null?void 0:L.type)&&g.isAppFromDevice&&!this.options.appId||g.isAppForIosVirtualDevice)return e();let T=g.sessionId,R=q=>y==null?void 0:y.message.includes(q),b=y&&y instanceof fr,v=y&&(R(Gh)||R(sp)),_=D.flags.retryOnSeleniumHubError.isEnabled()&&!!h.reason&&g.isSeleniumHubNoMatchSessionError(h.reason)&&!g.ignoreSeleniumHubError,$=v&&g.hasMoreTimeoutRetries(),A=g.hasMoreRetries()&&!b&&!v,S=!h.success&&(A||$||_);try{let q=g.retryKey;h.testRetryKey=q;let Y=g.getAppSource;if(await this.onTestCompleted(this.id,this.testId,h,T,S,Y),this.executionQueue.hasMoreTests()&&!((U=this.options.lightweightMode)!=null&&U.general)&&await oe(CS),await this.runTestCleanup(),S){if($&&await g.startNewTimeoutRetry(),_){Et.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:g.testId,retryReason:h.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(H=this.options.projectData)==null?void 0:H.projectId,pt=g.testResultId,It=g.testId;await jo(me,pt,It,{show:!1}),g.decreaseSeleniumHubRetry(),g.decreaseRetryCount(),await g.startNewRetry()}return A&&!_&&!$&&await g.startNewRetry(),Et.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:q,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,S)}return await e()}catch(q){if(q instanceof Kt)return;Et.error("failed to process test result",{error:q}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
218
- Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: network connectivity test failed)":""}`,n=h=>{let{DEVICE_OS_VERSION_TOO_LOW:g,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:T,TIMEOUT_ERROR:R,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Rc,v=h instanceof Error?h.message:h;return v.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),v.includes(Wh)||v.includes(R)?{errorType:Ln,reason:"timeout while getting device"}:v.includes(y)||v.includes(b)?{errorType:Ui,reason:"app doesn't exist on device"}:v.includes(T)?{errorType:Ui,reason:"app never started, check app permission or app activity"}:v.includes(g)?{errorType:Ui,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ui,reason:v}},o=(h,g)=>{let y=this.options.mode===Z.APPIUM?"device":"browser";if(!g&&D.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:RS,reason:r()};let T=h instanceof Error?h.message:h;if(T.includes(Wh))return{errorType:Ln,reason:`Test couldn't get ${y}`};if(T.includes(Gh))return{errorType:Ln,reason:"Test couldn't be started"};if(T.includes(sp)){if(!this.testRunTimeout)return{errorType:Ln,reason:"Test timeout reached: test is too long"};let R=op.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(R.asMinutes()),v=R.asSeconds(),I=b>0?` ${b} min`:"",C=v>0?` ${v} sec`:"";return{errorType:Ln,reason:`Test timeout reached (timeout:${I}${C}): test is too long`}}if(h instanceof fr&&h.type){if(h.type===np)return{errorType:np,reason:`Test couldn't get ${y} from grid - ${h.message}`};if(h.type===cr)return{errorType:cr,reason:`Failed to create new session - ${h.message}`}}return"type"in h&&h.type===AS?{errorType:cr,reason:`Session terminated, this is often caused to connection
219
- problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(h.message)||/Couldn't connect to selenium server/.test(h.message)?{errorType:cr,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(h.message)?{errorType:cr,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(h.message)?{errorType:cr,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(h.message)?{errorType:cr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:xS,reason:T}},i=async(h,g)=>{var v;let y=await yc();!y&&D.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),Et.warn("error on run",{err:h});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===Z.APPIUM?n(h):o(h,y);jo(T,this.testResultId,this.testId,{status:js.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:g.retryKey,setupStepResult:{status:js.COMPLETED,success:!1,reason:b,errorType:R}},g.remoteRunId),await t(kS(this.testId,this.testName,this.testResultId,b),g,h)},a=async(h,g)=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return Et.warn("Test failed. Not enough data to recover results via API",{err:h}),i(h,g);try{let I=await Er(y,T,R,b);if(Et.warn("Test failed. Got results via API",{err:h,testResult:Vh.default.omit(I,_S),resultId:T}),I&&I.status===js.COMPLETED&&!h.message.includes(sp))return await t(I,g);throw h}catch(I){return I!==h&&Et.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:I}),i(h,g)}},l=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(h,g)=>{try{await Promise.all([!c&&hs.joinToRemoteStep(this.testResultId),!l&&Ot.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Z.APPIUM&&h.validateRunConfig();let y=await this.runTest(h,this.customExtensionLocalLocation,g),T=await t(y,h);return M("After onRunComplete"),T}catch(y){return a(y,h)}finally{c||hs.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,d(m)):this.onQueueCompleted()}}});var ip,qh,ys,ap=w(()=>{"use strict";B();ip=E(require("p-retry"));B();j();K();qh=x("window-utils"),ys=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 qh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&qh.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"&&window.location!==void 0)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 Rt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,ip.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,ip.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var cp,bs,lp=w(()=>{"use strict";j();cp=x("cookies-utils"),bs=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 cp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw cp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw cp.error("failed to remove cookie",{err:t}),t}}}});var up,ji,zh=w(()=>{"use strict";up=E(require("p-retry")),ji=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,up.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,up.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.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 Kh(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 OS.warn("missing elementRect",Yh.omit(s,"image")),{};let{elementRect:i}=s,a=await Ts.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new pp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ts.default.MIME_PNG)}}async function LS(s,e){let t=await Ts.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Ts.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ts.default.MIME_PNG)}function DS(s,e){return LS(s,e)}async function NS(){}async function MS(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await NS(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 Jh(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 Yh,Ts,OS,pp,$i,Xh=w(()=>{"use strict";Yh=E(require("lodash"));B();Ts=E(require("jimp"));j();OS=x("image-capture-utils"),pp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};$i=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 Kh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Jh(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 MS({screenImage:t.image,absoluteScreenHighlight:Jh(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(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Kh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,R=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return R.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),DS(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Qh,Zh,Wi,Gi,ey=w(()=>{"use strict";Qh=E(require("p-retry")),Zh=E(require("semver"));B();j();ap();zh();Xh();we();Wi=x("tab-service"),Gi=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),Wi.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=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.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:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ys(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new $i(t,a,new ji(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}=te(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=te();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,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(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||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){Wi.error("failed to get url or title",{err:o})}}catch(n){Wi.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]){Wi.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,Qh.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=Zh.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 l,c;let{tabMatcher:r,commonConstants:n}=te();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;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=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var dp,Vi,mp=w(()=>{"use strict";dp=class{select(){return console.log(`
216
+ `,u=[],f=new yh.Worker(m,{eval:!0});try{return await ce(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ct.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ct.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:i}):ct.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{ct.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(h){if(!(h instanceof ne))throw h;return ct.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function aS(s){try{await fh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ct.warn("failed to remove install npm packages folder",{err:e})}}function bh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ds(s,e,t,r,n,o){let i=bh(n,e,s,t),{data:a}=await cS(i,r,o);return a}async function ms(s,e,t,r,n,o,i,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||L.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=bm(y.testimPackageLocalLocation);return[y.paramName,ps.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=bh(i,n,e,o);if(c){let y=await on(c);y&&(l=y)}Buffer.isBuffer(l)&&(ct.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ct.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await iS(u,t,r,s,m,a,l),nodeVersion:process.version}}async function cS(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Th(),i=L.flags.reuseCliPkgInstallFolder.isEnabled()?n:ps.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Tm(i,r,a,t),ct.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 u=hm(i,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ps.resolve(i,"node_modules",m.packageName)}}),installFolder:i}}catch(d){throw ct.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ce(l(),t)}catch(c){throw c instanceof ne&&ct.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Th(){return ps.join(gh.tmpdir(),"/testim_local_packages")}function lS(){let s=Th();return aS(s)}var fh,gh,ps,hh,yh,ct,fs=w(()=>{"use strict";fh=E(require("fs")),gh=E(require("os")),ps=E(require("path"));B();Yr();hh=E(require("data-uri-to-buffer")),yh=require("worker_threads");K();j();he();Yr();pe();ct=x("cli-service");lS().catch(s=>ct.warn("failed to clean local package folder",{err:s}))});var ar={};V(ar,{run:()=>pS});function uS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=L.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var pS,wh=w(()=>{"use strict";fs();K();pe();pS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await ms(r,n,o,i,a,l,c,d,m,u);return f&&uS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ne?new Error("Timeout while running action"):f}}});var qu={};V(qu,{run:()=>dS});var dS,vh=w(()=>{"use strict";fs();K();dS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ds(t,r,n,i,o,a),success:!0}}catch(l){if(l instanceof At)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ne)return{success:!1,code:"timeout"};throw l}}});async function Sh(s,e,t,r){try{return await wl(s,e,t,r)}catch{ki.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function fS(s,e,t,r,n){return ki.info("finished to run remote step",{stepId:t,sessionId:n}),await Sh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Eh(s,e,t,r,n){return ki.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Sh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Ih(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(),l=t.id;ki.info("start play remote step",{stepType:i,stepId:l,sessionId:a});let c=mS[i];if(!c)return await Eh(n,r,l,`Failed to find step type ${i}`,a);try{let d=await c.run(e,t,o);return await fS(n,r,l,d,a)}catch(d){return await Eh(n,r,l,d.message,a)}}var ki,mS,Rh=w(()=>{"use strict";wh();he();vh();j();ki=x("step-playback"),mS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":qu}});var zu,Ah,Cr,hS,Ku,vt,_i=w(()=>{"use strict";B();nt();zu=E(require("ws")),Ah=require("events");j();ue();Cr=x("socket-service"),hS=5e3,Ku=class extends Ah.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),hS)}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){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(od);return Zt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new zu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===zu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.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(l){n(l)&&o(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=i.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}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=se(),l={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",c=>c.id===a,i),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}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})}},vt=new Ku});var Ch,Ju,yS,bS,TS,xh,Oi,gs,Yu=w(()=>{"use strict";Ch=E(require("p-retry")),Ju=E(require("socket.io-client"));ue();B();j();yS=50,bS=10,TS=5e3,xh=10*1e3,Oi=x("base socket service"),gs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Oi.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{}Oi.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===bS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=yS)throw new Error(`Can't connect to Testim Servers.
217
+ Action required: Please allow opening a websockets connection to ${fe} 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",()=>{Oi.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:xh,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=`${fe}/${t}`,this._socket=Ju.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:xh,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=`${fe}/${t}`,this._socket=Ju.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,Ch.default)(()=>ce(n(),TS),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Oi.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Ph={};V(Ph,{remoteStepServiceSocketIO:()=>wS});var Xu,wS,kh=w(()=>{"use strict";Yu();Xu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}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.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},wS=new Xu});var _h={};V(_h,{remoteStepService:()=>hs});var Qu,_n,Zu,hs,Li=w(()=>{"use strict";_i();ae();pe();({REMOTE_STEP_SAVED:Qu}=Ct),Zu=class{async init(e){L.flags.useNewWSCLI.isEnabled()||(_n=(await Promise.resolve().then(()=>(kh(),Ph))).remoteStepServiceSocketIO,_n.init(e))}joinToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Qu]):_n.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(L.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Qu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}_n.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Qu]),Promise.resolve()):_n.unlistenToRemoteStep(e)}},hs=new Zu});var ep,Pr,Oh=w(()=>{"use strict";Yu();ep=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[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.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new ep});var Dh={};V(Dh,{testResultService:()=>Ot});var Lh,tp,Ot,Di=w(()=>{"use strict";Lh=require("events");_i();ae();pe();Oh();tp=class extends Lh.EventEmitter{init(e){if(L.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return L.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(L.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(L.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!L.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},Ot=new tp});var Mh,Uh,Fh,Ee,vS,Bh,Nh,Ni,jh=w(()=>{"use strict";Mh=E(require("lodash"));B();ue();$e();ts();nt();he();Rh();Uh=E(require("p-retry")),Fh=require("url");j();Qo();cs();ae();Li();Di();Ee=x("test-run-handler"),vS=3,Bh=20*1e3,Nh=s=>JSON.stringify(s).length<Bh,Ni=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 Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;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._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?qs(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}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}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[e])==null?void 0:a[t]:null}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 isAppFromDevice(){return Vs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?po.FROM_DEVICE:po.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/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 overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Zt(),refreshToken:Lo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:dd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,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},userAccessKey:await Do()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Nh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),Ee.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Bh} 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 fn(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 Ee.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&&Nh(e))return;let r=async()=>{try{return await vl(this._options.project,this._testId,this._testResultId,e)}catch(i){return Ee.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Tl(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){M("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{M("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};M("before Runtime.evaluate"),await(0,Uh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),M("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return M("after Runtime.evaluate"),c.value}catch(i){throw Ee.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 Fh.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)){Ee.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)&&(Ee.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:l,branch:c,_options:{project:d}}=this;try{let m=await Er(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){Ee.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Ot.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Er(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return Ee.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Ee.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw Ee.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Ot.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Ot.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Ee.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=Mh.debounce(async()=>{try{let i=await Er(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Ee.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"?(Ee.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 Ee.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Ot.on("socket-connected",async()=>{try{await Ot.joinToTestResult(this._testResultId,this.testId)}catch(i){Ee.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 ll(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Ee.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Ot.off("socket-connected",e)}}listenToRemoteStep(e){hs.listenToRemoteStep(this.testResultId,t=>{Ih(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:vS;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=se(),!((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 Mi,$h=w(()=>{"use strict";jh();Mi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Ni(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var ES,SS,IS,On,rp=w(()=>{"use strict";ns();is();j();ES=x("worker-utils"),SS=async(s,e,t)=>{e&&await uu(s,t)},IS=async(s,e,t)=>{await pu(s,e,t)},On=async(s,e,t,r,n,o)=>{ES.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await SS(s,e,t),n==="redis"&&await IS(s,r,t)}}});function kS(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Bi,Vh,Fi,op,Hh,Et,Wh,Gh,sp,Ln,RS,np,AS,cr,xS,Ui,CS,PS,_S,lt,Dn=w(()=>{"use strict";Bi=E(require("ms")),Vh=E(require("lodash")),Fi=E(require("p-retry")),op=E(require("dayjs")),Hh=E(require("dayjs/plugin/duration"));B();$e();ns();is();he();j();rp();_t();ni();pe();Li();Di();Ve();ae();K();op.default.extend(Hh.default);Et=x("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Wh,TEST_START_TIMEOUT_MSG:Gh,TEST_COMPLETE_TIMEOUT_MSG:sp}=Ue,{SETUP_TIMEOUT:Ln,NETWORK_ERROR:RS,GRID_ERROR:np,BROWSER_CLOSED:AS,SELENIUM_ERROR:cr,UNKNOWN_ERROR:xS,MOBILE_SESSION_ERROR:Ui}=$s,CS=(0,Bi.default)("1s"),PS=1;_S=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],lt=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.id=lt.getWorkerId();this.lambdatestService=new re;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}static getWorkerId(){return PS++}async getGridSlot(e,t){let r=await og(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ds(!0)}async getBrowserOnce(e,t,r,n){throw new Ds(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),Et.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Gr(L,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;return this.options.mode===Z.APPIUM?((e=this.options.gridData)==null?void 0:e.type)===O.BROWSERSTACK?Math.max((0,Bi.default)("600s"),this.options.getSessionTimeout):Math.max((0,Bi.default)("180s"),this.options.getSessionTimeout):Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,Fi.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,Fi.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(lg(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Jt?Et.info("could not get grid slot due to concurrency issue",r):Et.error("error getting grid slot",{error:e,...r}),await oe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{M("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);M("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,Fi.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await ig(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();M("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return M("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===Z.APPIUM?"device":"browser";throw Et.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Rt)&&this.options.mode!==Z.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),M("after getBrowserOnce retries")}catch(i){throw await On(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Rt,Br].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,np):new fr(i,cr)}return n}async runTest(e,t,r){var d;M("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Hs(this.options)&&this.handleMobileTest(e);if(i)return i;M("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return await this.runTestOnce(e,c)}finally{await On(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(h,g,y)=>{var D,U,H;if(Xe(h,this.options)||Gr(L,(D=this.options.gridData)==null?void 0:D.type)&&g.isAppFromDevice&&!this.options.appId||g.isAppForIosVirtualDevice)return e();let T=g.sessionId,R=q=>y==null?void 0:y.message.includes(q),b=y&&y instanceof fr,v=y&&(R(Gh)||R(sp)),_=L.flags.retryOnSeleniumHubError.isEnabled()&&!!h.reason&&g.isSeleniumHubNoMatchSessionError(h.reason)&&!g.ignoreSeleniumHubError,$=v&&g.hasMoreTimeoutRetries(),A=g.hasMoreRetries()&&!b&&!v,S=!h.success&&(A||$||_);try{let q=g.retryKey;h.testRetryKey=q;let Y=g.getAppSource;if(await this.onTestCompleted(this.id,this.testId,h,T,S,Y),this.executionQueue.hasMoreTests()&&!((U=this.options.lightweightMode)!=null&&U.general)&&await oe(CS),await this.runTestCleanup(),S){if($&&await g.startNewTimeoutRetry(),_){Et.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:g.testId,retryReason:h.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(H=this.options.projectData)==null?void 0:H.projectId,pt=g.testResultId,It=g.testId;await jo(me,pt,It,{show:!1}),g.decreaseSeleniumHubRetry(),g.decreaseRetryCount(),await g.startNewRetry()}return A&&!_&&!$&&await g.startNewRetry(),Et.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:q,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,S)}return await e()}catch(q){if(q instanceof Kt)return;Et.error("failed to process test result",{error:q}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
218
+ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: network connectivity test failed)":""}`,n=h=>{let{DEVICE_OS_VERSION_TOO_LOW:g,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:T,TIMEOUT_ERROR:R,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Rc,v=h instanceof Error?h.message:h;return v.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),v.includes(Wh)||v.includes(R)?{errorType:Ln,reason:"timeout while getting device"}:v.includes(y)||v.includes(b)?{errorType:Ui,reason:"app doesn't exist on device"}:v.includes(T)?{errorType:Ui,reason:"app never started, check app permission or app activity"}:v.includes(g)?{errorType:Ui,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ui,reason:v}},o=(h,g)=>{let y=this.options.mode===Z.APPIUM?"device":"browser";if(!g&&L.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:RS,reason:r()};let T=h instanceof Error?h.message:h;if(T.includes(Wh))return{errorType:Ln,reason:`Test couldn't get ${y}`};if(T.includes(Gh))return{errorType:Ln,reason:"Test couldn't be started"};if(T.includes(sp)){if(!this.testRunTimeout)return{errorType:Ln,reason:"Test timeout reached: test is too long"};let R=op.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(R.asMinutes()),v=R.asSeconds(),I=b>0?` ${b} min`:"",C=v>0?` ${v} sec`:"";return{errorType:Ln,reason:`Test timeout reached (timeout:${I}${C}): test is too long`}}if(h instanceof fr&&h.type){if(h.type===np)return{errorType:np,reason:`Test couldn't get ${y} from grid - ${h.message}`};if(h.type===cr)return{errorType:cr,reason:`Failed to create new session - ${h.message}`}}return"type"in h&&h.type===AS?{errorType:cr,reason:`Session terminated, this is often caused to connection
219
+ problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(h.message)||/Couldn't connect to selenium server/.test(h.message)?{errorType:cr,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(h.message)?{errorType:cr,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(h.message)?{errorType:cr,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(h.message)?{errorType:cr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:xS,reason:T}},i=async(h,g)=>{var v;let y=await yc();!y&&L.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),Et.warn("error on run",{err:h});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===Z.APPIUM?n(h):o(h,y);jo(T,this.testResultId,this.testId,{status:js.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:g.retryKey,setupStepResult:{status:js.COMPLETED,success:!1,reason:b,errorType:R}},g.remoteRunId),await t(kS(this.testId,this.testName,this.testResultId,b),g,h)},a=async(h,g)=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return Et.warn("Test failed. Not enough data to recover results via API",{err:h}),i(h,g);try{let I=await Er(y,T,R,b);if(Et.warn("Test failed. Got results via API",{err:h,testResult:Vh.default.omit(I,_S),resultId:T}),I&&I.status===js.COMPLETED&&!h.message.includes(sp))return await t(I,g);throw h}catch(I){return I!==h&&Et.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:I}),i(h,g)}},l=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(h,g)=>{try{await Promise.all([!c&&hs.joinToRemoteStep(this.testResultId),!l&&Ot.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==Z.APPIUM&&h.validateRunConfig();let y=await this.runTest(h,this.customExtensionLocalLocation,g),T=await t(y,h);return M("After onRunComplete"),T}catch(y){return a(y,h)}finally{c||hs.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,d(m)):this.onQueueCompleted()}}});var ip,qh,ys,ap=w(()=>{"use strict";B();ip=E(require("p-retry"));B();j();K();qh=x("window-utils"),ys=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 qh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&qh.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"&&window.location!==void 0)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 Rt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,ip.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,ip.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var cp,bs,lp=w(()=>{"use strict";j();cp=x("cookies-utils"),bs=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 cp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw cp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw cp.error("failed to remove cookie",{err:t}),t}}}});var up,ji,zh=w(()=>{"use strict";up=E(require("p-retry")),ji=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,up.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,up.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.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 Kh(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 OS.warn("missing elementRect",Yh.omit(s,"image")),{};let{elementRect:i}=s,a=await Ts.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new pp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ts.default.MIME_PNG)}}async function LS(s,e){let t=await Ts.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Ts.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ts.default.MIME_PNG)}function DS(s,e){return LS(s,e)}async function NS(){}async function MS(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await NS(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 Jh(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 Yh,Ts,OS,pp,$i,Xh=w(()=>{"use strict";Yh=E(require("lodash"));B();Ts=E(require("jimp"));j();OS=x("image-capture-utils"),pp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};$i=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 Kh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Jh(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 MS({screenImage:t.image,absoluteScreenHighlight:Jh(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(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Kh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,R=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return R.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),DS(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var Qh,Zh,Wi,Gi,ey=w(()=>{"use strict";Qh=E(require("p-retry")),Zh=E(require("semver"));B();j();ap();zh();Xh();we();Wi=x("tab-service"),Gi=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),Wi.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=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.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:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ys(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new $i(t,a,new ji(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}=te(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=te();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,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(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||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){Wi.error("failed to get url or title",{err:o})}}catch(n){Wi.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]){Wi.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,Qh.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=Zh.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 l,c;let{tabMatcher:r,commonConstants:n}=te();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;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=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var dp,Vi,mp=w(()=>{"use strict";dp=class{select(){return console.log(`
220
220
  internal error - cant use port selector in selenium!!!!
221
- `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Vi=new dp});var Nn,Hi,qi=w(()=>{"use strict";lp();we();Nn={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"},Hi=class{constructor(e){this.driver=e;this._abortedSteps=[];this.cookieUtils=new bs(this.driver)}get sessionPlayerInit(){return te()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}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=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function ry(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=ty(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:l}=te();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw US.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=ty(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,o,i,a,l){let c=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,o,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=i.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+h.top,left:o.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,o,i){let a=D.flags.enableFrameSwitchOptimization.isEnabled(),c=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),R=0;for(let b of T)R++,this.currentFrameHandler=await this.locate(b,R,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let u=await i.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,o,i,r);return g}}return e}var US,FS,ty,sy=w(()=>{"use strict";j();pe();we();Nr();US=x("frame-locator"),FS="ELEMENT",ty=s=>s?s[FS]||s[zt]:null});var zi,fp=w(()=>{"use strict";ue();zi=()=>{try{if(nd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,le=w(()=>{"use strict";we();G=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 te()}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 jS(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:D.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?D.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function $S(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 ny.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:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=te();if(jS(n,d,m,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||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(I){throw kr.error("failed to execute getVisibilityCode",{err:I}),I}let{value:T}=y||{},R=T.elementVisibilityInfo||BS,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(R,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=te();await s.execute(r(t))}}}var ny,kr,BS,Mn,oy=w(()=>{"use strict";le();j();pe();we();ny=require("linkedom"),kr=x("locate-step-action"),BS={opacity:1,clientRects:{}};Mn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return $S(e)}static getFrameIdByTestimFrameId(){throw kr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw kr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw kr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw kr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw kr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw kr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var iy={};V(iy,{scroll:()=>WS});var WS,ay=w(()=>{"use strict";WS=function(s,e,t,r,n,o,i,a){function l(R,b){if(!b)return{success:!1};elementScrollTo(b,R.x,R.y);let v=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-R.y)<1&&Math.abs(v-R.x)<1,actualX:v,actualY:I}}function c(R,b){if(!t)return{x:n,y:o};let v=getLocatedElement(b);if(r&&!v)return{x:R.scrollWidth,y:R.scrollHeight};if(!v)throw new Error("could not find target element");let I=v.getBoundingClientRect(),C=0,_=0,$=Math.max(window.innerHeight-(I.height+10),0),A=Math.max(window.innerWidth-(I.width+10),0);return C=a?R.scrollTop+I.top-Math.min(o,$):R.scrollTop,_=i?R.scrollLeft+I.left-Math.min(n,A):R.scrollLeft,{x:Math.round(_),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let R=T.getBoundingClientRect();g=R.left,y=R.top}return{success:h.success,actualX:g,actualY:y}}});var Ki,cy=w(()=>{"use strict";le();Ki=class extends G{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)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(ay(),iy)),d=`
221
+ `),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},Vi=new dp});var Nn,Hi,qi=w(()=>{"use strict";lp();we();Nn={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"},Hi=class{constructor(e){this.driver=e;this._abortedSteps=[];this.cookieUtils=new bs(this.driver)}get sessionPlayerInit(){return te()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}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=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function ry(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=ty(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:l}=te();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw US.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=ty(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,o,i,a,l){let c=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,o,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=i.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+h.top,left:o.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,o,i){let a=L.flags.enableFrameSwitchOptimization.isEnabled(),c=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),R=0;for(let b of T)R++,this.currentFrameHandler=await this.locate(b,R,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let u=await i.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,o,i,r);return g}}return e}var US,FS,ty,sy=w(()=>{"use strict";j();pe();we();Nr();US=x("frame-locator"),FS="ELEMENT",ty=s=>s?s[FS]||s[zt]:null});var zi,fp=w(()=>{"use strict";ue();zi=()=>{try{if(nd)return!1;if(require("inspector").url())return!0}catch{}return!1}});var G,le=w(()=>{"use strict";we();G=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 te()}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 jS(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:L.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?L.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function $S(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 ny.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:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=te();if(jS(n,d,m,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||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(I){throw kr.error("failed to execute getVisibilityCode",{err:I}),I}let{value:T}=y||{},R=T.elementVisibilityInfo||BS,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(R,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=te();await s.execute(r(t))}}}var ny,kr,BS,Mn,oy=w(()=>{"use strict";le();j();pe();we();ny=require("linkedom"),kr=x("locate-step-action"),BS={opacity:1,clientRects:{}};Mn=class extends G{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return $S(e)}static getFrameIdByTestimFrameId(){throw kr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw kr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw kr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw kr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw kr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw kr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var iy={};V(iy,{scroll:()=>WS});var WS,ay=w(()=>{"use strict";WS=function(s,e,t,r,n,o,i,a){function l(R,b){if(!b)return{success:!1};elementScrollTo(b,R.x,R.y);let v=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-R.y)<1&&Math.abs(v-R.x)<1,actualX:v,actualY:I}}function c(R,b){if(!t)return{x:n,y:o};let v=getLocatedElement(b);if(r&&!v)return{x:R.scrollWidth,y:R.scrollHeight};if(!v)throw new Error("could not find target element");let I=v.getBoundingClientRect(),C=0,_=0,$=Math.max(window.innerHeight-(I.height+10),0),A=Math.max(window.innerWidth-(I.width+10),0);return C=a?R.scrollTop+I.top-Math.min(o,$):R.scrollTop,_=i?R.scrollLeft+I.left-Math.min(n,A):R.scrollLeft,{x:Math.round(_),y:Math.round(C)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let R=T.getBoundingClientRect();g=R.left,y=R.top}return{success:h.success,actualX:g,actualY:y}}});var Ki,cy=w(()=>{"use strict";le();Ki=class extends G{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)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(ay(),iy)),d=`
222
222
  const getLocatedElement = ${n.getLocatedElementCode};
223
223
  const elementScrollTo = ${l.toString()};
224
224
  const scroll = ${c.toString()};
225
225
  return scroll.apply(null, arguments)
226
- `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,h)}}}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 ly,uy=w(()=>{"use strict";ly=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,l){e[t(a)]=l},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,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var py,dy=w(()=>{"use strict";py=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(S){e({status:"done",result:S,success:!0})}function a(S){S||={},e({status:"failed",result:S,success:!1,keep:!0})}function l(S){return S!=null&&S.toLowerCase?(S=S.toLowerCase(),S==="text"?"text/plain":S==="url"?"text/uri-list":S):S}function c(){try{return new DataTransfer}catch{return{data:{},setData(L,U){o[l(L)]=U},getData(L){return o[l(L)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(S){let L=S;for(;L&&L!==document.documentElement;){if(L.draggable)return L;L=L.parentElement}return null}function h(S,L,U){let H=L.element,{dispatchDragEventsOnClosestDraggable:q}=U;if(d.includes(S.type)&&q){if(!H&&L.lastDraggedElement)return L.lastDraggedElement;let Y=f(H);if(Y)return L.lastDraggedElement=Y,Y}return H}function g(S,L,U){function H(It,dr,k){return k>It&&k<dr}let q=S.pointerPosition||{};if(L)return{x:q.originX||0,y:q.originY||0};let Y=U.getBoundingClientRect(),me=q.originX&&H(Y.left,Y.left+Y.width,q.originX)?q.originX:Y.left+Y.width/2,pt=q.originY&&H(Y.top,Y.top+Y.height,q.originY)?q.originY:Y.top+Y.height/2;return{x:me,y:pt}}function y(S,L,U){let H=(L==null?void 0:L.modifiers)||{},q=g(S,U.isDrag,U.element),Y=(L==null?void 0:L.button)||0,me=S.event;return m.includes(me)?R(me,H,q.x,q.y,Y):u.includes(me)?v(me,H,q.x,q.y):b(me,H,q.x,q.y,Y)}function T(S,L,U){return{screenX:0,screenY:0,clientX:L,clientY:U,ctrlKey:Boolean(S.ctrl),altKey:Boolean(S.alt),shiftKey:Boolean(S.shift),metaKey:Boolean(S.meta),bubbles:!0,cancelable:!0,composed:!0}}function R(S,L,U,H,q){if(n){let me=T(L,U,H);return me.pointerType="mouse",me.isPrimary=!0,new window.PointerEvent(S,me)}let Y=document.createEvent("PointerEvent");return Y.initPointerEvent(S,!0,!0,document.defaultView,1,0,0,U,H,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),q,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Y}function b(S,L,U,H,q){let Y=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Y.initMouseEvent(S,!0,!0,document.defaultView,1,0,0,U,H,Boolean(L.ctrl),Boolean(L.alt),Boolean(L.shift),Boolean(L.meta),q,document.body?document.body.parentNode:document.documentElement),Y}function v(S,L,U,H){if(S==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let me=document.createEvent("CustomEvent");return me.initCustomEvent(S,!0,!0,null),Object.assign(me,{dataTransfer:window.TSTA.dataTransfer}),me}let q=T(L,U,H),Y=new window.DragEvent(S,q);return Object.defineProperties(Y,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Y}function I(S,L,U){let H=h(S,L,U);H==null||H.dispatchEvent(S)}function C(S,L){function U(){return S.event==="click"&&L.isDrag&&!L.allEventsOnSameElement}return U()}function _(S,L,U){if(U){let H=Math.min(U.timeStamp-L.timeStamp,40);setTimeout(()=>{$(S)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function $(S){let L,U=S.events[S.eventIndex],H=S.events[++S.eventIndex];try{S.element=getLocatedElement(U.locatedElement),L=y(U,s,S)}catch(q){return a(`exception in get event in drag step:${q.message}`)}if(C(U,S))return _(S,U,H);if(L)try{I(L,S,U)}catch(q){return a(`exception in executeEvent in drag step:${q.message}`)}else return a(`cannot execute event ${U.event}`);_(S,U,H)}let A={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{$(A)}catch(S){a(S)}},0)}});var my={};V(my,{doClick:()=>GS});var GS,fy=w(()=>{"use strict";GS=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var _;function I($){function A(){return o($).find(U=>[...U.classList||[]].includes("Select-control"))}function S(){let U=A();return U?U.querySelector("input"):null}let L=S();L==null||L.focus()}let C=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&C&&I(b.element)}function n(b,v){var C;let I=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&I&&document.body.focus()}function o(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function i(b){let v={status:"done",result:b,success:!0,...R.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},I=b.getBoundingClientRect(),C=I.left+I.width/2,_=I.top+I.height/2,S=f("mousemove",v,C,_,0);b.dispatchEvent(S)}function d(b,v){function I(S,L,U){return U>S&&U<L}let C=b.pointerPosition||{},_=v.getBoundingClientRect(),$=C.originX&&I(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,A=C.originY&&I(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:$,y:A}}function m(b,v,I){return{screenX:0,screenY:0,clientX:v,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 u(b,v,I,C){if(!window.PointerEvent)return;let _=m(v,I,C);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,v,I,C,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),$}function h(b,v){let I=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=d(b,v.element),$=v.button||0,A=b.event;return I.includes(A)?u(A,C,_.x,_.y):f(A,C,_.x,_.y,$)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let R={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!R.element){a("element not found");return}l(R.element),c(R.element);try{y(R);let b=g(),v=R.quirks,I=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!I&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var gy={};V(gy,{doDragPath:()=>VS});var VS,hy=w(()=>{"use strict";VS=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 v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},I=b.getBoundingClientRect(),C=I.left+I.width/2,_=I.top+I.height/2,S=u("mousemove",v,C,_,0);b.dispatchEvent(S)}function c(b,v){function I(S,L,U){return U>S&&U<L}let C=b.pointerPosition||{};if(R.isDrag)return{x:C.originX||0,y:C.originY||0};let _=v.getBoundingClientRect(),$=C.originX&&I(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,A=C.originY&&I(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:$,y:A}}function d(b,v,I){return{screenX:0,screenY:0,clientX:v,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 m(b,v,I,C,_){if(r){let A=d(v,I,C);return A.pointerType="mouse",A.isPrimary=!0,new window.PointerEvent(b,A)}let $=document.createEvent("PointerEvent");return $.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),$}function u(b,v,I,C,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),$}function f(b,v){let I=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=c(b,v.element),$=v.button||0,A=b.event;return I.includes(A)?m(A,C,_.x,_.y,$):u(A,C,_.x,_.y,$)}function h(b,v){function I(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return I()}function g(b,v,I){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)I();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,I)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let R={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(!R.element){i("element not found");return}a(R.element),l(R.element),y(R,()=>{o()})}});var Un,Ji,yy=w(()=>{"use strict";Un=E(require("lodash"));le();uy();pe();dy();Ji=class extends G{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 d;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:l}]=await Promise.all([Promise.resolve().then(()=>(fy(),my)),Promise.resolve().then(()=>(Cn(),xn))]),c=`
226
+ `;try{let m=await this.driver.executeJS(d,r,e??void 0,Boolean(t.isScrollToElement),Boolean(t.isDynamicScroll),a,i,t.shouldScrollLeft,t.shouldScrollTop);if(!(m!=null&&m.value))return{errorType:o.SCROLL_ACTION_FAILURE,success:!1};let{success:u,actualX:f,actualY:h}=m.value;return u?{success:!0}:{errorType:o.SCROLL_ACTION_FAILURE,success:!1,resultInfo:{error:this.getFailureString(t,a,i,f,h)}}}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 ly,uy=w(()=>{"use strict";ly=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,l){e[t(a)]=l},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,l){let c=document.createEvent("CustomEvent");c.initCustomEvent(l,!0,!0,null),Object.assign(c,{dataTransfer:r}),a.dispatchEvent?a.dispatchEvent(c):a.fireEvent&&a.fireEvent(`on${l}`,c)};i(n,"dragstart"),i(o,"drop"),i(n,"dragend")}});var py,dy=w(()=>{"use strict";py=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(S){e({status:"done",result:S,success:!0})}function a(S){S||={},e({status:"failed",result:S,success:!1,keep:!0})}function l(S){return S!=null&&S.toLowerCase?(S=S.toLowerCase(),S==="text"?"text/plain":S==="url"?"text/uri-list":S):S}function c(){try{return new DataTransfer}catch{return{data:{},setData(D,U){o[l(D)]=U},getData(D){return o[l(D)]}}}}let d=["drag","dragstart","dragend"],m=["pointerup","pointerdown","pointermove"],u=d.concat(["drop","dragenter","dragover"]);function f(S){let D=S;for(;D&&D!==document.documentElement;){if(D.draggable)return D;D=D.parentElement}return null}function h(S,D,U){let H=D.element,{dispatchDragEventsOnClosestDraggable:q}=U;if(d.includes(S.type)&&q){if(!H&&D.lastDraggedElement)return D.lastDraggedElement;let Y=f(H);if(Y)return D.lastDraggedElement=Y,Y}return H}function g(S,D,U){function H(It,dr,k){return k>It&&k<dr}let q=S.pointerPosition||{};if(D)return{x:q.originX||0,y:q.originY||0};let Y=U.getBoundingClientRect(),me=q.originX&&H(Y.left,Y.left+Y.width,q.originX)?q.originX:Y.left+Y.width/2,pt=q.originY&&H(Y.top,Y.top+Y.height,q.originY)?q.originY:Y.top+Y.height/2;return{x:me,y:pt}}function y(S,D,U){let H=(D==null?void 0:D.modifiers)||{},q=g(S,U.isDrag,U.element),Y=(D==null?void 0:D.button)||0,me=S.event;return m.includes(me)?R(me,H,q.x,q.y,Y):u.includes(me)?v(me,H,q.x,q.y):b(me,H,q.x,q.y,Y)}function T(S,D,U){return{screenX:0,screenY:0,clientX:D,clientY:U,ctrlKey:Boolean(S.ctrl),altKey:Boolean(S.alt),shiftKey:Boolean(S.shift),metaKey:Boolean(S.meta),bubbles:!0,cancelable:!0,composed:!0}}function R(S,D,U,H,q){if(n){let me=T(D,U,H);return me.pointerType="mouse",me.isPrimary=!0,new window.PointerEvent(S,me)}let Y=document.createEvent("PointerEvent");return Y.initPointerEvent(S,!0,!0,document.defaultView,1,0,0,U,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),q,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),Y}function b(S,D,U,H,q){let Y=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return Y.initMouseEvent(S,!0,!0,document.defaultView,1,0,0,U,H,Boolean(D.ctrl),Boolean(D.alt),Boolean(D.shift),Boolean(D.meta),q,document.body?document.body.parentNode:document.documentElement),Y}function v(S,D,U,H){if(S==="dragstart"&&(window.TSTA||={},window.TSTA.dataTransfer=c()),!r){let me=document.createEvent("CustomEvent");return me.initCustomEvent(S,!0,!0,null),Object.assign(me,{dataTransfer:window.TSTA.dataTransfer}),me}let q=T(D,U,H),Y=new window.DragEvent(S,q);return Object.defineProperties(Y,{dataTransfer:{get(){return window.TSTA.dataTransfer}}}),Y}function I(S,D,U){let H=h(S,D,U);H==null||H.dispatchEvent(S)}function C(S,D){function U(){return S.event==="click"&&D.isDrag&&!D.allEventsOnSameElement}return U()}function _(S,D,U){if(U){let H=Math.min(U.timeStamp-D.timeStamp,40);setTimeout(()=>{$(S)},H)}else window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),i()}function $(S){let D,U=S.events[S.eventIndex],H=S.events[++S.eventIndex];try{S.element=getLocatedElement(U.locatedElement),D=y(U,s,S)}catch(q){return a(`exception in get event in drag step:${q.message}`)}if(C(U,S))return _(S,U,H);if(D)try{I(D,S,U)}catch(q){return a(`exception in executeEvent in drag step:${q.message}`)}else return a(`cannot execute event ${U.event}`);_(S,U,H)}let A={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{$(A)}catch(S){a(S)}},0)}});var my={};V(my,{doClick:()=>GS});var GS,fy=w(()=>{"use strict";GS=(s,e)=>{let t=typeof Event=="function";window.__unloadNavigator=i,window.addEventListener("unload",window.__unloadNavigator);function r(b,v){var _;function I($){function A(){return o($).find(U=>[...U.classList||[]].includes("Select-control"))}function S(){let U=A();return U?U.querySelector("input"):null}let D=S();D==null||D.focus()}let C=(_=b.quirks)==null?void 0:_.isReactSelect;v.type==="mousedown"&&C&&I(b.element)}function n(b,v){var C;let I=(C=b.quirks)==null?void 0:C.isCKEditorFrame;v.type==="click"&&I&&document.body.focus()}function o(b){let v=[];for(;b!=null&&b.parentNode;)v.push(b),b=b.parentNode;return v}function i(b){let v={status:"done",result:b,success:!0,...R.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(v)}function a(b){b||="",e({status:"failed",result:b,success:!1})}function l(b){let v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function c(b){let v={},I=b.getBoundingClientRect(),C=I.left+I.width/2,_=I.top+I.height/2,S=f("mousemove",v,C,_,0);b.dispatchEvent(S)}function d(b,v){function I(S,D,U){return U>S&&U<D}let C=b.pointerPosition||{},_=v.getBoundingClientRect(),$=C.originX&&I(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,A=C.originY&&I(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:$,y:A}}function m(b,v,I){return{screenX:0,screenY:0,clientX:v,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 u(b,v,I,C){if(!window.PointerEvent)return;let _=m(v,I,C);return _.pointerType="mouse",_.isPrimary=!0,new window.PointerEvent(b,_)}function f(b,v,I,C,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),$}function h(b,v){let I=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=d(b,v.element),$=v.button||0,A=b.event;return I.includes(A)?u(A,C,_.x,_.y):f(A,C,_.x,_.y,$)}function g(){var v;let b=document.activeElement;for(;(v=b.shadowRoot)!=null&&v.activeElement;)b=b.shadowRoot.activeElement;return b}function y(b){b.events.map(v=>{try{return h(v,b)}catch{return}}).filter(Boolean).forEach(v=>{b.element.dispatchEvent(v),r(b,v),n(b,v)}),window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator)}let R={element:s.isRoot?document.documentElement:getLocatedElement(s.locatedElement),events:s.events,quirks:s.quirks,modifiers:s.modifiers,button:s.button};if(!R.element){a("element not found");return}l(R.element),c(R.element);try{y(R);let b=g(),v=R.quirks,I=v==null?void 0:v.isReactSelect,C=v==null?void 0:v.isCKEditorFrame;!I&&!C&&dispatchFocus(s.elementToFocusLocatedElement,b),i()}catch(b){a(b.toString())}}});var gy={};V(gy,{doDragPath:()=>VS});var VS,hy=w(()=>{"use strict";VS=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 v=t?new Event("mouseover",{composed:!0}):document.createEvent("Events");v.initEvent("mouseover",!0,!0),b.dispatchEvent(v)}function l(b){let v={},I=b.getBoundingClientRect(),C=I.left+I.width/2,_=I.top+I.height/2,S=u("mousemove",v,C,_,0);b.dispatchEvent(S)}function c(b,v){function I(S,D,U){return U>S&&U<D}let C=b.pointerPosition||{};if(R.isDrag)return{x:C.originX||0,y:C.originY||0};let _=v.getBoundingClientRect(),$=C.originX&&I(_.left,_.left+_.width,C.originX)?C.originX:_.left+_.width/2,A=C.originY&&I(_.top,_.top+_.height,C.originY)?C.originY:_.top+_.height/2;return{x:$,y:A}}function d(b,v,I){return{screenX:0,screenY:0,clientX:v,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 m(b,v,I,C,_){if(r){let A=d(v,I,C);return A.pointerType="mouse",A.isPrimary=!0,new window.PointerEvent(b,A)}let $=document.createEvent("PointerEvent");return $.initPointerEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement,0,0,0,0,0,0,0,0,0,"mouse",0,!0),$}function u(b,v,I,C,_){let $=t?new MouseEvent("click",{composed:!0}):document.createEvent("MouseEvents");return $.initMouseEvent(b,!0,!0,document.defaultView,1,0,0,I,C,Boolean(v.ctrl),Boolean(v.alt),Boolean(v.shift),Boolean(v.meta),_,document.body?document.body.parentNode:document.documentElement),$}function f(b,v){let I=["pointerup","pointerdown","pointermove"],C=v.modifiers||{},_=c(b,v.element),$=v.button||0,A=b.event;return I.includes(A)?m(A,C,_.x,_.y,$):u(A,C,_.x,_.y,$)}function h(b,v){function I(){return b.event==="click"&&v.isDrag&&!v.allEventsOnSameElement}return I()}function g(b,v,I){try{let C=f(v.events[b],v);h(C,v)||v.element.dispatchEvent(C)}catch{}if(b+1===v.events.length)I();else{let C=Math.min(v.events[b+1].timeStamp-v.events[b].timeStamp,n);setTimeout(()=>{g(b+1,v,I)},C)}}function y(b,v){g(0,b,()=>{window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v()})}let R={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(!R.element){i("element not found");return}a(R.element),l(R.element),y(R,()=>{o()})}});var Un,Ji,yy=w(()=>{"use strict";Un=E(require("lodash"));le();uy();pe();dy();Ji=class extends G{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 d;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:l}]=await Promise.all([Promise.resolve().then(()=>(fy(),my)),Promise.resolve().then(()=>(Cn(),xn))]),c=`
227
227
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
228
228
  var dispatchFocus = ${l.toString()};
229
229
  var doClick = ${a.toString()};
@@ -235,7 +235,7 @@ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: n
235
235
  var dispatchFocus = ${l.toString()};
236
236
  var doDragPath = ${a.toString()};
237
237
  return doDragPath.apply(null, arguments);
238
- `;try{return(m=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}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(D.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 d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,i)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(D.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,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},R=`
238
+ `;try{return(m=(await this.driver.executeCodeAsync(c,n,i)).value)!=null&&m.success?{success:!0}:{success:!1}}catch(u){return{success:!1,reason:u.message,exception:u}}}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(L.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 d={elementToFocusLocatedElement:e.elementToFocusLocatedElement,locatedElement:t,events:this.step.events,timeout:this.context.data.timeToPlayStep+3e3};return this.driver.doubleClick(r,d,i)}if(this.step.isDrag){if(this.step.toElement){let d=this.context.data.toElement;if(this.step.isHTML5Drag){if(L.flags.usePortedHtml5DragDrop.isEnabled()){let h=this.generateHTML5DragEventSequence(),g=this.context.data.timeToPlayStep+3e3,y=this.getTarget(),T={transactionId:`${this.context.testResultId}:${this.step.id}`,id:this.step.id,testResultId:this.context.testResultId,eventType:this.step.type,events:h,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},R=`
239
239
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
240
240
  var dnd = ${py.toString()};
241
241
  var eventData = arguments[0];
@@ -246,14 +246,14 @@ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: n
246
246
  var dnd = ${ly.toString()};
247
247
  var eventData = arguments[0];
248
248
  return dnd.call(null, eventData);
249
- `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?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 Fn,by=w(()=>{"use strict";le();Fn=class extends G{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:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ty,HS,Yi,wy=w(()=>{"use strict";Ty=E(require("lodash"));le();j();HS=x("evaluate-expression-step-action"),Yi=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{HS.info("runner running incoming params evaluation");let o=t.incomingParams||{};Ty.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,i.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var vy={};V(vy,{setText:()=>qS});var qS,Ey=w(()=>{"use strict";qS=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(){pt()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(k){try{if(!t)return;let N=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(N.data=k.eventData.data),N}catch{}}function l(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let F=1,z=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,F,z),N}catch{}}function c(k){return a(k)||l(k)}function d(k,N,F){try{return new KeyboardEvent(k,{bubbles:!0,cancelable:!0,location:N.location||0,key:N.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function m(k,N,F){try{let z=document.createEvent("KeyboardEvent");return z.initKeyEvent(k,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),N.key||"",0),z}catch{}}function u(k,N,F){try{let z=document.createEvent("Events");return z.initEvent(k,!0,!0),Object.assign(z,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:N.key||""}),z}catch{}}function f(k,N,F){return d(k,N,F)||m(k,N,F)||u(k,N,F)}function h(k){if(!o.has(k.event))return null;let N=k.eventData,F=N.modifiers||{},z=f(k.event,N,F);return Object.defineProperties(z,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(z,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),z}function g(k){return k.event==="textInput"?c(k):h(k)}function y(k,N){return(()=>{var z;return k.event==="textInput"&&!((z=N.quirks)!=null&&z.isAuth0Form)})()}function T(k,N){return k.event==="keyup"&&N.event==="keydown"?i:0}function R(k,N){let F=T(k,N);return Math.min(N.timeStamp-k.timeStamp,F)}function b(k){let N=Object.getOwnPropertyDescriptor(k,"value");if(!N)return;let F=k.value;k.value=`${F}#`,N.configurable&&delete k.value,k.value=F;let z=document.createEvent("HTMLEvents");z.initEvent("input",!0,!1),k.dispatchEvent(z),Object.defineProperty(k,"value",N)}function v(k){if(H(k.element))try{if(b(k.element),t)k.element.dispatchEvent(new Event("change"));else{let N=document.createEvent("HTMLEvents");N.initEvent("change",!1,!0),k.element.dispatchEvent(N)}}catch{}}function I(k,N,F){F?setTimeout(()=>{U(k)},R(N,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(k),pt())}function C(k,N){return(k==="change"||k==="blur")&&N.element.tagName==="OPTION"}function _(k,N,F){return C(k.type,N)?N.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):N.element}function $(k,N){let F=k.firstChild,z;for(;F;){if(F.nodeType===3){if(N.offset--<=0)return F}else if(F.nodeType===1&&(z=$(F,N),z))return z;F=F.nextSibling}return null}function A(k,N){if(!(!k||!N)){if(!isNaN(N.start))Object.assign(k,{selectionStart:N.start,selectionEnd:N.end});else if(!isNaN(N.nodeOffset)){let F;if(k.firstChild?F=$(k,{offset:N.nodeOffset}):F=k,F){let z=window.getSelection(),dt=document.createRange();try{z.removeAllRanges(),dt.setStart(F,N.textOffset),dt.setEnd(F,N.textOffset),z.addRange(dt)}catch{}}}}}function S(k,N){return k==="submit"&&Boolean(N.action)}function L(k,N,F){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{A(N.element,F.eventData.selection)}catch{}let z=_(k,N,F);if(!z)throw new Error("could not find element");S(k.type,z)?z.submit():z.dispatchEvent(k)}function U(k){let N,F=k.events[k.eventIndex],z=k.events[++k.eventIndex];try{N=g(F)}catch(dt){return It(`exception in get event in text step:${dt.message}`)}if(y(F,k))return I(k,F,z);if(N)try{L(N,k,F)}catch(dt){return It(`exception in executeEvent in text step:${dt.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,F);else return It(`cannot execute event ${F.event}`);I(k,F,z)}function H(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function q(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function Y(k,N){if(H(k.element)){k.element.value=N.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),k.element.dispatchEvent(F)}else k.isContentEditable&&(k.element.innerHTML=N.eventData.text)}function me(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function pt(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function It(k){k||="";let N={status:"failed",result:k,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}try{let k=H(n.element);n.isContentEditable=q(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=Y}catch(k){It(`exception in set text step:${k.message}`);return}let dr=me();dispatchFocus(s.elementToFocusLocatedElement,dr),U(n)}});var Xi,Sy=w(()=>{"use strict";le();B();Xi=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(De(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=o.codeSnippets;if(i.isDraftEditor&&l)return this.driver.executeJS(l(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Ey(),vy)),Promise.resolve().then(()=>(Cn(),xn))]),u=`
249
+ `,f={fromLocatedElement:t,toLocatedElement:d.locatedElement};return this.driver.executeJS(u,f)}let m=this.getDnDRectsAndOffsets(e,d,this.step.element.clickOffset,this.step.toElement.clickOffset);return this.driver.dragAndDrop(r,d.seleniumElement,m)}return this.dragPathJs()}let l=this.driver.isSafari()&&this.step.button===2,c=this.driver.isSafari()&&e.tagName==="SELECT";return c?{keep:!0,success:"skipped",forceTreatAsWarning:!0,reason:"Safari does not support clicking on select elements"}:!c&&(!this.step.nativeEvents||l)?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 Fn,by=w(()=>{"use strict";le();Fn=class extends G{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:l}=r.computeExpression(e.expression2,t,this.exportsGlobal,this.exportsTest);try{return n.compareOrMatch(l,a)?{success:!0}:{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:String(l),actual:a}}}catch{return{success:!1,errorType:o.stepResult.TEXT_COMPARE_FAILURE,resultInfo:{expected:l.toString(),actual:a}}}}catch(a){return{success:!1,reason:a.message,exception:a,shouldRetry:!0}}}}});var Ty,HS,Yi,wy=w(()=>{"use strict";Ty=E(require("lodash"));le();j();HS=x("evaluate-expression-step-action"),Yi=class extends G{async execute(){let{step:e,context:t,exportsGlobal:r,exportsTest:n}=this;try{HS.info("runner running incoming params evaluation");let o=t.incomingParams||{};Ty.isEmpty(o)&&(o=this.sessionPlayerInit.StepParamsBuilder.getStepInputs(e,t,r,n));let i=["context",...o.as.functionParameters],a=[t,...o.as.functionArguments],c=`return ${e.subType==="text"?`'${e.expression.replace(/'/g,"\\'")}'`:e.expression}`.replace(/\n/g,"\\n"),m=Function.apply(Function,i.concat([c]))(...a);return t.data[e.targetName]=m,t.data[e.targetId]=m,t.internalParams&&t.internalParams.add(e.targetId),{success:!0,evaluatedText:m,data:t.data}}catch(o){let{stepResult:i}=this.sessionPlayerInit.commonConstants;throw{errorType:i.EVALUATE_EXPRESSION_EXCEPTION,resultInfo:{exception:o.toString()},success:!1}}}}});var vy={};V(vy,{setText:()=>qS});var qS,Ey=w(()=>{"use strict";qS=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(){pt()},window.addEventListener("unload",window.__unloadNavigator);let o=new Set(["keydown","keyup","keypress"]),i=15;function a(k){try{if(!t)return;let N=new CustomEvent("textInput",{bubbles:!0,cancelable:!0});return k.eventData&&(N.data=k.eventData.data),N}catch{}}function l(k){try{let N=document.createEvent("TextEvent");N.data=k.eventData.data;let F=1,z=k.eventData.locale||"en-US";return N.initTextEvent("textInput",!0,!0,window,k.eventData.data,F,z),N}catch{}}function c(k){return a(k)||l(k)}function d(k,N,F){try{return new KeyboardEvent(k,{bubbles:!0,cancelable:!0,location:N.location||0,key:N.key||"",ctrlKey:Boolean(F.ctrl),shiftKey:Boolean(F.shift),altKey:Boolean(F.alt),metaKey:Boolean(F.meta)})}catch{}}function m(k,N,F){try{let z=document.createEvent("KeyboardEvent");return z.initKeyEvent(k,!0,!0,null,Boolean(F.ctrl),Boolean(F.alt),Boolean(F.shift),Boolean(F.meta),N.key||"",0),z}catch{}}function u(k,N,F){try{let z=document.createEvent("Events");return z.initEvent(k,!0,!0),Object.assign(z,{altKey:Boolean(F.alt),ctrlKey:Boolean(F.ctrl),metaKey:Boolean(F.meta),shiftKey:Boolean(F.shift),keyCode:N.key||""}),z}catch{}}function f(k,N,F){return d(k,N,F)||m(k,N,F)||u(k,N,F)}function h(k){if(!o.has(k.event))return null;let N=k.eventData,F=N.modifiers||{},z=f(k.event,N,F);return Object.defineProperties(z,{keyCode:{enumerable:!0,get(){return this._keyCode_}},charCode:{enumerable:!0,get(){return this._charCode_}},which:{enumerable:!0,get(){return this._keyCode_}}}),Object.assign(z,{_keyCode_:N.keyCode,_charCode_:N.charCode||0}),z}function g(k){return k.event==="textInput"?c(k):h(k)}function y(k,N){return(()=>{var z;return k.event==="textInput"&&!((z=N.quirks)!=null&&z.isAuth0Form)})()}function T(k,N){return k.event==="keyup"&&N.event==="keydown"?i:0}function R(k,N){let F=T(k,N);return Math.min(N.timeStamp-k.timeStamp,F)}function b(k){let N=Object.getOwnPropertyDescriptor(k,"value");if(!N)return;let F=k.value;k.value=`${F}#`,N.configurable&&delete k.value,k.value=F;let z=document.createEvent("HTMLEvents");z.initEvent("input",!0,!1),k.dispatchEvent(z),Object.defineProperty(k,"value",N)}function v(k){if(H(k.element))try{if(b(k.element),t)k.element.dispatchEvent(new Event("change"));else{let N=document.createEvent("HTMLEvents");N.initEvent("change",!1,!0),k.element.dispatchEvent(N)}}catch{}}function I(k,N,F){F?setTimeout(()=>{U(k)},R(N,F)):(window.__unloadNavigator&&window.removeEventListener("unload",window.__unloadNavigator),v(k),pt())}function C(k,N){return(k==="change"||k==="blur")&&N.element.tagName==="OPTION"}function _(k,N,F){return C(k.type,N)?N.element.parentElement:F.locatedElement?getLocatedElement(F.locatedElement):N.element}function $(k,N){let F=k.firstChild,z;for(;F;){if(F.nodeType===3){if(N.offset--<=0)return F}else if(F.nodeType===1&&(z=$(F,N),z))return z;F=F.nextSibling}return null}function A(k,N){if(!(!k||!N)){if(!isNaN(N.start))Object.assign(k,{selectionStart:N.start,selectionEnd:N.end});else if(!isNaN(N.nodeOffset)){let F;if(k.firstChild?F=$(k,{offset:N.nodeOffset}):F=k,F){let z=window.getSelection(),dt=document.createRange();try{z.removeAllRanges(),dt.setStart(F,N.textOffset),dt.setEnd(F,N.textOffset),z.addRange(dt)}catch{}}}}}function S(k,N){return k==="submit"&&Boolean(N.action)}function D(k,N,F){if(N.isFocusable&&N.isSelectable(k)&&k.type!=="submit")try{A(N.element,F.eventData.selection)}catch{}let z=_(k,N,F);if(!z)throw new Error("could not find element");S(k.type,z)?z.submit():z.dispatchEvent(k)}function U(k){let N,F=k.events[k.eventIndex],z=k.events[++k.eventIndex];try{N=g(F)}catch(dt){return It(`exception in get event in text step:${dt.message}`)}if(y(F,k))return I(k,F,z);if(N)try{D(N,k,F)}catch(dt){return It(`exception in executeEvent in text step:${dt.message}`)}else if(k.noEventExecuter)k.noEventExecuter(k,F);else return It(`cannot execute event ${F.event}`);I(k,F,z)}function H(k){let N=k.tagName;return N==="INPUT"||N==="TEXTAREA"}function q(k){return k.getAttribute?Boolean(k.getAttribute("contenteditable")==="true"):!1}function Y(k,N){if(H(k.element)){k.element.value=N.eventData.text;let F=document.createEvent("Event");F.initEvent("input",!0,!1),k.element.dispatchEvent(F)}else k.isContentEditable&&(k.element.innerHTML=N.eventData.text)}function me(){var N;let k=document.activeElement;for(;(N=k.shadowRoot)!=null&&N.activeElement;)k=k.shadowRoot.activeElement;return k}function pt(k){let N={status:"done",result:k,success:!0,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}function It(k){k||="";let N={status:"failed",result:k,success:!1,...n.isNonTextableElemnet&&{reason:"Set text on non input element"}};e(N)}try{let k=H(n.element);n.isContentEditable=q(n.element),!k&&!n.isContentEditable&&(n.isNonTextableElemnet=!0),n.isFocusable=k||n.isContentEditable,n.isSelectable=N=>N.type!=="keyup",n.noEventExecuter=Y}catch(k){It(`exception in set text step:${k.message}`);return}let dr=me();dispatchFocus(s.elementToFocusLocatedElement,dr),U(n)}});var Xi,Sy=w(()=>{"use strict";le();B();Xi=class extends G{async setValueNative(){let e=this.context,t=this.getTarget();return this.step.delayBetweenChars?(await this.driver.elementIdClear(De(t.seleniumElement)),await this.setTextDelayed()):this.driver.setValue(t.seleniumElement,e.stepText)}async setValueJS(){var h;let{step:{events:e,type:t,quirks:r},context:n,sessionPlayerInit:o}=this,i=this.getTarget(),a=n.data.timeToPlayStep+3e3,{setTextDraftJs:l}=o.codeSnippets;if(i.isDraftEditor&&l)return this.driver.executeJS(l(i.locatedElement,n.stepText));if(!(e!=null&&e.length))return;let c={eventType:t,events:e,quirks:r,locatedElement:i.locatedElement,isRoot:i.isRoot,elementToFocusLocatedElement:i.elementToFocusLocatedElement},[{setText:d},{dispatchFocus:m}]=await Promise.all([Promise.resolve().then(()=>(Ey(),vy)),Promise.resolve().then(()=>(Cn(),xn))]),u=`
250
250
  var getLocatedElement = ${o.codeSnippets.getLocatedElementCode};
251
251
  var dispatchFocus = ${m};
252
252
  var setText = ${d.toString()};
253
253
  var eventData = arguments[0];
254
254
  var done = arguments[1];
255
255
  return setText.call(null, eventData, done);
256
- `,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(De(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(De(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 Iy={};V(Iy,{runCode:()=>zS});var zS,Ry=w(()=>{"use strict";zS=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),R=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||R){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let I={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(I)),T||R)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let o={},i={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(o,i,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:o,exportsTest:i,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Qi,gp,lr,Zi=w(()=>{"use strict";Qi=E(require("lodash"));B();le();j();pe();gp=x("base-js-step-action"),lr=class extends G{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=D.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&gp.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=>{Qi.isObject(i)&&go(i,"seleniumElement",Qi.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,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){gp.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{gp.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===o);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-i<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=i,await oe(i),l()):{success:!0})};return l()}async executeInAut(t){let r=D.flags.experimentalPreCodeCompilation.isEnabled(),n=D.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=o.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
256
+ `,f=await this.driver.executeCodeAsync(u,a,c);return{success:Boolean((h=f.value)==null?void 0:h.success)}}async setTextDelayed(){let e=this.context.stepText,t=this.getTarget();for(let r=0;r<e.length;r++)await this.driver.elementIdValue(De(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(De(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 Iy={};V(Iy,{runCode:()=>zS});var zS,Ry=w(()=>{"use strict";zS=function(s,e){var d;function t(m,u){let f=`data-testim-${m}`,h="Native sessionStorage is not available";function g(y){return y!=null&&y.toString?y.toString().includes("[native code]"):!1}try{if(![window.sessionStorage.setItem,window.sessionStorage.getItem].every(g))throw new Error(h);let T={...JSON.parse(window.sessionStorage.getItem(f)||"{}"),...u};window.sessionStorage.setItem(f,JSON.stringify(T))}catch(y){let T=y.message.toLowerCase().includes("quota"),R=y.message===h;if(y.message.includes("sessionStorage")||y.message.includes("The operation is insecure")||T||R){let b=document.head.querySelector("#testim-storage-backup");b||(b=document.createElement("meta"),b.id="testim-storage-backup",document.head.append(b));let I={...JSON.parse(b.getAttribute(f)||"{}"),...u};if(b.setAttribute(f,JSON.stringify(I)),T||R)try{window.sessionStorage.removeItem(f)}catch{}return}throw y}}function r(m){return m.function?m.function.args.map(u=>u!=null&&u.locatedElement?getLocatedElement(u.locatedElement):u):m.directParams.map(u=>u.selector?document.querySelector(u.selector):u.value).concat(m.otherParams)}function n(m,u){function f(){return m.apply(null,u)}return f.prototype=m.prototype,new f}let o={},i={},a={},l=s.functionParams,c=s.transactionId;try{let m=r(s);m.push(o,i,a);let u=((d=s.function)==null?void 0:d.params)||l,h=(e||n(Function,u)).apply(null,m);typeof Promise<"u"&&h instanceof Promise?(t(c,{type:"promise"}),h.then(g=>{t(c,{status:"done",success:!0,result:{resultValue:g,exports:o,exportsTest:i,exportsGlobal:a}})},g=>{t(c,{status:"failed",success:!1,result:{resultValue:g.toString(),exports:o,exportsTest:i,exportsGlobal:a}})})):t(c,{status:"done",success:!0,result:{resultValue:h,exports:o,exportsTest:i,exportsGlobal:a}})}catch(m){t(c,{status:"failed",success:!1,result:{resultValue:m.toString(),exports:o,exportsTest:i,exportsGlobal:a}})}}});var Qi,gp,lr,Zi=w(()=>{"use strict";Qi=E(require("lodash"));B();le();j();pe();gp=x("base-js-step-action"),lr=class extends G{isExceedingMaxResultSize(t,r){var n;try{let o=(n=r.project.defaults)==null?void 0:n.enforceMaximumJsResultSize,i=L.flags.maximumJsResultSize.getValue(),a=JSON.stringify(t).length>i;return o?a:(a&&gp.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=>{Qi.isObject(i)&&go(i,"seleniumElement",Qi.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,l=async()=>{let c;try{c=await this.executeGetStatus(t)}catch(u){gp.warn("failed to get js status",{err:u}),c={value:'{ "status": "exception" }'}}let d;try{d=JSON.parse((c==null?void 0:c.value)||"{}")}catch{gp.warn("non object value",{selRes:c}),d={status:"exception"}}let m=n.abortedSteps.find(u=>u.id===o);return m||(d?d.status==="done"?d:d.status==="failed"?{success:!1,shouldRetry:!0,result:d.result}:a-i<=0?Object.assign(d,{success:!1,shouldRetry:!0}):(a-=i,await oe(i),l()):{success:!0})};return l()}async executeInAut(t){let r=L.flags.experimentalPreCodeCompilation.isEnabled(),n=L.flags.experimentalAsyncCustomCode.isEnabled(),o=this.constructJSFunParams(t),i=o.function.args.some(m=>Boolean(m==null?void 0:m.locatedElement)),a="undefined";if(r){let m=o.function.params.slice(0,-1);a=n?`async function(${m.join(",")}) {
257
257
  ${t.code}
258
258
  };`:`function(${m.join(",")}) {
259
259
  ${t.code}
@@ -263,7 +263,7 @@ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: n
263
263
  var eventData = arguments[0];
264
264
  var funcToRun = ${a};
265
265
  return runCode.call(null, eventData, funcToRun);
266
- `;if(!r)return this.driver.executeJS(d,o);try{return await this.driver.executeJS(d,o)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:l}=t;o.exports&&(n.data.exports=o.exports);let c={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}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{...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 qt,Ay=w(()=>{"use strict";Zi();qt=class extends lr{isFailedResult(e){return e===!1}}});var ws,xy=w(()=>{"use strict";Zi();ws=class extends lr{isFailedResult(e){return!e}}});var ea,Cy=w(()=>{"use strict";le();B();qi();ea=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(De(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(Nn[t]),this.setWithValueApi(e)}}});var ta,Py=w(()=>{"use strict";le();qi();ta=class extends G{async performAction(){var o,i;let e=this.context.config.os.startsWith("Mac");if(e&&!((o=this.step.keys)!=null&&o.mac)||!e&&!((i=this.step.keys)!=null&&i.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Nn[n])t.push(Nn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var ky={};V(ky,{selectOption:()=>KS});function KS(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 _y=w(()=>{"use strict"});var ra,Oy=w(()=>{"use strict";le();B();pe();ra=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(De(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(_y(),ky)),c=D.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
266
+ `;if(!r)return this.driver.executeJS(d,o);try{return await this.driver.executeJS(d,o)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:o={},tstConsoleLogs:i,nodeVersion:a,navigateToDifferentDomain:l}=t;o.exports&&(n.data.exports=o.exports);let c={nodeVersion:a,tstConsoleLogs:i,data:n.data};return this.isFailedResult(o.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:o,tstConsoleLogs:i},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:o.exportsTest,exportsGlobal:o.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}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{...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 qt,Ay=w(()=>{"use strict";Zi();qt=class extends lr{isFailedResult(e){return e===!1}}});var ws,xy=w(()=>{"use strict";Zi();ws=class extends lr{isFailedResult(e){return!e}}});var ea,Cy=w(()=>{"use strict";le();B();qi();ea=class extends G{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(De(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(Nn[t]),this.setWithValueApi(e)}}});var ta,Py=w(()=>{"use strict";le();qi();ta=class extends G{async performAction(){var o,i;let e=this.context.config.os.startsWith("Mac");if(e&&!((o=this.step.keys)!=null&&o.mac)||!e&&!((i=this.step.keys)!=null&&i.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Nn[n])t.push(Nn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var ky={};V(ky,{selectOption:()=>KS});function KS(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 _y=w(()=>{"use strict"});var ra,Oy=w(()=>{"use strict";le();B();pe();ra=class extends G{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,o=(await this.driver.getBrowserAndOS()).browserMajor,i=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!i||i&&o>=13&&!a)try{return await this.driver.elementIdClick(De(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(_y(),ky)),c=L.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
267
267
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
268
268
  const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
269
269
  const selectOption = ${l.toString()};
@@ -274,7 +274,7 @@ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: n
274
274
  var eventData = arguments[0];
275
275
  var done = arguments[1];
276
276
  return wheel.call(null, eventData, done);
277
- `;return{success:((m=(await this.driver.executeCodeAsync(c,a,i)).value)==null?void 0:m.state)==="success"}}}});var Fy={};V(Fy,{downloadFileAndFireDropEvent:()=>XS});var XS,By=w(()=>{"use strict";XS=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++i;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(i,a,l){let c=new XMLHttpRequest;c.open("GET",i),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.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 QS,ia,jy=w(()=>{"use strict";le();j();pe();QS=x("drop-file-step-action"),ia=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=D.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,QS),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(By(),Fy)),c=`
277
+ `;return{success:((m=(await this.driver.executeCodeAsync(c,a,i)).value)==null?void 0:m.state)==="success"}}}});var Fy={};V(Fy,{downloadFileAndFireDropEvent:()=>XS});var XS,By=w(()=>{"use strict";XS=function(s,e){let t=getLocatedElement(s);if(!t)throw new Error("element not found");function r(){let i=-1,a=0,l=[],c={endWithCallback:void 0,waitOn(){let d=++i;return function(m){d in l||(l[d]=m,a++,e.length===a&&c.endWithCallback(l))}},endWith(d){c.endWithCallback=d}};return c}function n(i,a,l){let c=new XMLHttpRequest;c.open("GET",i),c.responseType="blob",c.onload=function(){if(this.status>=200&&this.status<300)l({blob:c.response,name:a});else throw new Error("Failed to load blob response code is not between 200 - 300")},c.onerror=function(){throw new Error("Failed to load blob")},c.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 QS,ia,jy=w(()=>{"use strict";le();j();pe();QS=x("drop-file-step-action"),ia=class extends G{async performAction(){let{sessionPlayerInit:{codeSnippets:e,utils:t},context:r,step:n}=this,o=this.getTarget(),i=L.flags.overrideAzureStorageUrl.isEnabled(),a=await t.addTokenToFileUrls(r.project.id,n.fileUrls,this.stepActionUtils.testimServicesApi,i,QS),{downloadFileAndFireDropEvent:l}=await Promise.resolve().then(()=>(By(),Fy)),c=`
278
278
  const getLocatedElement = ${e.getLocatedElementCode};
279
279
  const createDropEvent = ${e.createDropEvent.toString()};
280
280
  const downloadFileAndFireDropEvent = ${l.toString()};
@@ -402,14 +402,14 @@ Please make sure the CLI has stable access to the internet. ${bc()?"(Internal: n
402
402
  var getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
403
403
  var getVisibleElement = ${Gy(r)};
404
404
  return getVisibleElement.apply(null, arguments);
405
- `;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 aa.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.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw aa.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=D.flags.overrideAzureStorageUrl.isEnabled(),n=D.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,aa);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
405
+ `;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 aa.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.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw aa.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=L.flags.overrideAzureStorageUrl.isEnabled(),n=L.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,aa);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
406
406
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
407
407
  const downloadAndUploadFile = ${nI()};
408
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Vy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var la,ua,zy=w(()=>{"use strict";la=require("url");le();ua=class extends G{async updateBaseUrl(e){let t=new la.URL(e),r=new la.URL(this.context.recordedBaseUrl),n=new la.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 pa,Ky=w(()=>{"use strict";le();B();pa=class extends G{async performAction(){await oe(this.step.durationMS||0)}}});var da,Jy=w(()=>{"use strict";le();da=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Bn,Yy=w(()=>{"use strict";le();Bn=class extends G{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,forceUseFetch:["android","ios"].includes(r.project.type),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 ma,Xy=w(()=>{"use strict";le();ma=class extends G{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 Qy,hp,yp,Zy=w(()=>{"use strict";Qy=E(require("@applitools/spec-driver-webdriverio"));Zn();we();hp=class{constructor(){let{EyeSdkBuilder:e}=te(),t=Zp["@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:Qy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=te(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},yp=new hp});var tb,eb,jn,rb=w(()=>{"use strict";tb=E(require("lodash"));le();j();Zy();eb=x("pixel-validation-step-action"),jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await yp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};tb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),eb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){eb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await yp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,bp=w(()=>{"use strict";fs();K();Zi();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.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:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,sb=w(()=>{"use strict";bp();ur=class extends vs{isFailedResult(e){return e===!1}}});var fa,nb=w(()=>{"use strict";bp();fa=class extends vs{isFailedResult(e){return!e}}});var ga,ob=w(()=>{"use strict";fs();le();K();ga=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ib=w(()=>{"use strict";le();_r=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,ab=w(()=>{"use strict";le();ye=class extends G{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 ha,cb=w(()=>{"use strict";le();ha=class extends G{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 ya,lb=w(()=>{"use strict";le();ya=class extends G{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 oI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ba(s,e){oI(iI,e),e.registerLocateStepActionUtils(Mn.getUtils(s))}var iI,Tp=w(()=>{"use strict";oy();cy();yy();by();wy();Sy();Ay();xy();Cy();Py();Oy();Ly();Dy();Uy();jy();qy();zy();Ky();Jy();Yy();Xy();rb();sb();nb();ob();ib();ab();cb();lb();iI={locate:Mn,scroll:Ki,mouse:Ji,submit:sa,text:Xi,"special-key":ea,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Yi,"text-validation":Fn,"wait-for-text-validation":Fn,"select-option":ra,"drop-file":ia,"input-file":ca,hover:na,navigation:ua,wheel:oa,sleep:pa,refresh:da,"keyboard-shortcut-step":ta,"api-validation":Bn,"api-action":Bn,"api-code-step":qt,"extract-text":ma,"simple-ui-verification":jn,"wait-for-simple-ui-verification":jn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":fa,"node-package":ga,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ya,"sfdc-recorded-step":ha,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":_r,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var ub,aI,Es,wp=w(()=>{"use strict";ub=["simple-ui-verification","wait-for-simple-ui-verification"],aI=[...ub,"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","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Es=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=aI.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 ub.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 db={};V(db,{SeleniumTestPlayer:()=>$n});var pb,cI,$n,vp=w(()=>{"use strict";B();pb=require("@applitools/eyes-sdk-core");Pn();K();j();lp();ey();mp();qi();sy();fp();we();Tp();wp();cI=x("SeleniumTestPlayer"),$n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=te();this.driver=n??new xr;let d=new Hi(this.driver);this.stepActionFactory=new c(d),ba(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Gi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=ry(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Vi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pb.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(l.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}=te(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&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 r=await this.driver.getTabIds();if(!Array.isArray(r)){cI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await 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(l=>a.url.includes(l))){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 mb={};V(mb,{WorkerSelenium:()=>Ep});function uI(s){let{playback:e}=te().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ta,lI,Ep,fb=w(()=>{"use strict";B();$e();Dn();j();_t();Qo();ae();ap();K();vp();we();nt();Ta=x("worker-selenium"),lI=1e9,Ep=class extends lt{initPlayer(t){return new $n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,lI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Rt||d||m?new Rt(`Page '${l}' is not available`):(Ta.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:No(),initializedFromCache:Mo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=te(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),uI(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 c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});i.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ta.error("failed to run test once",{err:u}),u}}}});var gb,hb,He,pI,dI,Sp,St,wa=w(()=>{"use strict";gb=E(require("ora")),hb=E(require("jimp"));ue();Ve();he();j();ae();we();pe();He=x("mobile-grid-service"),pI="https://tdc.tricentis-cloud.com",dI="https://ui.headspin.io",Sp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Ka}/${Ya}/devices`:t===O.TESTIM_TDC?`${r||Ja}/${Ya}/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),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw He.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)}/device_id:${t}/automation-config`;try{let o=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}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){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.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,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Cl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=te();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=te(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await hb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?dI:pI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await Te(`${bd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),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:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(D.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await kl({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){let i=await an({appId:e,projectId:t});return{appUrl:`${fe}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(yd*60))+1)*60*1e3,Math.max(hd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,gb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Pl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Os}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let f=`${i.includes("eu-central-1")?vd:wd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${Xa}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Ka:Ja}/${Xa}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Td}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,h=await fc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Te(e,void 0,n)}},St=new Sp});function yb({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.");if(t.mode!=="local"&&!mI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function fI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.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 gI(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 hI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&D.flags.enableBatchHeadSpin.isEnabled(),d=i&&(D.flags.enableBatchTDC.isEnabled()||D.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...D.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:gI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function va(s){return"id"in s?s.id:s.packageName}function yI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function bI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=yI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":va(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":va(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:va(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:va(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function bb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=hI(i.type,o,n);return bI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Sa({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 Ia({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Qa:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Qa:".*")}function TI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function wI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ea(s,Ss)}}function Tb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function vI(s){return Tb(s,e=>e.startsWith("browserstack."),"browserstack.")}function EI(s){return Tb(s,e=>!e.startsWith("browserstack."))}function wb(s){return!s||!vb(s)?"2.0.0":s}function vb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Eb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=vb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ea(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=TI(o,s),f=Sa({osVersion:l,mobileConfig:d}),h=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=D.flags.enableAppium2pCloudy.isEnabled(),g=Sa({osVersion:l,mobileConfig:d}),y=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ed),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=wI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ss}})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Eb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:wb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ea(h,Ss),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=vI(n.browserstack),g=(0,Or.omit)(EI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{};if(Eb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let v={userName:o.user,accessKey:o.key,appiumVersion:wb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},I={"appium:platformVersion":u,"appium:deviceName":f,...Ea(g,Ss),"bstack:options":{...v,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:I,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let b={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ea(h,"browserstack.")};return Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return bb(s);if(O.TESTIM_TVC===s.gridInfo.type)return SI(s);if(O.P_CLOUDY===s.gridInfo.type)return II(s);if(O.SAUCELABS===s.gridInfo.type)return RI(s);if(O.BROWSERSTACK===s.gridInfo.type)return AI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function CI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Sb(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}`);yb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=xI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=CI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(m)){let u=Object.entries(m).map(([f,h])=>h.split(",").map(g=>g===".*"||g==="="?"":`${f}:${g}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Ib(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;yb({nativeAppMetadata:r,appPath:o,gridInfo:t}),fI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=bb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Rb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function Ab(s){var t,r;let e={...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"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Ss,mI,Ip=w(()=>{"use strict";pe();ae();wa();Or=require("lodash");B();ue();Ss="appium:",mI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Ra,Cb=w(()=>{"use strict";Ra=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 kb,Pb,Aa,_b=w(()=>{"use strict";kb=require("linkedom"),Pb=new kb.DOMParser,Aa=class{constructor(e){this.driver=e;this._abortedSteps=[]}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}unescapeHTML(e){return Pb.parseFromString(`<html><body>${e}</body></html>`,"text/html").documentElement.textContent}getLinksFromUnescapeHTML(e){return[...Pb.parseFromString(`<html><body>${e}</body></html>`,"text/html").getElementsByTagName("a")].map(r=>r.href).filter(Boolean)}}});var Rp,xa,Ob=w(()=>{"use strict";j();Rp=x("mobile-frame-locator-mock"),xa=class{foundFrameCallback(){return Rp.info("foundFrameCallback-mock invoked"),{}}locate(){return Rp.info("locate-mock invoked"),{}}async findFrame(){return Rp.info("findFrame-mock invoked"),{}}}});var PI,Db,Lb,Is,Ap=w(()=>{"use strict";PI=E(require("webdriverio")),Db=require("@applitools/eyes-sdk-core");Cb();mp();j();_b();fp();we();Tp();Ob();wp();Lb=x("appium-test-player"),Is=class{constructor(e,t,r,n=PI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=te(),m=new Aa(this.driver);this.stepActionFactory=new c(m),ba(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(zi()),this.sessionPlayer=new a(e,{tabService:new Ra,cookieUtils:void 0,FrameLocator:xa,portSelector:Vi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Db.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(l.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{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Lb.info("appium session deleted",{...o}))}catch(i){Lb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=te();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function kI(s){return await Te(`${s}/api/status`)}async function Nb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Mb(s){if((await kI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Ub=w(()=>{"use strict";Ve()});var Fb={};V(Fb,{WorkerLocalTma:()=>kp});var Ca,xp,Cp,Pp,kp,Bb=w(()=>{"use strict";Ve();Ip();Dn();B();j();_t();Ap();we();Ub();wa();Ca=x("worker-appium"),xp=class extends Error{},Cp=class extends Error{},Pp=class extends Error{},kp=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=te(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var I;if(Q.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:l}=this.options;await Mb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:C,testResultId:_}=t,{mobileApp:$}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:C,testResultId:_});t.nativeApp=$}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Nb(i,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},_=Rb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},A=await this.requestNewAppiumSessionFromTma(i,$,g);this.sessionData=A;let S=await m.attach({sessionId:A.sessionId,capabilities:_});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Ca.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(C){throw Ca.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Pp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Te(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Mt(n);await Fs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Cp(c,{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 xp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=te(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Ca.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Ca.error("failed to run test once",{err:c}),c}}}});var $b={};V($b,{WorkerAppium:()=>_p});var jb,Dr,_p,Wb=w(()=>{"use strict";Ip();jb=require("linkedom");Dn();j();_t();Ap();we();wa();ae();is();Dr=x("worker-appium"),_p=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(o,this.options.deviceUdid),f=await Ib(u)):f=Sb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Ab(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let r=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(n){Dr.error("failed to keep appium session alive",{err:n})}};this.keepAliveIndex=setInterval(r,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&ug(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/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 u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=te(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await St.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,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:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,jb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Pa,Gb=w(()=>{"use strict";B();Pn();K();Pa=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Vb,ka,Hb=w(()=>{"use strict";Vb=E(require("ws"));B();ka=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 Vb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(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((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Oa,Op,_a,qb=w(()=>{"use strict";B();Oa=E(require("chrome-launcher"));ju();Hb();un();Op=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ka}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=xi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Oa.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Oa.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Op(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Kb={};V(Kb,{WorkerExtension:()=>Wn});function _I(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function zb(s){return _I(s)?s:new Error(s)}var ut,Wn,Lp=w(()=>{"use strict";$e();K();Dn();B();j();_t();ae();Gb();qb();nt();ut=x("worker-ext"),Wn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Pa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:No(),initializedFromCache:Mo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.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;M("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await lc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),zb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),zb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Jb={};V(Jb,{WorkerExtensionSingleBrowser:()=>Dp});var OI,LI,Dp,Yb=w(()=>{"use strict";$e();B();j();rp();_t();Lp();OI=x("base-worker"),LI=500,Dp=class extends Wn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.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()&&(OI.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;M("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(LI)}}});function DI(s,e){e===0?s():setTimeout(s,e*ud)}var Np,La,Xb=w(()=>{"use strict";Pn();ue();$e();Pu();nt();Hu();K();j();ae();$h();Np=x("parallel-worker-manager"),La=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Z.SELENIUM:return(fb(),be(mb)).WorkerSelenium;case Z.APPIUM:return e.localTmaUrl?(Bb(),be(Fb)).WorkerLocalTma:(Wb(),be($b)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Yb(),be(Jb)).WorkerExtensionSingleBrowser:(Lp(),be(Kb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return M("before new Worker",n.mode),new o(t,...r)}finally{M("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,h)=>new Promise(g=>{var dr,k,N,F,z,dt,Fa,qp;let y=o.project,T=new Mi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,C=(N=o.company)==null?void 0:N.name,_=o.source||"cli",$=o.user,A=(F=o.company)==null?void 0:F.planType,S=(z=o.company)==null?void 0:z.isStartUp,L=(dt=o.projectData)==null?void 0:dt.name,U=(Fa=o.projectData)==null?void 0:Fa.type,H=o.lightweightMode,q=(qp=o.gridData)==null?void 0:qp.type,Y=(Lt,mt,ve,Ba,Vn,ja)=>(m++,Ig({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:H,isStartUp:S,projectType:U,appSource:ja,gridType:q}),t.testStartAndReport(Lt,r,ve,Ba,Vn)),me=async(Lt,mt,ve,Ba,Vn,ja)=>{var zp,Kp,Jp;m--;let et={...(H==null?void 0:H.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((zp=o.gridData)==null?void 0:zp.name),et.gridType=(Kp=o.gridData)==null?void 0:Kp.type,et.gridProvider=(Jp=o.gridData)==null?void 0:Jp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,ve,r,Ba,Vn,et).catch(PT=>Np.error("testEndAndReport threw an error",{err:PT})),Vn)return;R[ve.resultId]=ve,Rg({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:C,projectName:L,companyPlan:A,source:_,user:$,lightweightMode:H,logger:Np,isStartUp:S,projectType:U,appSource:ja}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Lt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Lt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Lt,mt)=>t.onGridSlot(Lt,mt);o.userData={loginData:{...jt(),refreshToken:Lo(),authData:jt(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},M("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Lt,mt)=>{M("before schedule worker.run after createWorkers"),DI(()=>{M("right before worker.run"),Lt.run()},mt)})});try{let f=await Zt(),h=await Do(),g=await u(f,h);if(d)throw new Kt;return g}catch(f){throw Np.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function Zb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await al({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 Mp(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 Up(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Qb.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Qb,eT=w(()=>{"use strict";Qb=E(require("lodash"));B();ts();he();K()});var Gn,dD,Fp,Bp,Da,tT=w(()=>{"use strict";Gn=E(require("lodash"));B();j();ue();ae();$e();ns();du();Pu();he();nt();_t();qg();K();Xb();eT();({testRunStatus:dD,CLI_MODE:Fp}=Ut),Bp=x("test-plan-runner"),Da=class{constructor(e){this.startTime=Date.now();this.workerManager=new La(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=ro||o.parallel,y=!1;M("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};Ag({executionId:i,projectId:o.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(Bp.error("error running test plan",{err:g}),g instanceof Kt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Fp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Sl(o.project),Gn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;nc(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ai(m,n,i,a),f=Gn.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);M("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),M("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Bp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Gn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await il(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Fp.APPIUM&&await Up(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await sg(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Mp(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Mp(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await sl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Bp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await Zb(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await an({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Fp.APPIUM&&await Up(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=vn(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Gn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var oT={};V(oT,{init:()=>tR,run:()=>YI});async function NI(s){let e=s.project,t=await cl(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function MI(s,e){var i,a,l,c,d,m,u,f;let t=ho(e.activePlan),r=s.parallel;if(t==="free"&&r>sT)throw new P(`The free plan allows only ${sT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)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=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
409
- 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)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function UI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await NI(s)}catch(t){if([P,Ls].some(r=>t instanceof r))throw t;jp.error("could not validate cli account",{err:t})}}function FI(s){let e=jt();return lf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function BI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(D.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Li(),_h));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Di(),Dh));r.init(s)}}function jI(s,e){let{branch:t,autoDetect:r}=s;if(pg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function $I(s,e){let{id:t,type:r}=e,o=nT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&D.flags.sfdcHybridCompany.isEnabled(),i=vn();o&&(s.sfdcCredential=await tl({projectId:t,branch:i}))}function WI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=ho(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<rT?rT:s.newBrowserWaitTimeout),D.setCompanyId(t),D.setIsPOC(a),D.setIsStartUp(l),D.setPlanType(c),kt.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function GI(s,e){s.editorUrl=_s||e.editorUrl}function VI(s,e){s.allGrids=e}function HI(s,e){s.authData=e}function qI(s,e){let{id:t,name:r,type:n,defaults:o}=e;D.setProjectId(t),D.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function zI(s){var e;s.gridData=await ng(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}async function KI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Ym(s.overrideMappingFile))}async function JI(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Df(),M("in runner.js after checkNpmVersion"),await UI(s),M("in runRunner before tunnel.connect"),await ii(s),M("in runRunner after tunnel.connect");let a=await new Da(e).run(s);return M("before tunnel.disconnect"),await ai(s),await ZI(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function XI(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
408
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Vy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var la,ua,zy=w(()=>{"use strict";la=require("url");le();ua=class extends G{async updateBaseUrl(e){let t=new la.URL(e),r=new la.URL(this.context.recordedBaseUrl),n=new la.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 pa,Ky=w(()=>{"use strict";le();B();pa=class extends G{async performAction(){await oe(this.step.durationMS||0)}}});var da,Jy=w(()=>{"use strict";le();da=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Bn,Yy=w(()=>{"use strict";le();Bn=class extends G{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,forceUseFetch:["android","ios"].includes(r.project.type),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 ma,Xy=w(()=>{"use strict";le();ma=class extends G{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 Qy,hp,yp,Zy=w(()=>{"use strict";Qy=E(require("@applitools/spec-driver-webdriverio"));Zn();we();hp=class{constructor(){let{EyeSdkBuilder:e}=te(),t=Zp["@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:Qy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=te(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},yp=new hp});var tb,eb,jn,rb=w(()=>{"use strict";tb=E(require("lodash"));le();j();Zy();eb=x("pixel-validation-step-action"),jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await yp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};tb.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),eb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){eb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await yp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,bp=w(()=>{"use strict";fs();K();Zi();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.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:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,sb=w(()=>{"use strict";bp();ur=class extends vs{isFailedResult(e){return e===!1}}});var fa,nb=w(()=>{"use strict";bp();fa=class extends vs{isFailedResult(e){return!e}}});var ga,ob=w(()=>{"use strict";fs();le();K();ga=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ib=w(()=>{"use strict";le();_r=class extends G{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,ab=w(()=>{"use strict";le();ye=class extends G{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 ha,cb=w(()=>{"use strict";le();ha=class extends G{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 ya,lb=w(()=>{"use strict";le();ya=class extends G{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 oI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ba(s,e){oI(iI,e),e.registerLocateStepActionUtils(Mn.getUtils(s))}var iI,Tp=w(()=>{"use strict";oy();cy();yy();by();wy();Sy();Ay();xy();Cy();Py();Oy();Ly();Dy();Uy();jy();qy();zy();Ky();Jy();Yy();Xy();rb();sb();nb();ob();ib();ab();cb();lb();iI={locate:Mn,scroll:Ki,mouse:Ji,submit:sa,text:Xi,"special-key":ea,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Yi,"text-validation":Fn,"wait-for-text-validation":Fn,"select-option":ra,"drop-file":ia,"input-file":ca,hover:na,navigation:ua,wheel:oa,sleep:pa,refresh:da,"keyboard-shortcut-step":ta,"api-validation":Bn,"api-action":Bn,"api-code-step":qt,"extract-text":ma,"simple-ui-verification":jn,"wait-for-simple-ui-verification":jn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":fa,"node-package":ga,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":ya,"sfdc-recorded-step":ha,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":_r,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var ub,aI,Es,wp=w(()=>{"use strict";ub=["simple-ui-verification","wait-for-simple-ui-verification"],aI=[...ub,"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","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Es=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=aI.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 ub.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 db={};V(db,{SeleniumTestPlayer:()=>$n});var pb,cI,$n,vp=w(()=>{"use strict";B();pb=require("@applitools/eyes-sdk-core");Pn();K();j();lp();ey();mp();qi();sy();fp();we();Tp();wp();cI=x("SeleniumTestPlayer"),$n=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=te();this.driver=n??new xr;let d=new Hi(this.driver);this.stepActionFactory=new c(d),ba(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Gi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=ry(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Vi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:pb.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(l.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}=te(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&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 r=await this.driver.getTabIds();if(!Array.isArray(r)){cI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await 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(l=>a.url.includes(l))){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 mb={};V(mb,{WorkerSelenium:()=>Ep});function uI(s){let{playback:e}=te().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var Ta,lI,Ep,fb=w(()=>{"use strict";B();$e();Dn();j();_t();Qo();ae();ap();K();vp();we();nt();Ta=x("worker-selenium"),lI=1e9,Ep=class extends lt{initPlayer(t){return new $n(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,lI),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof Rt||d||m?new Rt(`Page '${l}' is not available`):(Ta.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:No(),initializedFromCache:Mo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=te(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),uI(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 c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ta.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(Ta.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});i.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw Ta.error("failed to run test once",{err:u}),u}}}});var gb,hb,He,pI,dI,Sp,St,wa=w(()=>{"use strict";gb=E(require("ora")),hb=E(require("jimp"));ue();Ve();he();j();ae();we();pe();He=x("mobile-grid-service"),pI="https://tdc.tricentis-cloud.com",dI="https://ui.headspin.io",Sp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Ka}/${Ya}/devices`:t===O.TESTIM_TDC?`${r||Ja}/${Ya}/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),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw He.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)}/device_id:${t}/automation-config`;try{let o=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}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){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.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,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Cl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=te();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=te(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await hb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?dI:pI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await Te(`${bd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),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:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(L.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await kl({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){let i=await an({appId:e,projectId:t});return{appUrl:`${fe}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(yd*60))+1)*60*1e3,Math.max(hd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,gb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Pl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Os}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let f=`${i.includes("eu-central-1")?vd:wd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${Xa}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Ka:Ja}/${Xa}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${Td}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,h=await fc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Te(e,void 0,n)}},St=new Sp});function yb({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.");if(t.mode!=="local"&&!mI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function fI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.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 gI(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 hI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=i&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:gI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function va(s){return"id"in s?s.id:s.packageName}function yI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function bI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=yI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":va(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":va(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:va(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:va(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function bb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=hI(i.type,o,n);return bI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Sa({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 Ia({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Qa:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Qa:".*")}function TI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function wI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ea(s,Ss)}}function Tb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function vI(s){return Tb(s,e=>e.startsWith("browserstack."),"browserstack.")}function EI(s){return Tb(s,e=>!e.startsWith("browserstack."))}function wb(s){return!s||!vb(s)?"2.0.0":s}function vb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Eb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=vb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ea(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=TI(o,s),f=Sa({osVersion:l,mobileConfig:d}),h=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=L.flags.enableAppium2pCloudy.isEnabled(),g=Sa({osVersion:l,mobileConfig:d}),y=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ed),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=wI(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ss}})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Eb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:wb(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ea(h,Ss),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Sa({osVersion:l,mobileConfig:d}),f=Ia({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=vI(n.browserstack),g=(0,Or.omit)(EI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||Eb({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let I={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":wb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},C={"appium:platformVersion":u,"appium:deviceName":f,...Ea(g,Ss),"bstack:options":{...I,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:C,appiumPrefix:Ss,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ea(h,"browserstack.")};return Lr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function xI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return bb(s);if(O.TESTIM_TVC===s.gridInfo.type)return SI(s);if(O.P_CLOUDY===s.gridInfo.type)return II(s);if(O.SAUCELABS===s.gridInfo.type)return RI(s);if(O.BROWSERSTACK===s.gridInfo.type)return AI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function CI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function Sb(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}`);yb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),l=xI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=CI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(m)){let u=Object.entries(m).map(([f,h])=>h.split(",").map(g=>g===".*"||g==="="?"":`${f}:${g}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Ib(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;yb({nativeAppMetadata:r,appPath:o,gridInfo:t}),fI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=bb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Rb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function Ab(s){var t,r;let e={...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"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Ss,mI,Ip=w(()=>{"use strict";pe();ae();wa();Or=require("lodash");B();ue();Ss="appium:",mI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var Ra,Cb=w(()=>{"use strict";Ra=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 kb,Pb,Aa,_b=w(()=>{"use strict";kb=require("linkedom"),Pb=new kb.DOMParser,Aa=class{constructor(e){this.driver=e;this._abortedSteps=[]}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}unescapeHTML(e){return Pb.parseFromString(`<html><body>${e}</body></html>`,"text/html").documentElement.textContent}getLinksFromUnescapeHTML(e){return[...Pb.parseFromString(`<html><body>${e}</body></html>`,"text/html").getElementsByTagName("a")].map(r=>r.href).filter(Boolean)}}});var Rp,xa,Ob=w(()=>{"use strict";j();Rp=x("mobile-frame-locator-mock"),xa=class{foundFrameCallback(){return Rp.info("foundFrameCallback-mock invoked"),{}}locate(){return Rp.info("locate-mock invoked"),{}}async findFrame(){return Rp.info("findFrame-mock invoked"),{}}}});var PI,Db,Lb,Is,Ap=w(()=>{"use strict";PI=E(require("webdriverio")),Db=require("@applitools/eyes-sdk-core");Cb();mp();j();_b();fp();we();Tp();Ob();wp();Lb=x("appium-test-player"),Is=class{constructor(e,t,r,n=PI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=te(),m=new Aa(this.driver);this.stepActionFactory=new c(m),ba(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(zi()),this.sessionPlayer=new a(e,{tabService:new Ra,cookieUtils:void 0,FrameLocator:xa,portSelector:Vi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Db.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(l.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{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Lb.info("appium session deleted",{...o}))}catch(i){Lb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=te();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function kI(s){return await Te(`${s}/api/status`)}async function Nb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Mb(s){if((await kI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Ub=w(()=>{"use strict";Ve()});var Fb={};V(Fb,{WorkerLocalTma:()=>kp});var Ca,xp,Cp,Pp,kp,Bb=w(()=>{"use strict";Ve();Ip();Dn();B();j();_t();Ap();we();Ub();wa();Ca=x("worker-appium"),xp=class extends Error{},Cp=class extends Error{},Pp=class extends Error{},kp=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=te(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var I;if(Q.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:l}=this.options;await Mb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:C,testResultId:_}=t,{mobileApp:$}=await St.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:C,testResultId:_});t.nativeApp=$}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Nb(i,a)]).catch(C=>{throw this.handleDeviceNotFoundError(C),C});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let C={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},_=Rb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:C,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},A=await this.requestNewAppiumSessionFromTma(i,$,g);this.sessionData=A;let S=await m.attach({sessionId:A.sessionId,capabilities:_});this.device=await St.updateTmaDeviceDetails(a,this.options,t),Ca.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:S.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:S.capabilities})}catch(C){throw Ca.error("failed to start application",{err:C}),C}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Pp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Te(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Mt(n);await Fs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Cp(c,{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 xp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=te(),{sessionPlayer:i}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Ca.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Ca.error("failed to run test once",{err:c}),c}}}});var $b={};V($b,{WorkerAppium:()=>_p});var jb,Dr,_p,Wb=w(()=>{"use strict";Ip();jb=require("linkedom");Dn();j();_t();Ap();we();wa();ae();is();Dr=x("worker-appium"),_p=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(o,this.options.deviceUdid),f=await Ib(u)):f=Sb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Ab(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let r=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(n){Dr.error("failed to keep appium session alive",{err:n})}};this.keepAliveIndex=setInterval(r,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&ug(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/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 u,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=te(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await St.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,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:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,jb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Pa,Gb=w(()=>{"use strict";B();Pn();K();Pa=class{constructor(e){this.id=e;this.driver=new xr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Vb,ka,Hb=w(()=>{"use strict";Vb=E(require("ws"));B();ka=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 Vb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(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((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Oa,Op,_a,qb=w(()=>{"use strict";B();Oa=E(require("chrome-launcher"));ju();Hb();un();Op=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ka}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=xi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Oa.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Oa.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>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}},_a=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Op(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Kb={};V(Kb,{WorkerExtension:()=>Wn});function _I(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function zb(s){return _I(s)?s:new Error(s)}var ut,Wn,Lp=w(()=>{"use strict";$e();K();Dn();B();j();_t();ae();Gb();qb();nt();ut=x("worker-ext"),Wn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new Pa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:No(),initializedFromCache:Mo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.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;M("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ut.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await lc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),zb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),zb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Jb={};V(Jb,{WorkerExtensionSingleBrowser:()=>Dp});var OI,LI,Dp,Yb=w(()=>{"use strict";$e();B();j();rp();_t();Lp();OI=x("base-worker"),LI=500,Dp=class extends Wn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return Q.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()&&(OI.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;M("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(LI)}}});function DI(s,e){e===0?s():setTimeout(s,e*ud)}var Np,La,Xb=w(()=>{"use strict";Pn();ue();$e();Pu();nt();Hu();K();j();ae();$h();Np=x("parallel-worker-manager"),La=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Z.SELENIUM:return(fb(),be(mb)).WorkerSelenium;case Z.APPIUM:return e.localTmaUrl?(Bb(),be(Fb)).WorkerLocalTma:(Wb(),be($b)).WorkerAppium;default:return Pi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Yb(),be(Jb)).WorkerExtensionSingleBrowser:(Lp(),be(Kb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return M("before new Worker",n.mode),new o(t,...r)}finally{M("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=(f,h)=>new Promise(g=>{var dr,k,N,F,z,dt,Fa,qp;let y=o.project,T=new Mi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,C=(N=o.company)==null?void 0:N.name,_=o.source||"cli",$=o.user,A=(F=o.company)==null?void 0:F.planType,S=(z=o.company)==null?void 0:z.isStartUp,D=(dt=o.projectData)==null?void 0:dt.name,U=(Fa=o.projectData)==null?void 0:Fa.type,H=o.lightweightMode,q=(qp=o.gridData)==null?void 0:qp.type,Y=(Lt,mt,ve,Ba,Vn,ja)=>(m++,Ig({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:C,projectName:D,companyPlan:A,source:_,user:$,lightweightMode:H,isStartUp:S,projectType:U,appSource:ja,gridType:q}),t.testStartAndReport(Lt,r,ve,Ba,Vn)),me=async(Lt,mt,ve,Ba,Vn,ja)=>{var zp,Kp,Jp;m--;let et={...(H==null?void 0:H.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((zp=o.gridData)==null?void 0:zp.name),et.gridType=(Kp=o.gridData)==null?void 0:Kp.type,et.gridProvider=(Jp=o.gridData)==null?void 0:Jp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,ve,r,Ba,Vn,et).catch(PT=>Np.error("testEndAndReport threw an error",{err:PT})),Vn)return;R[ve.resultId]=ve,Rg({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:C,projectName:D,companyPlan:A,source:_,user:$,lightweightMode:H,logger:Np,isStartUp:S,projectType:U,appSource:ja}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Lt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Lt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Lt,mt)=>t.onGridSlot(Lt,mt);o.userData={loginData:{...jt(),refreshToken:Lo(),authData:jt(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},M("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Lt,mt)=>{M("before schedule worker.run after createWorkers"),DI(()=>{M("right before worker.run"),Lt.run()},mt)})});try{let f=await Zt(),h=await Do(),g=await u(f,h);if(d)throw new Kt;return g}catch(f){throw Np.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function Zb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await al({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 Mp(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 Up(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Qb.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Qb,eT=w(()=>{"use strict";Qb=E(require("lodash"));B();ts();he();K()});var Gn,dD,Fp,Bp,Da,tT=w(()=>{"use strict";Gn=E(require("lodash"));B();j();ue();ae();$e();ns();du();Pu();he();nt();_t();qg();K();Xb();eT();({testRunStatus:dD,CLI_MODE:Fp}=Ut),Bp=x("test-plan-runner"),Da=class{constructor(e){this.startTime=Date.now();this.workerManager=new La(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=ro||o.parallel,y=!1;M("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};Ag({executionId:i,projectId:o.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(Bp.error("error running test plan",{err:g}),g instanceof Kt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Fp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=v();await C.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Sl(o.project),Gn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;nc(c),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ai(m,n,i,a),f=Gn.default.chain(m).map(C=>{var _;return((_=C.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(C=>C.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);M("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),M("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Bp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Gn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await il(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Fp.APPIUM&&await Up(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await sg(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Mp(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,C)=>Object.assign(I,C),{}),b=Mp(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await sl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Bp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await Zb(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.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;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await an({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Fp.APPIUM&&await Up(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=vn(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Gn.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var oT={};V(oT,{init:()=>tR,run:()=>YI});async function NI(s){let e=s.project,t=await cl(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function MI(s,e){var i,a,l,c,d,m,u,f;let t=ho(e.activePlan),r=s.parallel;if(t==="free"&&r>sT)throw new P(`The free plan allows only ${sT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)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=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
409
+ 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)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function UI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await NI(s)}catch(t){if([P,Ls].some(r=>t instanceof r))throw t;jp.error("could not validate cli account",{err:t})}}function FI(s){let e=jt();return lf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function BI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(L.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Li(),_h));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Di(),Dh));r.init(s)}}function jI(s,e){let{branch:t,autoDetect:r}=s;if(pg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function $I(s,e){let{id:t,type:r}=e,o=nT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&L.flags.sfdcHybridCompany.isEnabled(),i=vn();o&&(s.sfdcCredential=await tl({projectId:t,branch:i}))}function WI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=ho(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<rT?rT:s.newBrowserWaitTimeout),L.setCompanyId(t),L.setIsPOC(a),L.setIsStartUp(l),L.setPlanType(c),kt.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function GI(s,e){s.editorUrl=_s||e.editorUrl}function VI(s,e){s.allGrids=e}function HI(s,e){s.authData=e}function qI(s,e){let{id:t,name:r,type:n,defaults:o}=e;L.setProjectId(t),L.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function zI(s){var e;s.gridData=await ng(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}async function KI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Ym(s.overrideMappingFile))}async function JI(s,e){M("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Df(),M("in runner.js after checkNpmVersion"),await UI(s),M("in runRunner before tunnel.connect"),await ii(s),M("in runRunner after tunnel.connect");let a=await new Da(e).run(s);return M("before tunnel.disconnect"),await ai(s),await ZI(s.slotService,t,s.company.companyId),M("after tunnel.disconnect and gridService.keepAlive.end"),a}function XI(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
410
410
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
411
411
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
412
- `)}function QI(s,e,t){s==="redis"&&Tn.start(t,e),s==="mongo"&&yn.start(e)}async function ZI(s,e,t){s==="redis"&&await Tn.end(t,e),s==="mongo"&&await yn.end(e)}function eR(s,e){var o,i,a,l,c,d;let t=D.flags.redisSlotManager.isEnabled(),r=((o=s.projectData)==null?void 0:o.type)==="ios"||((i=s.projectData)==null?void 0:i.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function tR(s){var h,g,y;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=BI(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await cn(s);if(s.printGrids){let T=u.sort((R,b)=>R.type.localeCompare(b.type));console.table(T.reduce((R,b)=>{class v{constructor(_,$){this.Type=_,this.Browsers=$}}let I=Object.entries(b.browsers||{"N/A":""}).map(C=>C.join(":")).join(", ");return R[b.name]=new v(b.type,I),R},{})),process.exit(0)}if(await i,M("after featureFlagsReady and socketConnected"),GI(s,l),WI(s,c),qI(s,d),jI(s,m),VI(s,u),HI(s,a),await $I(s,d),await zI(s),MI(s,c),eR(s,c),D.flags.clearRunnerFileCache.isEnabled())try{await Kr(),jp.info("runner file cache cleared")}catch(T){jp.error("failed to clear runner file cache",{err:T})}(h=s.lightweightMode)!=null&&h.disableLabs||await Pi.loadLabFeatures(d.id,c.activePlan),((g=s.lightweightMode)==null?void 0:g.type)==="turboMode"&&(D.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&console.log(`
412
+ `)}function QI(s,e,t){s==="redis"&&Tn.start(t,e),s==="mongo"&&yn.start(e)}async function ZI(s,e,t){s==="redis"&&await Tn.end(t,e),s==="mongo"&&await yn.end(e)}function eR(s,e){var o,i,a,l,c,d;let t=L.flags.redisSlotManager.isEnabled(),r=((o=s.projectData)==null?void 0:o.type)==="ios"||((i=s.projectData)==null?void 0:i.type)==="android",n=t&&r;if(e.followL2CPlan){let m=(l=(a=e.l2cLicense)==null?void 0:a.shadowCatalogId)==null?void 0:l.includes("testim_mobile"),u=!!((c=e.tvcLicense)!=null&&c.maxParallel);n&&u&&m&&(s.slotService="redis")}!e.followL2CPlan&&n&&((d=e.mobile)!=null&&d.maxParallel)&&(s.slotService="redis")}async function tR(s){var h,g,y;M("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:o}=s,i=BI(e,{disableResults:o||Boolean((t==null?void 0:t.disableResults)&&(r||n!=="extension")),disableRemoteStep:o||Boolean(t==null?void 0:t.disableRemoteStep)});i.catch(()=>{});let{authData:a,editorConfig:l,companyByProjectId:c,projectById:d,branchName:m,allGrids:u}=await cn(s);if(s.printGrids){let T=u.sort((R,b)=>R.type.localeCompare(b.type));console.table(T.reduce((R,b)=>{class v{constructor(_,$){this.Type=_,this.Browsers=$}}let I=Object.entries(b.browsers||{"N/A":""}).map(C=>C.join(":")).join(", ");return R[b.name]=new v(b.type,I),R},{})),process.exit(0)}if(await i,M("after featureFlagsReady and socketConnected"),GI(s,l),WI(s,c),qI(s,d),jI(s,m),VI(s,u),HI(s,a),await $I(s,d),await zI(s),MI(s,c),eR(s,c),L.flags.clearRunnerFileCache.isEnabled())try{await Kr(),jp.info("runner file cache cleared")}catch(T){jp.error("failed to clear runner file cache",{err:T})}(h=s.lightweightMode)!=null&&h.disableLabs||await Pi.loadLabFeatures(d.id,c.activePlan),((g=s.lightweightMode)==null?void 0:g.type)==="turboMode"&&(L.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&console.log(`
413
413
  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`),QI(s.slotService,e,c.id),FI(e),await KI(s),XI(s);let f=vn();await Q.setOptions(s,f)}var nT,rT,sT,jp,YI,iT=w(()=>{"use strict";nT=E(require("lodash"));B();su();lu();$e();ns();is();ts();du();he();nt();Bt();j();_t();ue();ae();K();tT();_i();Hu();pe();Sn();Fl();rT=30*60*1e3,sT=1,jp=x("runner");YI=JI});function aT(s){s.get("/",(e,t)=>{let r=$p();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:ru()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Kl({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var cT=w(()=>{"use strict";Yo();Wp();su()});var Gp,lT,Rs,Na,uT=w(()=>{"use strict";Gp=E(require("chalk"));fs();lT=require("express");j();K();Rs=x("cli-router"),Na=(0,lT.Router)();Na.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:o,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d}=s.body;if(typeof t!="string"||!r||!n||!o||!i||typeof a!="number"||!l||typeof c!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let m={stepId:r,testResultId:i,retryIndex:a,stepResultId:l,timeout:c,fileDataUrl:d,nodePackageParams:n.nodePackageParams};try{let u=await ms(t,r,n,o,i,a,l,c,d);u.success||(console.log(Gp.default.red(u.result.resultValue)),Rs.error("CLI Action Failure",{message:u.result.resultValue,...m})),e.status(200).json({success:!0,data:u})}catch(u){Rs.error("failed to run cli code",{err:u,...m}),console.log(Gp.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});Na.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}let l={stepId:t,testResultId:r,retryIndex:n,stepResultId:i,timeout:a,packageData:o};try{let c=await ds(t,r,n,o,i,a);Rs.info("installed packages successfully",l),e.status(200).json({success:!0,data:c})}catch(c){if(c instanceof At){Rs.error("failed to install node packages",{err:c,...l}),e.status(200).json({success:!1,code:"invalid-node-package",message:c.message});return}if(c instanceof ne){Rs.error("timeout installing node package",{err:c,...l}),e.status(200).json({success:!1,code:"timeout"});return}Rs.error("failed to install node packages",{err:c,...l}),e.status(500).json({success:!1,code:"internal-error"})}})});var pT=w(()=>{"use strict";uT()});var gT={};V(gT,{orchestrateRoutes:()=>rR});function rR(s){let e=(0,mT.default)();s(e),e.use(Vp.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,fT.default)()),e.use(Vp.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:Oe||sd?"*":["http://localhost:3000","https://app.testim.io","https://staging.testim.io","https://playground.testim.io","https://app.staging.testim.cc","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,dT.default)(r)),aT(e),e.use("/cliJs",Na),e.use((n,o)=>{o.status(404).send("Endpoint Not Found")}),e}var dT,mT,Vp,fT,hT=w(()=>{"use strict";dT=E(require("cors")),mT=E(require("express")),Vp=E(require("body-parser")),fT=E(require("compression"));cT();pT();ue()});var bT={};V(bT,{init:()=>sR});async function sR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(hT(),gT));return new Promise((o,i)=>{let a=()=>{};t&&(Fm(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let l=n(a),c=yT.createServer(l);c.listen(s,e),c.on("error",d),c.on("listening",m);function d(u){if(u.syscall!=="listen")return i(u);switch(u.code){case"EACCES":case"EPERM":return i(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return i(new P(`Port ${s} is already in use, is another Testim instance running?`));default:return i(u)}}function m(){let{port:u}=c.address();console.log(`Running on port: ${u}`),nR()}})}async function nR(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var yT,TT=w(()=>{"use strict";yT=E(require("http"));nt();K()});var AT={};V(AT,{getStartedWithStart:()=>$p,runAgentMode:()=>cR});async function cR(s){var r;let e;if(await Tr(s.playerLocation,s.canary),s.startTestimBrowser){await pR();try{e=await uR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new P('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(TT(),bT));return e!=null&&e.webdriverApi&&setTimeout(async()=>{setTimeout(()=>(vp(),be(db)))},6e3),t.init(s)}function $p(){return IT}function wT(s){try{return process.kill(s,0)}catch{return!1}}async function lR(s,e,t){let r=pr.join(Ft,`chrome-${Zs}-process`),n=3e3,o=()=>{Pe.rmSync(r,{recursive:!0}),console.log(`
414
414
 
415
415
  Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Pe.readFileSync(r));if(wT(f.pid)){let h=()=>wT(f.pid)?setTimeout(h,n):o();return h(),{webdriverApi:f}}}let i=await Oo();await ge(As)||await Pe.promises.mkdir(As,{recursive:!0});let l=[...RT(As,e,t,i).desiredCapabilities.chromeOptions.args,...Ua.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],c={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},d=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`,m=await Ua.launch({chromeFlags:l,startingUrl:d,ignoreDefaultFlags:!0,userDataDir:As,chromePath:i,envVars:c}),u={port:m.port,pid:m.pid,cdpUrl:await yr(`localhost:${m.port}`)};return Pe.writeFileSync(r,JSON.stringify(u)),m.process.once("exit",o),m.process.once("close",o),{webdriverApi:u}}async function uR(s){let e=`${md}/extension/testim-full-master.zip`,t=pr.basename(e),r=pr.join(Ft,t),n=pr.join(Ft,`${t}__unzipped__`),o=!(s.ext||s.extensionPath);if(o&&await ge(r)){let f=await Pe.promises.stat(r);o=Date.now()-iR>f.mtimeMs}if(await Pe.promises.mkdir(Ft,{recursive:!0}),o){let f=(0,ET.default)("Downloading Testim Editor").start();await Je(e,r);try{await rt(r,n)}catch{await Pe.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await rt(r,n)}catch{throw await Pe.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Pe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let i=s.extensionPath?null:(await Pe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await lR(s,i,n);await Js({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=RT(As,i,s.extensionPath,s.chromeBinaryLocations),{WebDriver:l}=(Pn(),be(mh)),{SeleniumPerfStats:c}=(cs(),be(jg)),d=new l;d.seleniumPerfStats=new c;let m=await d.initClient(a);IT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":"https://app.testim.io"}?startMode=true`;await d.url(u),Object.assign(d,{initialUrl:u});try{d.cdpUrl=await yr(m.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:d}}function RT(s,e,t,r){let n=e?[e]:[],o=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];return t&&o.push(`--load-extension=${t}`),{logLevel:oR,desiredCapabilities:{chromeOptions:{args:o,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function pR(){if(await ge(Ma))try{let{webSocketDebuggerUrl:s}=await dR();await mR(s),await Pe.promises.unlink(Ma)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Pe.promises.unlink(Ma)}}async function dR(){let s=await Pe.promises.readFile(Ma,{encoding:"utf8"}),[e,t]=s.split(`
@@ -417,5 +417,5 @@ Browser session ended`),process.exit(0)};if(await ge(r)){let f=JSON.parse(Pe.rea
417
417
  `):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new mr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new xs("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new Yn("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,o=(this._url.protocol==="http:"?Ps:$a).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof qn.default&&t.pipe(o),this._request=o,this.timeout&&o.setTimeout(this.timeout,()=>this._onHttpTimeout(o)),o.on("response",i=>this._onHttpResponse(o,i)),o.on("error",()=>this._onHttpRequestError(o)),this.upload._startUpload(o),this._request===o&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof qn.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",o=>this._onHttpResponseData(r,o)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=Ps.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new xs(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,o,i=this.nodejsBaseUrl===null?t:Cs.resolve(this.nodejsBaseUrl,t),a=Cs.parse(i,!1,!0);return a.hash=null,a.auth&&(o!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?o||(o=a.auth):(o||(o=a.substring(0,r)),n||(n=a.substring(r+1)))),(o||n)&&(a.auth=`${o}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let o=r.toLowerCase();this._privateHeaders[o]||(this._mimeOverride!==null&&o==="content-type"&&(n=this._mimeOverride),this._responseHeaders[o]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let o=0;o<t.length;o++)n[o]=t[o];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},ke=Ie;ke.SyntaxError=Jn,ke.ProgressEvent=xs,ke.SecurityError=Xn,ke.XMLHttpRequest=Ie,ke.InvalidStateError=mr,ke.XMLHttpRequestUpload=Kn,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var xT=E(require("semver"));$e();Fl();Bt();Xs();var Hp=E(require("chalk")),CT=require("events");ae();un();K();ae();Uo();j();var Zm=E(require("os")),Bl=E(require("path")),jl=E(require("chalk")),Vo=require("fs");ue();function ef(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Zm.homedir();(0,Vo.mkdirSync)(Bl.resolve(n,".testim_logs"),{recursive:!0});let o=Bl.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${o}`),cd&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(i=>i.includes("player-require-path"))&&(console.log(jl.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(jl.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Vo.writeFileSync)(o,`${s}
418
418
  ${s==null?void 0:s.stack}
419
419
 
420
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Ks();var cv=x("process-handler"),tf=!1;function lv(s){return s instanceof Error?1:tf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(de.SKIPPED)||[t,o].includes(de.FAILED)&&n===Ye.EVALUATING?!1:r!==!0)?1:0)}function uv(){try{Qt("chromedriver").stop()}catch{}}function rf(){tf=!0}async function $l(s){s!=null&&s.stack&&(Qr?console.error(s,s.stack):ef(s)),uv(),await cv.waitForFlush(),process.exit(lv(s))}he();j();pe();var gR=x("cli-entry");function hR(s){if(!xT.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Hp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function yR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),J)),Promise.resolve().then(()=>(Rf(),If))]);M("Starting Testim.io CLI"),Qm($l);try{hR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await D.fetch();let t=await e.process();if(M("in main, after options.process"),ic(global.proxyUri),CT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,oc(t.project),cm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(mn(),Pf));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Kr(),await cn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Qo(),_f));await o(t),!t.playerRequirePath&&t.mode!==Z.EXTENSION&&await Tr(t.playerLocation,t.canary);let i=await im();i.success?console.log(`created prefetched data at ${Eo()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(iT(),oT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(lu(),cu));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Wp(),AT));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(Lu(),Vg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&rf(),M("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([Jm(t),r.init(t)]);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Fr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await xl({...r,error:t.message}).catch(()=>{}),t instanceof P?(console.log(Hp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),gR.error("runner ended with unexpected error",{err:t}),t)}}yR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),$l(s)});
420
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}Ks();var cv=x("process-handler"),tf=!1;function lv(s){return s instanceof Error?1:tf?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:o})=>[t,o].includes(de.SKIPPED)||[t,o].includes(de.FAILED)&&n===Ye.EVALUATING?!1:r!==!0)?1:0)}function uv(){try{Qt("chromedriver").stop()}catch{}}function rf(){tf=!0}async function $l(s){s!=null&&s.stack&&(Qr?console.error(s,s.stack):ef(s)),uv(),await cv.waitForFlush(),process.exit(lv(s))}he();j();pe();var gR=x("cli-entry");function hR(s){if(!xT.satisfies(process.version,s))throw new P(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),o=n<=new Date,i=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new P(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&o)throw new P(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(Hp.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${i}. please upgrade to a newer Node.js version.`))}async function yR(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(B(),J)),Promise.resolve().then(()=>(Rf(),If))]);M("Starting Testim.io CLI"),Qm($l);try{hR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await L.fetch();let t=await e.process();if(M("in main, after options.process"),ic(global.proxyUri),CT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,oc(t.project),cm("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:o}=await Promise.resolve().then(()=>(mn(),Pf));return await o()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Kr(),await cn(t);let{preloadTests:o}=await Promise.resolve().then(()=>(Qo(),_f));await o(t),!t.playerRequirePath&&t.mode!==Z.EXTENSION&&await Tr(t.playerLocation,t.canary);let i=await im();i.success?console.log(`created prefetched data at ${Eo()}`):console.error("failed to create prefetch data",i.error);return}let r=await Promise.resolve().then(()=>(iT(),oT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:o}=await Promise.resolve().then(()=>(lu(),cu));await o(t);return}if(s.isAgentMode(t)){let{runAgentMode:o}=await Promise.resolve().then(()=>(Wp(),AT));return o(t)}if(t.saveRCALocally){let{initServer:o}=await Promise.resolve().then(()=>(Lu(),Vg)),{port:i}=await o(t);t.localRCASaver=`http://localhost:${i}`}t.exitCodeIgnoreFailingTests&&rf(),M("right before testRunner.init/prepareRunner.prepare");let[n]=await Promise.all([Jm(t),r.init(t)]);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof Fr)return;let r=s.getArgsOnRemoteRunFailure();return r&&await xl({...r,error:t.message}).catch(()=>{}),t instanceof P?(console.log(Hp.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),gR.error("runner ended with unexpected error",{err:t}),t)}}yR().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),$l(s)});
421
421
  //# sourceMappingURL=cli.js.map