@testim/testim-cli 4.155.0 → 4.156.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
@@ -1,6 +1,6 @@
1
1
  #! /usr/bin/env node
2
2
  "use strict";var KT=Object.create;var li=Object.defineProperty;var JT=Object.getOwnPropertyDescriptor;var YT=Object.getOwnPropertyNames;var XT=Object.getPrototypeOf,QT=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)li(s,t,{get:e[t],enumerable:!0})},yd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of YT(e))!QT.call(s,n)&&n!==t&&li(s,n,{get:()=>e[n],enumerable:!(r=JT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?KT(XT(s)):{},yd(e||!s||!s.__esModule?li(t,"default",{value:s,enumerable:!0}):t,s)),qe=s=>yd(li({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>U,measure:()=>ew});function U(...s){if(!Td)return;let e=Date.now();console.log(`${e-ZT} ${e-bd} `,...s),bd=e}function ew(s,e){if(!Td)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Td,ZT,bd,$e=v(()=>{"use strict";Td=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,ZT=Date.now(),bd=Date.now()});var qt,Hr=v(()=>{"use strict";qt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ze(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function uc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Le(s){let e=/^(https?:\/\/)/i,t=new RegExp("^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$","i");return e.test(s)||t.test(s)}var pc=v(()=>{"use strict"});var mc,wd,vd,yi=v(()=>{mc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"2.0.1"},wd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.2",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.0",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.44.1",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},vd={node:">= 18.0.0"}});var dr,sw,Sd,mr,Rt,nw,js,Ed,Id,bi,tt,Rd,he,xd,Ad,Ti,We,fc,Cd,wi,Pd,kd,qR,zR,Od,_d,$s,Ld,Dd,Nd,Md,gc,hc,yc,bc,Ud,Ws,Fd,Tc,Vs,ae=v(()=>{"use strict";dr=process.env.SERVICES_HOST||"https://services.testim.io",sw="https://testimstatic.blob.core.windows.net",Sd="https://tstresultfiles.azureedge.net",mr="https://app.testim.io";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:dr,dr=process.env.SERVICES_HOST);Rt=process.env.RUNNER_ENVIRONMENT||"production",nw={production:"",staging:".staging",development:".dev"},js=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${nw[Rt]}.testim.io`,Ed=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Id=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),bi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),tt=process.env.EDITOR_URL,Rd=process.env.WEBSOCKET_HOST||`${dr}/ws`,he=()=>dr,xd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Ad=parseInt(process.env.LOGGER_DEBUG||"0",10),Ti=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),fc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Cd=parseInt(process.env.DEBUG_MODE||"0",10),wi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,Pd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",kd=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",qR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),zR=process.env.APPIUM_VERSION||"1.10.1",Od=process.env.GATEWAY_URL,_d=()=>process.env.EXTENSION_SERVICES_HOST||dr,$s=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:sw,Ld=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Sd,Dd=Sd,Nd=5*60*1e3,Md=40,gc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",hc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",yc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",bc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Ud=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Ws=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Fd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Tc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Vs=s=>{dr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:dr}});var Bd,vi,jd=v(()=>{"use strict";Bd=I(require("superagent"));ae();vi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=kd,this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=Bd.default.post(this.url).set("Content-Type","application/json; charset=UTF-8").set("Authorization",`Bearer ${this.token}`).send(e);this.proxy&&t.proxy(this.proxy),await t}catch{}}}});var Wd={};z(Wd,{CoralogixTransport:()=>wc});var $d,iw,ow,wc,Vd=v(()=>{"use strict";$d=I(require("winston-transport"));jd();iw={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},ow=["err","error","reason","e"],wc=class extends $d.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new vi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},d={severity:iw[i],text:o,category:n||this.category};l.className&&(d.className=l.className),l.methodName&&(d.methodName=l.methodName),l.threadId&&(d.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let m=!1;a instanceof Error&&(m=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
- ${l.msg}`));for(let u of ow)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(o&&!m&&(l.msg=o),d.text=JSON.stringify(l)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function lw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Vd(),qe(Wd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(xd){let r={depth:5,colors:!0};s.push(new ft.transports.Console({format:ft.format.combine(ft.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),ft.format.timestamp({format:"HH:mm:ss:SSS"}),ft.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ei.inspect(n.meta,r)}`))}))}return[s,e,t]}function Yd(s){vc=s}function Xd(s){Jd=s}function Qd(s){We||!s||dw(s)}function Hd(s){return{projectId:Jd,time:new Date().toISOString(),...vc&&!s&&{executionId:vc}}}function C(s){return new Sc(gw.child({category:s}))}var qd,ft,Ei,Si,zd,aw,cw,Gd,Kd,uw,pw,dw,mw,fw,gw,vc,Jd,Sc,$=v(()=>{"use strict";qd=I(require("node:os")),ft=I(require("winston"));ae();Ei=I(require("node:util")),Si=I(require("chalk")),zd=I(require("dayjs"));B();aw=qd.hostname(),cw=rt();Gd={depth:5,colors:!0},Kd=(s,e,t)=>{let r=`[${(0,zd.default)().format("HH:mm:ss:SSS")}]`,n=Ei.inspect(e,Gd),i=Ei.inspect(t,Gd);return`${Si.default.white(r)} ${Si.default.reset()}SessionPlayer-${Si.default.red(s)} ${n} ${i}`},[uw,pw,dw]=lw(),mw=Ad?"debug":"info",fw={release:Boolean(!1),branch:"runner-v4.155.0"},gw=ft.createLogger({levels:ft.config.syslog.levels,level:mw,transports:uw,defaultMeta:{name:"runner",hostname:aw,nodeVersion:process.version,runnerVersion:cw,...fw}}),vc=null,Jd=null;Sc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Hd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Hd(n)})}catch{}}}waitForFlush(){return pw()}}});var Ai,qr,A,zt,fr,xt,Ii,zr,ce,Gs,st,Kt,At,Ri,Kr,xi,Hs,X=v(()=>{"use strict";Ai=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},A=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},zt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},xt=class extends Ai.AbortError{},Ii=class extends Ai.AbortError{},zr=class extends Ai.AbortError{},ce=class extends Error{},Gs=class extends Error{},st=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Kt=class extends st{constructor(){super(...arguments);this.name="GridConcurrencyError"}},At=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Ri=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},xi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Hs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ec(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ue(s){return(0,tm.setTimeout)(s)}function Ic(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function pe(s,e,t="Timeout Error"){bi&&!Zd&&(Zd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=bi?Number(bi)||6e5:e,Promise.race([s,ue(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){em||=(await import("p-limit")).default;let r=em(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Jt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var tm,Zd,em,Rc=v(()=>{"use strict";tm=require("timers/promises");X();ae();Zd=!1});var zs,rm,yw,qs,sm,bw,Tw,nm,im=v(()=>{"use strict";zs=I(require("lodash"));ae();rm=require("dns");$();Rc();yw=C("http-request-counters"),qs=!1,sm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>rm.promises.lookup(t)));return e||(qs=!0),e}catch{return yw.error("network connectivity test failed"),qs=!0,!1}},bw=zs.throttle(sm,10*1e3),Tw=60*1e3*15,nm=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},Tw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),qs||bw(),a}}}async function r(){if(qs||!await sm())return!1;let n=zs.sum([...s.fail.values()]),i=zs.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>qs,t}});var Ke={};z(Ke,{deleteReq:()=>Ks,didNetworkConnectivityTestFail:()=>_c,download:()=>kc,get:()=>Te,getFullRes:()=>Iw,getText:()=>Ys,head:()=>Rw,isNetworkHealthy:()=>Oc,post:()=>Ve,postForm:()=>Js,postText:()=>Cc,put:()=>Pc});function vw(){return global.caFileContent}function Sw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Ew(){return!gt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(gt.default),global.proxyUri}function gr(s,e=!1){let t=vw();t&&s.ca(t);let r=!e&&Ew();r&&s.proxy(r)}async function om(s,e,t={},r=Jr,n=0){let i=gt.default.post(s).send(e).timeout(r).set(t);gr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Ac(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=gt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),gr(o,i),await o}var gt,xc,nt,Jr,ww,Ut,Ks,Ve,Js,Ys,Cc,Te,Iw,Rw,Pc,kc,Oc,_c,Ge=v(()=>{"use strict";gt=I(require("superagent"));$();im();xc=C("http-request"),nt=nm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ww=6e4;Ut=(s,e,t)=>{let r=e.response;e.response instanceof gt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw xc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ks=nt(async(s,e={},t={},r=Jr)=>{try{let n=gt.default.delete(s).send(e).timeout(r).set(t);gr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Ut("failed to delete request",n,{url:s})}}),Ve=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await om(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Ut("failed to post request",i,{url:s})}});Js=nt(async(s,e,t,r={},n=Jr)=>{let i=gt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),gr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Ut("failed to post request",o,{url:s})}});Ys=nt(async(s,e,t)=>{try{return(await Ac(s,e,t)).text}catch(r){return Ut("failed to getText request",r,{url:s,query:e})}}),Cc=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await om(s,e,t,r,n)).text}catch(i){return Ut("failed to post request",i,{url:s})}}),Te=nt(async(s,e,t,r,n)=>{try{return(await Ac(s,e,t,r,n)).body}catch(i){return Ut("failed to get request",i,{url:s,query:e})}}),Iw=nt((s,e,t,r)=>Ac(s,e,t,r)),Rw=nt(async s=>{let e=gt.default.head(s).timeout(Jr);gr(e);try{return await e}catch(t){return Ut("failed to head request",t,{url:s})}}),Pc=nt(async(s,e,t={},r=Jr)=>{let n=gt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(i){return Ut("failed to put request",i,{url:s})}}),kc=nt(async s=>{xc.info("start to download",{url:s});let e=gt.default.get(s).set("User-Agent","Testim.io").timeout(ww).buffer(!0).parse(Sw);gr(e);try{let t=await e;return xc.info("finished to download",{url:s}),t}catch(t){return Ut("failed to download",t,{url:s})}}),Oc=nt.isNetworkHealthy,_c=nt.didNetworkConnectivityTestFail});function ht(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Ft.resolve(__dirname,"../../"):s=Ft.resolve(__dirname,""),s):process.cwd()}function Ci(s,e){return Le(s)?e||Ft.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Ft.basename(s)}function rt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Nc(){try{return vd.node}catch{return""}}async function lm(s,e,t=!0){let r=await it.promises.readdir(s,{withFileTypes:!0});await it.promises.mkdir(e,{recursive:t});for(let n of r){let i=Ft.join(s,n.name),o=Ft.join(e,n.name);n.isDirectory()?await lm(i,o):await it.promises.copyFile(i,o)}}async function ye(s){try{return await it.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Ft,am,cm,it,xw,Bt,Je,Pi,Lc,ot,Dc,um=v(()=>{"use strict";Ft=I(require("node:path"));pc();yi();am=I(require("unzip-stream")),cm=I(require("p-retry")),it=require("node:fs"),xw=3;Bt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,cm.default)(()=>e.download(s),{retries:xw,factor:1})},Je=async(s,e)=>{let t=await Bt(s);return it.promises.writeFile(e,t.body)};Pi=async(s,e)=>{let t=Ci(s,e);return Le(s)?Je(s,t):it.promises.copyFile(s,t)},Lc=async s=>Le(s)?Bt(s):it.promises.readFile(s),ot=async(s,e)=>(0,it.createReadStream)(s).pipe(am.Extract({path:e})),Dc=s=>(0,it.statSync)(s).size/1e6});var jt={};z(jt,{APPIUM_SESSION_MESSAGE:()=>jc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>ki,MOBILE_RUN_SKIP_REASON:()=>Bc,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>$c,gridMessages:()=>yt,gridTypes:()=>_,mobileWeb:()=>Uc,runnerStatus:()=>Mc,runnerTestStatus:()=>fe,socketEventTypes:()=>Ct,stepResult:()=>Qs,test:()=>Fc,testRunStatus:()=>Xs,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,Xs,Mc,fe,Ye,yt,Uc,Fc,Ct,K,_,Qs,ki,Bc,jc,$c,Yr,oe=v(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Xs={COMPLETED:"completed"},Mc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},yt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Uc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Fc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Ct={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Qs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},ki={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Bc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},jc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},$c="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"}});function Zs(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Aw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var en,pm,Xe,Cw,Pw,kw,Ow,_w,Wc,Vc,dm=v(()=>{"use strict";oe();en=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},pm=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!pm(e)&&!e.runQuarantinedTests;Cw=s=>Boolean(s.loginMode),Pw=s=>Boolean(s.tunnelOnlyMode),kw=s=>Boolean(s.createPrefechedData),Ow=s=>Boolean(s.installLazyDepsMode),_w=s=>Boolean(s.agentMode),Wc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Vc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function _i(s=0){return Oi.default.duration(s).format("HH:mm:ss.SSS")}function Gc(s=0){return Oi.default.duration(s).asSeconds()}var Oi,mm,fm=v(()=>{"use strict";Oi=I(require("dayjs")),mm=I(require("dayjs/plugin/duration"));Oi.default.extend(mm.default)});var tn,Xr,Yt,gm,Qr,hm=v(()=>{"use strict";oe();tn=s=>!(!s||"fileName"in s),Xr=(s,e)=>{if(e===_.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Yt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},gm=s=>s===_.TESTIM_TVC,Qr=(s,e)=>gm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Hc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var ym=v(()=>{"use strict"});var Y={};z(Y,{OSS:()=>Zr,TESTIM_BROWSER_DIR:()=>$t,buildBasicHeader:()=>uc,calcPercentile:()=>Ni,copyDir:()=>lm,delay:()=>ue,doesPathExist:()=>ye,download:()=>Bt,downloadAndSave:()=>Je,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>Aw,getBrowserInfo:()=>Dw,getCdpAddressForHost:()=>br,getCliLocation:()=>ht,getDuration:()=>_i,getDurationSec:()=>Gc,getEnginesVersion:()=>Nc,getEnvironmentGitBranch:()=>yr,getLinksFromUnescapeHTML:()=>nn,getLocalFileSizeInMB:()=>Dc,getMemorySnapshot:()=>Hc,getPlanType:()=>Di,getRunConfigByBrowserName:()=>rn,getRunnerVersion:()=>rt,getSource:()=>Pi,getSourceAsBuffer:()=>Lc,getSourcePath:()=>Ci,getTestUrl:()=>ze,getUniqBrowsers:()=>Zs,groupTestsByRetries:()=>zc,guid:()=>re,hasTestPlanFlag:()=>en,isAgentMode:()=>_w,isAppFromDevice:()=>tn,isAppFromDeviceDisabled:()=>Qr,isCreatePrefetchedDataMode:()=>kw,isInstallLazyDepsMode:()=>Ow,isLoginMode:()=>Cw,isMobileProject:()=>Yt,isPromise:()=>Ec,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>pm,isTestimVirtualGrid:()=>gm,isTunnelOnlyMode:()=>Pw,isURL:()=>Le,promiseAbort:()=>Ic,promiseFromCallback:()=>Jt,promiseMap:()=>se,promiseTimeout:()=>pe,removePropertyFromObject:()=>Li,replaceArgsWithNoDashes:()=>Wc,sanitizeNumberValue:()=>hr,shouldBlockVirtualIosBuild:()=>Xr,spreadObjectToArgs:()=>Vc,unescapeHTML:()=>sn,unzipFile:()=>ot});function hr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Dw(s){return s=s.toLowerCase(),qc.find(e=>e.browserValue===s)}function rn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=qc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||qc[0],n=Zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=Zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=Zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=Zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=Zr.find(i=>i.bs.platform===t.platform))),es.merge(r,n)}function yr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Li(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Li(s[r],e,t))}function De(s){return s.ELEMENT||s[qt]}function Di(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function zc(s=[]){return es.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=es.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function sn(s){return vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function nn(s){return[...vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function br(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var bm,es,Tm,wm,Lw,$t,Zr,qc,Ni,vm,B=v(()=>{"use strict";bm=I(require("os")),es=I(require("lodash")),Tm=I(require("path")),wm=require("linkedom");Hr();um();dm();fm();pc();Rc();hm();ym();Lw=bm.homedir(),$t=Tm.join(Lw,".testim-browser-profile"),Zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],qc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ni=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};vm=new wm.DOMParser});var Kc={};z(Kc,{$schema:()=>Nw,default:()=>jw,definitions:()=>Mw,properties:()=>Bw,required:()=>Fw,type:()=>Uw});var Nw,Mw,Uw,Fw,Bw,jw,Sm=v(()=>{Nw="http://json-schema.org/draft-07/schema#",Mw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Uw="object",Fw=["entries"],Bw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},jw={$schema:Nw,definitions:Mw,type:Uw,required:Fw,properties:Bw}});async function Pm(){try{return await pe(Mi.promises.readFile(ji()).then(async s=>{let e=await Cm;return Vw(e,s)}),3e4)}catch{return{}}}function Vw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=rs.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Pt(s,e,t=$w,r=void 0){return async()=>{if(!Rm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Yc(e);if(i)return on.debug("cache hit:",{fnName:e}),i;if(on.debug("cache miss:",{fnName:e}),!xm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Gw(e,o,t),o}}async function Yc(s){let t=(await $i)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Gw(s,e,t){if(Jc)throw on.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await $i;r[s]={value:e,expiry:Date.now()+t},Am=new Promise(n=>{Bi=n}),Ww(r)}catch{on.error("failed updating cache")}}async function ss(){let s=await $i;Object.keys(s).forEach(e=>{delete s[e]})}function km(s){Rm=s}function Hw(s=!0){xm=s}async function Om(){try{return Jc=!0,await Am}finally{Jc=!1}}function _m(s){Fi=s,$i=Pm()}var Mi,Ui,rs,Em,on,Fi,Im,Bi,Rm,xm,Jc,Am,Cm,$w,ji,$i,Ww,Lm,Dm,Ex,Nm,Xt=v(()=>{"use strict";Mi=I(require("fs")),Ui=I(require("path")),rs=I(require("crypto"));B();Em=require("lodash");$();on=C("local cache"),Fi=Ui.resolve(ht(),"testim-cache"),Rm=!0,xm=!0,Jc=!1,Am=new Promise(s=>{Bi=s}),Cm=new Promise(s=>{Im=s}),$w=1e3*60*60*3,ji=()=>Ui.resolve(Ui.resolve(Fi,"testim.cache"));$i=Pm(),Ww=(0,Em.debounce)(async s=>{let e;try{let t=await Cm,r=rs.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=rs.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Fi)||await Mi.promises.mkdir(Fi,{recursive:!0}),await Mi.promises.writeFile(ji(),a)}catch(t){on.error("failed saving cache",{err:t}),e=t}Bi(e?{success:!1,error:e}:{success:!0})},200);Lm=Im,Dm=km.bind(void 0,!1),Ex=km.bind(void 0,!0),Nm=()=>Hw(!1)});function Wi(){return{cliLocation:ht(),userInfo:ns.userInfo(),platform:ns.platform(),release:ns.release()}}var ns,Xc=v(()=>{"use strict";ns=I(require("node:os"));B()});function qw(s){try{return Vi.resolve(Vi.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Qt(s){let e=qw(s);return require(e)}var Vi,an=v(()=>{"use strict";Vi=I(require("path"))});function zw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Kw(s){return/The "to" argument must be of type string./.exec(s)}function Bm(s,e,t){let r=zw(s),n=Kw(s);return r||n?(Fm.info("Failed to install package due to insufficient write access",{...Wi(),package:t,path:r}),console.error(`
3
+ ${l.msg}`));for(let u of ow)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(o&&!m&&(l.msg=o),d.text=JSON.stringify(l)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function lw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Vd(),qe(Wd)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(xd){let r={depth:5,colors:!0};s.push(new ft.transports.Console({format:ft.format.combine(ft.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),ft.format.timestamp({format:"HH:mm:ss:SSS"}),ft.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ei.inspect(n.meta,r)}`))}))}return[s,e,t]}function Yd(s){vc=s}function Xd(s){Jd=s}function Qd(s){We||!s||dw(s)}function Hd(s){return{projectId:Jd,time:new Date().toISOString(),...vc&&!s&&{executionId:vc}}}function C(s){return new Sc(gw.child({category:s}))}var qd,ft,Ei,Si,zd,aw,cw,Gd,Kd,uw,pw,dw,mw,fw,gw,vc,Jd,Sc,$=v(()=>{"use strict";qd=I(require("node:os")),ft=I(require("winston"));ae();Ei=I(require("node:util")),Si=I(require("chalk")),zd=I(require("dayjs"));B();aw=qd.hostname(),cw=rt();Gd={depth:5,colors:!0},Kd=(s,e,t)=>{let r=`[${(0,zd.default)().format("HH:mm:ss:SSS")}]`,n=Ei.inspect(e,Gd),i=Ei.inspect(t,Gd);return`${Si.default.white(r)} ${Si.default.reset()}SessionPlayer-${Si.default.red(s)} ${n} ${i}`},[uw,pw,dw]=lw(),mw=Ad?"debug":"info",fw={release:Boolean(!1),branch:"runner-v4.156.0"},gw=ft.createLogger({levels:ft.config.syslog.levels,level:mw,transports:uw,defaultMeta:{name:"runner",hostname:aw,nodeVersion:process.version,runnerVersion:cw,...fw}}),vc=null,Jd=null;Sc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Hd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Hd(n)})}catch{}}}waitForFlush(){return pw()}}});var Ai,qr,A,zt,fr,xt,Ii,zr,ce,Gs,st,Kt,At,Ri,Kr,xi,Hs,X=v(()=>{"use strict";Ai=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},A=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},zt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},fr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},xt=class extends Ai.AbortError{},Ii=class extends Ai.AbortError{},zr=class extends Ai.AbortError{},ce=class extends Error{},Gs=class extends Error{},st=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Kt=class extends st{constructor(){super(...arguments);this.name="GridConcurrencyError"}},At=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Ri=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},xi=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Hs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ec(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ue(s){return(0,tm.setTimeout)(s)}function Ic(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function pe(s,e,t="Timeout Error"){bi&&!Zd&&(Zd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=bi?Number(bi)||6e5:e,Promise.race([s,ue(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){em||=(await import("p-limit")).default;let r=em(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Jt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var tm,Zd,em,Rc=v(()=>{"use strict";tm=require("timers/promises");X();ae();Zd=!1});var zs,rm,yw,qs,sm,bw,Tw,nm,im=v(()=>{"use strict";zs=I(require("lodash"));ae();rm=require("dns");$();Rc();yw=C("http-request-counters"),qs=!1,sm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>rm.promises.lookup(t)));return e||(qs=!0),e}catch{return yw.error("network connectivity test failed"),qs=!0,!1}},bw=zs.throttle(sm,10*1e3),Tw=60*1e3*15,nm=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},Tw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),qs||bw(),a}}}async function r(){if(qs||!await sm())return!1;let n=zs.sum([...s.fail.values()]),i=zs.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>qs,t}});var Ke={};z(Ke,{deleteReq:()=>Ks,didNetworkConnectivityTestFail:()=>_c,download:()=>kc,get:()=>Te,getFullRes:()=>Iw,getText:()=>Ys,head:()=>Rw,isNetworkHealthy:()=>Oc,post:()=>Ve,postForm:()=>Js,postText:()=>Cc,put:()=>Pc});function vw(){return global.caFileContent}function Sw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Ew(){return!gt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(gt.default),global.proxyUri}function gr(s,e=!1){let t=vw();t&&s.ca(t);let r=!e&&Ew();r&&s.proxy(r)}async function om(s,e,t={},r=Jr,n=0){let i=gt.default.post(s).send(e).timeout(r).set(t);gr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Ac(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=gt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),gr(o,i),await o}var gt,xc,nt,Jr,ww,Ut,Ks,Ve,Js,Ys,Cc,Te,Iw,Rw,Pc,kc,Oc,_c,Ge=v(()=>{"use strict";gt=I(require("superagent"));$();im();xc=C("http-request"),nt=nm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,ww=6e4;Ut=(s,e,t)=>{let r=e.response;e.response instanceof gt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw xc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ks=nt(async(s,e={},t={},r=Jr)=>{try{let n=gt.default.delete(s).send(e).timeout(r).set(t);gr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Ut("failed to delete request",n,{url:s})}}),Ve=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await om(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Ut("failed to post request",i,{url:s})}});Js=nt(async(s,e,t,r={},n=Jr)=>{let i=gt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),gr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Ut("failed to post request",o,{url:s})}});Ys=nt(async(s,e,t)=>{try{return(await Ac(s,e,t)).text}catch(r){return Ut("failed to getText request",r,{url:s,query:e})}}),Cc=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await om(s,e,t,r,n)).text}catch(i){return Ut("failed to post request",i,{url:s})}}),Te=nt(async(s,e,t,r,n)=>{try{return(await Ac(s,e,t,r,n)).body}catch(i){return Ut("failed to get request",i,{url:s,query:e})}}),Iw=nt((s,e,t,r)=>Ac(s,e,t,r)),Rw=nt(async s=>{let e=gt.default.head(s).timeout(Jr);gr(e);try{return await e}catch(t){return Ut("failed to head request",t,{url:s})}}),Pc=nt(async(s,e,t={},r=Jr)=>{let n=gt.default.put(s).send(e).timeout(r).set(t);gr(n);try{return(await n).body}catch(i){return Ut("failed to put request",i,{url:s})}}),kc=nt(async s=>{xc.info("start to download",{url:s});let e=gt.default.get(s).set("User-Agent","Testim.io").timeout(ww).buffer(!0).parse(Sw);gr(e);try{let t=await e;return xc.info("finished to download",{url:s}),t}catch(t){return Ut("failed to download",t,{url:s})}}),Oc=nt.isNetworkHealthy,_c=nt.didNetworkConnectivityTestFail});function ht(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Ft.resolve(__dirname,"../../"):s=Ft.resolve(__dirname,""),s):process.cwd()}function Ci(s,e){return Le(s)?e||Ft.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Ft.basename(s)}function rt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Nc(){try{return vd.node}catch{return""}}async function lm(s,e,t=!0){let r=await it.promises.readdir(s,{withFileTypes:!0});await it.promises.mkdir(e,{recursive:t});for(let n of r){let i=Ft.join(s,n.name),o=Ft.join(e,n.name);n.isDirectory()?await lm(i,o):await it.promises.copyFile(i,o)}}async function ye(s){try{return await it.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Ft,am,cm,it,xw,Bt,Je,Pi,Lc,ot,Dc,um=v(()=>{"use strict";Ft=I(require("node:path"));pc();yi();am=I(require("unzip-stream")),cm=I(require("p-retry")),it=require("node:fs"),xw=3;Bt=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,cm.default)(()=>e.download(s),{retries:xw,factor:1})},Je=async(s,e)=>{let t=await Bt(s);return it.promises.writeFile(e,t.body)};Pi=async(s,e)=>{let t=Ci(s,e);return Le(s)?Je(s,t):it.promises.copyFile(s,t)},Lc=async s=>Le(s)?Bt(s):it.promises.readFile(s),ot=async(s,e)=>(0,it.createReadStream)(s).pipe(am.Extract({path:e})),Dc=s=>(0,it.statSync)(s).size/1e6});var jt={};z(jt,{APPIUM_SESSION_MESSAGE:()=>jc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>ki,MOBILE_RUN_SKIP_REASON:()=>Bc,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>$c,gridMessages:()=>yt,gridTypes:()=>_,mobileWeb:()=>Uc,runnerStatus:()=>Mc,runnerTestStatus:()=>fe,socketEventTypes:()=>Ct,stepResult:()=>Qs,test:()=>Fc,testRunStatus:()=>Xs,testStatus:()=>Ye,timeoutMessages:()=>Ue});var Ue,Xs,Mc,fe,Ye,yt,Uc,Fc,Ct,K,_,Qs,ki,Bc,jc,$c,Yr,oe=v(()=>{"use strict";Ue={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Xs={COMPLETED:"completed"},Mc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Ye={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},yt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Uc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Fc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Ct={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Qs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},ki={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Bc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},jc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},$c="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"}});function Zs(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Aw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var en,pm,Xe,Cw,Pw,kw,Ow,_w,Wc,Vc,dm=v(()=>{"use strict";oe();en=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},pm=s=>Boolean(s.resultId&&s.source==="remote-run"),Xe=(s,e)=>s.testStatus===Ye.QUARANTINE&&!pm(e)&&!e.runQuarantinedTests;Cw=s=>Boolean(s.loginMode),Pw=s=>Boolean(s.tunnelOnlyMode),kw=s=>Boolean(s.createPrefechedData),Ow=s=>Boolean(s.installLazyDepsMode),_w=s=>Boolean(s.agentMode),Wc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Vc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function _i(s=0){return Oi.default.duration(s).format("HH:mm:ss.SSS")}function Gc(s=0){return Oi.default.duration(s).asSeconds()}var Oi,mm,fm=v(()=>{"use strict";Oi=I(require("dayjs")),mm=I(require("dayjs/plugin/duration"));Oi.default.extend(mm.default)});var tn,Xr,Yt,gm,Qr,hm=v(()=>{"use strict";oe();tn=s=>!(!s||"fileName"in s),Xr=(s,e)=>{if(e===_.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Yt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},gm=s=>s===_.TESTIM_TVC,Qr=(s,e)=>gm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Hc(s=4e3){let e=process.memoryUsage(),t=r=>Math.round(r/1024/1024*100)/100;return{isOverThreshold:t(e.rss)>s,rss:`${t(e.rss)} MB -> Resident Set Size - total memory allocated for the process execution`,heapTotal:`${t(e.heapTotal)} MB -> total size of the allocated heap`,heapUsed:`${t(e.heapUsed)} MB -> actual memory used during the execution`,external:`${t(e.external)} MB -> V8 external memory`}}var ym=v(()=>{"use strict"});var Y={};z(Y,{OSS:()=>Zr,TESTIM_BROWSER_DIR:()=>$t,buildBasicHeader:()=>uc,calcPercentile:()=>Ni,copyDir:()=>lm,delay:()=>ue,doesPathExist:()=>ye,download:()=>Bt,downloadAndSave:()=>Je,extractElementId:()=>De,getArgsOnRemoteRunFailure:()=>Aw,getBrowserInfo:()=>Dw,getCdpAddressForHost:()=>br,getCliLocation:()=>ht,getDuration:()=>_i,getDurationSec:()=>Gc,getEnginesVersion:()=>Nc,getEnvironmentGitBranch:()=>yr,getLinksFromUnescapeHTML:()=>nn,getLocalFileSizeInMB:()=>Dc,getMemorySnapshot:()=>Hc,getPlanType:()=>Di,getRunConfigByBrowserName:()=>rn,getRunnerVersion:()=>rt,getSource:()=>Pi,getSourceAsBuffer:()=>Lc,getSourcePath:()=>Ci,getTestUrl:()=>ze,getUniqBrowsers:()=>Zs,groupTestsByRetries:()=>zc,guid:()=>re,hasTestPlanFlag:()=>en,isAgentMode:()=>_w,isAppFromDevice:()=>tn,isAppFromDeviceDisabled:()=>Qr,isCreatePrefetchedDataMode:()=>kw,isInstallLazyDepsMode:()=>Ow,isLoginMode:()=>Cw,isMobileProject:()=>Yt,isPromise:()=>Ec,isQuarantineAndNotRemoteRun:()=>Xe,isRemoteRun:()=>pm,isTestimVirtualGrid:()=>gm,isTunnelOnlyMode:()=>Pw,isURL:()=>Le,promiseAbort:()=>Ic,promiseFromCallback:()=>Jt,promiseMap:()=>se,promiseTimeout:()=>pe,removePropertyFromObject:()=>Li,replaceArgsWithNoDashes:()=>Wc,sanitizeNumberValue:()=>hr,shouldBlockVirtualIosBuild:()=>Xr,spreadObjectToArgs:()=>Vc,unescapeHTML:()=>sn,unzipFile:()=>ot});function hr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Dw(s){return s=s.toLowerCase(),qc.find(e=>e.browserValue===s)}function rn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=qc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||qc[0],n=Zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=Zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=Zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=Zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=Zr.find(i=>i.bs.platform===t.platform))),es.merge(r,n)}function yr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Li(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Li(s[r],e,t))}function De(s){return s.ELEMENT||s[qt]}function Di(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function zc(s=[]){return es.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=es.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function sn(s){return vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function nn(s){return[...vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function br(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var bm,es,Tm,wm,Lw,$t,Zr,qc,Ni,vm,B=v(()=>{"use strict";bm=I(require("os")),es=I(require("lodash")),Tm=I(require("path")),wm=require("linkedom");Hr();um();dm();fm();pc();Rc();hm();ym();Lw=bm.homedir(),$t=Tm.join(Lw,".testim-browser-profile"),Zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],qc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:"112"},sl:{browserName:"chrome",version:"94.0"},browserValue:"chrome"},{browserName:"Firefox",bs:{browser:"Firefox",browser_version:"89"},sl:{browserName:"firefox",version:"89.0"},browserValue:"firefox"},{browserName:"Safari",bs:{browser:"Safari"},sl:{browserName:"safari"},browserValue:"safari"},{browserName:"Edge Chromium",bs:{browser:"Edge",browser_version:"112"},sl:{browserName:"MicrosoftEdge",version:"94"},synonyms:["edge-chromium"],browserValue:"edge-chromium",seleniumName:"MicrosoftEdge"},{browserName:"Browser",bs:{},sl:{browserName:"Browser"},browserValue:"browser"},{browserName:"Android",bs:{browserName:"android"},sl:{},browserValue:"android"},{browserName:"iPad",bs:{browserName:"iPad"},sl:{},browserValue:"ipad"},{browserName:"iPhone",bs:{browserName:"iPhone"},sl:{},browserValue:"iphone"}];Ni=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};vm=new wm.DOMParser});var Kc={};z(Kc,{$schema:()=>Nw,default:()=>jw,definitions:()=>Mw,properties:()=>Bw,required:()=>Fw,type:()=>Uw});var Nw,Mw,Uw,Fw,Bw,jw,Sm=v(()=>{Nw="http://json-schema.org/draft-07/schema#",Mw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Uw="object",Fw=["entries"],Bw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},jw={$schema:Nw,definitions:Mw,type:Uw,required:Fw,properties:Bw}});async function Pm(){try{return await pe(Mi.promises.readFile(ji()).then(async s=>{let e=await Cm;return Vw(e,s)}),3e4)}catch{return{}}}function Vw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=rs.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Pt(s,e,t=$w,r=void 0){return async()=>{if(!Rm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Yc(e);if(i)return on.debug("cache hit:",{fnName:e}),i;if(on.debug("cache miss:",{fnName:e}),!xm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Gw(e,o,t),o}}async function Yc(s){let t=(await $i)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Gw(s,e,t){if(Jc)throw on.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await $i;r[s]={value:e,expiry:Date.now()+t},Am=new Promise(n=>{Bi=n}),Ww(r)}catch{on.error("failed updating cache")}}async function ss(){let s=await $i;Object.keys(s).forEach(e=>{delete s[e]})}function km(s){Rm=s}function Hw(s=!0){xm=s}async function Om(){try{return Jc=!0,await Am}finally{Jc=!1}}function _m(s){Fi=s,$i=Pm()}var Mi,Ui,rs,Em,on,Fi,Im,Bi,Rm,xm,Jc,Am,Cm,$w,ji,$i,Ww,Lm,Dm,Ex,Nm,Xt=v(()=>{"use strict";Mi=I(require("fs")),Ui=I(require("path")),rs=I(require("crypto"));B();Em=require("lodash");$();on=C("local cache"),Fi=Ui.resolve(ht(),"testim-cache"),Rm=!0,xm=!0,Jc=!1,Am=new Promise(s=>{Bi=s}),Cm=new Promise(s=>{Im=s}),$w=1e3*60*60*3,ji=()=>Ui.resolve(Ui.resolve(Fi,"testim.cache"));$i=Pm(),Ww=(0,Em.debounce)(async s=>{let e;try{let t=await Cm,r=rs.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=rs.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Fi)||await Mi.promises.mkdir(Fi,{recursive:!0}),await Mi.promises.writeFile(ji(),a)}catch(t){on.error("failed saving cache",{err:t}),e=t}Bi(e?{success:!1,error:e}:{success:!0})},200);Lm=Im,Dm=km.bind(void 0,!1),Ex=km.bind(void 0,!0),Nm=()=>Hw(!1)});function Wi(){return{cliLocation:ht(),userInfo:ns.userInfo(),platform:ns.platform(),release:ns.release()}}var ns,Xc=v(()=>{"use strict";ns=I(require("node:os"));B()});function qw(s){try{return Vi.resolve(Vi.dirname(require.resolve(`${s}/package.json`)),require(`${s}/package.json`).main||"")}catch(e){if(e.code==="ERR_PACKAGE_PATH_NOT_EXPORTED")return require.resolve(s);throw e}}function Qt(s){let e=qw(s);return require(e)}var Vi,an=v(()=>{"use strict";Vi=I(require("path"))});function zw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Kw(s){return/The "to" argument must be of type string./.exec(s)}function Bm(s,e,t){let r=zw(s),n=Kw(s);return r||n?(Fm.info("Failed to install package due to insufficient write access",{...Wi(),package:t,path:r}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${t||""} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
@@ -209,7 +209,7 @@ Testim had missing write access to ${r||e}
209
209
  });
210
210
  })();
211
211
  `,u=[],f=new Qg.Worker(m,{eval:!0});try{return await pe(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};dt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?dt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):dt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{dt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ce))throw h;return dt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function $S(s){try{await Jg.promises.rm(s,{recursive:!0,force:!0})}catch(e){dt.warn("failed to remove install npm packages folder",{err:e})}}function Zg(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ws(s,e,t,r,n,i){let o=Zg(n,e,s,t),{data:a}=await WS(o,r,i);return a}async function vs(s,e,t,r,n,i,o,a,c,l){var g;let d=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=Wm(y.testimPackageLocalLocation);return[y.paramName,Ts.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=Zg(o,n,e,i);if(l){let y=await kn(l);y&&(c=y)}Buffer.isBuffer(c)&&(dt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(dt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await jS(u,t,r,s,m,a,c),nodeVersion:process.version}}async function WS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=eh(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Ts.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await tl(o,r,a,t),dt.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=jm(o,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:Ts.resolve(o,"node_modules",m.packageName)}}),installFolder:o}}catch(d){throw dt.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await pe(c(),t)}catch(l){throw l instanceof ce&&dt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function eh(){return Ts.join(Yg.tmpdir(),"/testim_local_packages")}function VS(){let s=eh();return $S(s)}var Jg,Yg,Ts,Xg,Qg,dt,Ss=v(()=>{"use strict";Jg=I(require("fs")),Yg=I(require("os")),Ts=I(require("path"));B();is();Xg=I(require("data-uri-to-buffer")),Qg=require("worker_threads");X();$();ge();is();de();dt=C("cli-service");VS().catch(s=>dt.warn("failed to clean local package folder",{err:s}))});var nr={};z(nr,{run:()=>HS});function GS(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 HS,th=v(()=>{"use strict";Ss();X();de();HS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await vs(r,n,i,o,a,c,l,d,m,u);return f&&GS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ce?new Error("Timeout while running action"):f}}});var bu={};z(bu,{run:()=>qS});var qS,rh=v(()=>{"use strict";Ss();X();qS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await ws(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof At)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function nh(s,e,t,r){try{return await Tu(s,e,t,r)}catch{Do.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function KS(s,e,t,r,n){return Do.info("finished to run remote step",{stepId:t,sessionId:n}),await nh(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function sh(s,e,t,r,n){return Do.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await nh(s,e,t,{status:"completed",success:!1,failureReason:r})}async function ih(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;Do.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=zS[o];if(!l)return await sh(n,r,c,`Failed to find step type ${o}`,a);try{let d=await l.run(e,t,i);return await KS(n,r,c,d,a)}catch(d){return await sh(n,r,c,d.message,a)}}var Do,zS,oh=v(()=>{"use strict";th();ge();rh();$();Do=C("step-playback"),zS={"cli-validation-code-step":nr,"cli-wait-for-code-step":nr,"cli-action-code-step":nr,"cli-api-code-step":nr,"cli-condition-step":nr,"cli-download-code-step":nr,"node-package":bu}});var ch={};z(ch,{preloadTests:()=>jn});async function jn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await Pt(async()=>{let t=await se(s.testId,r=>$n({...e,testId:r}),{concurrency:2});return ah.keyBy(t,"testData.id")},"loadTests",YS,[e,s.testId])()}var ah,YS,No=v(()=>{"use strict";ah=I(require("lodash"));Xt();ge();B();YS=1e3*60*60*10});var wu,lh,Lr,XS,vu,wt,Mo=v(()=>{"use strict";B();ct();wu=I(require("ws")),lh=require("events");$();ae();Lr=C("socket-service"),XS=5e3,vu=class extends lh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Lr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),XS)}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){Lr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(Rd);return kt().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new wu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return Lr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{Lr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===wu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Lr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){Lr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Lr.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(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}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})}},wt=new vu});var ph,Su,QS,ZS,eE,uh,Uo,Es,Eu=v(()=>{"use strict";ph=I(require("p-retry")),Su=I(require("socket.io-client"));ae();B();$();QS=50,ZS=10,eE=5e3,uh=10*1e3,Uo=C("base socket service"),Es=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Uo.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{}Uo.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===ZS&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=QS)throw new Error(`Can't connect to Testim Servers.
212
- Action required: Please allow opening a websockets connection to ${he()} 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",()=>{Uo.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:uh,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=`${he()}/${t}`,this._socket=Su.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:uh,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=`${he()}/${t}`,this._socket=Su.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,ph.default)(()=>pe(n(),eE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Uo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var dh={};z(dh,{remoteStepServiceSocketIO:()=>tE});var Iu,tE,mh=v(()=>{"use strict";Eu();Iu=class extends Es{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))}},tE=new Iu});var fh={};z(fh,{remoteStepService:()=>Is});var Ru,Wn,xu,Is,Fo=v(()=>{"use strict";Mo();oe();de();({REMOTE_STEP_SAVED:Ru}=Ct),xu=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Wn=(await Promise.resolve().then(()=>(mh(),dh))).remoteStepServiceSocketIO,Wn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:remoteStep`,{resultId:e},[Ru]):Wn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:remoteStep`,[Ru],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Wn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(wt.removeFilter(`${e}:remoteStep`,[Ru]),Promise.resolve()):Wn.unlistenToRemoteStep(e)}},Is=new xu});var Au,Dr,gh=v(()=>{"use strict";Eu();Au=class extends Es{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}},Dr=new Au});var yh={};z(yh,{testResultService:()=>Lt});var hh,Cu,Lt,Bo=v(()=>{"use strict";hh=require("events");Mo();oe();de();gh();Cu=class extends hh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){wt.onConnect=()=>this.emit("socket-connected");return}Dr.init(e),Dr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Dr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){wt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Dr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Dr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Dr.getSocket()}},Lt=new Cu});var Th,wh,vh,Se,rE,Sh,bh,sE,jo,Eh=v(()=>{"use strict";Th=I(require("lodash"));B();ae();$e();Rr();ct();ge();oh();wh=I(require("p-retry")),vh=require("node:url");$();No();gs();oe();Fo();Bo();ge();Se=C("test-run-handler"),rE=3,Sh=20*1e3,bh=s=>JSON.stringify(s).length<Sh,sE="Test couldn't be started",jo=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 Ar;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,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=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?rn(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 tn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Xr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?ki.FROM_DEVICE:ki.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/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 isTestRecordedWithEnhancedMode(){return(await $n({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await kt(),refreshToken:Yi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:_d(),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 Xi()};if(this._options.disableMockNetwork&&bt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=bh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Sh} 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 jn(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 Se.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 testOptimization(){return this._testOptimization}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&&bh(e))return;let r=async()=>{try{return await Ou(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),ku(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)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===sE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}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=new Set(["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.has(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:c}=o||{};U("before Runtime.evaluate"),await(0,wh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);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:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return U("after Runtime.evaluate"),l.value}catch(o){throw Se.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 vh.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)){Se.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.isRerunOnInfraError(i.reason)&&(Se.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:c,branch:l,_options:{project:d}}=this;try{let m=await Nr(a,c,d,l);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Lt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Nr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Lt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Lt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.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=Th.debounce(async()=>{try{await Lt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Nr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.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"?(Se.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 Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Lt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Pu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Lt.off("socket-connected",e)}}listenToRemoteStep(e){Is.listenToRemoteStep(this.testResultId,t=>{ih(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:rE;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=re(),!((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 $o,Ih=v(()=>{"use strict";Eh();$o=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new jo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function xh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Du({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function _u(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Lu(s,e){let t=s.mode===K.EXTENSION?Mr:Vn,r=Rh.difference(Zs(s,e),t);if(r.length>0)throw bt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new A(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Rh,Mr,Vn,Wo=v(()=>{"use strict";Rh=I(require("lodash"));B();Rr();ge();X();oe();Mr=["edge-chromium","chrome"],Vn=[...Mr,"firefox","safari","safari technology preview"]});var nE,iE,oE,Gn,Nu=v(()=>{"use strict";as();ds();$();nE=C("worker-utils"),iE=async(s,e,t)=>{e&&await Tl(s,t)},oE=async(s,e,t)=>{await Gl(s,e,t)},Gn=async(s,e,t,r,n,i)=>{nE.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 oE(s,r,t)}}});function uE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Go,Ph,Ho,Fu,kh,vt,Ah,Ch,Mu,Hn,aE,Uu,cE,ir,lE,Vo,pE,Dt,qn=v(()=>{"use strict";Go=I(require("ms")),Ph=I(require("lodash")),Ho=I(require("p-retry")),Fu=I(require("dayjs")),kh=I(require("dayjs/plugin/duration"));B();$e();as();ds();ge();$();Nu();_t();Ao();de();Fo();Bo();ct();Ge();oe();X();Fu.default.extend(kh.default);vt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ah,TEST_START_TIMEOUT_MSG:Ch,TEST_COMPLETE_TIMEOUT_MSG:Mu}=Ue,{SETUP_TIMEOUT:Hn,NETWORK_ERROR:aE,GRID_ERROR:Uu,BROWSER_CLOSED:cE,SELENIUM_ERROR:ir,UNKNOWN_ERROR:lE,MOBILE_SESSION_ERROR:Vo}=Qs;pE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Dt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await bf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Hs(!0)}async getBrowserOnce(e,t,r,n){throw new Hs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),vt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),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:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};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=Qr(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:fe.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===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=hr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Go.default)("2m")),i=hr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,Go.default)("10m"):o+(0,Go.default)("1m")}getSessionTimeout(){if(Yt(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,Ho.default)(async()=>{let n=Date.now();try{return await pe(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.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,Ho.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 pe(Gf(o,a,this.id),this.options.getBrowserTimeout,Ue.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 Kt?vt.info("could not get grid slot due to concurrency issue",r):vt.error("error getting grid slot",{error:e,...r}),await ue(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 c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Ho.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await Tf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,U("before getBrowserOnce");let f=await pe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Ue.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===K.APPIUM?"device":"browser";throw vt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof xt)&&this.options.mode!==K.APPIUM&&await ue(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await Gn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[xt,zr].some(a=>o instanceof a)?o:o instanceof st?new fr(o,Uu):new fr(o,ir)}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=Yt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await kt(),await this.runTestOnce(e,l)}finally{await Gn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var L,M;if(Xe(g,this.options)||Qr(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof fr,S=w(Ch),E=y&&(w(Mu)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,G=E&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!b&&!E,R=!g.success&&(x||G||D);try{let V=e.retryKey;g.testRetryKey=V;let W=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,R,W),await this.runTestCleanup(),R){if(G&&await e.startNewTimeoutRetry(),D){vt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(M=this.options.projectData)==null?void 0:M.projectId,ie=e.testResultId,Ee=e.testId;await qo(q,ie,Ee,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return x&&!D&&!G&&await e.startNewRetry(),vt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(R)}t(this.id,...r);return}catch(V){if(V instanceof zt)return;vt.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.
212
+ Action required: Please allow opening a websockets connection to ${he()} 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",()=>{Uo.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:uh,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=`${he()}/${t}`,this._socket=Su.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:uh,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=`${he()}/${t}`,this._socket=Su.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,ph.default)(()=>pe(n(),eE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Uo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var dh={};z(dh,{remoteStepServiceSocketIO:()=>tE});var Iu,tE,mh=v(()=>{"use strict";Eu();Iu=class extends Es{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))}},tE=new Iu});var fh={};z(fh,{remoteStepService:()=>Is});var Ru,Wn,xu,Is,Fo=v(()=>{"use strict";Mo();oe();de();({REMOTE_STEP_SAVED:Ru}=Ct),xu=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Wn=(await Promise.resolve().then(()=>(mh(),dh))).remoteStepServiceSocketIO,Wn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:remoteStep`,{resultId:e},[Ru]):Wn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:remoteStep`,[Ru],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Wn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(wt.removeFilter(`${e}:remoteStep`,[Ru]),Promise.resolve()):Wn.unlistenToRemoteStep(e)}},Is=new xu});var Au,Dr,gh=v(()=>{"use strict";Eu();Au=class extends Es{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}},Dr=new Au});var yh={};z(yh,{testResultService:()=>Lt});var hh,Cu,Lt,Bo=v(()=>{"use strict";hh=require("events");Mo();oe();de();gh();Cu=class extends hh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){wt.onConnect=()=>this.emit("socket-connected");return}Dr.init(e),Dr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?wt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Dr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){wt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Dr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){wt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Dr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Dr.getSocket()}},Lt=new Cu});var Th,wh,vh,Se,rE,Sh,bh,sE,jo,Eh=v(()=>{"use strict";Th=I(require("lodash"));B();ae();$e();Rr();ct();ge();oh();wh=I(require("p-retry")),vh=require("node:url");$();No();gs();oe();Fo();Bo();ge();Se=C("test-run-handler"),rE=3,Sh=20*1e3,bh=s=>JSON.stringify(s).length<Sh,sE="Test couldn't be started",jo=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 Ar;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,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=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?rn(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 nativeApp(){return this._nativeApp}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 tn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Xr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?ki.FROM_DEVICE:ki.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/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 isTestRecordedWithEnhancedMode(){return(await $n({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await kt(),refreshToken:Yi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:_d(),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 Xi()};if(this._options.disableMockNetwork&&bt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=bh(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Se.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Sh} 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 jn(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 Se.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 testOptimization(){return this._testOptimization}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&&bh(e))return;let r=async()=>{try{return await Ou(this._options.project,this._testId,this._testResultId,e)}catch(o){return Se.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),ku(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)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===sE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}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=new Set(["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.has(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:c}=o||{};U("before Runtime.evaluate"),await(0,wh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);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:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return U("after Runtime.evaluate"),l.value}catch(o){throw Se.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 vh.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)){Se.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.isRerunOnInfraError(i.reason)&&(Se.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:c,branch:l,_options:{project:d}}=this;try{let m=await Nr(a,c,d,l);n(m),r||setTimeout(o,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Lt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Nr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Se.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Se.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(i){throw Se.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Lt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Lt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Se.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=Th.debounce(async()=>{try{await Lt.joinToTestResult(this._testResultId,this.testId)}catch(o){Se.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Nr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Se.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"?(Se.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 Se.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Lt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Pu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Se.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Lt.off("socket-connected",e)}}listenToRemoteStep(e){Is.listenToRemoteStep(this.testResultId,t=>{ih(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:rE;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=re(),!((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 $o,Ih=v(()=>{"use strict";Eh();$o=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new jo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function xh(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Du({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function _u(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Lu(s,e){let t=s.mode===K.EXTENSION?Mr:Vn,r=Rh.difference(Zs(s,e),t);if(r.length>0)throw bt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new A(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Rh,Mr,Vn,Wo=v(()=>{"use strict";Rh=I(require("lodash"));B();Rr();ge();X();oe();Mr=["edge-chromium","chrome"],Vn=[...Mr,"firefox","safari","safari technology preview"]});var nE,iE,oE,Gn,Nu=v(()=>{"use strict";as();ds();$();nE=C("worker-utils"),iE=async(s,e,t)=>{e&&await Tl(s,t)},oE=async(s,e,t)=>{await Gl(s,e,t)},Gn=async(s,e,t,r,n,i)=>{nE.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 oE(s,r,t)}}});function uE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var Go,Ph,Ho,Fu,kh,vt,Ah,Ch,Mu,Hn,aE,Uu,cE,ir,lE,Vo,pE,Dt,qn=v(()=>{"use strict";Go=I(require("ms")),Ph=I(require("lodash")),Ho=I(require("p-retry")),Fu=I(require("dayjs")),kh=I(require("dayjs/plugin/duration"));B();$e();as();ds();ge();$();Nu();_t();Ao();de();Fo();Bo();ct();Ge();oe();X();Fu.default.extend(kh.default);vt=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ah,TEST_START_TIMEOUT_MSG:Ch,TEST_COMPLETE_TIMEOUT_MSG:Mu}=Ue,{SETUP_TIMEOUT:Hn,NETWORK_ERROR:aE,GRID_ERROR:Uu,BROWSER_CLOSED:cE,SELENIUM_ERROR:ir,UNKNOWN_ERROR:lE,MOBILE_SESSION_ERROR:Vo}=Qs;pE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Dt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await bf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Hs(!0)}async getBrowserOnce(e,t,r,n){throw new Hs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),vt.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),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:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};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=Qr(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:fe.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===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=hr(O.flags.appiumConnectionRequestTimeout.getValue(),(0,Go.default)("2m")),i=hr(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,Go.default)("10m"):o+(0,Go.default)("1m")}getSessionTimeout(){if(Yt(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,Ho.default)(async()=>{let n=Date.now();try{return await pe(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.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,Ho.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 pe(Gf(o,a,this.id),this.options.getBrowserTimeout,Ue.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 Kt?vt.info("could not get grid slot due to concurrency issue",r):vt.error("error getting grid slot",{error:e,...r}),await ue(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 c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,Ho.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await Tf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,U("before getBrowserOnce");let f=await pe(this.getBrowserOnce(e,t,m,u),this.getSessionTimeout(),Ue.GET_BROWSER_TIMEOUT_MSG);return U("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),m||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===K.APPIUM?"device":"browser";throw vt.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++l),m.onDone(),!(u instanceof xt)&&this.options.mode!==K.APPIUM&&await ue(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:c-1,minTimeout:0,factor:1}),U("after getBrowserOnce retries")}catch(o){throw await Gn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[xt,zr].some(a=>o instanceof a)?o:o instanceof st?new fr(o,Uu):new fr(o,ir)}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=Yt(this.options)&&this.handleMobileTest(e);if(o)return o;U("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await kt(),await this.runTestOnce(e,l)}finally{await Gn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var L,M;if(Xe(g,this.options)||Qr(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let w=V=>y==null?void 0:y.message.includes(V),b=y&&y instanceof fr,S=w(Ch),E=y&&(w(Mu)||S&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||S)&&e.retryOnInfraErrors,G=E&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!b&&!E,R=!g.success&&(x||G||D);try{let V=e.retryKey;g.testRetryKey=V;let W=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,R,W),await this.runTestCleanup(),R){if(G&&await e.startNewTimeoutRetry(),D){vt.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(M=this.options.projectData)==null?void 0:M.projectId,ie=e.testResultId,Ee=e.testId;await qo(q,ie,Ee,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return x&&!D&&!G&&await e.startNewRetry(),vt.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:E,testRetryKey:V,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(R)}t(this.id,...r);return}catch(V){if(V instanceof zt)return;vt.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.
213
213
  Please make sure the CLI has stable access to the internet. ${_c()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:w,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:S}=jc,E=g instanceof Error?g.message:g;return E.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),E.includes(Ah)||E.includes(b)?{errorType:Hn,reason:"timeout while getting device"}:E.includes(T)||E.includes(S)?{errorType:Vo,reason:"app doesn't exist on device"}:E.includes(w)?{errorType:Vo,reason:"app never started, check app permission or app activity"}:E.includes(y)?{errorType:Vo,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Vo,reason:E}},a=(g,y)=>{let T=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:aE,reason:i()};let w=g instanceof Error?g.message:g;if(w.includes(Ah))return{errorType:Hn,reason:`Test couldn't get ${T}`};if(w.includes(Ch))return{errorType:Hn,reason:"Test couldn't be started"};if(w.includes(Mu)){if(!this.testRunTimeout)return{errorType:Hn,reason:"Test timeout reached: test is too long"};let b=Fu.default.duration({milliseconds:this.testRunTimeout}),S=Math.floor(b.asMinutes()),E=b.asSeconds(),k=S>0?` ${S} min`:"",D=E>0?` ${E} sec`:"";return{errorType:Hn,reason:`Test timeout reached (timeout:${k}${D}): test is too long`}}if(g instanceof fr&&g.type){if(g.type===Uu)return{errorType:Uu,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===ir)return{errorType:ir,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===cE?{errorType:ir,reason:`Session terminated, this is often caused to connection
214
214
  problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:ir,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(g.message)?{errorType:ir,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(g.message)?{errorType:ir,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(g.message)?{errorType:ir,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:lE,reason:w}},c=async g=>{var S;let y=await Oc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),vt.warn("error on run",{err:g});let T=(S=this.userData)==null?void 0:S.projectId,{errorType:w,reason:b}=this.options.mode===K.APPIUM?o(g):a(g,y);qo(T,this.testResultId,this.testId,{status:Xs.COMPLETED,success:!1,reason:b,errorType:w,testRetryKey:e.retryKey,setupStepResult:{status:Xs.COMPLETED,success:!1,reason:b,errorType:w}},e.remoteRunId),await n(uE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var S;let y=this.testId,T=this.testResultId,w=(S=this.userData)==null?void 0:S.projectId,b=this.branch;if(!y||!T||!w||!b)return vt.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let E=await Nr(y,T,w,b);if(vt.warn("Test failed. Got results via API",{err:g,testResult:Ph.default.omit(E,pE),resultId:T}),E&&E.status===Xs.COMPLETED&&!g.message.includes(Mu))return await n(E);throw g}catch(E){return E!==g&&vt.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:w,branch:b,err:E}),c(g)}},d=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),m=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!m&&Is.joinToRemoteStep(this.testResultId),!d&&Lt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),U("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{m||Is.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 _h,Oh,Rs,Bu=v(()=>{"use strict";B();_h=I(require("p-retry"));B();$();X();Oh=C("window-utils"),Rs=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 Oh.warn("selenium navigation failed. retrying to navigate",{err:i}),await ue(1500),r(n-1);throw!i.seleniumStack&&o&&Oh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),ue(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),ue(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 ue(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 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.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new xt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,_h.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var ju,xs,$u=v(()=>{"use strict";$();ju=C("cookies-utils"),xs=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 ju.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw ju.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw ju.error("failed to remove cookie",{err:t}),t}}}});var Wu,zo,Lh=v(()=>{"use strict";Wu=I(require("p-retry")),zo=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,Wu.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,Wu.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.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 Dh(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 dE.warn("missing elementRect",Mh.omit(s,"image")),{};let{elementRect:o}=s,a=await Ko.Jimp.fromBuffer(Buffer.from(n[1],"base64")),c=o.left*r+i.left*r,l=o.top*r+i.top*r,d=o.width*r,m=o.height*r;c<0&&(d+=c,d=Math.max(d,0),c=0),l<0&&(m+=l,m=Math.max(m,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+d>u&&(d=u-c),l+m>f&&(m=f-l),m<=0||d<=0)throw new Vu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:d,h:m}).getBase64(Uh)}}async function mE(s,e){let t=new Ko.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Ko.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(Uh)}function fE(s,e){return mE(s,e)}async function gE(){}async function hE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await gE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Nh(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 Mh,Ko,dE,Uh,Vu,Jo,Fh=v(()=>{"use strict";Mh=I(require("lodash"));B();Ko=require("jimp");$();dE=C("image-capture-utils"),Uh="image/png",Vu=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 Dh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Nh(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 hE({screenImage:t.image,absoluteScreenHighlight:Nh(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=()=>ue(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Dh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,w=Array.from({length:Math.ceil(h/g)},(S,E)=>({scrollX:Math.min(E*g,h-g),cropX:E*g-Math.min(E*g,h-g),cropW:g-(E*g-Math.min(E*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(S,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 w.flatMap(S=>b.map(E=>({scrollPos:{x:S.scrollX,y:E.scrollY},cropData:{top:E.cropY,left:S.cropX,width:S.cropW,height:E.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),fE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(d,m)}}});var Bh,jh,Yo,Xo,$h=v(()=>{"use strict";Bh=I(require("p-retry")),jh=I(require("semver"));B();$();Bu();Lh();Fh();we();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=re();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.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:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Rs(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 zo(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}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),d=r.map(m=>i.urlBreaker(m)).map(m=>n(m)).filter(m=>m===c);return c===l&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let l=this.getAllTabInfos(e),d=Object.keys(l).map(m=>l[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(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(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 ue(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,Bh.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=jh.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 c,l;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.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=(l=t.tabInfo)==null?void 0:l.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 Gu,Qo,Hu=v(()=>{"use strict";Gu=class{select(){return console.log(`
215
215
  internal error - cant use port selector in selenium!!!!
@@ -400,7 +400,7 @@ Please make sure the CLI has stable access to the internet. ${_c()?"(Internal: n
400
400
  `;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.",c="element not interactable",l="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(c)||f.includes(l)){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:c,driver:l}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.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:f})=>{let h=await Bt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),l.isSafari()||l.isFirefox()||l.isEdgeChromium()){await this.driver.executeJS(`
401
401
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
402
402
  const downloadAndUploadFile = ${FE()};
403
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Oy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ya,ba,Dy=v(()=>{"use strict";ya=require("url");me();ba=class extends H{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,Ny=v(()=>{"use strict";me();B();Ta=class extends H{async performAction(){await ue(this.step.durationMS||0)}}});var wa,My=v(()=>{"use strict";me();wa=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Qn,Uy=v(()=>{"use strict";me();Qn=class extends H{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.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var va,Fy=v(()=>{"use strict";me();va=class extends H{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 By,zu,Ku,jy=v(()=>{"use strict";By=I(require("@applitools/spec-driver-webdriverio"));yi();we();zu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=wd["@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:By.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ku=new zu});var Wy,$y,Zn,Vy=v(()=>{"use strict";Wy=I(require("lodash"));me();$();jy();$y=C("pixel-validation-step-action"),Zn=class extends H{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,c=await Ku.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Wy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),$y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){$y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ku.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Cs,Ju=v(()=>{"use strict";Ss();X();aa();Cs=class extends or{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await vs(i,o,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,Gy=v(()=>{"use strict";Ju();ar=class extends Cs{isFailedResult(e){return e===!1}}});var Sa,Hy=v(()=>{"use strict";Ju();Sa=class extends Cs{isFailedResult(e){return!e}}});var Ea,qy=v(()=>{"use strict";Ss();me();X();Ea=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await ws(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Fr,zy=v(()=>{"use strict";me();Fr=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Ky=v(()=>{"use strict";me();be=class extends H{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,Jy=v(()=>{"use strict";me();Ia=class extends H{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,Yy=v(()=>{"use strict";me();Ra=class extends H{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 BE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){BE(jE,e),e.registerLocateStepActionUtils(Kn.getUtils(s))}var jE,Yu=v(()=>{"use strict";qh();Jh();ny();iy();ay();uy();my();fy();gy();hy();Ty();wy();vy();Iy();Ay();Ly();Dy();Ny();My();Uy();Fy();Vy();Gy();Hy();qy();zy();Ky();Jy();Yy();jE={locate:Kn,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":As,"skip-code-step":As,"element-code-step":As,"evaluate-expression":na,"text-validation":Yn,"wait-for-text-validation":Yn,"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":Qn,"api-action":Qn,"api-code-step":Gt,"extract-text":va,"simple-ui-verification":Zn,"wait-for-simple-ui-verification":Zn,"cli-validation-download-file":Fr,"cli-wait-for-download-file":Fr,"network-validation-step":Fr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Sa,"node-package":Ea,"email-code-step":Gt,"cli-email-code-step":ar,"sfdc-internal-test-step":Ra,"sfdc-recorded-step":Ia,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Fr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Xy,$E,Ps,Xu=v(()=>{"use strict";Xy=["simple-ui-verification","wait-for-simple-ui-verification"],$E=[...Xy,"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"],Ps=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=$E.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 Xy.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 Zy={};z(Zy,{SeleniumTestPlayer:()=>ei});var Qy,WE,ei,Qu=v(()=>{"use strict";B();Qy=require("@applitools/eyes-sdk-core");Un();X();$();$u();$h();Hu();ea();Gh();qu();we();Yu();Xu();ae();WE=C("SeleniumTestPlayer"),ei=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ps(ta());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new _r;let d=new Zo(this.driver);this.stepActionFactory=new l(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Xo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Vh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new xs(this.driver),FrameLocator:m,portSelector:Qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Qy.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(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await pe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&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)){WE.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=[new URL(tt||mr).hostname].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(c=>a.url.includes(c))){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 ep={};z(ep,{WorkerSelenium:()=>Zu});function GE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Aa,VE,Zu,tp=v(()=>{"use strict";B();$e();qn();$();_t();No();oe();Bu();X();Qu();we();ct();Aa=C("worker-selenium"),VE=1e9,Zu=class extends Dt{initPlayer(t){return new ei(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Rs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=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:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),U("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,VE),await this.windowUtils.validatePageIsAvailable(),U("in WorkerSelenium after navigate")}catch(l){let d=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof xt||d||m?new xt(`Page '${c}' is not available`):(Aa.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:Qi(),initializedFromCache:Zi()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),GE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await jn(this.options))[this.testId]);let d=async()=>pe(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Aa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(Aa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});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 Aa.error("failed to run test once",{err:u}),u}}}});var eb,tb,He,HE,qE,rp,St,Ca=v(()=>{"use strict";eb=I(require("ora")),tb=require("jimp");ae();Ge();ge();$();oe();we();de();He=C("mobile-grid-service"),HE="https://tdc.tricentis-cloud.com",qE="https://ui.headspin.io",rp=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.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===_.TESTIM_HEADSPIN?`${r||gc}/${yc}/devices`:t===_.TESTIM_TDC?`${r||hc}/${yc}/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 Te(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 Ys(`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===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.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,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let d=await ri({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===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.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,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Pr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(c,"base64"),m=await tb.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ws}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?qE:HE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Pr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}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 np({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 ti({appId:e,projectId:t});return{appUrl:`${he()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Md*60))+1)*60*1e3,Math.max(Nd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.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 c=r||t.mobileApp,l=(0,eb.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 sp({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.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 c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,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:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Ws}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${bc}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?gc:hc}/${bc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Ud}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,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(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Cc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},St=new rp});function rb({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"&&!zE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function KE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.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 JE(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 YE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:JE(t),[`${c}:enableBatch`]:l||d,...!r&&{"appium:noReset":n},...m&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Pa(s){return"id"in s?s.id:s.packageName}function XE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function QE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=XE(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&&c};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&&c};default:throw Error(`unsupported mobile project ${s}`)}}function jr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Pa(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"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 sb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=YE(o.type,i,n);return QE({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Oa({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 _a({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Tc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Tc:".*")}function ZE(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 eI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...ka(s,ks)}}function nb(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 tI(s){return nb(s,e=>e.startsWith("browserstack."),"browserstack.")}function rI(s){return nb(s,e=>!e.startsWith("browserstack."))}function ib(s){return!s||!ob(s)?"2.0.0":s}function ob(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function ab({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),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=ob(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}async function sI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=ZE(i,s),h=await ri({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Oa({osVersion:l,mobileConfig:m}),T=(g==null?void 0:g.name)??_a({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function nI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Oa({osVersion:c,mobileConfig:d}),y=_a({deviceName:l,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...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,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Fd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=eI(b)),t="",jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:ks}})}function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:c,mobileConfig:d}),f=_a({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h=(0,Br.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ab({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:ib(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...ka(h,ks),"sauce:options":{...T,...w,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:s,sessionCaps:b,appiumPrefix:ks,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return jr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function oI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:d}=i,m=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Oa({osVersion:l,mobileConfig:m}),h=_a({deviceName:d,mobileConfig:m,projectType:e,gridType:u}),g=tI(i.browserstack),y=(0,Br.omit)(rI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},w=O.flags.enableAppium2BrowserStack.isEnabled();if(w||ab({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let S={...T,userName:o.user,accessKey:o.key,appiumVersion:w?"2.0.1":ib(g.appiumVersion),debug:!0,networkLogs:!0},E={"appium:platformVersion":f,"appium:deviceName":h,...ka(y,ks),"bstack:options":{...S,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:e,sessionCaps:E,appiumPrefix:ks,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...ka(g,"browserstack.")};return jr({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function aI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return sb(s);if(_.TESTIM_TVC===s.gridInfo.type)return await sI(s);if(_.P_CLOUDY===s.gridInfo.type)return nI(s);if(_.SAUCELABS===s.gridInfo.type)return iI(s);if(_.BROWSERSTACK===s.gridInfo.type)return oI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function cI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function cb(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}`);rb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),c=await aI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=cI(r,i==null?void 0:i.mobile);if(!(0,Br.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();c[`${y}:selector`]=w}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,ip.default)("2m"),f=(0,ip.default)("12m"),h=hr(O.flags.appiumConnectionRetryCount.getValue(),m),g=hr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function lb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;rb({nativeAppMetadata:r,appPath:i,gridInfo:t}),KE({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=sb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function ub(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=jr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function pb(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 ip,Br,ks,zE,op=v(()=>{"use strict";ip=I(require("ms"));de();oe();Ca();Br=require("lodash");B();ae();ge();ks="appium:",zE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var La,mb=v(()=>{"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,fb=v(()=>{"use strict";B();Da=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn}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 ap,Na,gb=v(()=>{"use strict";$();ap=C("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return ap.info("foundFrameCallback-mock invoked"),{}}locate(){return ap.info("locate-mock invoked"),{}}async findFrame(){return ap.info("findFrame-mock invoked"),{}}}});var lI,yb,hb,Os,cp=v(()=>{"use strict";lI=I(require("webdriverio")),yb=require("@applitools/eyes-sdk-core");mb();Hu();$();fb();qu();we();Yu();gb();Xu();hb=C("appium-test-player"),Os=class{constructor(e,t,r,n=lI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=Z(),m=new Da(this.driver);this.stepActionFactory=new l(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ps(ta()),this.sessionPlayer=new a(e,{tabService:new La,cookieUtils:void 0,FrameLocator:Na,portSelector:Qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:yb.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(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),hb.info("appium session deleted",{...i}))}catch(o){hb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function uI(s){return await Te(`${s}/api/status`)}async function bb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Tb(s){if((await uI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var wb=v(()=>{"use strict";Ge()});var vb={};z(vb,{WorkerLocalTma:()=>dp});var $r,lp,up,pp,dp,Sb=v(()=>{"use strict";Ge();op();qn();B();$();_t();cp();we();wb();Ca();$r=C("worker-appium"),lp=class extends Error{},up=class extends Error{},pp=class extends Error{},dp=class extends Dt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Os(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}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.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:c}=this.options;await Tb(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:k}=await St.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=k}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),bb(o,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if($r.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),$r.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=ub({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:k,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),G={capabilities:{udid:a,...D}};$r.info("requesting new appium session from TMA",{tmaSessionSettings:G,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,G,g);this.sessionData=x;let R=await m.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await St.updateTmaDeviceDetails(a,this.options,t),$r.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(k){throw $r.error("failed to start application",{err:k}),k}}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}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new pp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Bt(n);await Js(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new up(l,{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 lp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.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 c=async()=>{try{let l=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(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw $r.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw $r.error("failed to run test once",{err:l}),l}}}});var Ib={};z(Ib,{WorkerAppium:()=>mp});var Eb,Wr,mp,Rb=v(()=>{"use strict";B();op();Eb=require("linkedom");qn();$();_t();cp();we();Ca();oe();ds();Wr=C("worker-appium"),mp=class extends Dt{initPlayer(t){return new Os(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,executionName:t.executionName,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}`},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:m,appPath:l,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(i,this.options.deviceUdid),h=await lb(f)):h=await cb({...f,shouldRunInEnhancedMode:a}),Wr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:pb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Wr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Wr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Wr.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"&&Hf(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){Wr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await St.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||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,Eb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Wr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await pe(u(),l)}catch(y){throw Wr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.155.0"}}});var Ma,xb=v(()=>{"use strict";B();Un();X();Ma=class{constructor(e){this.id=e;this.driver=new _r}async onDone(){try{await pe(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function Ab(){let s=await Promise.any(pI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var pI,Ua,Fa=v(()=>{"use strict";Ge();pI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ua=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Cb,Ba,Pb=v(()=>{"use strict";Cb=I(require("ws"));B();Fa();Ba=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=Ua({timeout:e}),r=new Cb.default(this._cdpUrl,t),n=Jt(o=>{r.once("open",o)}),i=Jt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),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((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var $a,fp,ja,kb=v(()=>{"use strict";B();$a=I(require("chrome-launcher"));Oo();Pb();An();fp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ba}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=ko({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...$a.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await $a.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 f=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),ms(()=>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}},ja=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new fp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var gp={};z(gp,{WorkerExtension:()=>si});function dI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ob(s){return dI(s)?s:new Error(s)}var mt,si,Wa=v(()=>{"use strict";$e();X();qn();B();$();_t();oe();xb();kb();ct();mt=C("worker-ext"),si=class extends Dt{initPlayer(){return this.options.useChromeLauncher?new ja(this.id):new Ma(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw mt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Qi(),initializedFromCache:Zi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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 pe(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return mt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw mt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw mt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await pe(Promise.all([a(t.driver,h,u),c(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ce))throw T;mt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),mt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=pe(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),w=await Ic(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){mt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(mt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(mt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw mt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Ob(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw mt.warn("failed to start url",{err:h}),Ob(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await l()}catch(d){throw mt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var yp={};z(yp,{WorkerExtensionSingleBrowser:()=>hp});var mI,fI,hp,bp=v(()=>{"use strict";$e();B();$();Nu();_t();Wa();mI=C("base-worker"),fI=500,hp=class extends si{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Gn(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 Q.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()&&(mI.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 ue(fI)}}});var Tp,Va,_b=v(()=>{"use strict";Un();ae();$e();xl();ct();hu();X();$();oe();Ih();Wo();Tp=C("worker-manager"),Va=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 K.SELENIUM:return(await Promise.resolve().then(()=>(tp(),ep))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Sb(),vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerAppium;default:return Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(bp(),yp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Wa(),gp))).WorkerExtension}else switch(r){case(Mr.find(n=>n===r)&&Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(bp(),yp))).WorkerExtensionSingleBrowser;case Mr.find(n=>n===r):return(await Promise.resolve().then(()=>(Wa(),gp))).WorkerExtension;case Vn.find(n=>n===r):return(await Promise.resolve().then(()=>(tp(),ep))).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,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var ie,Ee,Et,Gr,P,N,j,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new $o(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",w=(Ee=i.company)==null?void 0:Ee.companyId,b=(Et=i.company)==null?void 0:Et.name,S=i.source||"cli",E=i.user,k=(Gr=i.company)==null?void 0:Gr.planType,D=(P=i.company)==null?void 0:P.isStartUp,G=(N=i.projectData)==null?void 0:N.name,x=(j=i.projectData)==null?void 0:j.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(Oe,It,ve,ac,ci,cc)=>(d++,Pf({executionId:r,projectId:g,testId:It,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:G,companyPlan:k,source:S,user:E,lightweightMode:R,isStartUp:D,projectType:x,appSource:cc,gridType:L}),t.testStartAndReport(Oe,r,ve,ac,ci)),V=async(Oe,It,ve,ac,ci,cc)=>{var fd,gd,hd;d--;let et={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((fd=i.gridData)==null?void 0:fd.name),et.gridType=(gd=i.gridData)==null?void 0:gd.type,et.gridProvider=(hd=i.gridData)==null?void 0:hd.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(Oe,ve,r,ac,ci,et).catch(zT=>Tp.error("testEndAndReport threw an error",{err:zT})),ci)return;this.combinedTestResults[ve.resultId]=ve,kf({executionId:r,projectId:g,testId:It,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:G,companyPlan:k,source:S,user:E,lightweightMode:R,logger:Tp,isStartUp:D,projectType:x,appSource:cc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},W=(Oe,It)=>{this.combinedTestResults[It.resultId]=It,t.onTestIgnored(Oe,It.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},q=(Oe,It)=>t.onGridSlot(Oe,It);for(i.userData={loginData:{...Er(),refreshToken:Yi(),authData:Er(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,V,q,W)});try{let u=await kt(),f=await Xi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new zt;return h}catch(u){throw Tp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var wp,le,Lb=v(()=>{"use strict";wp=class{static colorString(e,t){return`${e}${t}${wp.Reset}`}},le=wp;le.Reset="\x1B[0m",le.Bright="\x1B[1m",le.Dim="\x1B[2m",le.Underscore="\x1B[4m",le.Blink="\x1B[5m",le.Reverse="\x1B[7m",le.Hidden="\x1B[8m",le.FgBlack="\x1B[30m",le.FgRed="\x1B[31m",le.FgGreen="\x1B[32m",le.FgYellow="\x1B[33m",le.FgBlue="\x1B[34m",le.FgMagenta="\x1B[35m",le.FgCyan="\x1B[36m",le.FgWhite="\x1B[37m",le.FgGray="\x1B[90m",le.BgBlack="\x1B[40m",le.BgRed="\x1B[41m",le.BgGreen="\x1B[42m",le.BgYellow="\x1B[43m",le.BgBlue="\x1B[44m",le.BgMagenta="\x1B[45m",le.BgCyan="\x1B[46m",le.BgWhite="\x1B[47m",le.BgGray="\x1B[100m"});var ni,Db,Ga,vp,Sp,Vr,Ep=v(()=>{"use strict";ni=I(require("lodash"));B();$();ae();oe();$e();as();Rl();xl();ge();de();_t();hg();X();_b();Wo();Db=require("uuid");Lb();({CLI_MODE:Ga}=jt),vp=C("test-plan-runner"),Sp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Sp._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},d=new Va(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=wi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,c,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};Of({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),l}catch(g){if(vp.error("error running test plan",{err:g}),g instanceof zt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ga.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),rr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=S();await k.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await Ap(i.project),ni.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,S,E;let l=re(),d=n.project;Yd(l),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new So(m,n,o,a),f=ni.default.chain(m).map(k=>{var D;return((D=k.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),U("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(l),U("after executionEnd"),{results:w,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(le.colorString(le.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Ip(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Rp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){vp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ni.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ii(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ii(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ii(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new A(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new A(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ga.APPIUM&&await Lu(e,r(l)),await se(c,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 hf(e,d);let f=u.overrideExecutionName||d.name;return await se(l[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:_u(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,k)=>Object.assign(E,k),{}),b=_u(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await xp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var c;vp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await xh(e,t);if(U("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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===Ga.APPIUM&&(a=await ti({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==Ga.APPIUM&&await Lu(e,l),U("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=wn(),r=[];await this.reportTestRunnerStarted(e.project,e),en(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ni.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Vr=Sp;Vr._id=(0,Db.v4)()});var Ae={};z(Ae,{addTestRetry:()=>nu,clearTestResult:()=>ku,deleteCloudflareTunnel:()=>Np,fetchLambdatestConfig:()=>ou,fixGridAppIDStructure:()=>np,forceUpdateCloudflareTunnelRoutes:()=>Dp,getAllGrids:()=>Il,getAppDetails:()=>ti,getApplitoolsIntegrationData:()=>Ap,getBrowserStackSessionMetaData:()=>II,getCloudflareTunnel:()=>Lp,getEditorUrl:()=>vI,getGridSlot:()=>El,getHybridGridProvider:()=>Sl,getLabFeaturesByProjectId:()=>yu,getMobileDevicesFromGrid:()=>ri,getRealData:()=>Xl,getS3Artifact:()=>kn,getS3ArtifactText:()=>Yl,getSuiteTestList:()=>Du,getTestPlan:()=>wI,getTestPlanTestList:()=>ii,getTestResults:()=>Nr,getUsageForCurrentBillingPeriod:()=>Op,initializeUserWithAuth:()=>_p,isTestResultCompleted:()=>Pu,keepAliveCompanySlots:()=>Kl,keepAliveGrid:()=>wl,loadSfdcCredential:()=>kp,loadTest:()=>$n,releaseCompanySlot:()=>ql,releaseGridSlot:()=>vl,reportExecutionFinished:()=>Eo,reportExecutionStarted:()=>su,reportRunnerFinished:()=>Rp,reportRunnerStarted:()=>Ip,requestCompanySlot:()=>Hl,saveRemoteStep:()=>Tu,saveTestPlanResult:()=>xp,updateCompanySlot:()=>zl,updateExecutionTests:()=>ru,updateRemoteRunFailure:()=>Mp,updateTestDataArtifact:()=>Io,updateTestResult:()=>qo,updateTestStatus:()=>Pr,uploadAppToGrid:()=>sp,uploadRunDataArtifact:()=>Ou,validateUserAccessKey:()=>bl});async function _s(){let s=await kt();if(!s)throw new Error("Failed to get token from server");return{[$c]:Vr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await _s(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function bI(s,e,t,r={},n=void 0){let i=await _s(),o={...r,...i};return await Js(`${he()}${s||""}`,e,t,o,n)}async function oi(s,e){let t=await _s();return await Pc(`${he()}${s||""}`,e,t)}async function Mb(s,e){let t=await _s();return await Ks(`${he()}${s||""}`,e,t)}async function TI(s,e){let t=await _s();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function Pe(s,e,t,r){let n=await _s();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function kn(s,e){return(0,ee.default)(()=>Pe(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Yl(s){return(0,ee.default)(()=>TI(`/storage${s}`))}async function Ip(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Rp(s){return await Mb("/test-runner",{projectId:s})}async function wI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Pe("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function kp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Pe(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function $n({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Pe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function xp(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Pr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>oi("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:gI,...i}),{retries:o,factor:1})}function ru(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>oi("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function su({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(so(),xf));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Eo(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>oi("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ii(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Du({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:te,factor:1})}async function ti({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Pe(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Op(s){try{return await(0,ee.default)(()=>Pe(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Nt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Pu(s,e,t){return(0,ee.default)(()=>Pe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Nr(s,e,t,r){return(0,ee.default)(()=>Pe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function wl(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function vl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Sl(s){return Re({url:"/grid/hybrid/provider",body:s})}function El(s){return(0,ee.default)(()=>Pe("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function _p({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Nt.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new A("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new A("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Cp.default[y](Cp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Nt.error("Error parsing error message from server",f)}throw f}}async function vI(){if(tt)return{editorUrl:tt};try{return await(0,ee.default)(()=>Pe("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Nt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Il(s){return(0,ee.default)(()=>Pe("/grid",{companyId:s}),{retries:te,factor:1})}function Xl(s,e,t){return(0,ee.default)(()=>Pe(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function qo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function ku(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Tu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function SI(s){return s.startsWith("/")?s:`/${s}`}function EI(s,e,t){let r=SI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ub(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=EI(c,yI,s),d=Buffer.from(Nb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>bI(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function nu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Ap(s){try{return await Pe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Nt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Lp(s,e){try{return await oi("/tunnel",{companyId:s,routes:e})}catch(t){return Nt.warn("could'nt get tunnel.",{err:t}),{}}}async function Dp(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Nt.warn("could'nt get tunnel.",{err:t});return}}async function Np(s,e){try{return await Mb(`/tunnel/${e}`,{companyId:s})}catch(t){Nt.warn("could'nt get tunnel.",{err:t});return}}function Mp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function ri({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${hI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Pe(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Nt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function sp({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function np(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Hl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function ql(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function zl(s,e,t){return(0,ee.default)(()=>oi("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Kl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function II(s,e){return await Te(`${Ws}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function bl(s){try{return await Pe("/v2/project/validateUserAccessKey",s),!0}catch(e){return Nt.error("error validating user access key",{error:e}),!1}}var Cp,cr,Nb,ee,Pp,gI,Nt,te,hI,yI,ou,yu,Ou,Io,ge=v(()=>{"use strict";Cp=I(require("chalk")),cr=I(require("lodash")),Nb=I(require("pako"));B();ae();oe();Ge();ct();ee=I(require("p-retry")),Pp=I(require("object-hash"));X();$();Ep();gI=rt(),Nt=C("testim service api"),te=3,hI="/grid",yI="test-result-artifacts";ou=async s=>(0,ee.default)(()=>Pe("/grid/lt/config",{companyId:s}),{retries:te,factor:1}),yu=async s=>(0,ee.default)(()=>Pe(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Ou=cr.memoize(async(s,e,t,r)=>{if(!cr.isEmpty(r))return await Ub(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Pp.default)(r)}:${e}:${t}`),Io=cr.memoize(async(s,e,t,r,n)=>!r||cr.isEmpty(r)?void 0:await Ub(s,e,t,JSON.stringify((()=>{let o=cr.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Fc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Pp.default)(r)}:${e}:${t}`)});function Ha(){return rt()}var Up=v(()=>{"use strict";B()});function AI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(rr)).getSessionPlayer()}catch{}})}function CI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Fp.default[i](Fp.default[n](r.text)))})}function PI(s){let{serviceUrl:e}=s;Vs(e),Pt(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:e})()}async function ai(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?xI:RI,f=Ha(),h=Nc(),g=await Vm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Ab()}catch(b){Fb.error("failed to get public ip",b)}let T=!0;U("before initializeUserWithAuth");let w=await Pt(async()=>(AI(a),T=!1,await _p({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:y})();return CI(w),PI(w.clientConfig),s.publicIps=[w.clientPublicIp],U("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Fb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),uf(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Fp,Fb,RI,xI,Bb=v(()=>{"use strict";Fp=I(require("chalk"));$e();ge();Xt();ct();Fa();oe();$();de();Up();B();is();ae();Fb=C("initializeUserWithAuth"),RI=1e3*60*5,xI=1e3*60*60*10});async function Wb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Ji():s.chromeBinaryLocation,e=cn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==K.EXTENSION&&await vr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await cl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await al(s.installCustomExtension,n)}return await e,t}async function Vb(s){var o;kI.info("prepare MockNetwork",{location:s});let e=await Lc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>jb*1e6)throw new Error(`${Bp} exceeded ${jb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Bp} cannot be parsed.${qa.EOL}${a}`)}let n=new $b.default;if(!n.validate(Kc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(qa.EOL);throw new Error(`${Bp} is malformed.${qa.EOL}${a}`)}return r.entries}var qa,$b,jb,Bp,kI,jp=v(()=>{"use strict";qa=I(require("node:os"));B();Sm();un();$b=I(require("ajv"));oe();dl();$();Bb();jb=1,Bp="JSON file supplied to --mock-network-pattern",kI=C("prepare runner")});function Kb(s){return s.start&&Ir(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Jb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new A("Agent port is not number");let t=Ro(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Yb=v(()=>{"use strict";_n();Rr();X()});var Ls,Gp,Xb=v(()=>{"use strict";Ls="SECRETS",Gp={get secretsKey(){return Ls},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ls}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ls]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ls):JSON.stringify(s).includes(Ls)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ls}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Jp={};z(Jp,{doLogin:()=>Kp,getProjectId:()=>MI,getToken:()=>UI});async function MI(){return eT("projectId")}async function UI(){return eT("token")}function Zb(s,e){return Promise.race([s,ue(e).then(()=>{throw new ce("timeout")})])}async function FI(){let s=(await import("express")).default(),e=async function(){return Zb(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ae)),{editorUrl:n}=await r();go(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${tt||mr}`)}return await e}async function Kp({overwriteExisting:s=!0,projects:e=null}={}){let t=Hp.homedir(),r=qp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Zb(FI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await Qb(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=l.project.ci.token,i.projectId=l.project.id,await Qb(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Qb(s,e){await zp.promises.writeFile(s,Ka.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function eT(s){let e=Hp.homedir(),t=qp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ka.parse((await zp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Hp,qp,Ka,zp,Ja=v(()=>{"use strict";Hp=I(require("os")),qp=I(require("path")),Ka=I(require("yaml"));B();zp=require("fs");X();$l();ae()});var lT={};z(lT,{process:()=>KI,program:()=>p});var Xp,iT,Ya,oT,Ht,Me,aT,BI,jI,Ne,Zp,$I,WI,rT,cT,VI,Qp,Xa,ed,Yp,Mt,sT,GI,HI,p,qI,zI,nT,KI,td=v(()=>{"use strict";Xp=I(require("ms")),iT=I(require("chalk")),Ya=I(require("node:fs")),oT=I(require("node:url")),Ht=I(require("lodash")),Me=I(require("node:path"));B();_n();Rr();Yb();Xt();aT=require("commander");oe();X();Hr();B();de();Xb();Wo();ae();BI="Testim Automation",jI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),Zp=new aT.Command,$I=s=>s.split(","),WI=(s,e)=>!s||s.length===0?e:s,rT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],cT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Zp.help(g=>g.split(`
403
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Oy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ya,ba,Dy=v(()=>{"use strict";ya=require("url");me();ba=class extends H{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,Ny=v(()=>{"use strict";me();B();Ta=class extends H{async performAction(){await ue(this.step.durationMS||0)}}});var wa,My=v(()=>{"use strict";me();wa=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Qn,Uy=v(()=>{"use strict";me();Qn=class extends H{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.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var va,Fy=v(()=>{"use strict";me();va=class extends H{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 By,zu,Ku,jy=v(()=>{"use strict";By=I(require("@applitools/spec-driver-webdriverio"));yi();we();zu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=wd["@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:By.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Ku=new zu});var Wy,$y,Zn,Vy=v(()=>{"use strict";Wy=I(require("lodash"));me();$();jy();$y=C("pixel-validation-step-action"),Zn=class extends H{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,c=await Ku.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},d;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Wy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),$y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){$y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Ku.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Cs,Ju=v(()=>{"use strict";Ss();X();aa();Cs=class extends or{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await vs(i,o,a,m,c,l,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,Gy=v(()=>{"use strict";Ju();ar=class extends Cs{isFailedResult(e){return e===!1}}});var Sa,Hy=v(()=>{"use strict";Ju();Sa=class extends Cs{isFailedResult(e){return!e}}});var Ea,qy=v(()=>{"use strict";Ss();me();X();Ea=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await ws(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Fr,zy=v(()=>{"use strict";me();Fr=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Ky=v(()=>{"use strict";me();be=class extends H{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,Jy=v(()=>{"use strict";me();Ia=class extends H{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,Yy=v(()=>{"use strict";me();Ra=class extends H{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 BE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function xa(s,e){BE(jE,e),e.registerLocateStepActionUtils(Kn.getUtils(s))}var jE,Yu=v(()=>{"use strict";qh();Jh();ny();iy();ay();uy();my();fy();gy();hy();Ty();wy();vy();Iy();Ay();Ly();Dy();Ny();My();Uy();Fy();Vy();Gy();Hy();qy();zy();Ky();Jy();Yy();jE={locate:Kn,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":As,"skip-code-step":As,"element-code-step":As,"evaluate-expression":na,"text-validation":Yn,"wait-for-text-validation":Yn,"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":Qn,"api-action":Qn,"api-code-step":Gt,"extract-text":va,"simple-ui-verification":Zn,"wait-for-simple-ui-verification":Zn,"cli-validation-download-file":Fr,"cli-wait-for-download-file":Fr,"network-validation-step":Fr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Sa,"node-package":Ea,"email-code-step":Gt,"cli-email-code-step":ar,"sfdc-internal-test-step":Ra,"sfdc-recorded-step":Ia,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Fr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Xy,$E,Ps,Xu=v(()=>{"use strict";Xy=["simple-ui-verification","wait-for-simple-ui-verification"],$E=[...Xy,"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"],Ps=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=$E.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 Xy.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 Zy={};z(Zy,{SeleniumTestPlayer:()=>ei});var Qy,WE,ei,Qu=v(()=>{"use strict";B();Qy=require("@applitools/eyes-sdk-core");Un();X();$();$u();$h();Hu();ea();Gh();qu();we();Yu();Xu();ae();WE=C("SeleniumTestPlayer"),ei=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Ps(ta());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new _r;let d=new Zo(this.driver);this.stepActionFactory=new l(d),xa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Xo(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Vh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new xs(this.driver),FrameLocator:m,portSelector:Qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Qy.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(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await pe((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&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)){WE.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=[new URL(tt||mr).hostname].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(c=>a.url.includes(c))){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 ep={};z(ep,{WorkerSelenium:()=>Zu});function GE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>U(`Got event ${t}`))}var Aa,VE,Zu,tp=v(()=>{"use strict";B();$e();qn();$();_t();No();oe();Bu();X();Qu();we();ct();Aa=C("worker-selenium"),VE=1e9,Zu=class extends Dt{initPlayer(t){return new ei(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){U("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Rs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=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:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),U("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),U("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,VE),await this.windowUtils.validatePageIsAvailable(),U("in WorkerSelenium after navigate")}catch(l){let d=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=l.message&&l.message==="invalid argument";throw l instanceof xt||d||m?new xt(`Page '${c}' is not available`):(Aa.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:Qi(),initializedFromCache:Zi()}),l)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),GE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(l=(await jn(this.options))[this.testId]);let d=async()=>pe(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(Aa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(Aa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});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 Aa.error("failed to run test once",{err:u}),u}}}});var eb,tb,He,HE,qE,rp,St,Ca=v(()=>{"use strict";eb=I(require("ora")),tb=require("jimp");ae();Ge();ge();$();oe();we();de();He=C("mobile-grid-service"),HE="https://tdc.tricentis-cloud.com",qE="https://ui.headspin.io",rp=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.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===_.TESTIM_HEADSPIN?`${r||gc}/${yc}/devices`:t===_.TESTIM_TDC?`${r||hc}/${yc}/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 Te(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 Ys(`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===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.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,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let d=await ri({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===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.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,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Pr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(c,"base64"),m=await tb.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ws}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?qE:HE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Pr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}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 np({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 ti({appId:e,projectId:t});return{appUrl:`${he()}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Md*60))+1)*60*1e3,Math.max(Nd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.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 c=r||t.mobileApp,l=(0,eb.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 sp({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw l.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 c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,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:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:m,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Ws}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${bc}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?gc:hc}/${bc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Ud}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,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(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Cc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},St=new rp});function rb({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"&&!zE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function KE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.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 JE(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 YE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),d=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:JE(t),[`${c}:enableBatch`]:l||d,...!r&&{"appium:noReset":n},...m&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Pa(s){return"id"in s?s.id:s.packageName}function XE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function QE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=XE(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&&c};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&&c};default:throw Error(`unsupported mobile project ${s}`)}}function jr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Pa(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"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 sb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=YE(o.type,i,n);return QE({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Oa({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 _a({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Tc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Tc:".*")}function ZE(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 eI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...ka(s,ks)}}function nb(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 tI(s){return nb(s,e=>e.startsWith("browserstack."),"browserstack.")}function rI(s){return nb(s,e=>!e.startsWith("browserstack."))}function ib(s){return!s||!ob(s)?"2.0.0":s}function ob(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function ab({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),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),d=c||l;if(t){let m=ob(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}async function sI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=ZE(i,s),h=await ri({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Oa({osVersion:l,mobileConfig:m}),T=(g==null?void 0:g.name)??_a({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function nI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Oa({osVersion:c,mobileConfig:d}),y=_a({deviceName:l,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...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,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Fd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=eI(b)),t="",jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:ks}})}function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Oa({osVersion:c,mobileConfig:d}),f=_a({deviceName:l,mobileConfig:d,projectType:s,gridType:m}),h=(0,Br.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ab({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:ib(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...ka(h,ks),"sauce:options":{...T,...w,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:s,sessionCaps:b,appiumPrefix:ks,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return jr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function oI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:d}=i,m=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Oa({osVersion:l,mobileConfig:m}),h=_a({deviceName:d,mobileConfig:m,projectType:e,gridType:u}),g=tI(i.browserstack),y=(0,Br.omit)(rI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},w=O.flags.enableAppium2BrowserStack.isEnabled();if(w||ab({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let S={...T,userName:o.user,accessKey:o.key,appiumVersion:w?"2.0.1":ib(g.appiumVersion),debug:!0,networkLogs:!0},E={"appium:platformVersion":f,"appium:deviceName":h,...ka(y,ks),"bstack:options":{...S,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:e,sessionCaps:E,appiumPrefix:ks,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...ka(g,"browserstack.")};return jr({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function aI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return sb(s);if(_.TESTIM_TVC===s.gridInfo.type)return await sI(s);if(_.P_CLOUDY===s.gridInfo.type)return nI(s);if(_.SAUCELABS===s.gridInfo.type)return iI(s);if(_.BROWSERSTACK===s.gridInfo.type)return oI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function cI(s,e){var l,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function cb(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}`);rb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=St.getGridConnection(e),c=await aI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=cI(r,i==null?void 0:i.mobile);if(!(0,Br.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();c[`${y}:selector`]=w}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,d=O.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,ip.default)("2m"),f=(0,ip.default)("12m"),h=hr(O.flags.appiumConnectionRetryCount.getValue(),m),g=hr(O.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function lb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;rb({nativeAppMetadata:r,appPath:i,gridInfo:t}),KE({deviceUdid:l,gridInfo:t,testRunConfig:c});let d=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await St.getGridDirectConnection(t,d),f=sb({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function ub(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=jr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function pb(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 ip,Br,ks,zE,op=v(()=>{"use strict";ip=I(require("ms"));de();oe();Ca();Br=require("lodash");B();ae();ge();ks="appium:",zE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var La,mb=v(()=>{"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,fb=v(()=>{"use strict";B();Da=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn}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 ap,Na,gb=v(()=>{"use strict";$();ap=C("mobile-frame-locator-mock"),Na=class{foundFrameCallback(){return ap.info("foundFrameCallback-mock invoked"),{}}locate(){return ap.info("locate-mock invoked"),{}}async findFrame(){return ap.info("findFrame-mock invoked"),{}}}});var lI,yb,hb,Os,cp=v(()=>{"use strict";lI=I(require("webdriverio")),yb=require("@applitools/eyes-sdk-core");mb();Hu();$();fb();qu();we();Yu();gb();Xu();hb=C("appium-test-player"),Os=class{constructor(e,t,r,n=lI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:d}=Z(),m=new Da(this.driver);this.stepActionFactory=new l(m),xa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ps(ta()),this.sessionPlayer=new a(e,{tabService:new La,cookieUtils:void 0,FrameLocator:Na,portSelector:Qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:yb.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(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),hb.info("appium session deleted",{...i}))}catch(o){hb.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function uI(s){return await Te(`${s}/api/status`)}async function bb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Tb(s){if((await uI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var wb=v(()=>{"use strict";Ge()});var vb={};z(vb,{WorkerLocalTma:()=>dp});var $r,lp,up,pp,dp,Sb=v(()=>{"use strict";Ge();op();qn();B();$();_t();cp();we();wb();Ca();$r=C("worker-appium"),lp=class extends Error{},up=class extends Error{},pp=class extends Error{},dp=class extends Dt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Os(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}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.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:c}=this.options;await Tb(o);let{project:l,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:k}=await St.getMobileAppDataByAppId({appId:f,projectId:l,token:d});t.nativeApp=k}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),bb(o,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if($r.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),$r.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=ub({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:k,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),G={capabilities:{udid:a,...D}};$r.info("requesting new appium session from TMA",{tmaSessionSettings:G,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,G,g);this.sessionData=x;let R=await m.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await St.updateTmaDeviceDetails(a,this.options,t),$r.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(k){throw $r.error("failed to start application",{err:k}),k}}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}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new pp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Bt(n);await Js(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new up(l,{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 lp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=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(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw $r.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw $r.error("failed to run test once",{err:l}),l}}}});var Ib={};z(Ib,{WorkerAppium:()=>mp});var Eb,Wr,mp,Rb=v(()=>{"use strict";B();op();Eb=require("linkedom");qn();$();_t();cp();we();Ca();oe();ds();Wr=C("worker-appium"),mp=class extends Dt{initPlayer(t){return new Os(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await St.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,executionName:t.executionName,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}`},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:m,appPath:l,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await St.lockDevice(i,this.options.deviceUdid),h=await lb(f)):h=await cb({...f,shouldRunInEnhancedMode:a}),Wr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:pb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await St.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Wr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Wr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Wr.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"&&Hf(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){Wr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await St.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||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,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,Eb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Wr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await pe(u(),l)}catch(y){throw Wr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.156.0"}}});var Ma,xb=v(()=>{"use strict";B();Un();X();Ma=class{constructor(e){this.id=e;this.driver=new _r}async onDone(){try{await pe(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function Ab(){let s=await Promise.any(pI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var pI,Ua,Fa=v(()=>{"use strict";Ge();pI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];Ua=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Cb,Ba,Pb=v(()=>{"use strict";Cb=I(require("ws"));B();Fa();Ba=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=Ua({timeout:e}),r=new Cb.default(this._cdpUrl,t),n=Jt(o=>{r.once("open",o)}),i=Jt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),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((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var $a,fp,ja,kb=v(()=>{"use strict";B();$a=I(require("chrome-launcher"));Oo();Pb();An();fp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ba}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}=e,m=ko({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...$a.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await $a.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 f=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),ms(()=>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}},ja=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new fp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var gp={};z(gp,{WorkerExtension:()=>si});function dI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Ob(s){return dI(s)?s:new Error(s)}var mt,si,Wa=v(()=>{"use strict";$e();X();qn();B();$();_t();oe();xb();kb();ct();mt=C("worker-ext"),si=class extends Dt{initPlayer(){return this.options.useChromeLauncher?new ja(this.id):new Ma(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw mt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Qi(),initializedFromCache:Zi(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var 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 pe(e.runTestUsingCDP(d.cdpTestRunner),m,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return mt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw mt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},c=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},l=async()=>{var f;if(U("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw mt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await pe(Promise.all([a(t.driver,h,u),c(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ce))throw T;mt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),mt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=Qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=pe(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),w=await Ic(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){mt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(mt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(mt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw mt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),Ob(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw mt.warn("failed to start url",{err:h}),Ob(h)}};t.driver.start();try{return await super.runTestOnce(e,t),U("WorkerExtension super.runTestOnce"),await l()}catch(d){throw mt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var yp={};z(yp,{WorkerExtensionSingleBrowser:()=>hp});var mI,fI,hp,bp=v(()=>{"use strict";$e();B();$();Nu();_t();Wa();mI=C("base-worker"),fI=500,hp=class extends si{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Gn(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 Q.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()&&(mI.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 ue(fI)}}});var Tp,Va,_b=v(()=>{"use strict";Un();ae();$e();xl();ct();hu();X();$();oe();Ih();Wo();Tp=C("worker-manager"),Va=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 K.SELENIUM:return(await Promise.resolve().then(()=>(tp(),ep))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Sb(),vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerAppium;default:return Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(bp(),yp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Wa(),gp))).WorkerExtension}else switch(r){case(Mr.find(n=>n===r)&&Fn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(bp(),yp))).WorkerExtensionSingleBrowser;case Mr.find(n=>n===r):return(await Promise.resolve().then(()=>(Wa(),gp))).WorkerExtension;case Vn.find(n=>n===r):return(await Promise.resolve().then(()=>(tp(),ep))).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,c){if(e&&e.length===0)return;let l=!1,d=0,m=(u,f)=>new Promise(h=>{var ie,Ee,Et,Gr,P,N,j,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new $o(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",w=(Ee=i.company)==null?void 0:Ee.companyId,b=(Et=i.company)==null?void 0:Et.name,S=i.source||"cli",E=i.user,k=(Gr=i.company)==null?void 0:Gr.planType,D=(P=i.company)==null?void 0:P.isStartUp,G=(N=i.projectData)==null?void 0:N.name,x=(j=i.projectData)==null?void 0:j.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(Oe,It,ve,ac,ci,cc)=>(d++,Pf({executionId:r,projectId:g,testId:It,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:G,companyPlan:k,source:S,user:E,lightweightMode:R,isStartUp:D,projectType:x,appSource:cc,gridType:L}),t.testStartAndReport(Oe,r,ve,ac,ci)),V=async(Oe,It,ve,ac,ci,cc)=>{var fd,gd,hd;d--;let et={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((fd=i.gridData)==null?void 0:fd.name),et.gridType=(gd=i.gridData)==null?void 0:gd.type,et.gridProvider=(hd=i.gridData)==null?void 0:hd.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(Oe,ve,r,ac,ci,et).catch(zT=>Tp.error("testEndAndReport threw an error",{err:zT})),ci)return;this.combinedTestResults[ve.resultId]=ve,kf({executionId:r,projectId:g,testId:It,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:G,companyPlan:k,source:S,user:E,lightweightMode:R,logger:Tp,isStartUp:D,projectType:x,appSource:cc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},W=(Oe,It)=>{this.combinedTestResults[It.resultId]=It,t.onTestIgnored(Oe,It.resultId),d--,(Object.keys(this.combinedTestResults).length===y||l&&d===0)&&h(this.combinedTestResults)},q=(Oe,It)=>t.onGridSlot(Oe,It);for(i.userData={loginData:{...Er(),refreshToken:Yi(),authData:Er(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},U("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,V,q,W)});try{let u=await kt(),f=await Xi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new zt;return h}catch(u){throw Tp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var wp,le,Lb=v(()=>{"use strict";wp=class{static colorString(e,t){return`${e}${t}${wp.Reset}`}},le=wp;le.Reset="\x1B[0m",le.Bright="\x1B[1m",le.Dim="\x1B[2m",le.Underscore="\x1B[4m",le.Blink="\x1B[5m",le.Reverse="\x1B[7m",le.Hidden="\x1B[8m",le.FgBlack="\x1B[30m",le.FgRed="\x1B[31m",le.FgGreen="\x1B[32m",le.FgYellow="\x1B[33m",le.FgBlue="\x1B[34m",le.FgMagenta="\x1B[35m",le.FgCyan="\x1B[36m",le.FgWhite="\x1B[37m",le.FgGray="\x1B[90m",le.BgBlack="\x1B[40m",le.BgRed="\x1B[41m",le.BgGreen="\x1B[42m",le.BgYellow="\x1B[43m",le.BgBlue="\x1B[44m",le.BgMagenta="\x1B[45m",le.BgCyan="\x1B[46m",le.BgWhite="\x1B[47m",le.BgGray="\x1B[100m"});var ni,Db,Ga,vp,Sp,Vr,Ep=v(()=>{"use strict";ni=I(require("lodash"));B();$();ae();oe();$e();as();Rl();xl();ge();de();_t();hg();X();_b();Wo();Db=require("uuid");Lb();({CLI_MODE:Ga}=jt),vp=C("test-plan-runner"),Sp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Sp._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},d=new Va(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=wi||i.parallel,y=!1;U("right before this.workerManager.runTests");let T=await d.runTests(t,c,o,a,i,n,g,y);U("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};Of({executionId:o,projectId:i.project}),U("right before runBeforeTests");try{return await m(),U("right before runTestPlanTests"),await u(),U("right after runTestPlanTests"),await f(),l}catch(g){if(vp.error("error running test plan",{err:g}),g instanceof zt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ga.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),rr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=S();await k.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await Ap(i.project),ni.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,S,E;let l=re(),d=n.project;Yd(l),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new So(m,n,o,a),f=ni.default.chain(m).map(k=>{var D;return((D=k.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,d,this.startTime,i,g);U("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),U("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return U("before executionEnd"),await u.executionEnd(l),U("after executionEnd"),{results:w,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(le.colorString(le.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Ip(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await Rp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){vp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ni.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ii(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ii(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ii(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new A(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new A(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ga.APPIUM&&await Lu(e,r(l)),await se(c,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 hf(e,d);let f=u.overrideExecutionName||d.name;return await se(l[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:_u(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,k)=>Object.assign(E,k),{}),b=_u(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await xp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var c;vp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),U("before getSuite");let r=await xh(e,t);if(U("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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===Ga.APPIUM&&(a=await ti({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=l[0];m.resultId=e.resultId,l=[m]}e.mode!==Ga.APPIUM&&await Lu(e,l),U("right before runTestPlan");let d=await this.runTestPlan([],l,[],e,i,null,t,o);return U("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=wn(),r=[];await this.reportTestRunnerStarted(e.project,e),en(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ni.default.flattenDeep(r);return U("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),U("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Vr=Sp;Vr._id=(0,Db.v4)()});var Ae={};z(Ae,{addTestRetry:()=>nu,clearTestResult:()=>ku,deleteCloudflareTunnel:()=>Np,fetchLambdatestConfig:()=>ou,fixGridAppIDStructure:()=>np,forceUpdateCloudflareTunnelRoutes:()=>Dp,getAllGrids:()=>Il,getAppDetails:()=>ti,getApplitoolsIntegrationData:()=>Ap,getBrowserStackSessionMetaData:()=>II,getCloudflareTunnel:()=>Lp,getEditorUrl:()=>vI,getGridSlot:()=>El,getHybridGridProvider:()=>Sl,getLabFeaturesByProjectId:()=>yu,getMobileDevicesFromGrid:()=>ri,getRealData:()=>Xl,getS3Artifact:()=>kn,getS3ArtifactText:()=>Yl,getSuiteTestList:()=>Du,getTestPlan:()=>wI,getTestPlanTestList:()=>ii,getTestResults:()=>Nr,getUsageForCurrentBillingPeriod:()=>Op,initializeUserWithAuth:()=>_p,isTestResultCompleted:()=>Pu,keepAliveCompanySlots:()=>Kl,keepAliveGrid:()=>wl,loadSfdcCredential:()=>kp,loadTest:()=>$n,releaseCompanySlot:()=>ql,releaseGridSlot:()=>vl,reportExecutionFinished:()=>Eo,reportExecutionStarted:()=>su,reportRunnerFinished:()=>Rp,reportRunnerStarted:()=>Ip,requestCompanySlot:()=>Hl,saveRemoteStep:()=>Tu,saveTestPlanResult:()=>xp,updateCompanySlot:()=>zl,updateExecutionTests:()=>ru,updateRemoteRunFailure:()=>Mp,updateTestDataArtifact:()=>Io,updateTestResult:()=>qo,updateTestStatus:()=>Pr,uploadAppToGrid:()=>sp,uploadRunDataArtifact:()=>Ou,validateUserAccessKey:()=>bl});async function _s(){let s=await kt();if(!s)throw new Error("Failed to get token from server");return{[$c]:Vr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await _s(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function bI(s,e,t,r={},n=void 0){let i=await _s(),o={...r,...i};return await Js(`${he()}${s||""}`,e,t,o,n)}async function oi(s,e){let t=await _s();return await Pc(`${he()}${s||""}`,e,t)}async function Mb(s,e){let t=await _s();return await Ks(`${he()}${s||""}`,e,t)}async function TI(s,e){let t=await _s();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function Pe(s,e,t,r){let n=await _s();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function kn(s,e){return(0,ee.default)(()=>Pe(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Yl(s){return(0,ee.default)(()=>TI(`/storage${s}`))}async function Ip(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function Rp(s){return await Mb("/test-runner",{projectId:s})}async function wI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Pe("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function kp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Pe(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function $n({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Pe(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function xp(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Pr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>oi("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:gI,...i}),{retries:o,factor:1})}function ru(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>oi("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function su({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(so(),xf));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:c,isLocalRun:l}},retry:3})}function Eo(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>oi("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ii(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Du({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:d}}),{retries:te,factor:1})}async function ti({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Pe(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Op(s){try{return await(0,ee.default)(()=>Pe(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Nt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Pu(s,e,t){return(0,ee.default)(()=>Pe(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Nr(s,e,t,r){return(0,ee.default)(()=>Pe(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function wl(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function vl(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Sl(s){return Re({url:"/grid/hybrid/provider",body:s})}function El(s){return(0,ee.default)(()=>Pe("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function _p({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Nt.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new A("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new A("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Cp.default[y](Cp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Nt.error("Error parsing error message from server",f)}throw f}}async function vI(){if(tt)return{editorUrl:tt};try{return await(0,ee.default)(()=>Pe("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Nt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function Il(s){return(0,ee.default)(()=>Pe("/grid",{companyId:s}),{retries:te,factor:1})}function Xl(s,e,t){return(0,ee.default)(()=>Pe(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function qo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function ku(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Tu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function SI(s){return s.startsWith("/")?s:`/${s}`}function EI(s,e,t){let r=SI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ub(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=EI(c,yI,s),d=Buffer.from(Nb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>bI(`/storage${l}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function nu({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Ap(s){try{return await Pe(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Nt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Lp(s,e){try{return await oi("/tunnel",{companyId:s,routes:e})}catch(t){return Nt.warn("could'nt get tunnel.",{err:t}),{}}}async function Dp(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Nt.warn("could'nt get tunnel.",{err:t});return}}async function Np(s,e){try{return await Mb(`/tunnel/${e}`,{companyId:s})}catch(t){Nt.warn("could'nt get tunnel.",{err:t});return}}function Mp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function ri({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${hI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Pe(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Nt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function sp({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function np(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Hl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function ql(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function zl(s,e,t){return(0,ee.default)(()=>oi("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Kl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function II(s,e){return await Te(`${Ws}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function bl(s){try{return await Pe("/v2/project/validateUserAccessKey",s),!0}catch(e){return Nt.error("error validating user access key",{error:e}),!1}}var Cp,cr,Nb,ee,Pp,gI,Nt,te,hI,yI,ou,yu,Ou,Io,ge=v(()=>{"use strict";Cp=I(require("chalk")),cr=I(require("lodash")),Nb=I(require("pako"));B();ae();oe();Ge();ct();ee=I(require("p-retry")),Pp=I(require("object-hash"));X();$();Ep();gI=rt(),Nt=C("testim service api"),te=3,hI="/grid",yI="test-result-artifacts";ou=async s=>(0,ee.default)(()=>Pe("/grid/lt/config",{companyId:s}),{retries:te,factor:1}),yu=async s=>(0,ee.default)(()=>Pe(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Ou=cr.memoize(async(s,e,t,r)=>{if(!cr.isEmpty(r))return await Ub(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,Pp.default)(r)}:${e}:${t}`),Io=cr.memoize(async(s,e,t,r,n)=>!r||cr.isEmpty(r)?void 0:await Ub(s,e,t,JSON.stringify((()=>{let o=cr.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:Fc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,Pp.default)(r)}:${e}:${t}`)});function Ha(){return rt()}var Up=v(()=>{"use strict";B()});function AI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(rr)).getSessionPlayer()}catch{}})}function CI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Fp.default[i](Fp.default[n](r.text)))})}function PI(s){let{serviceUrl:e}=s;Vs(e),Pt(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:e})()}async function ai(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?xI:RI,f=Ha(),h=Nc(),g=await Vm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Ab()}catch(b){Fb.error("failed to get public ip",b)}let T=!0;U("before initializeUserWithAuth");let w=await Pt(async()=>(AI(a),T=!1,await _p({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:c,grid:l,publicIp:y})();return CI(w),PI(w.clientConfig),s.publicIps=[w.clientPublicIp],U("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(Fb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),uf(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Fp,Fb,RI,xI,Bb=v(()=>{"use strict";Fp=I(require("chalk"));$e();ge();Xt();ct();Fa();oe();$();de();Up();B();is();ae();Fb=C("initializeUserWithAuth"),RI=1e3*60*5,xI=1e3*60*60*10});async function Wb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Ji():s.chromeBinaryLocation,e=cn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==K.EXTENSION&&await vr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await cl(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await al(s.installCustomExtension,n)}return await e,t}async function Vb(s){var o;kI.info("prepare MockNetwork",{location:s});let e=await Lc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>jb*1e6)throw new Error(`${Bp} exceeded ${jb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${Bp} cannot be parsed.${qa.EOL}${a}`)}let n=new $b.default;if(!n.validate(Kc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(qa.EOL);throw new Error(`${Bp} is malformed.${qa.EOL}${a}`)}return r.entries}var qa,$b,jb,Bp,kI,jp=v(()=>{"use strict";qa=I(require("node:os"));B();Sm();un();$b=I(require("ajv"));oe();dl();$();Bb();jb=1,Bp="JSON file supplied to --mock-network-pattern",kI=C("prepare runner")});function Kb(s){return s.start&&Ir(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Jb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new A("Agent port is not number");let t=Ro(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Yb=v(()=>{"use strict";_n();Rr();X()});var Ls,Gp,Xb=v(()=>{"use strict";Ls="SECRETS",Gp={get secretsKey(){return Ls},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ls}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ls]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ls):JSON.stringify(s).includes(Ls)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ls}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let d=l[1];o[c]=e[d]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let d=l[1];o[a]=e[d]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Jp={};z(Jp,{doLogin:()=>Kp,getProjectId:()=>MI,getToken:()=>UI});async function MI(){return eT("projectId")}async function UI(){return eT("token")}function Zb(s,e){return Promise.race([s,ue(e).then(()=>{throw new ce("timeout")})])}async function FI(){let s=(await import("express")).default(),e=async function(){return Zb(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Ae)),{editorUrl:n}=await r();go(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${tt||mr}`)}return await e}async function Kp({overwriteExisting:s=!0,projects:e=null}={}){let t=Hp.homedir(),r=qp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await Zb(FI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await Qb(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=l.project.ci.token,i.projectId=l.project.id,await Qb(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Qb(s,e){await zp.promises.writeFile(s,Ka.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function eT(s){let e=Hp.homedir(),t=qp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ka.parse((await zp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Hp,qp,Ka,zp,Ja=v(()=>{"use strict";Hp=I(require("os")),qp=I(require("path")),Ka=I(require("yaml"));B();zp=require("fs");X();$l();ae()});var lT={};z(lT,{process:()=>KI,program:()=>p});var Xp,iT,Ya,oT,Ht,Me,aT,BI,jI,Ne,Zp,$I,WI,rT,cT,VI,Qp,Xa,ed,Yp,Mt,sT,GI,HI,p,qI,zI,nT,KI,td=v(()=>{"use strict";Xp=I(require("ms")),iT=I(require("chalk")),Ya=I(require("node:fs")),oT=I(require("node:url")),Ht=I(require("lodash")),Me=I(require("node:path"));B();_n();Rr();Yb();Xt();aT=require("commander");oe();X();Hr();B();de();Xb();Wo();ae();BI="Testim Automation",jI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Ne=(s,e)=>(e.push(s),e),Zp=new aT.Command,$I=s=>s.split(","),WI=(s,e)=>!s||s.length===0?e:s,rT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],cT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Zp.help(g=>g.split(`
404
404
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!c(T)&&!l(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
405
405
  `))},VI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(iT.default.yellow(`
406
406
  WARNING: ${s} is deprecated. ${t}