@testim/testim-cli 4.122.0 → 4.123.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
@@ -406,7 +406,7 @@ Please make sure the CLI has stable access to the internet. ${Ic()?"(Internal: n
406
406
  `;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 ga.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 i="The element is not editable",o="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",g=n?n.message:"";if(g===d||g.startsWith(m)||g.startsWith(i)||g.startsWith(o)||g.startsWith(a)||g.includes(u)||g.includes(l)||g.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ga.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=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,ga);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:g})=>{let h=await Nt(g);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
407
407
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
408
408
  const downloadAndUploadFile = ${sI()};
409
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Zy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ya,ba,rb=w(()=>{"use strict";ya=require("url");ue();ba=class extends G{async updateBaseUrl(e){let t=new ya.URL(e),r=new ya.URL(this.context.recordedBaseUrl),n=new ya.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 Ta,sb=w(()=>{"use strict";ue();F();Ta=class extends G{async performAction(){await ce(this.step.durationMS||0)}}});var wa,nb=w(()=>{"use strict";ue();wa=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,ib=w(()=>{"use strict";ue();Kn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.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.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}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},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var va,ob=w(()=>{"use strict";ue();va=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 ab,Sp,Ep,cb=w(()=>{"use strict";ab=S(require("@applitools/spec-driver-webdriverio"));ci();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=od["@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:ab.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Q(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ep=new Sp});var ub,lb,Jn,pb=w(()=>{"use strict";ub=S(require("lodash"));ue();W();cb();lb=C("pixel-validation-step-action"),Jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let g=await l.openEyes({driver:this.driver.client,config:r,logger:n}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ub.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(f,o.applitoolsStepSettings),lb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await g.check({settings:f}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){lb.error("Applitools SDK step failed",{err:g,info:g.info}),d={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Es,Ip=w(()=>{"use strict";hs();J();aa();Es=class extends cr{async executeCliCode(){var h,f,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(f=(h=t.company)==null?void 0:h.activePlan)==null?void 0:f.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,db=w(()=>{"use strict";Ip();lr=class extends Es{isFailedResult(e){return e===!1}}});var Sa,mb=w(()=>{"use strict";Ip();Sa=class extends Es{isFailedResult(e){return!e}}});var Ea,fb=w(()=>{"use strict";hs();ue();J();Ea=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,gb=w(()=>{"use strict";ue();Or=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,hb=w(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ia,yb=w(()=>{"use strict";ue();Ia=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));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(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,bb=w(()=>{"use strict";ue();Ra=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 nI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Aa(s,e){nI(iI,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var iI,Rp=w(()=>{"use strict";fy();yy();Ay();xy();Py();Oy();My();Ny();Uy();Fy();$y();Wy();Vy();qy();Jy();tb();rb();sb();nb();ib();ob();pb();db();mb();fb();gb();hb();yb();bb();iI={locate:Gn,scroll:ra,mouse:sa,submit:pa,text:ia,"special-key":ca,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":na,"text-validation":qn,"wait-for-text-validation":qn,"select-option":ua,"drop-file":fa,"input-file":ha,hover:da,navigation:ba,wheel:ma,sleep:Ta,refresh:wa,"keyboard-shortcut-step":la,"api-validation":Kn,"api-action":Kn,"api-code-step":Gt,"extract-text":va,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Sa,"node-package":Ea,"email-code-step":Gt,"cli-email-code-step":lr,"sfdc-internal-test-step":Ra,"sfdc-recorded-step":Ia,"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":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var Tb,oI,Is,Ap=w(()=>{"use strict";Tb=["simple-ui-verification","wait-for-simple-ui-verification"],oI=[...Tb,"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"],Is=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=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=oI.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 Tb.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 vb={};H(vb,{SeleniumTestPlayer:()=>Yn});var wb,aI,Yn,xp=w(()=>{"use strict";F();wb=require("@applitools/eyes-sdk-core");Nn();J();W();hp();ly();wp();ea();dy();vp();Te();Rp();Ap();aI=C("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(ta());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new Cr;let d=new Zo(this.driver);this.stepActionFactory=new c(d),Aa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Xo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=py(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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}=Q(),t=1e3*60*2;try{await oe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&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)){aI.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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function lI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var xa,cI,Cp,kp=w(()=>{"use strict";F();We();Wn();W();kt();oo();ne();fp();J();xp();Te();it();xa=C("worker-selenium"),cI=1e9,Cp=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,cI),await this.windowUtils.validatePageIsAvailable(),U("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 It||d||m?new It(`Page '${l}' is not available`):(xa.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Vi(),initializedFromCache:Gi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Q(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),lI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await wn(this.options))[this.testId]);let d=async()=>oe(new Promise((u,g)=>{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(g)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof ie&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(xa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=o.maxKeepAliveGap();g>=3e4&&(xa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let f={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${f.success?"passed":"failed"}`).catch(()=>{}),f});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw xa.error("failed to run test once",{err:u}),u}}}});var Sb,Eb,He,uI,pI,_p,vt,Ca=w(()=>{"use strict";Sb=S(require("ora")),Eb=S(require("jimp"));pe();Ge();he();W();ne();Te();le();He=C("mobile-grid-service"),uI="https://tdc.tricentis-cloud.com",pI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.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===L.TESTIM_HEADSPIN?`${r||tc}/${sc}/devices`:t===L.TESTIM_TDC?`${r||rc}/${sc}/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),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ws(`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,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.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===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.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:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Ml({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.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:i,testId:o,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,g=t.capabilities,h=g.platformName,f;if(u===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Q();f=T(t.capabilities)}else f=await this.getDeviceFromAppiumCapabilities(g,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,g);return await vr(l,i,o,a,"RUNNING",{device:f,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:i,testId:o,device:f,remoteResultLink:y,gridType:u}),f}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.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 i=e.deviceScreenSize.split("x"),o=Number(i[0]),a=Number(i[1]);return{scaleFactor:e.pixelRatio,width:o,height:a}}try{let{AppiumApi:i}=Q(),o=new i(t,r.sessionId,null),[a,l]=await Promise.all([o.getScreenshot(),o.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Eb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(i){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:i}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,i);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ms}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?pI:uI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${Sd}/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:i,testResultId:o}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,i,o,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ul({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(vd*60))+1)*60*1e3,Math.max(wd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].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,Sb.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 Nl({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:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,f=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=g===L.BROWSERSTACK||g===L.TESTIM_TVC||g===L.P_CLOUDY;if(f){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:f,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:f,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=f),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:f,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!f&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ms}/recent_apps`,g=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(g)?g.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let g=`${o.includes("eu-central-1")?Rd:Id}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:g,user:i,key:a})).items.some(f=>f.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${nc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?tc:rc}/${nc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,g=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:g,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),g=`https://${o}/api/drive`,h=await wc({url:g,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 be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},vt=new _p});function Ib({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"&&!dI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function mI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.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 fI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function gI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:fI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function Pa(s){return"id"in s?s.id:s.packageName}function hI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function yI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=hI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Pa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Pa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Dr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Pa(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Pa(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Rb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=gI(o.type,i,n);return yI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _a({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 Oa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?ic:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":ic:".*")}function bI(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 TI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...ka(s,Rs)}}function Ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function wI(s){return Ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function vI(s){return Ab(s,e=>!e.startsWith("browserstack."))}function xb(s){return!s||!Cb(s)?"2.0.0":s}function Cb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Pb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Cb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function ka(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=bI(i,s),g=_a({osVersion:l,mobileConfig:d}),h=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),f=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),y=O.flags.enableWaldoRunner.isEnabled(),T={device:h,os_version:g,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":f,...y&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:u}};return Dr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function EI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:g}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),f=_a({osVersion:l,mobileConfig:d}),y=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:g}),T=/^[a-zA-Z]+$/.test(y),R={...f!==".*"&&{pCloudy_DeviceVersion:f},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ad),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=TI(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Rs}})}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),g=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),f={...h["sauce:options"]};if(delete h["sauce:options"],Pb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:f.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:xb(f.appiumVersion),deviceName:g,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":g,...ka(h,Rs),"sauce:options":{...T,...R,...(0,Lr.omit)(f,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:g,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...f};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),g=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=wI(n.browserstack),f=(0,Lr.omit)(vI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{},b=O.flags.enableAppium2BrowserStack.isEnabled();if(b||Pb({osVersion:f.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":xb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":g,...ka(f,Rs),"bstack:options":{...E,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:x,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:f.platformVersion||u,device:f.deviceName||g,realDevice:!0,name:R||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...f,...ka(h,"browserstack.")};return Dr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Rb(s);if(L.TESTIM_TVC===s.gridInfo.type)return SI(s);if(L.P_CLOUDY===s.gridInfo.type)return EI(s);if(L.SAUCELABS===s.gridInfo.type)return II(s);if(L.BROWSERSTACK===s.gridInfo.type)return RI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function xI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((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),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function kb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=AI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=xI(r,i==null?void 0:i.mobile);if(!(0,Lr.isEmpty)(T)){let R=Object.entries(T).map(([b,v])=>v.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=R}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Op.default)("2m"),g=(0,Op.default)("8m"),h=fr(O.flags.appiumConnectionRetryCount.getValue(),m),f=fr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&f<g&&(f=g),{...a,desiredCapabilities:l,connectionRetryTimeout:f,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function _b(s){var h,f;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),mI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((f=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:f.deviceUdid),m=await vt.getGridDirectConnection(t,d),g=Rb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(g["appium:udid"]=d),{...m,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function Lb(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 Op,Lr,Rs,dI,Lp=w(()=>{"use strict";Op=S(require("ms"));le();ne();Ca();Lr=require("lodash");F();pe();Rs="appium:",dI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var La,Mb=w(()=>{"use strict";La=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 Da,Nb=w(()=>{"use strict";F();Da=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys}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)")}}});var Dp,Ma,Ub=w(()=>{"use strict";W();Dp=C("mobile-frame-locator-mock"),Ma=class{foundFrameCallback(){return Dp.info("foundFrameCallback-mock invoked"),{}}locate(){return Dp.info("locate-mock invoked"),{}}async findFrame(){return Dp.info("findFrame-mock invoked"),{}}}});var CI,Bb,Fb,As,Mp=w(()=>{"use strict";CI=S(require("webdriverio")),Bb=require("@applitools/eyes-sdk-core");Mb();wp();W();Nb();vp();Te();Rp();Ub();Ap();Fb=C("appium-test-player"),As=class{constructor(e,t,r,n=CI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Da(this.driver);this.stepActionFactory=new c(m),Aa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(ta()),this.sessionPlayer=new a(e,{tabService:new La,cookieUtils:void 0,FrameLocator:Ma,portSelector:Qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Fb.info("appium session deleted",{...i}))}catch(o){Fb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Q();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function PI(s){return await be(`${s}/api/status`)}async function jb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function $b(s){if((await PI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Wb=w(()=>{"use strict";Ge()});var Vb={};H(Vb,{WorkerLocalTma:()=>Bp});var Mr,Np,Up,Fp,Bp,Gb=w(()=>{"use strict";Ge();Lp();Wn();F();W();kt();Mp();Te();Wb();Ca();Mr=C("worker-appium"),Np=class extends Error{},Up=class extends Error{},Fp=class extends Error{},Bp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new As(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}=Q(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await $b(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,g=this.options.appId;if(g){let{mobileApp:x}=await vt.getMobileAppDataByAppId({appId:g,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,f=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!f)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(o,a,T),jb(o,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Mr.info("device status and app state",{deviceStatus:v,appInstalled:R,version:b,executionId:this.executionId,testResultId:this.testResultId}),!R&&t.isAppFromDevice&&!g)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(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:f,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),I={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:I,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,I,f);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:f,sessionCaps:k.capabilities})}catch(x){throw Mr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({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=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Fp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).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 i,o;try{let a=await Nt(n);await $s(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Up(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Np(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Q(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.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 i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var qb={};H(qb,{WorkerAppium:()=>jp});var Hb,Nr,jp,zb=w(()=>{"use strict";F();Lp();Hb=require("linkedom");Wn();W();kt();Mp();Te();Ca();ne();cs();Nr=C("worker-appium"),jp=class extends Ot{initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await vt.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.uniqueId}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),g=await _b(u)):g=kb(u),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Lb(g)});let h=this.getServerAddressFromGrid();this.activeSession=await o.remote(g),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let f=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(f),Nr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Nr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await t.getOrientation()}catch(i){Nr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&bg(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){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:i,directConnectPath:o}=t;if(r&&n&&i&&o)return`${r}://${n}:${i}${o}`}async runTestOnce(t,r){var g,h;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Q(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((g=this.testRunConfig.mobile)==null?void 0:g.staticAllocation.deviceUdid),{protocol:y,hostname:T,port:R,path:b}=await vt.getHeadSpinDeviceConnection(this.options.gridData,f);d=`${y}://${T}:${R}${b}`}else d=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Hb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let f=await new Promise((T,R)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:T,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(R)});return this.stopKeepAlive(),await o.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw Nr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),this.stopKeepAlive(),f}};try{return await super.runTestOnce(t,r),await oe(u(),c)}catch(f){throw Nr.error("failed to run test once",{err:f}),f}}}});var Na,Kb=w(()=>{"use strict";F();Nn();J();Na=class{constructor(e){this.id=e;this.driver=new Cr}async onDone(){try{await oe(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Jb,Ua,Yb=w(()=>{"use strict";Jb=S(require("ws"));F();Ua=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 Jb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),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 i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ba,$p,Fa,Xb=w(()=>{"use strict";F();Ba=S(require("chrome-launcher"));zu();Yb();fn();$p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ua}async init(e){var h,f,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=No({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(f=m.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ba.Launcher.defaultFlags().filter(R=>R!=="--disable-extensions")];this.chrome=await Ba.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await hr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),rs(()=>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}},Fa=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new $p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Wp={};H(Wp,{WorkerExtension:()=>Xn});function kI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Qb(s){return kI(s)?s:new Error(s)}var ut,Xn,ja=w(()=>{"use strict";We();J();Wn();F();W();kt();ne();Kb();Xb();it();ut=C("worker-ext"),Xn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Fa(this.id):new Na(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.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:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Vi(),initializedFromCache:Gi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.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 i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await oe(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))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 g=await d.url(m);return u.driverUrlFinished=!0,g}catch(g){throw ut.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),g}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var g;if(U("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(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();Z.onWaitToTestStart(this.id);try{await oe(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let f=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Gs.BROWSER_CLOSED,f.abort(T)};m.registerToClosedBrowser(y);try{let T=oe(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),R=await hc(T,f.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(E){ut.error("Could not update the grid about the test status",{err:E})}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:i}),Qb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Qb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Gp={};H(Gp,{WorkerExtensionSingleBrowser:()=>Vp});var _I,OI,Vp,Hp=w(()=>{"use strict";We();F();W();lp();kt();ja();_I=C("base-worker"),OI=500,Vp=class extends Xn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(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,i){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(_I.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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.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 ce(OI)}}});var qp,$a,Zb=w(()=>{"use strict";Nn();pe();We();Fu();it();Qu();J();W();ne();Yh();eo();qp=C("worker-manager"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Gb(),Vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(zb(),qb))).WorkerAppium;default:return Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension;case bn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new A(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,g)=>new Promise(h=>{var de,Lt,St,Ur,P,M,j,z;let f=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Go(r,n,e,i,o,t),this.combinedTestResults={};let T=((de=i.company)==null?void 0:de.ucid)||"",R=(Lt=i.company)==null?void 0:Lt.companyId,b=(St=i.company)==null?void 0:St.name,v=i.source||"cli",E=i.user,x=(Ur=i.company)==null?void 0:Ur.planType,D=(P=i.company)==null?void 0:P.isStartUp,I=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(z=i.gridData)==null?void 0:z.type,$=(Pe,Et,we,za,Zn,Ka)=>(d++,Og({executionId:r,projectId:f,testId:Et,resultId:we,ucid:T,companyId:R,companyName:b,projectName:I,companyPlan:x,source:v,user:E,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ka,gridType:_}),t.testStartAndReport(Pe,r,we,za,Zn)),V=async(Pe,Et,we,za,Zn,Ka)=>{var ed,td,rd;d--;let et={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((ed=i.gridData)==null?void 0:ed.name),et.gridType=(td=i.gridData)==null?void 0:td.type,et.gridProvider=(rd=i.gridData)==null?void 0:rd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,we,r,za,Zn,et).catch(CT=>qp.error("testEndAndReport threw an error",{err:CT})),Zn)return;this.combinedTestResults[we.resultId]=we,Lg({executionId:r,projectId:f,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:R,companyName:b,projectName:I,companyPlan:x,source:v,user:E,lightweightMode:k,logger:qp,isStartUp:D,projectType:N,appSource:Ka}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},te=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:$i(),authData:wr(),token:u,userAccessKey:g},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,te,Y)});try{let u=await xt(),g=await Wi(),h=await m(u,g);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw qp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Qn,Wa,zp,Va,eT=w(()=>{"use strict";Qn=S(require("lodash"));F();W();pe();ne();We();os();vu();Fu();he();kt();eh();J();Zb();eo();({CLI_MODE:Wa}=Ut),zp=C("test-plan-runner"),Va=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new $a(this.customExtensionLocalLocation),m=async()=>{let f=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,f,y);Object.assign(c,T)},u=async()=>{let f=pi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,f,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},g=async()=>{let f=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,f,y);Object.assign(c,T)};Dg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await g(),c}catch(f){if(zp.error("error running test plan",{err:f}),f instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw f}finally{await h()}async function h(){var y,T,R,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Wa.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),er)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(o,E);return}let f;try{if(!((b=(R=(T=i.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(f=await kl(i.project),Qn.default.isEmpty(f)||!o))return;let{runKey:v,url:E}=f;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,v,E;let c=se(),d=n.project;pc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),g=Qn.default.chain(m).map(x=>{var D;return((D=x.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(g==null?void 0:g.length)===1?g[0]:null,f=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,f);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:R,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){zp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Qn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await ml(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new A(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new A(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Wa.APPIUM&&await Ql(e,r(c)),await ae(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 pg(e,d);let g=u.overrideExecutionName||d.name;return await ae(c[m],async f=>{let y=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,u,g,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Xl(n[m][E])})),R=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,x)=>Object.assign(E,x),{}),b=Xl(R);Object.assign(i,R);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ul(o,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await wf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new A("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new A("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new A("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Wa.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await ae(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!==Wa.APPIUM&&await Ql(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Cn(),r=[];qs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Qn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var nT={};H(nT,{init:()=>tR,run:()=>YI});async function LI(s){let e=s.project,t=await gl(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"),hn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ns}function DI(s,e){var i,o,a,l,c,d,m,u;let t=Ii(e.activePlan),r=s.parallel;if(t==="free"&&r>rT)throw new A(`The free plan allows only ${rT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let g=(o=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:o.tunnel;if(s.tunnel&&!g)throw new A("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 h=(l=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!h&&(console.warn(`
409
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Zy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ya,ba,rb=w(()=>{"use strict";ya=require("url");ue();ba=class extends G{async updateBaseUrl(e){let t=new ya.URL(e),r=new ya.URL(this.context.recordedBaseUrl),n=new ya.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 Ta,sb=w(()=>{"use strict";ue();F();Ta=class extends G{async performAction(){await ce(this.step.durationMS||0)}}});var wa,nb=w(()=>{"use strict";ue();wa=class extends G{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,ib=w(()=>{"use strict";ue();Kn=class extends G{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.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.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}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},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var va,ob=w(()=>{"use strict";ue();va=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 ab,Sp,Ep,cb=w(()=>{"use strict";ab=S(require("@applitools/spec-driver-webdriverio"));ci();Te();Sp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=od["@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:ab.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Q(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ep=new Sp});var ub,lb,Jn,pb=w(()=>{"use strict";ub=S(require("lodash"));ue();W();cb();lb=C("pixel-validation-step-action"),Jn=class extends G{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Ep.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let g=await l.openEyes({driver:this.driver.client,config:r,logger:n}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ub.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(f,o.applitoolsStepSettings),lb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await g.check({settings:f}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){lb.error("Applitools SDK step failed",{err:g,info:g.info}),d={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Ep.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Es,Ip=w(()=>{"use strict";hs();J();aa();Es=class extends cr{async executeCliCode(){var h,f,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(f=(h=t.company)==null?void 0:h.activePlan)==null?void 0:f.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ie?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,db=w(()=>{"use strict";Ip();lr=class extends Es{isFailedResult(e){return e===!1}}});var Sa,mb=w(()=>{"use strict";Ip();Sa=class extends Es{isFailedResult(e){return!e}}});var Ea,fb=w(()=>{"use strict";hs();ue();J();Ea=class extends G{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ie?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Or,gb=w(()=>{"use strict";ue();Or=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,hb=w(()=>{"use strict";ue();ye=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ia,yb=w(()=>{"use strict";ue();Ia=class extends G{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));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(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ra,bb=w(()=>{"use strict";ue();Ra=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 nI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Aa(s,e){nI(iI,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var iI,Rp=w(()=>{"use strict";fy();yy();Ay();xy();Py();Oy();My();Ny();Uy();Fy();$y();Wy();Vy();qy();Jy();tb();rb();sb();nb();ib();ob();pb();db();mb();fb();gb();hb();yb();bb();iI={locate:Gn,scroll:ra,mouse:sa,submit:pa,text:ia,"special-key":ca,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":na,"text-validation":qn,"wait-for-text-validation":qn,"select-option":ua,"drop-file":fa,"input-file":ha,hover:da,navigation:ba,wheel:ma,sleep:Ta,refresh:wa,"keyboard-shortcut-step":la,"api-validation":Kn,"api-action":Kn,"api-code-step":Gt,"extract-text":va,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Or,"cli-wait-for-download-file":Or,"network-validation-step":Or,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Sa,"node-package":Ea,"email-code-step":Gt,"cli-email-code-step":lr,"sfdc-internal-test-step":Ra,"sfdc-recorded-step":Ia,"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":Or,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var Tb,oI,Is,Ap=w(()=>{"use strict";Tb=["simple-ui-verification","wait-for-simple-ui-verification"],oI=[...Tb,"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"],Is=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=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=oI.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 Tb.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 vb={};H(vb,{SeleniumTestPlayer:()=>Yn});var wb,aI,Yn,xp=w(()=>{"use strict";F();wb=require("@applitools/eyes-sdk-core");Nn();J();W();hp();ly();wp();ea();dy();vp();Te();Rp();Ap();aI=C("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Is(ta());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new Cr;let d=new Zo(this.driver);this.stepActionFactory=new c(d),Aa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Xo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=py(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:Qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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}=Q(),t=1e3*60*2;try{await oe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ie&&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)){aI.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(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Pp={};H(Pp,{WorkerSelenium:()=>Cp});function lI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var xa,cI,Cp,kp=w(()=>{"use strict";F();We();Wn();W();kt();oo();ne();fp();J();xp();Te();it();xa=C("worker-selenium"),cI=1e9,Cp=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),U("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,cI),await this.windowUtils.validatePageIsAvailable(),U("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 It||d||m?new It(`Page '${l}' is not available`):(xa.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Vi(),initializedFromCache:Gi()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Q(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),lI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await wn(this.options))[this.testId]);let d=async()=>oe(new Promise((u,g)=>{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(g)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof ie&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(xa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=o.maxKeepAliveGap();g>=3e4&&(xa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let f={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${f.success?"passed":"failed"}`).catch(()=>{}),f});o.start(),U("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),U("right after super.runTestOnce in workerSelenium");let u=await d();return U("right after runSeleniumTest"),u}catch(u){throw xa.error("failed to run test once",{err:u}),u}}}});var Sb,Eb,He,uI,pI,_p,vt,Ca=w(()=>{"use strict";Sb=S(require("ora")),Eb=S(require("jimp"));pe();Ge();he();W();ne();Te();le();He=C("mobile-grid-service"),uI="https://tdc.tricentis-cloud.com",pI="https://ui.headspin.io",_p=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.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===L.TESTIM_HEADSPIN?`${r||tc}/${sc}/devices`:t===L.TESTIM_TDC?`${r||rc}/${sc}/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),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ws(`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,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.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===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.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:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Ml({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.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:i,testId:o,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,g=t.capabilities,h=g.platformName,f;if(u===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Q();f=T(t.capabilities)}else f=await this.getDeviceFromAppiumCapabilities(g,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,g);return await vr(l,i,o,a,"RUNNING",{device:f,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:i,testId:o,device:f,remoteResultLink:y,gridType:u}),f}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.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 i=e.deviceScreenSize.split("x"),o=Number(i[0]),a=Number(i[1]);return{scaleFactor:e.pixelRatio,width:o,height:a}}try{let{AppiumApi:i}=Q(),o=new i(t,r.sessionId,null),[a,l]=await Promise.all([o.getScreenshot(),o.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Eb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(i){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:i}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,i);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ms}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?pI:uI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${Sd}/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:i,testResultId:o}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,i,o,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ul({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await pn({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(vd*60))+1)*60*1e3,Math.max(wd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].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,Sb.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 Nl({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:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,f=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=g===L.BROWSERSTACK||g===L.TESTIM_TVC||g===L.P_CLOUDY;if(f){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:f,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:f,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=f),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:f,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!f&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Ms}/recent_apps`,g=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(g)?g.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let g=`${o.includes("eu-central-1")?Rd:Id}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:g,user:i,key:a})).items.some(f=>f.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${nc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?tc:rc}/${nc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Ed}/versions/${e}/info`,g=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:g,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),g=`https://${o}/api/drive`,h=await wc({url:g,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 be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,i)}},vt=new _p});function Ib({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"&&!dI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function mI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.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 fI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function gI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:fI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Pa(s){return"id"in s?s.id:s.packageName}function hI(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function yI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=hI(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Pa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Pa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Dr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i=""}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Pa(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Pa(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Rb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o}){let a=gI(o.type,i,n);return yI({projectType:s,sessionCaps:a,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _a({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 Oa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?ic:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":ic:".*")}function bI(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 TI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...ka(s,Rs)}}function Ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function wI(s){return Ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function vI(s){return Ab(s,e=>!e.startsWith("browserstack."))}function xb(s){return!s||!Cb(s)?"2.0.0":s}function Cb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Pb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Cb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function ka(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}function SI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=bI(i,s),g=_a({osVersion:l,mobileConfig:d}),h=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),f=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),y=O.flags.enableWaldoRunner.isEnabled(),T={device:h,os_version:g,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":f,...y&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:u}};return Dr({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function EI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:g}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),f=_a({osVersion:l,mobileConfig:d}),y=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:g}),T=/^[a-zA-Z]+$/.test(y),R={...f!==".*"&&{pCloudy_DeviceVersion:f},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ad),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=TI(b)),t="",Dr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Rs}})}function II({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),g=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Lr.omit)({...n.saucelabs},["automationName","platformName"]),f={...h["sauce:options"]};if(delete h["sauce:options"],Pb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:f.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:xb(f.appiumVersion),deviceName:g,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":g,...ka(h,Rs),"sauce:options":{...T,...R,...(0,Lr.omit)(f,"appiumVersion")}};return Dr({projectType:s,sessionCaps:b,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:g,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...f};return Dr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=_a({osVersion:l,mobileConfig:d}),g=Oa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=wI(n.browserstack),f=(0,Lr.omit)(vI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{},b=O.flags.enableAppium2BrowserStack.isEnabled();if(b||Pb({osVersion:f.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":xb(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":g,...ka(f,Rs),"bstack:options":{...E,...(0,Lr.omit)(h,"appiumVersion")}};return Dr({projectType:s,sessionCaps:x,appiumPrefix:Rs,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:f.platformVersion||u,device:f.deviceName||g,realDevice:!0,name:R||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...f,...ka(h,"browserstack.")};return Dr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Rb(s);if(L.TESTIM_TVC===s.gridInfo.type)return SI(s);if(L.P_CLOUDY===s.gridInfo.type)return EI(s);if(L.SAUCELABS===s.gridInfo.type)return II(s);if(L.BROWSERSTACK===s.gridInfo.type)return RI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function xI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((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),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function kb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);Ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=AI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=xI(r,i==null?void 0:i.mobile);if(!(0,Lr.isEmpty)(T)){let R=Object.entries(T).map(([b,v])=>v.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=R}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Op.default)("2m"),g=(0,Op.default)("12m"),h=fr(O.flags.appiumConnectionRetryCount.getValue(),m),f=fr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&f<g&&(f=g),{...a,desiredCapabilities:l,connectionRetryTimeout:f,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function _b(s){var h,f;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),mI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((f=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:f.deviceUdid),m=await vt.getGridDirectConnection(t,d),g=Rb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(g["appium:udid"]=d),{...m,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Dr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function Lb(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 Op,Lr,Rs,dI,Lp=w(()=>{"use strict";Op=S(require("ms"));le();ne();Ca();Lr=require("lodash");F();pe();Rs="appium:",dI=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var La,Mb=w(()=>{"use strict";La=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 Da,Nb=w(()=>{"use strict";F();Da=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Js;this.getLinksFromUnescapeHTML=Ys}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)")}}});var Dp,Ma,Ub=w(()=>{"use strict";W();Dp=C("mobile-frame-locator-mock"),Ma=class{foundFrameCallback(){return Dp.info("foundFrameCallback-mock invoked"),{}}locate(){return Dp.info("locate-mock invoked"),{}}async findFrame(){return Dp.info("findFrame-mock invoked"),{}}}});var CI,Bb,Fb,As,Mp=w(()=>{"use strict";CI=S(require("webdriverio")),Bb=require("@applitools/eyes-sdk-core");Mb();wp();W();Nb();vp();Te();Rp();Ub();Ap();Fb=C("appium-test-player"),As=class{constructor(e,t,r,n=CI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Da(this.driver);this.stepActionFactory=new c(m),Aa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Is(ta()),this.sessionPlayer=new a(e,{tabService:new La,cookieUtils:void 0,FrameLocator:Ma,portSelector:Qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,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,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Fb.info("appium session deleted",{...i}))}catch(o){Fb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Q();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function PI(s){return await be(`${s}/api/status`)}async function jb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function $b(s){if((await PI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Wb=w(()=>{"use strict";Ge()});var Vb={};H(Vb,{WorkerLocalTma:()=>Bp});var Mr,Np,Up,Fp,Bp,Gb=w(()=>{"use strict";Ge();Lp();Wn();F();W();kt();Mp();Te();Wb();Ca();Mr=C("worker-appium"),Np=class extends Error{},Up=class extends Error{},Fp=class extends Error{},Bp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new As(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}=Q(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Z.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await $b(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,g=this.options.appId;if(g){let{mobileApp:x}=await vt.getMobileAppDataByAppId({appId:g,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,f=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!f)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(o,a,T),jb(o,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Mr.info("device status and app state",{deviceStatus:v,appInstalled:R,version:b,executionId:this.executionId,testResultId:this.testResultId}),!R&&t.isAppFromDevice&&!g)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(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:f,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),I={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:I,executionId:this.executionId,testResultId:this.testResultId});let N=await this.requestNewAppiumSessionFromTma(o,I,f);this.sessionData=N;let k=await m.attach({sessionId:N.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:k.sessionId,testResultId:this.testResultId,nativeAppMetadata:f,sessionCaps:k.capabilities})}catch(x){throw Mr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({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=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Fp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await be(o)).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 i,o;try{let a=await Nt(n);await $s(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Up(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Np(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Q(),{sessionPlayer:o}=r,a=n||"runner";Z.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.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 i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var qb={};H(qb,{WorkerAppium:()=>jp});var Hb,Nr,jp,zb=w(()=>{"use strict";F();Lp();Hb=require("linkedom");Wn();W();kt();Mp();Te();Ca();ne();cs();Nr=C("worker-appium"),jp=class extends Ot{initPlayer(t){return new As(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n,a=this.options.projectData.type,l=await vt.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.uniqueId}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),g=await _b(u)):g=kb(u),Nr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Lb(g)});let h=this.getServerAddressFromGrid();this.activeSession=await o.remote(g),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let f=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(f),Nr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Nr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await t.getOrientation()}catch(i){Nr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&bg(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){Nr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:i,directConnectPath:o}=t;if(r&&n&&i&&o)return`${r}://${n}:${i}${o}`}async runTestOnce(t,r){var g,h;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Q(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((g=this.testRunConfig.mobile)==null?void 0:g.staticAllocation.deviceUdid),{protocol:y,hostname:T,port:R,path:b}=await vt.getHeadSpinDeviceConnection(this.options.gridData,f);d=`${y}://${T}:${R}${b}`}else d=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Hb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let f=await new Promise((T,R)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:T,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(R)});return this.stopKeepAlive(),await o.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw Nr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),this.stopKeepAlive(),f}};try{return await super.runTestOnce(t,r),await oe(u(),c)}catch(f){throw Nr.error("failed to run test once",{err:f}),f}}}});var Na,Kb=w(()=>{"use strict";F();Nn();J();Na=class{constructor(e){this.id=e;this.driver=new Cr}async onDone(){try{await oe(this.driver.end(),12e4)}catch(t){t instanceof ie&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Jb,Ua,Yb=w(()=>{"use strict";Jb=S(require("ws"));F();Ua=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 Jb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),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 i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ba,$p,Fa,Xb=w(()=>{"use strict";F();Ba=S(require("chrome-launcher"));zu();Yb();fn();$p=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ua}async init(e){var h,f,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=No({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(f=m.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ba.Launcher.defaultFlags().filter(R=>R!=="--disable-extensions")];this.chrome=await Ba.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await hr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),rs(()=>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}},Fa=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new $p(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Wp={};H(Wp,{WorkerExtension:()=>Xn});function kI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Qb(s){return kI(s)?s:new Error(s)}var ut,Xn,ja=w(()=>{"use strict";We();J();Wn();F();W();kt();ne();Kb();Xb();it();ut=C("worker-ext"),Xn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new Fa(this.id):new Na(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.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:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Vi(),initializedFromCache:Gi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.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 i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;U("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await oe(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ie))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 g=await d.url(m);return u.driverUrlFinished=!0,g}catch(g){throw ut.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),g}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var g;if(U("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await o(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();Z.onWaitToTestStart(this.id);try{await oe(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ie))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let f=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Gs.BROWSER_CLOSED,f.abort(T)};m.registerToClosedBrowser(y);try{let T=oe(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),R=await hc(T,f.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(E){ut.error("Could not update the grid about the test status",{err:E})}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:i}),Qb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Qb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Gp={};H(Gp,{WorkerExtensionSingleBrowser:()=>Vp});var _I,OI,Vp,Hp=w(()=>{"use strict";We();F();W();lp();kt();ja();_I=C("base-worker"),OI=500,Vp=class extends Xn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(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,i){return Z.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(_I.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 i=this.handleQuarantine(t);if(i)return i;U("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.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 ce(OI)}}});var qp,$a,Zb=w(()=>{"use strict";Nn();pe();We();Fu();it();Qu();J();W();ne();Yh();eo();qp=C("worker-manager"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Gb(),Vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(zb(),qb))).WorkerAppium;default:return Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension}else switch(r){case(Er.find(n=>n===r)&&Un.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Hp(),Gp))).WorkerExtensionSingleBrowser;case Er.find(n=>n===r):return(await Promise.resolve().then(()=>(ja(),Wp))).WorkerExtension;case bn.find(n=>n===r):return(await Promise.resolve().then(()=>(kp(),Pp))).WorkerSelenium;default:throw new A(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return U("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{U("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,g)=>new Promise(h=>{var de,Lt,St,Ur,P,M,j,z;let f=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Go(r,n,e,i,o,t),this.combinedTestResults={};let T=((de=i.company)==null?void 0:de.ucid)||"",R=(Lt=i.company)==null?void 0:Lt.companyId,b=(St=i.company)==null?void 0:St.name,v=i.source||"cli",E=i.user,x=(Ur=i.company)==null?void 0:Ur.planType,D=(P=i.company)==null?void 0:P.isStartUp,I=(M=i.projectData)==null?void 0:M.name,N=(j=i.projectData)==null?void 0:j.type,k=i.lightweightMode,_=(z=i.gridData)==null?void 0:z.type,$=(Pe,Et,we,za,Zn,Ka)=>(d++,Og({executionId:r,projectId:f,testId:Et,resultId:we,ucid:T,companyId:R,companyName:b,projectName:I,companyPlan:x,source:v,user:E,lightweightMode:k,isStartUp:D,projectType:N,appSource:Ka,gridType:_}),t.testStartAndReport(Pe,r,we,za,Zn)),V=async(Pe,Et,we,za,Zn,Ka)=>{var ed,td,rd;d--;let et={...(k==null?void 0:k.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...i.host&&{gridHost:i.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((ed=i.gridData)==null?void 0:ed.name),et.gridType=(td=i.gridData)==null?void 0:td.type,et.gridProvider=(rd=i.gridData)==null?void 0:rd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,we,r,za,Zn,et).catch(CT=>qp.error("testEndAndReport threw an error",{err:CT})),Zn)return;this.combinedTestResults[we.resultId]=we,Lg({executionId:r,projectId:f,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:R,companyName:b,projectName:I,companyPlan:x,source:v,user:E,lightweightMode:k,logger:qp,isStartUp:D,projectType:N,appSource:Ka}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},te=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:$i(),authData:wr(),token:u,userAccessKey:g},projectId:i.project,company:i.company,servicesUrl:fe},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,$,V,te,Y)});try{let u=await xt(),g=await Wi(),h=await m(u,g);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw qp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Qn,Wa,zp,Va,eT=w(()=>{"use strict";Qn=S(require("lodash"));F();W();pe();ne();We();os();vu();Fu();he();kt();eh();J();Zb();eo();({CLI_MODE:Wa}=Ut),zp=C("test-plan-runner"),Va=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new $a(this.customExtensionLocalLocation),m=async()=>{let f=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,f,y);Object.assign(c,T)},u=async()=>{let f=pi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,f,y);U("right after this.workerManager.runTests"),Object.assign(c,T)},g=async()=>{let f=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,f,y);Object.assign(c,T)};Dg({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await g(),c}catch(f){if(zp.error("error running test plan",{err:f}),f instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw f}finally{await h()}async function h(){var y,T,R,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Wa.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),er)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(o,E);return}let f;try{if(!((b=(R=(T=i.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(f=await kl(i.project),Qn.default.isEmpty(f)||!o))return;let{runKey:v,url:E}=f;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,v,E;let c=se(),d=n.project;pc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Do(m,n,o,a),g=Qn.default.chain(m).map(x=>{var D;return((D=x.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(g==null?void 0:g.length)===1?g[0]:null,f=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,f);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),U("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(c),U("after executionEnd"),{results:R,executionId:c,testPlanName:i,configName:h}}async runTestPlans(e,t){zp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Qn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a=await ml(o,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new A(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new A(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Wa.APPIUM&&await Ql(e,r(c)),await ae(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 pg(e,d);let g=u.overrideExecutionName||d.name;return await ae(c[m],async f=>{let y=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,u,g,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Xl(n[m][E])})),R=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,x)=>Object.assign(E,x),{}),b=Xl(R);Object.assign(i,R);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await ul(o,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;zp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await wf(e,t);if(U("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new A("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new A("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new A("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;U("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Wa.APPIUM&&(a=await pn({appId:e.appId,projectId:e.project})),await ae(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!==Wa.APPIUM&&await Ql(e,c),U("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return U("right after runTestPlan"),await Z.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=Cn(),r=[];qs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Qn.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}}});var nT={};H(nT,{init:()=>tR,run:()=>YI});async function LI(s){let e=s.project,t=await gl(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"),hn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ns}function DI(s,e){var i,o,a,l,c,d,m,u;let t=Ii(e.activePlan),r=s.parallel;if(t==="free"&&r>rT)throw new A(`The free plan allows only ${rT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let g=(o=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:o.tunnel;if(s.tunnel&&!g)throw new A("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 h=(l=(a=e.activePlan)==null?void 0:a.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!h&&(console.warn(`
410
410
  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&&((c=s.gridData)==null?void 0:c.type)===L.TESTIM_TVC){let g=e.tvcLicense.expireAt||1;if(Date.now()>g&&!e.churnedByL2C)throw new A("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let h=Number(e.tvcLicense.maxParallel);if(r>h)throw new A(`Your license allows only ${h} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((d=s.gridData)==null?void 0:d.type)===L.TESTIM_TDC){let g=e.tdcLicense.expireAt||1;if(Date.now()>g)throw new A("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){let g=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>g)throw new A(`Retention days (${n}) cannot be greater than the company's retention days (${g}). Run aborted`)}if(Jt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let g=e.tvcLicense,h=e.tdcLicense;if(g!=null&&g.isPaid||h!=null&&h.isPaid)return;let f=e==null?void 0:e.createdAt;if(new Date(f)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let T=s.retries;T&&T>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function MI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await LI(s)}catch(t){if([A,Ns].some(r=>t instanceof r))throw t;Kp.error("could not validate cli account",{err:t})}}function NI(s){let e=wr();return mf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function UI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>($o(),jh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Wo(),Vh));r.init(s)}}function FI(s,e){let{branch:t,autoDetect:r}=s;if(Tg(e,r),!e&&!r)throw new A(`branch ${t} does not exist, run aborted.`)}async function BI(s,e){let{id:t,type:r}=e,i=sT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=Cn();i&&(s.sfdcCredential=await cl({projectId:t,branch:o}))}function jI(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ii(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<tT?tT:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),Pt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function $I(s,e){s.editorUrl=Ls||e.editorUrl}function WI(s,e){s.allGrids=e}function VI(s,e){s.authData=e}function GI(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function HI(s){var e;s.gridData=await dg(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function qI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}function zI(s,e){s.getBrowserRetries=["android","ios"].includes(e.type||"")?1:s.getBrowserRetries}async function KI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await ef(s.overrideMappingFile))}async function JI(s,e){U("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await $f(),U("in runner.js after checkNpmVersion"),await MI(s),U("in runRunner before tunnel.connect"),await fo(s),U("in runRunner after tunnel.connect");let a=await new Va(e).run(s);return U("before tunnel.disconnect"),await go(s),await ZI(s.slotService,t,s.company.companyId),U("after tunnel.disconnect and gridService.keepAlive.end"),a}function XI(s){var e;Pt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
411
411
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
412
412
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m