@testim/testim-cli 4.121.0 → 4.122.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
@@ -215,7 +215,7 @@ ${r.stdoutResult}`:n)}},go=async s=>{if(s.tunnel)try{ng(s)?await re.disconnectTu
215
215
  });
216
216
  })();
217
217
  `,u=[],g=new Ah.Worker(m,{eval:!0});try{return await oe(new Promise(h=>{g.on("message",f=>{if(f.action==="finish"){let{data:y}=f,T={...y,tstConsoleLogs:u};lt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else f.action==="progress"&&u.push(f.data)}).on("error",f=>{f.message==="malformed data: URI"?lt.error("Run code worker error",{err:f,transactionId:s,fileDataUrl:o}):lt.error("Run code worker error",{err:f,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:f==null?void 0:f.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{lt.debug("Run code worker has been terminated",{transactionId:s})}),g.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ie))throw h;return lt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{g==null||g.terminate()}}async function cE(s){try{await Eh.promises.rm(s,{recursive:!0,force:!0})}catch(e){lt.warn("failed to remove install npm packages folder",{err:e})}}function xh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function fs(s,e,t,r,n,i){let o=xh(n,e,s,t),{data:a}=await lE(o,r,i);return a}async function gs(s,e,t,r,n,i,o,a,l,c){var f;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((f=t.nodePackageParams)==null?void 0:f.map(y=>{if(d){let T=Im(y.testimPackageLocalLocation);return[y.paramName,ms.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=xh(o,n,e,i);if(c){let y=await un(c);y&&(l=y)}Buffer.isBuffer(l)&&(lt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let g="data:,";return l==="data:"&&(lt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=g),{...await aE(u,t,r,s,m,a,l),nodeVersion:process.version}}async function lE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Ch(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:ms.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Rm(o,r,a,t),lt.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=Sm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ms.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw lt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await oe(l(),t)}catch(c){throw c instanceof ie&&lt.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Ch(){return ms.join(Ih.tmpdir(),"/testim_local_packages")}function uE(){let s=Ch();return cE(s)}var Eh,Ih,ms,Rh,Ah,lt,hs=w(()=>{"use strict";Eh=S(require("fs")),Ih=S(require("os")),ms=S(require("path"));F();Qr();Rh=S(require("data-uri-to-buffer")),Ah=require("worker_threads");J();W();he();Qr();le();lt=C("cli-service");uE().catch(s=>lt.warn("failed to clean local package folder",{err:s}))});var or={};H(or,{run:()=>dE});function pE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var dE,Ph=w(()=>{"use strict";hs();J();le();dE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let g=await gs(r,n,i,o,a,l,c,d,m,u);return g&&pE({result:g.result,tstConsoleLogs:g.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:g,success:!0}}catch(g){throw g instanceof ie?new Error("Timeout while running action"):g}}});var Zu={};H(Zu,{run:()=>mE});var mE,kh=w(()=>{"use strict";hs();J();mE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await fs(t,r,n,o,i,a),success:!0}}catch(l){if(l instanceof Rt)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ie)return{success:!1,code:"timeout"};throw l}}});async function Oh(s,e,t,r){try{return await xl(s,e,t,r)}catch{Fo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function gE(s,e,t,r,n){return Fo.info("finished to run remote step",{stepId:t,sessionId:n}),await Oh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function _h(s,e,t,r,n){return Fo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Oh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function Lh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),l=t.id;Fo.info("start play remote step",{stepType:o,stepId:l,sessionId:a});let c=fE[o];if(!c)return await _h(n,r,l,`Failed to find step type ${o}`,a);try{let d=await c.run(e,t,i);return await gE(n,r,l,d,a)}catch(d){return await _h(n,r,l,d.message,a)}}var Fo,fE,Dh=w(()=>{"use strict";Ph();he();kh();W();Fo=C("step-playback"),fE={"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":or,"cli-download-code-step":or,"node-package":Zu}});var ep,Mh,Pr,yE,tp,Tt,Bo=w(()=>{"use strict";F();it();ep=S(require("ws")),Mh=require("events");W();pe();Pr=C("socket-service"),yE=5e3,tp=class extends Mh.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Pr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),yE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Pr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(pd);return xt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new ep.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Pr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Pr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===ep.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Pr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Pr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Pr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(l){n(l)&&i(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=o.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=se(),l={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",c=>c.id===a,o),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},Tt=new tp});var Uh,rp,bE,TE,wE,Nh,jo,ys,sp=w(()=>{"use strict";Uh=S(require("p-retry")),rp=S(require("socket.io-client"));pe();F();W();bE=50,TE=10,wE=5e3,Nh=10*1e3,jo=C("base socket service"),ys=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);jo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}jo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===TE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=bE)throw new Error(`Can't connect to Testim Servers.
218
- Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{jo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Nh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Nh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Uh.default)(()=>oe(n(),wE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&jo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Fh={};H(Fh,{remoteStepServiceSocketIO:()=>vE});var np,vE,Bh=w(()=>{"use strict";sp();np=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},vE=new np});var jh={};H(jh,{remoteStepService:()=>bs});var ip,Bn,op,bs,$o=w(()=>{"use strict";Bo();ne();le();({REMOTE_STEP_SAVED:ip}=At),op=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Bn=(await Promise.resolve().then(()=>(Bh(),Fh))).remoteStepServiceSocketIO,Bn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[ip]):Bn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[ip],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Bn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[ip]),Promise.resolve()):Bn.unlistenToRemoteStep(e)}},bs=new op});var ap,kr,$h=w(()=>{"use strict";sp();ap=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},kr=new ap});var Vh={};H(Vh,{testResultService:()=>_t});var Wh,cp,_t,Wo=w(()=>{"use strict";Wh=require("events");Bo();ne();le();$h();cp=class extends Wh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new cp});var Hh,qh,zh,ve,SE,Kh,Gh,Vo,Jh=w(()=>{"use strict";Hh=S(require("lodash"));F();pe();We();ss();it();he();Dh();qh=S(require("p-retry")),zh=require("url");W();oo();us();ne();$o();Wo();ve=C("test-run-handler"),SE=3,Kh=20*1e3,Gh=s=>JSON.stringify(s).length<Kh,Vo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Rr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ks(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return zs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?wi.FROM_DEVICE:wi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:$i(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:yd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Wi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Gh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Kh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await wn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Gh(e))return;let r=async()=>{try{return await Cl(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Al(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(o=>o.type==="background_page"&&r.includes(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("before Runtime.evaluate"),await(0,qh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),U("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new zh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Sr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Hh.debounce(async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)_t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await hl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Lh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:SE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Go,Yh=w(()=>{"use strict";Jh();Go=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Vo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var EE,IE,RE,jn,lp=w(()=>{"use strict";os();cs();W();EE=C("worker-utils"),IE=async(s,e,t)=>{e&&await Tu(s,t)},RE=async(s,e,t)=>{await wu(s,e,t)},jn=async(s,e,t,r,n,i)=>{EE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await IE(s,e,t),n==="redis"&&await RE(s,r,t)}}});function PE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,Zh,zo,dp,ey,wt,Xh,Qh,up,$n,AE,pp,xE,ar,CE,Ho,kE,Ot,Wn=w(()=>{"use strict";qo=S(require("ms")),Zh=S(require("lodash")),zo=S(require("p-retry")),dp=S(require("dayjs")),ey=S(require("dayjs/plugin/duration"));F();We();os();cs();he();W();lp();kt();po();le();$o();Wo();it();Ge();ne();J();dp.default.extend(ey.default);wt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Xh,TEST_START_TIMEOUT_MSG:Qh,TEST_COMPLETE_TIMEOUT_MSG:up}=Fe,{SETUP_TIMEOUT:$n,NETWORK_ERROR:AE,GRID_ERROR:pp,BROWSER_CLOSED:xE,SELENIUM_ERROR:ar,UNKNOWN_ERROR:CE,MOBILE_SESSION_ERROR:Ho}=Gs;kE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await mg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,r,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=fr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=fr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(0,qo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,zo.default)(async()=>{let n=Date.now();try{return await oe(this.getSlotOnce(e),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await oe(yg(o,a,this.id),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,zo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await fg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,U("before getBrowserOnce");let g=await oe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Fe.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||g}catch(u){let g={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await jn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,$r].some(a=>o instanceof a)?o:o instanceof ze?new dr(o,pp):new dr(o,ar)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await jn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var g,h;let n=async(f,y)=>{var _,$;if(Xe(f,this.options)||Hr(O,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId,R=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof dr,v=y&&(R(Qh)||R(up)),D=O.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&e.isSeleniumHubNoMatchSessionError(f.reason)&&!e.ignoreSeleniumHubError,I=v&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!v,k=!f.success&&(N||I||D);try{let V=e.retryKey;f.testRetryKey=V;let Y=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,T,k,Y),await this.runTestCleanup(),k){if(I&&await e.startNewTimeoutRetry(),D){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:e.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let te=($=this.options.projectData)==null?void 0:$.projectId,de=e.testResultId,Lt=e.testId;await Ki(te,de,Lt,{show:!1}),e.decreaseSeleniumHubRetry(),e.decreaseRetryCount(),await e.startNewRetry()}return N&&!D&&!I&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof qt)return;wt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
218
+ Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{jo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:Nh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:Nh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=rp.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,Uh.default)(()=>oe(n(),wE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&jo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Fh={};H(Fh,{remoteStepServiceSocketIO:()=>vE});var np,vE,Bh=w(()=>{"use strict";sp();np=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},vE=new np});var jh={};H(jh,{remoteStepService:()=>bs});var ip,Bn,op,bs,$o=w(()=>{"use strict";Bo();ne();le();({REMOTE_STEP_SAVED:ip}=At),op=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Bn=(await Promise.resolve().then(()=>(Bh(),Fh))).remoteStepServiceSocketIO,Bn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:remoteStep`,{resultId:e},[ip]):Bn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:remoteStep`,[ip],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Bn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(Tt.removeFilter(`${e}:remoteStep`,[ip]),Promise.resolve()):Bn.unlistenToRemoteStep(e)}},bs=new op});var ap,kr,$h=w(()=>{"use strict";sp();ap=class extends ys{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},kr=new ap});var Vh={};H(Vh,{testResultService:()=>_t});var Wh,cp,_t,Wo=w(()=>{"use strict";Wh=require("events");Bo();ne();le();$h();cp=class extends Wh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){Tt.onConnect=()=>this.emit("socket-connected");return}kr.init(e),kr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?Tt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]):kr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){Tt.removeFilter(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED]);return}await kr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){Tt.listenTo(`${e}:testResult`,[At.TEST_RESULT_UPDATED,At.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}kr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return kr.getSocket()}},_t=new cp});var Hh,qh,zh,ve,SE,Kh,Gh,Vo,Jh=w(()=>{"use strict";Hh=S(require("lodash"));F();pe();We();ss();it();he();Dh();qh=S(require("p-retry")),zh=require("url");W();oo();us();ne();$o();Wo();ve=C("test-run-handler"),SE=3,Kh=20*1e3,Gh=s=>JSON.stringify(s).length<Kh,Vo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new Rr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?Ks(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return zs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Gr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?wi.FROM_DEVICE:wi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await xt(),refreshToken:$i(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:yd,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Wi()};if(this._options.disableMockNetwork&&yt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Gh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,l=this.testId;o?(Object.assign(t,{runData:i}),ve.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):ve.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Kh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await wn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return ve.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Gh(e))return;let r=async()=>{try{return await Cl(this._options.project,this._testId,this._testResultId,e)}catch(o){return ve.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Al(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){U("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"],{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.includes(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{U("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=o||{};U("before Runtime.evaluate"),await(0,qh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),U("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return U("after Runtime.evaluate"),c.value}catch(o){throw ve.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new zh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){ve.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(i.reason)&&(ve.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(o,3e3)}catch(m){ve.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else _t.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Sr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return ve.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw ve.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}catch(i){throw ve.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Fe.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await _t.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){ve.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||_t.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){ve.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Hh.debounce(async()=>{try{await _t.joinToTestResult(this._testResultId,this.testId)}catch(o){ve.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(ve.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(ve.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return ve.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)_t.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await hl(this._testResultId,this._options.project,this.retryKey);a?await e()||(ve.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){ve.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&_t.off("socket-connected",e)}}listenToRemoteStep(e){bs.listenToRemoteStep(this.testResultId,t=>{Lh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:SE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Go,Yh=w(()=>{"use strict";Jh();Go=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Vo(e,t,l,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var EE,IE,RE,jn,lp=w(()=>{"use strict";os();cs();W();EE=C("worker-utils"),IE=async(s,e,t)=>{e&&await Tu(s,t)},RE=async(s,e,t)=>{await wu(s,e,t)},jn=async(s,e,t,r,n,i)=>{EE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await IE(s,e,t),n==="redis"&&await RE(s,r,t)}}});function PE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,Zh,zo,dp,ey,wt,Xh,Qh,up,$n,AE,pp,xE,ar,CE,Ho,kE,Ot,Wn=w(()=>{"use strict";qo=S(require("ms")),Zh=S(require("lodash")),zo=S(require("p-retry")),dp=S(require("dayjs")),ey=S(require("dayjs/plugin/duration"));F();We();os();cs();he();W();lp();kt();po();le();$o();Wo();it();Ge();ne();J();dp.default.extend(ey.default);wt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Xh,TEST_START_TIMEOUT_MSG:Qh,TEST_COMPLETE_TIMEOUT_MSG:up}=Fe,{SETUP_TIMEOUT:$n,NETWORK_ERROR:AE,GRID_ERROR:pp,BROWSER_CLOSED:xE,SELENIUM_ERROR:ar,UNKNOWN_ERROR:CE,MOBILE_SESSION_ERROR:Ho}=Gs;kE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Ot=class{constructor(e,t,r,n,i,o,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.lambdatestService=new re;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await mg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Us(!0)}async getBrowserOnce(e,t,r,n){throw new Us(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),wt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Hr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:me.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN,n=fr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=fr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===L.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(0,qo.default)("1m")}getSessionTimeout(){if(Jt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,zo.default)(async()=>{let n=Date.now();try{return await oe(this.getSlotOnce(e),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await oe(yg(o,a,this.id),this.options.getBrowserTimeout,Fe.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof zt?wt.info("could not get grid slot due to concurrency issue",r):wt.error("error getting grid slot",{error:e,...r}),await ce(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{U("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);U("before getBrowserOnce retries");let l=this.options.getBrowserRetries-o;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,zo.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await fg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c,U("before getBrowserOnce");let g=await oe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Fe.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||g}catch(u){let g={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===q.APPIUM?"device":"browser";throw wt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:g,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof It)&&this.options.mode!==q.APPIUM&&await ce(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await jn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[It,$r].some(a=>o instanceof a)?o:o instanceof ze?new dr(o,pp):new dr(o,ar)}return n}async runTest(e,t,r){var d;U("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Jt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await xt(),await this.runTestOnce(e,c)}finally{await jn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var g,h;let n=async(f,y)=>{var _,$;if(Xe(f,this.options)||Hr(O,(_=this.options.gridData)==null?void 0:_.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId,R=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof dr,v=y&&(R(Qh)||R(up)),D=O.flags.retryOnSeleniumHubError.isEnabled()&&!!f.reason&&e.isSeleniumHubNoMatchSessionError(f.reason)&&!e.ignoreSeleniumHubError,I=v&&e.hasMoreTimeoutRetries(),N=e.hasMoreRetries()&&!b&&!v,k=!f.success&&(N||I||D);try{let V=e.retryKey;f.testRetryKey=V;let Y=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,f,T,k,Y),await this.runTestCleanup(),k){if(I&&await e.startNewTimeoutRetry(),D){wt.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:e.testId,retryReason:f.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let te=($=this.options.projectData)==null?void 0:$.projectId,de=e.testResultId,Lt=e.testId;await Ki(te,de,Lt,{show:!1}),e.decreaseSeleniumHubRetry(),e.decreaseRetryCount(),await e.startNewRetry()}return N&&!D&&!I&&await e.startNewRetry(),wt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(k)}t(this.id,...r);return}catch(V){if(V instanceof qt)return;wt.error("failed to process test result",{error:V}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
219
219
  Please make sure the CLI has stable access to the internet. ${Ic()?"(Internal: network connectivity test failed)":""}`,o=f=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:R,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:v}=_c,E=f instanceof Error?f.message:f;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Xh)||E.includes(b)?{errorType:$n,reason:"timeout while getting device"}:E.includes(T)||E.includes(v)?{errorType:Ho,reason:"app doesn't exist on device"}:E.includes(R)?{errorType:Ho,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Ho,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ho,reason:E}},a=(f,y)=>{let T=this.options.mode===q.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:AE,reason:i()};let R=f instanceof Error?f.message:f;if(R.includes(Xh))return{errorType:$n,reason:`Test couldn't get ${T}`};if(R.includes(Qh))return{errorType:$n,reason:"Test couldn't be started"};if(R.includes(up)){if(!this.testRunTimeout)return{errorType:$n,reason:"Test timeout reached: test is too long"};let b=dp.default.duration({milliseconds:this.testRunTimeout}),v=Math.floor(b.asMinutes()),E=b.asSeconds(),x=v>0?` ${v} min`:"",D=E>0?` ${E} sec`:"";return{errorType:$n,reason:`Test timeout reached (timeout:${x}${D}): test is too long`}}if(f instanceof dr&&f.type){if(f.type===pp)return{errorType:pp,reason:`Test couldn't get ${T} from grid - ${f.message}`};if(f.type===ar)return{errorType:ar,reason:`Failed to create new session - ${f.message}`}}return"type"in f&&f.type===xE?{errorType:ar,reason:`Session terminated, this is often caused to connection
220
220
  problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(f.message)||/Couldn't connect to selenium server/.test(f.message)?{errorType:ar,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(f.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(f.message)?{errorType:ar,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(f.message)?{errorType:ar,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:CE,reason:R}},l=async f=>{var v;let y=await Ec();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),wt.warn("error on run",{err:f});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===q.APPIUM?o(f):a(f,y);Ki(T,this.testResultId,this.testId,{status:Vs.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:e.retryKey,setupStepResult:{status:Vs.COMPLETED,success:!1,reason:b,errorType:R}},e.remoteRunId),await n(PE(this.testId,this.testName,this.testResultId,b),f)},c=async f=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return wt.warn("Test failed. Not enough data to recover results via API",{err:f}),l(f);try{let E=await Sr(y,T,R,b);if(wt.warn("Test failed. Got results via API",{err:f,testResult:Zh.default.omit(E,kE),resultId:T}),E&&E.status===Vs.COMPLETED&&!f.message.includes(up))return await n(E);throw f}catch(E){return E!==f&&wt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:E}),l(f)}},d=this.options.disableSockets||((g=this.options.lightweightMode)==null?void 0:g.disableResults)&&(this.options.useChromeLauncher||this.options.mode===q.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async f=>{try{await Promise.all([!m&&bs.joinToRemoteStep(this.testResultId),!d&&_t.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==q.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,f);await n(y),U("After onRunComplete"),t(this.id,...r)}catch(y){await c(y),t(this.id,...r)}finally{m||bs.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var mp,ty,Ts,fp=w(()=>{"use strict";F();mp=S(require("p-retry"));F();W();J();ty=C("window-utils"),Ts=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return ty.warn("selenium navigation failed. retrying to navigate",{err:i}),await ce(1500),r(n-1);throw!i.seleniumStack&&o&&ty.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ce(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ce(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await ce(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new It("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,mp.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,mp.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var gp,ws,hp=w(()=>{"use strict";W();gp=C("cookies-utils"),ws=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw gp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw gp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw gp.error("failed to remove cookie",{err:t}),t}}}});var yp,Ko,ry=w(()=>{"use strict";yp=S(require("p-retry")),Ko=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,yp.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,yp.default)(i,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function sy(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return _E.warn("missing elementRect",iy.omit(s,"image")),{};let{elementRect:o}=s,a=await vs.default.read(Buffer.from(n[1],"base64")),l=o.left*r+i.left*r,c=o.top*r+i.top*r,d=o.width*r,m=o.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,g=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>g&&(m=g-c),m<=0||d<=0)throw new bp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(vs.default.MIME_PNG)}}async function OE(s,e){let t=await vs.default.read(s.width,s.height);for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await vs.default.read(Buffer.from(i[1],"base64"));await new Promise((a,l)=>{t.composite(o,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(vs.default.MIME_PNG)}function LE(s,e){return OE(s,e)}async function DE(){}async function ME(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await DE(s[i]);return{key:i,url:o}}let r=await ae(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function ny(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var iy,vs,_E,bp,Jo,oy=w(()=>{"use strict";iy=S(require("lodash"));F();vs=S(require("jimp"));W();_E=C("image-capture-utils"),bp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Jo=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await sy(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:ny(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return ME({screenImage:t.image,absoluteScreenHighlight:ny(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>ce(250),i=Boolean(e);async function o(u,g){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),f=await sy({elementRect:g},h);return{position:{left:u.x+g.left,top:u.y+g.top},size:{width:g.width,height:g.height},image:f.elementImage}}async function a(u){let g=[];for(let h of u){let f=await o(h.scrollPos,h.cropData);g.push(f)}return g}function l(u,g){let h=Math.max(u.width,g.width),f=g.width,y=Math.max(u.height,g.height),T=g.height,R=Array.from({length:Math.ceil(h/f)},(v,E)=>({scrollX:Math.min(E*f,h-f),cropX:E*f-Math.min(E*f,h-f),cropW:f-(E*f-Math.min(E*f,h-f))})),b=Array.from({length:Math.ceil(y/T)},(v,E)=>({scrollY:Math.min(E*T,y-T),cropY:E*T-Math.min(E*T,y-T),cropH:T-(E*T-Math.min(E*T,y-T))}));return R.flatMap(v=>b.map(E=>({scrollPos:{x:v.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:v.cropX,width:v.cropW,height:E.cropH}})))}async function c(u,g){let h=await t.getCurrentScrollPosition(),f=l(u,g),y=await a(f);return await t.scrollToPosition(h),LE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var ay,cy,Yo,Xo,ly=w(()=>{"use strict";ay=S(require("p-retry")),cy=S(require("semver"));F();W();fp();ry();oy();Te();Yo=C("tab-service"),Xo=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Yo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=se();function l(c){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!c.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Ts(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Jo(t,a,new Ko(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Q(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),l=n(o),c=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Q();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(c=>i[c].url);if(this.exactUrlMatch(t,r,o))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,o,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Yo.error("failed to get url or title",{err:i})}}catch(n){Yo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await ce(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Yo.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ay.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=cy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Q();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let i=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var Tp,Qo,wp=w(()=>{"use strict";Tp=class{select(){return console.log(`
221
221
  internal error - cant use port selector in selenium!!!!
@@ -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,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},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`]:!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(`
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