@testim/testim-cli 4.43.0 → 4.44.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
- "use strict";var Kb=Object.create;var Mn=Object.defineProperty;var Jb=Object.getOwnPropertyDescriptor;var Yb=Object.getOwnPropertyNames;var Xb=Object.getPrototypeOf,Qb=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Mn(s,t,{get:e[t],enumerable:!0})},Tp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Yb(e))!Qb.call(s,n)&&n!==t&&Mn(s,n,{get:()=>e[n],enumerable:!(r=Jb(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?Kb(Xb(s)):{},Tp(e||!s||!s.__esModule?Mn(t,"default",{value:s,enumerable:!0}):t,s)),fe=s=>Tp(Mn({},"__esModule",{value:!0}),s);var Fe={};V(Fe,{log:()=>D,measure:()=>eT});function D(...s){if(!Ep)return;let e=Date.now();console.log(`${e-Zb} ${e-vp} `,...s),vp=e}function eT(s,e){if(!Ep)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Ep,Zb,vp,Be=T(()=>{"use strict";Ep=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,Zb=Date.now(),vp=Date.now()});var Ta,Gt,wa,Or=T(()=>{"use strict";Ta={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},Gt="element-6066-11e4-a52e-4f735466cecf",wa=79});function te(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 at(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function va(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function je(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 Ea=T(()=>{"use strict"});var Ia,Sp,Ip,Vn=T(()=>{Ia={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","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:"1.4.5-lts.1"},Sp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",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",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsonwebtoken:"9.0.0",linkedom:"0.15.3",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"8.19.2","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":"5.0.0","rox-node":"4.9.18",semver:"7.5.4","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.5.0",yaml:"2.2.2"},Ip={node:">= 16.0.0"}});var As,Rp,Ap,Gn,xp,Hn,xs,Pp,me,Cp,kp,qn,ke,Ra,Op,zn,_p,RI,Lp,AI,Dp,Mp,_r,Np,Up,Fp,Bp,jp,$p,Wp,Vp,Gp,Hp,qp,zp,Kp,Aa,Jp,le=T(()=>{"use strict";As=process.env.SERVICES_HOST||"https://services.testim.io",Rp="https://testimstatic.blob.core.windows.net",Ap="https://tstresultfiles.azureedge.net";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:As,As=process.env.SERVICES_HOST);Gn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),xp=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Hn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),xs=process.env.EDITOR_URL,Pp=process.env.WEBSOCKET_HOST||`${As}/ws`,me=As,Cp=parseInt(process.env.LOGGER_CONSOLE||"0",10),kp=parseInt(process.env.LOGGER_DEBUG||"0",10),qn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),ke=parseInt(process.env.IS_ON_PREM||"0",10),Ra=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Op=parseInt(process.env.DEBUG_MODE||"0",10),zn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,_p=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",RI=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Lp=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),AI=process.env.APPIUM_VERSION||"1.10.1",Dp=process.env.GATEWAY_URL,Mp=process.env.EXTENSION_SERVICES_HOST||As,_r=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Rp,Np=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Ap,Up=Rp,Fp=Ap,Bp=5*60*1e3,jp=40,$p=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",Wp=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",Vp=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",Gp=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",Hp=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",qp=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",zp=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Kp=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Aa=process.env.PCLOUDY_MOBILE_API_URL||"https://device.pcloudy.com/api",Jp=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api"});var xa={};V(xa,{CoralogixTransport:()=>Lr});var Ie,Yp,sT,nT,Lr,Pa=T(()=>{"use strict";Ie=require("@testim/coralogix-logger"),Yp=E(require("winston-transport")),sT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},nT=["err","error","reason","e"],Lr=class extends Yp.default{constructor(t){t=Object.assign({},Lr.options,t);super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),m=new Ie.Log;m.severity=sT[o],m.text=i,m.category=n,l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
3
- ${l.msg}`));for(let u of nT)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&&(i&&!d&&(l.msg=i),m.text=l),this.logger.addLog(m),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Lr.options=t}}});var Da={};V(Da,{getLogger:()=>A,setExecutionId:()=>Oa,setProjectId:()=>_a,setProxyUri:()=>La});function aT(){let s=[],e=()=>Promise.resolve();if(!ke){let{CoralogixTransport:t}=(Pa(),fe(xa));t.configure(Zp);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Cp&&s.push(new bt.transports.Console({format:bt.format.combine(bt.format.colorize(),bt.format.simple())})),[s,e]}function Oa(s){Ca=s}function _a(s){ed=s}function La(s){if(ke||!s)return;let{CoralogixTransport:e}=(Pa(),fe(xa));e.configure({...Zp,proxyUri:s})}function Xp(s){return{projectId:ed,time:new Date().toISOString(),...Ca&&!s&&{executionId:Ca}}}function A(s){return new ka(dT.child({category:s}))}var Qp,bt,oT,iT,Zp,cT,lT,uT,pT,dT,Ca,ed,ka,j=T(()=>{"use strict";Qp=E(require("os")),bt=E(require("winston"));le();B();oT=Qp.hostname(),iT=ct(),Zp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[cT,lT]=aT(),uT=kp?"debug":"info",pT={release:Boolean(!0),branch:"production"},dT=bt.createLogger({levels:bt.config.syslog.levels,level:uT,transports:cT,defaultMeta:{name:"runner",hostname:oT,nodeVersion:process.version,runnerVersion:iT,...pT}}),Ca=null,ed=null;ka=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,Object.assign({meta:r,message:t},Xp(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Xp(n)))}catch{}}}waitForFlush(){return lT()}}});var Yn,Dr,P,Ht,ur,Tt,Kn,Mr,re,Ps,wt,Nr,vt,Jn,Ur,Fr,Br,Cs,z=T(()=>{"use strict";Yn=require("p-retry"),Dr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Ht=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},ur=class extends Error{constructor(t,r){super(t);this.type=r}},Tt=class extends Yn.AbortError{},Kn=class extends Yn.AbortError{},Mr=class extends Yn.AbortError{},re=class extends Error{},Ps=class extends Error{},wt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Nr=class extends wt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},vt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Jn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Ur=class extends Error{},Fr=class extends Error{constructor(t){super();this.innerStack=t}},Br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Cs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ma(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ie(s){return(0,sd.setTimeout)(s)}function Na(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){Hn&&!td&&(td=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new re(t);return e=Hn?Number(Hn)||6e5:e,Promise.race([s,ie(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){rd||=(await import("p-limit")).default;let r=rd(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var sd,td,rd,Ua=T(()=>{"use strict";sd=require("timers/promises");z();le();td=!1});var Os,nd,mT,ks,od,fT,gT,id,ad=T(()=>{"use strict";Os=E(require("lodash"));le();nd=require("dns");j();Ua();mT=A("http-request-counters"),ks=!1,od=async()=>{if(ke)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>nd.promises.lookup(t)));return e||(ks=!0),e}catch{return mT.error("network connectivity test failed"),ks=!0,!1}},fT=Os.throttle(od,10*1e3),gT=60*1e3*15,id=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},gT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),ks||fT(),a}}}async function r(){if(ks||!await od())return!1;let n=Os.sum([...s.fail.values()]),o=Os.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>ks,t}});var Ze={};V(Ze,{deleteFullRes:()=>wT,deleteReq:()=>_s,didNetworkConnectivityTestFail:()=>Ha,download:()=>Va,get:()=>Re,getFullRes:()=>ET,getText:()=>Ds,head:()=>ST,isNetworkHealthy:()=>Ga,post:()=>We,postForm:()=>Ls,postFullRes:()=>vT,postText:()=>$a,put:()=>Wa});function yT(){return global.caFileContent}function bT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function TT(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function pr(s,e=!1){let t=yT();t&&s.ca(t);let r=!e&&TT();r&&s.proxy(r)}async function cd(s,e={},t={},r=jr){let n=Et.default.delete(s).send(e).timeout(r).set(t);return pr(n),await n}async function Ba(s,e,t={},r=jr,n=0){let o=Et.default.post(s).send(e).timeout(r).set(t);pr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function ja(s,e,t={},r=jr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),pr(i,o),await i}var Et,Fa,$e,jr,hT,Ot,_s,wT,We,vT,Ls,Ds,$a,Re,ET,ST,Wa,Va,Ga,Ha,He=T(()=>{"use strict";Et=E(require("superagent"));j();ad();Fa=A("http-request"),$e=id(),jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,hT=6e4;Ot=(s,e,t)=>{throw Fa.error(s,{...t,error:e}),e};_s=$e(async(s,e,t,r)=>{try{let n=await cd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Ot("failed to delete request",n,{url:s})}});wT=$e(cd),We=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Ba(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Ot("failed to post request",o,{url:s})}});vT=$e(Ba),Ls=$e(async(s,e,t,r={},n=jr)=>{let o=Et.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),pr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Ot("failed to post request",i,{url:s})}});Ds=$e(async(s,e,t)=>{try{return(await ja(s,e,t)).text}catch(r){return Ot("failed to getText request",r,{url:s,query:e})}}),$a=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Ba(s,e,t,r,n)).text}catch(o){return Ot("failed to post request",o,{url:s})}}),Re=$e(async(s,e,t,r,n)=>{try{return(await ja(s,e,t,r,n)).body}catch(o){return Ot("failed to get request",o,{url:s,query:e})}}),ET=$e((s,e,t,r)=>ja(s,e,t,r)),ST=$e(async s=>{let e=Et.default.head(s).timeout(jr);pr(e);try{return await e}catch(t){return Ot("failed to head request",t,{url:s})}}),Wa=$e(async(s,e,t={},r=jr)=>{let n=Et.default.put(s).send(e).timeout(r).set(t);pr(n);try{return(await n).body}catch(o){return Ot("failed to put request",o,{url:s})}}),Va=$e(async s=>{Fa.info("start to download",{url:s});let e=Et.default.get(s).timeout(hT).buffer(!0).parse(bT);pr(e);try{let t=await e;return Fa.info("finished to download",{url:s}),t}catch(t){return Ot("failed to download",t,{url:s})}}),Ga=$e.isNetworkHealthy,Ha=$e.didNetworkConnectivityTestFail});function lt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=_t.resolve(__dirname,"../../"):s=_t.resolve(__dirname,""),s):process.cwd()}function Xn(s,e){return je(s)?e||_t.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||_t.basename(s)}function ct(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function RT(){try{return Ip.node}catch{return""}}async function pd(s,e,t=!0){let r=await St.promises.readdir(s,{withFileTypes:!0});await St.promises.mkdir(e,{recursive:t});for(let n of r){let o=_t.join(s,n.name),i=_t.join(e,n.name);n.isDirectory()?await pd(o,i):await St.promises.copyFile(o,i)}}async function ge(s){try{return await St.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var _t,ld,ud,St,IT,Lt,qe,Qn,qa,et,za,dd=T(()=>{"use strict";_t=E(require("path"));Ea();Vn();ld=E(require("p-retry")),ud=E(require("decompress")),St=require("fs"),IT=3;Lt=async s=>{let e=await Promise.resolve().then(()=>(He(),Ze));return(0,ld.default)(()=>e.download(s),{retries:IT,factor:1})},qe=async(s,e)=>{let t=await Lt(s);return St.promises.writeFile(e,t.body)};Qn=async(s,e)=>{let t=Xn(s,e);return je(s)?qe(s,t):St.promises.copyFile(s,t)},qa=async s=>je(s)?Lt(s):St.promises.readFile(s),et=async(s,e)=>await(0,ud.default)(s,e),za=s=>(0,St.statSync)(s).size/1e6});var Dt={};V(Dt,{APPIUM_SESSION_MESSAGE:()=>Qa,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>Zn,MOBILE_RUN_SKIP_REASON:()=>Xa,gridMessages:()=>$r,gridTypes:()=>_,mobileWeb:()=>Ja,runnerStatus:()=>Ka,runnerTestStatus:()=>pe,socketEventTypes:()=>It,stepResult:()=>Ns,test:()=>Ya,testRunStatus:()=>Ms,testStatus:()=>ze,timeoutMessages:()=>Ve});var Ve,Ms,Ka,pe,ze,$r,Ja,Ya,It,Y,_,Ns,Zn,Xa,Qa,oe=T(()=>{"use strict";Ve={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ms={COMPLETED:"completed",RUNNING:"running"},Ka={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},pe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},$r={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Ja={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Ya={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},It={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",PCLOUDY:"pcloudy"},Ns={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"},Zn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Xa={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Qa={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"}});function Us(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function AT(){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 Fs,md,Ke,xT,PT,CT,kT,OT,Za,ec,fd=T(()=>{"use strict";oe();Fs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},md=s=>Boolean(s.resultId&&s.source==="remote-run"),Ke=(s,e)=>s.testStatus===ze.QUARANTINE&&!md(e)&&!e.runQuarantinedTests;xT=s=>Boolean(s.loginMode),PT=s=>Boolean(s.tunnelOnlyMode),CT=s=>Boolean(s.createPrefechedData),kT=s=>Boolean(s.installLazyDepsMode),OT=s=>Boolean(s.agentMode),Za=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},ec=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function to(s=0){return eo.default.duration(s).format("HH:mm:ss.SSS")}function tc(s=0){return eo.default.duration(s).asSeconds()}var eo,gd,hd=T(()=>{"use strict";eo=E(require("dayjs")),gd=E(require("dayjs/plugin/duration"));eo.default.extend(gd.default)});var Bs,Wr,js,yd=T(()=>{"use strict";oe();Bs=s=>!(!s||"fileName"in s),Wr=(s,e)=>e===_.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,js=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"}});function rc(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 bd=T(()=>{"use strict"});var K={};V(K,{TESTIM_BROWSER_DIR:()=>Mt,buildBasicHeader:()=>va,calcPercentile:()=>no,copyDir:()=>pd,delay:()=>ie,doesPathExist:()=>ge,download:()=>Lt,downloadAndSave:()=>qe,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>AT,getBrowserInfo:()=>LT,getCdpAddressForHost:()=>fr,getCliLocation:()=>lt,getDuration:()=>to,getDurationSec:()=>tc,getEnginesVersion:()=>RT,getEnvironmentGitBranch:()=>mr,getLocalFileSizeInMB:()=>za,getMemorySnapshot:()=>rc,getPlanType:()=>so,getRunConfigByBrowserName:()=>Ws,getRunnerVersion:()=>ct,getSource:()=>Qn,getSourceAsBuffer:()=>qa,getSourcePath:()=>Xn,getTestUrl:()=>at,getUniqBrowsers:()=>Us,groupTestsByRetries:()=>nc,guid:()=>te,hasTestPlanFlag:()=>Fs,isAgentMode:()=>OT,isAppFromDevice:()=>Bs,isCreatePrefetchedDataMode:()=>CT,isInstallLazyDepsMode:()=>kT,isLoginMode:()=>xT,isMobileProject:()=>js,isPromise:()=>Ma,isQuarantineAndNotRemoteRun:()=>Ke,isRemoteRun:()=>md,isTunnelOnlyMode:()=>PT,isURL:()=>je,promiseAbort:()=>Na,promiseFromCallback:()=>qt,promiseMap:()=>ae,promiseTimeout:()=>ce,removePropertyFromObject:()=>ro,replaceArgsWithNoDashes:()=>Za,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>ec,unzipFile:()=>et});function LT(s){return s=s.toLowerCase(),sc.find(e=>e.browserValue===s)}function Ws(s,e,t){s=s.toLowerCase();let r=sc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||sc[0],n=$s.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=$s.find(o=>o.sl.platform===e.platform):e.platformName&&(n=$s.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=$s.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=$s.find(o=>o.bs.platform===t.platform))),dr.merge(r,n)}function mr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function ro(s,e,t){for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&ro(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function so(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function nc(s=[]){return dr.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=dr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=dr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function fr(s,e){let t=await Promise.resolve().then(()=>(He(),Ze));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 Td,dr,wd,_T,Mt,$s,sc,no,B=T(()=>{"use strict";Td=E(require("os")),dr=E(require("lodash")),wd=E(require("path"));Or();dd();fd();hd();Ea();Ua();yd();bd();_T=Td.homedir(),Mt=wd.join(_T,".testim-browser-profile"),$s=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{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 Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{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:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{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:"6.0"}},{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"}}],sc=[{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"}];no=(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]}});var oc={};V(oc,{$schema:()=>DT,default:()=>BT,definitions:()=>MT,properties:()=>FT,required:()=>UT,type:()=>NT});var DT,MT,NT,UT,FT,BT,vd=T(()=>{DT="http://json-schema.org/draft-07/schema#",MT={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}}}},NT="object",UT=["entries"],FT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},BT={$schema:DT,definitions:MT,type:NT,required:UT,properties:FT}});async function Pd(){try{return await ce(oo.promises.readFile(lo()).then(async s=>{let e=await xd;return WT(e,s)}),3e4)}catch{return{}}}function WT(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Gr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function ut(s,e,t=jT,r=void 0){return async()=>{if(!Id)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await VT(e);if(o)return Vs.debug("cache hit:",{fnName:e}),o;if(Vs.debug("cache miss:",{fnName:e}),!Rd)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await GT(e,i,t),i}}async function VT(s){let t=(await uo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function GT(s,e,t){if(ic)throw Vs.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 uo;r[s]={value:e,expiry:Date.now()+t},Ad=new Promise(n=>{co=n}),$T(r)}catch{Vs.error("failed updating cache")}}async function Cd(){let s=await uo;Object.keys(s).forEach(e=>{delete s[e]})}function kd(s){Id=s}function HT(s=!0){Rd=s}async function Od(){try{return ic=!0,await Ad}finally{ic=!1}}function _d(s){ao=s,uo=Pd()}var oo,io,Gr,Ed,Vs,ao,Sd,co,Id,Rd,ic,Ad,xd,jT,lo,uo,$T,Ld,Dd,ZI,Md,zt=T(()=>{"use strict";oo=E(require("fs")),io=E(require("path")),Gr=E(require("crypto"));B();Ed=require("lodash");j();Vs=A("local cache"),ao=io.resolve(lt(),"testim-cache"),Id=!0,Rd=!0,ic=!1,Ad=new Promise(s=>{co=s}),xd=new Promise(s=>{Sd=s}),jT=1e3*60*60*3,lo=()=>io.resolve(io.resolve(ao,"testim.cache"));uo=Pd(),$T=(0,Ed.debounce)(async s=>{let e;try{let t=await xd,r=Gr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Gr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(ao)||await oo.promises.mkdir(ao,{recursive:!0}),await oo.promises.writeFile(lo(),a)}catch(t){Vs.error("failed saving cache",{err:t}),e=t}co(e?{success:!1,error:e}:{success:!0})},200);Ld=Sd,Dd=kd.bind(void 0,!1),ZI=kd.bind(void 0,!0),Md=()=>HT(!1)});function po(){return{cliLocation:lt(),userInfo:Hr.userInfo(),platform:Hr.platform(),release:Hr.release()}}var Hr,ac=T(()=>{"use strict";Hr=E(require("os"));B()});function qT(s){try{return mo.resolve(mo.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 Kt(s){let e=qT(s);return require(e)}var mo,Gs=T(()=>{"use strict";mo=E(require("path"))});async function Bd(s){return(await Ud(`npm view ${s} version`)).stdout.trim()}function lc(s){try{return Kt(s)}catch{return!1}}function jd(s,e){return require(qr.join(s,`./node_modules/${e}/package.json`)).version}async function go(s,e,t){function r(c){let m=/EACCES[^']+'(.+)'/.exec(c.stderr);return m===null?!1:m[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=qr.join(s,"npm-shrinkwrap.json"),i=qr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ge(o)&&(await cc.promises.rename(o,i),a=!0)}catch{}return await Ud(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(c=>{let l=r(c),m=n(c);throw l||m?(Fd.info("Failed to install package due to insufficient write access",{...po(),package:e,path:l||s}),console.error(`
2
+ "use strict";var Kb=Object.create;var Mn=Object.defineProperty;var Jb=Object.getOwnPropertyDescriptor;var Yb=Object.getOwnPropertyNames;var Xb=Object.getPrototypeOf,Qb=Object.prototype.hasOwnProperty;var T=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Mn(s,t,{get:e[t],enumerable:!0})},Tp=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Yb(e))!Qb.call(s,n)&&n!==t&&Mn(s,n,{get:()=>e[n],enumerable:!(r=Jb(e,n))||r.enumerable});return s};var E=(s,e,t)=>(t=s!=null?Kb(Xb(s)):{},Tp(e||!s||!s.__esModule?Mn(t,"default",{value:s,enumerable:!0}):t,s)),fe=s=>Tp(Mn({},"__esModule",{value:!0}),s);var Fe={};V(Fe,{log:()=>D,measure:()=>eT});function D(...s){if(!Ep)return;let e=Date.now();console.log(`${e-Zb} ${e-vp} `,...s),vp=e}function eT(s,e){if(!Ep)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var Ep,Zb,vp,Be=T(()=>{"use strict";Ep=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,Zb=Date.now(),vp=Date.now()});var Ta,Gt,wa,Or=T(()=>{"use strict";Ta={NULL:"\uE000",Unidentified:"\uE000",Cancel:"\uE001",Help:"\uE002","Back space":"\uE003",Backspace:"\uE003",Tab:"\uE004",Clear:"\uE005",Return:"\uE006",Enter:"\uE007",Shift:"\uE008",Control:"\uE009",Alt:"\uE00A",Pause:"\uE00B",Escape:"\uE00C",Space:"\uE00D"," ":"\uE00D",Pageup:"\uE00E",PageUp:"\uE00E",Page_Up:"\uE00E",Pagedown:"\uE00F",PageDown:"\uE00F",Page_Down:"\uE00F",End:"\uE010",Home:"\uE011","Left arrow":"\uE012",Arrow_Left:"\uE012",ArrowLeft:"\uE012","Up arrow":"\uE013",Arrow_Up:"\uE013",ArrowUp:"\uE013","Right arrow":"\uE014",Arrow_Right:"\uE014",ArrowRight:"\uE014","Down arrow":"\uE015",Arrow_Down:"\uE015",ArrowDown:"\uE015",Insert:"\uE016",Delete:"\uE017",Semicolon:"\uE018",Equals:"\uE019","Numpad 0":"\uE01A","Numpad 1":"\uE01B","Numpad 2":"\uE01C","Numpad 3":"\uE01D","Numpad 4":"\uE01E","Numpad 5":"\uE01F","Numpad 6":"\uE020","Numpad 7":"\uE021","Numpad 8":"\uE022","Numpad 9":"\uE023",Multiply:"\uE024",Add:"\uE025",Separator:"\uE026",Subtract:"\uE027",Decimal:"\uE028",Divide:"\uE029",F1:"\uE031",F2:"\uE032",F3:"\uE033",F4:"\uE034",F5:"\uE035",F6:"\uE036",F7:"\uE037",F8:"\uE038",F9:"\uE039",F10:"\uE03A",F11:"\uE03B",F12:"\uE03C",Command:"\uE03D",Meta:"\uE03D",Zenkaku_Hankaku:"\uE040",ZenkakuHankaku:"\uE040"},Gt="element-6066-11e4-a52e-4f735466cecf",wa=79});function te(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 at(s,e,t,r,n){let o="";return n=n?encodeURIComponent(n):"master",e&&t&&(o=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(o+=`?result-id=${r}`)),o}function va(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function je(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 Ea=T(()=>{"use strict"});var Ia,Sp,Ip,Vn=T(()=>{Ia={ngrok:"4.3.3",webpack:"5.74.0",playwright:"0.12.1",puppeteer:"2.1.1","selenium-webdriver":"3.6.0","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:"1.4.5-lts.1"},Sp={"@applitools/eyes-sdk-core":"13.11.32","@applitools/spec-driver-webdriverio":"1.4.29","@testim/coralogix-logger":"1.1.27-beta.1","abort-controller":"3.0.0",ajv:"6.12.6","analytics-node":"5.0.0","body-parser":"1.20.1",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",decompress:"4.2.1",express:"4.17.3",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"5.0.0","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"0.16.2",jsonwebtoken:"9.0.0",linkedom:"0.15.3",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2",npm:"8.19.2","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":"5.0.0","rox-node":"4.9.18",semver:"7.5.4","serialize-error":"7.0.1","socket.io-client":"4.6.2","source-map-support":"0.5.19",superagent:"3.8.3","superagent-proxy":"3.0.0","test-exclude":"6.0.0","ua-parser-js":"0.7.33","validate-npm-package-name":"3.0.0",webdriverio:"7.24.0",winston:"3.6.0","winston-transport":"4.5.0",ws:"8.5.0",xml2js:"0.5.0",yaml:"2.2.2"},Ip={node:">= 16.0.0"}});var As,Rp,Ap,Gn,xp,Hn,xs,Pp,me,Cp,kp,qn,ke,Ra,Op,zn,_p,RI,Lp,AI,Dp,Mp,_r,Np,Up,Fp,Bp,jp,$p,Wp,Vp,Gp,Hp,qp,zp,Kp,Aa,Jp,le=T(()=>{"use strict";As=process.env.SERVICES_HOST||"https://services.testim.io",Rp="https://testimstatic.blob.core.windows.net",Ap="https://tstresultfiles.azureedge.net";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:As,As=process.env.SERVICES_HOST);Gn=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),xp=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Hn=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),xs=process.env.EDITOR_URL,Pp=process.env.WEBSOCKET_HOST||`${As}/ws`,me=As,Cp=parseInt(process.env.LOGGER_CONSOLE||"0",10),kp=parseInt(process.env.LOGGER_DEBUG||"0",10),qn=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),ke=parseInt(process.env.IS_ON_PREM||"0",10),Ra=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Op=parseInt(process.env.DEBUG_MODE||"0",10),zn=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,_p=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",RI=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),Lp=parseInt(process.env.START_WORKER_DELAY_MS||"1500",10),AI=process.env.APPIUM_VERSION||"1.10.1",Dp=process.env.GATEWAY_URL,Mp=process.env.EXTENSION_SERVICES_HOST||As,_r=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:Rp,Np=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:Ap,Up=Rp,Fp=Ap,Bp=5*60*1e3,jp=40,$p=process.env.HEADSPIN_MOBILE_DEVICES_API_URL||"https://api-dev.headspin.io/v0",Wp=process.env.HEADSPIN_MOBILE_APPS_API_URL||"https://api-dev.headspin.io/v1",Vp=process.env.TDC_MOBILE_DEVICES_API_URL||"https://api.tdc.tricentis-cloud.com/v0",Gp=process.env.TDC_MOBILE_APPS_API_URL||"https://api.tdc.tricentis-cloud.com/v1",Hp=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",qp=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",zp=process.env.SAUCE_LABS_US_APPS_API_URL||"https://api.us-west-1.saucelabs.com/v1",Kp=process.env.SAUCE_LABS_EU_APPS_API_URL||"https://api.eu-central-1.saucelabs.com/v1",Aa=process.env.P_CLOUDY_MOBILE_API_URL||"https://device.pcloudy.com/api",Jp=process.env.TMA_BASE_API_URL||"http://127.0.0.1:8585/api"});var xa={};V(xa,{CoralogixTransport:()=>Lr});var Ie,Yp,sT,nT,Lr,Pa=T(()=>{"use strict";Ie=require("@testim/coralogix-logger"),Yp=E(require("winston-transport")),sT={debug:Ie.Severity.debug,silly:Ie.Severity.verbose,verbose:Ie.Severity.verbose,silent:Ie.Severity.verbose,info:Ie.Severity.info,http:Ie.Severity.info,warn:Ie.Severity.warning,warning:Ie.Severity.warning,error:Ie.Severity.error,critical:Ie.Severity.critical,crit:Ie.Severity.critical},nT=["err","error","reason","e"],Lr=class extends Yp.default{constructor(t){t=Object.assign({},Lr.options,t);super(t);this.options=t,this.logger=new Ie.CoralogixLogger(t.category||""),this.name="Coralogix Transport",t.timestamp&&(this.timestamp=t.timestamp)}log(t,r){let{category:n,level:o,message:i,meta:a={},...c}=t,l=Object.assign({},a,this.options.extraFields,c),m=new Ie.Log;m.severity=sT[o],m.text=i,m.category=n,l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,i&&(l.msg=`${i}
3
+ ${l.msg}`));for(let u of nT)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&&(i&&!d&&(l.msg=i),m.text=l),this.logger.addLog(m),r(null,!0)}waitForFlush(){return this.logger.waitForFlush()}static configure(t){Ie.CoralogixLogger.configure(t),Lr.options=t}}});var Da={};V(Da,{getLogger:()=>A,setExecutionId:()=>Oa,setProjectId:()=>_a,setProxyUri:()=>La});function aT(){let s=[],e=()=>Promise.resolve();if(!ke){let{CoralogixTransport:t}=(Pa(),fe(xa));t.configure(Zp);let r=new t({category:"ROOT"});s.push(r),e=()=>r.waitForFlush()}return Cp&&s.push(new bt.transports.Console({format:bt.format.combine(bt.format.colorize(),bt.format.simple())})),[s,e]}function Oa(s){Ca=s}function _a(s){ed=s}function La(s){if(ke||!s)return;let{CoralogixTransport:e}=(Pa(),fe(xa));e.configure({...Zp,proxyUri:s})}function Xp(s){return{projectId:ed,time:new Date().toISOString(),...Ca&&!s&&{executionId:Ca}}}function A(s){return new ka(dT.child({category:s}))}var Qp,bt,oT,iT,Zp,cT,lT,uT,pT,dT,Ca,ed,ka,j=T(()=>{"use strict";Qp=E(require("os")),bt=E(require("winston"));le();B();oT=Qp.hostname(),iT=ct(),Zp={privateKey:"d0eb01da-f966-1663-63c6-8871225d7c39",applicationName:"testim",subsystemName:"runner"};[cT,lT]=aT(),uT=kp?"debug":"info",pT={release:Boolean(!0),branch:"production"},dT=bt.createLogger({levels:bt.config.syslog.levels,level:uT,transports:cT,defaultMeta:{name:"runner",hostname:oT,nodeVersion:process.version,runnerVersion:iT,...pT}}),Ca=null,ed=null;ka=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,Object.assign({meta:r,message:t},Xp(n)))}catch(o){try{this._logger.log("crit",Object.assign({message:`failed to log message ${o.message}, ${o.stack}`},Xp(n)))}catch{}}}waitForFlush(){return lT()}}});var Yn,Dr,P,Ht,ur,Tt,Kn,Mr,re,Ps,wt,Nr,vt,Jn,Ur,Fr,Br,Cs,z=T(()=>{"use strict";Yn=require("p-retry"),Dr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},P=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Ht=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},ur=class extends Error{constructor(t,r){super(t);this.type=r}},Tt=class extends Yn.AbortError{},Kn=class extends Yn.AbortError{},Mr=class extends Yn.AbortError{},re=class extends Error{},Ps=class extends Error{},wt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Nr=class extends wt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},vt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},Jn=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Ur=class extends Error{},Fr=class extends Error{constructor(t){super();this.innerStack=t}},Br=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Cs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Ma(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ie(s){return(0,sd.setTimeout)(s)}function Na(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function ce(s,e,t="Timeout Error"){Hn&&!td&&(td=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new re(t);return e=Hn?Number(Hn)||6e5:e,Promise.race([s,ie(e).then(()=>{throw r})])}async function ae(s,e,{concurrency:t}={}){if(t){rd||=(await import("p-limit")).default;let r=rd(t);return await Promise.all(Array.from(s,(n,o)=>r(()=>e(n,o))))}return await Promise.all(Array.from(s,e))}function qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var sd,td,rd,Ua=T(()=>{"use strict";sd=require("timers/promises");z();le();td=!1});var Os,nd,mT,ks,od,fT,gT,id,ad=T(()=>{"use strict";Os=E(require("lodash"));le();nd=require("dns");j();Ua();mT=A("http-request-counters"),ks=!1,od=async()=>{if(ke)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await ae(s,t=>nd.promises.lookup(t)));return e||(ks=!0),e}catch{return mT.error("network connectivity test failed"),ks=!0,!1}},fT=Os.throttle(od,10*1e3),gT=60*1e3*15,id=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,o){let i=n.get(o)||0;n.set(o,i+1),setTimeout(()=>{let a=n.get(o)||1;n.set(o,a-1)},gT)}function t(n,o=n.name){return async function(...i){e(s.call,o);try{let a=await n.call(null,...i);return e(s.success,o),a}catch(a){throw e(s.fail,o),ks||fT(),a}}}async function r(){if(ks||!await od())return!1;let n=Os.sum([...s.fail.values()]),o=Os.sum([...s.call.values()]);return n<o*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>ks,t}});var Ze={};V(Ze,{deleteFullRes:()=>wT,deleteReq:()=>_s,didNetworkConnectivityTestFail:()=>Ha,download:()=>Va,get:()=>Re,getFullRes:()=>ET,getText:()=>Ds,head:()=>ST,isNetworkHealthy:()=>Ga,post:()=>We,postForm:()=>Ls,postFullRes:()=>vT,postText:()=>$a,put:()=>Wa});function yT(){return global.caFileContent}function bT(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function TT(){return!Et.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(Et.default),global.proxyUri}function pr(s,e=!1){let t=yT();t&&s.ca(t);let r=!e&&TT();r&&s.proxy(r)}async function cd(s,e={},t={},r=jr){let n=Et.default.delete(s).send(e).timeout(r).set(t);return pr(n),await n}async function Ba(s,e,t={},r=jr,n=0){let o=Et.default.post(s).send(e).timeout(r).set(t);pr(o),n&&o.retry(n);try{return await o}catch(i){throw i.url=s,i.originalRequestTimeout=r,i.additionalSetHeaders=t,i}}async function ja(s,e,t={},r=jr,{isBinary:n=!1,skipProxy:o=!1}={}){let i=Et.default.get(s).query(e||{}).timeout(r).set(t);return n&&i.buffer(!0),pr(i,o),await i}var Et,Fa,$e,jr,hT,Ot,_s,wT,We,vT,Ls,Ds,$a,Re,ET,ST,Wa,Va,Ga,Ha,He=T(()=>{"use strict";Et=E(require("superagent"));j();ad();Fa=A("http-request"),$e=id(),jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,hT=6e4;Ot=(s,e,t)=>{throw Fa.error(s,{...t,error:e}),e};_s=$e(async(s,e,t,r)=>{try{let n=await cd(s,e,t,r);return n.type==="text/plain"?n.text:n.body}catch(n){return Ot("failed to delete request",n,{url:s})}});wT=$e(cd),We=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let o=await Ba(s,e,t,r,n);return o.type==="text/plain"?o.text:o.body}catch(o){return Ot("failed to post request",o,{url:s})}});vT=$e(Ba),Ls=$e(async(s,e,t,r={},n=jr)=>{let o=Et.default.post(s).type("form").timeout(n).set(r);o.field(e),Object.entries(t).forEach(([i,a])=>{o.attach(i,a.buffer,a.fileName)}),pr(o);try{let i=await o;return i.type==="text/plain"?i.text:i.body}catch(i){return Ot("failed to post request",i,{url:s})}});Ds=$e(async(s,e,t)=>{try{return(await ja(s,e,t)).text}catch(r){return Ot("failed to getText request",r,{url:s,query:e})}}),$a=$e(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Ba(s,e,t,r,n)).text}catch(o){return Ot("failed to post request",o,{url:s})}}),Re=$e(async(s,e,t,r,n)=>{try{return(await ja(s,e,t,r,n)).body}catch(o){return Ot("failed to get request",o,{url:s,query:e})}}),ET=$e((s,e,t,r)=>ja(s,e,t,r)),ST=$e(async s=>{let e=Et.default.head(s).timeout(jr);pr(e);try{return await e}catch(t){return Ot("failed to head request",t,{url:s})}}),Wa=$e(async(s,e,t={},r=jr)=>{let n=Et.default.put(s).send(e).timeout(r).set(t);pr(n);try{return(await n).body}catch(o){return Ot("failed to put request",o,{url:s})}}),Va=$e(async s=>{Fa.info("start to download",{url:s});let e=Et.default.get(s).timeout(hT).buffer(!0).parse(bT);pr(e);try{let t=await e;return Fa.info("finished to download",{url:s}),t}catch(t){return Ot("failed to download",t,{url:s})}}),Ga=$e.isNetworkHealthy,Ha=$e.didNetworkConnectivityTestFail});function lt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=_t.resolve(__dirname,"../../"):s=_t.resolve(__dirname,""),s):process.cwd()}function Xn(s,e){return je(s)?e||_t.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||_t.basename(s)}function ct(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function RT(){try{return Ip.node}catch{return""}}async function pd(s,e,t=!0){let r=await St.promises.readdir(s,{withFileTypes:!0});await St.promises.mkdir(e,{recursive:t});for(let n of r){let o=_t.join(s,n.name),i=_t.join(e,n.name);n.isDirectory()?await pd(o,i):await St.promises.copyFile(o,i)}}async function ge(s){try{return await St.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var _t,ld,ud,St,IT,Lt,qe,Qn,qa,et,za,dd=T(()=>{"use strict";_t=E(require("path"));Ea();Vn();ld=E(require("p-retry")),ud=E(require("decompress")),St=require("fs"),IT=3;Lt=async s=>{let e=await Promise.resolve().then(()=>(He(),Ze));return(0,ld.default)(()=>e.download(s),{retries:IT,factor:1})},qe=async(s,e)=>{let t=await Lt(s);return St.promises.writeFile(e,t.body)};Qn=async(s,e)=>{let t=Xn(s,e);return je(s)?qe(s,t):St.promises.copyFile(s,t)},qa=async s=>je(s)?Lt(s):St.promises.readFile(s),et=async(s,e)=>await(0,ud.default)(s,e),za=s=>(0,St.statSync)(s).size/1e6});var Dt={};V(Dt,{APPIUM_SESSION_MESSAGE:()=>Qa,CLI_MODE:()=>Y,MOBILE_APP_SOURCE:()=>Zn,MOBILE_RUN_SKIP_REASON:()=>Xa,gridMessages:()=>$r,gridTypes:()=>_,mobileWeb:()=>Ja,runnerStatus:()=>Ka,runnerTestStatus:()=>pe,socketEventTypes:()=>It,stepResult:()=>Ns,test:()=>Ya,testRunStatus:()=>Ms,testStatus:()=>ze,timeoutMessages:()=>Ve});var Ve,Ms,Ka,pe,ze,$r,Ja,Ya,It,Y,_,Ns,Zn,Xa,Qa,oe=T(()=>{"use strict";Ve={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Ms={COMPLETED:"completed",RUNNING:"running"},Ka={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},pe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},ze={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},$r={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Ja={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Ya={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},It={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},Y={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Ns={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"},Zn={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},Xa={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Qa={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"}});function Us(s,e){var t,r,n;return((t=s.testConfigNames)!=null&&t.length||(r=s.testConfigIds)!=null&&r.length||s.testPlan.length||s.testPlanIds.length)&&!s.browser?[...new Set(e.map(o=>{var i;return(i=o.runConfig)==null?void 0:i.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function AT(){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 Fs,md,Ke,xT,PT,CT,kT,OT,Za,ec,fd=T(()=>{"use strict";oe();Fs=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},md=s=>Boolean(s.resultId&&s.source==="remote-run"),Ke=(s,e)=>s.testStatus===ze.QUARANTINE&&!md(e)&&!e.runQuarantinedTests;xT=s=>Boolean(s.loginMode),PT=s=>Boolean(s.tunnelOnlyMode),CT=s=>Boolean(s.createPrefechedData),kT=s=>Boolean(s.installLazyDepsMode),OT=s=>Boolean(s.agentMode),Za=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},ec=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function to(s=0){return eo.default.duration(s).format("HH:mm:ss.SSS")}function tc(s=0){return eo.default.duration(s).asSeconds()}var eo,gd,hd=T(()=>{"use strict";eo=E(require("dayjs")),gd=E(require("dayjs/plugin/duration"));eo.default.extend(gd.default)});var Bs,Wr,js,yd=T(()=>{"use strict";oe();Bs=s=>!(!s||"fileName"in s),Wr=(s,e)=>e===_.TESTIM_TVC?!1:s&&"fileName"in s?s.fileName.endsWith(".app"):!1,js=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"}});function rc(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 bd=T(()=>{"use strict"});var K={};V(K,{TESTIM_BROWSER_DIR:()=>Mt,buildBasicHeader:()=>va,calcPercentile:()=>no,copyDir:()=>pd,delay:()=>ie,doesPathExist:()=>ge,download:()=>Lt,downloadAndSave:()=>qe,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>AT,getBrowserInfo:()=>LT,getCdpAddressForHost:()=>fr,getCliLocation:()=>lt,getDuration:()=>to,getDurationSec:()=>tc,getEnginesVersion:()=>RT,getEnvironmentGitBranch:()=>mr,getLocalFileSizeInMB:()=>za,getMemorySnapshot:()=>rc,getPlanType:()=>so,getRunConfigByBrowserName:()=>Ws,getRunnerVersion:()=>ct,getSource:()=>Qn,getSourceAsBuffer:()=>qa,getSourcePath:()=>Xn,getTestUrl:()=>at,getUniqBrowsers:()=>Us,groupTestsByRetries:()=>nc,guid:()=>te,hasTestPlanFlag:()=>Fs,isAgentMode:()=>OT,isAppFromDevice:()=>Bs,isCreatePrefetchedDataMode:()=>CT,isInstallLazyDepsMode:()=>kT,isLoginMode:()=>xT,isMobileProject:()=>js,isPromise:()=>Ma,isQuarantineAndNotRemoteRun:()=>Ke,isRemoteRun:()=>md,isTunnelOnlyMode:()=>PT,isURL:()=>je,promiseAbort:()=>Na,promiseFromCallback:()=>qt,promiseMap:()=>ae,promiseTimeout:()=>ce,removePropertyFromObject:()=>ro,replaceArgsWithNoDashes:()=>Za,shouldBlockVirtualIosBuild:()=>Wr,spreadObjectToArgs:()=>ec,unzipFile:()=>et});function LT(s){return s=s.toLowerCase(),sc.find(e=>e.browserValue===s)}function Ws(s,e,t){s=s.toLowerCase();let r=sc.find(o=>o.browserName.toLowerCase()===s||s.includes(o.synonyms))||sc[0],n=$s.find(o=>o.osName==="Windows 10");return e&&(e.platform?n=$s.find(o=>o.sl.platform===e.platform):e.platformName&&(n=$s.find(o=>o.sl.platformName===e.platformName))),t&&(t.os_version?n=$s.find(o=>o.bs.os_version===t.os_version):t.platform&&(n=$s.find(o=>o.bs.platform===t.platform))),dr.merge(r,n)}function mr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function ro(s,e,t){for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&ro(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function so(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function nc(s=[]){return dr.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=dr.orderBy(t,o=>typeof o.retryCount=="number"?o.retryCount:1),n=dr.chain(r).last().cloneDeep().value();return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}async function fr(s,e){let t=await Promise.resolve().then(()=>(He(),Ze));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 Td,dr,wd,_T,Mt,$s,sc,no,B=T(()=>{"use strict";Td=E(require("os")),dr=E(require("lodash")),wd=E(require("path"));Or();dd();fd();hd();Ea();Ua();yd();bd();_T=Td.homedir(),Mt=wd.join(_T,".testim-browser-profile"),$s=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{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 Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14"},sl:{platform:"macOS 11",safari_version:"14"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13"},sl:{platform:"macOS 10.15",safari_version:"13"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12"},sl:{platform:"macOS 10.14",safari_version:"12"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11"},sl:{platform:"macOS 10.13",safari_version:"11"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10"},sl:{platform:"macOS 10.12",safari_version:"10.0"}},{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:"9.0"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"8.0"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"7.0"}},{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:"6.0"}},{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"}}],sc=[{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"}];no=(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]}});var oc={};V(oc,{$schema:()=>DT,default:()=>BT,definitions:()=>MT,properties:()=>FT,required:()=>UT,type:()=>NT});var DT,MT,NT,UT,FT,BT,vd=T(()=>{DT="http://json-schema.org/draft-07/schema#",MT={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}}}},NT="object",UT=["entries"],FT={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},BT={$schema:DT,definitions:MT,type:NT,required:UT,properties:FT}});async function Pd(){try{return await ce(oo.promises.readFile(lo()).then(async s=>{let e=await xd;return WT(e,s)}),3e4)}catch{return{}}}function WT(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),o=Gr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),i=o.update(r);return JSON.parse(Buffer.concat([i,o.final()]))}function ut(s,e,t=jT,r=void 0){return async()=>{if(!Id)return await s();let n=e;r&&(e+=JSON.stringify(r));let o=await VT(e);if(o)return Vs.debug("cache hit:",{fnName:e}),o;if(Vs.debug("cache miss:",{fnName:e}),!Rd)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let i=await s();return i&&await GT(e,i,t),i}}async function VT(s){let t=(await uo)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function GT(s,e,t){if(ic)throw Vs.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 uo;r[s]={value:e,expiry:Date.now()+t},Ad=new Promise(n=>{co=n}),$T(r)}catch{Vs.error("failed updating cache")}}async function Cd(){let s=await uo;Object.keys(s).forEach(e=>{delete s[e]})}function kd(s){Id=s}function HT(s=!0){Rd=s}async function Od(){try{return ic=!0,await Ad}finally{ic=!1}}function _d(s){ao=s,uo=Pd()}var oo,io,Gr,Ed,Vs,ao,Sd,co,Id,Rd,ic,Ad,xd,jT,lo,uo,$T,Ld,Dd,ZI,Md,zt=T(()=>{"use strict";oo=E(require("fs")),io=E(require("path")),Gr=E(require("crypto"));B();Ed=require("lodash");j();Vs=A("local cache"),ao=io.resolve(lt(),"testim-cache"),Id=!0,Rd=!0,ic=!1,Ad=new Promise(s=>{co=s}),xd=new Promise(s=>{Sd=s}),jT=1e3*60*60*3,lo=()=>io.resolve(io.resolve(ao,"testim.cache"));uo=Pd(),$T=(0,Ed.debounce)(async s=>{let e;try{let t=await xd,r=Gr.randomBytes(16),n=JSON.stringify(s),o=Buffer.from(t),i=Gr.createCipheriv("aes-256-cbc",Buffer.concat([o,Buffer.alloc(32)],32),r),a=Buffer.concat([r,i.update(n),i.final()]);await ge(ao)||await oo.promises.mkdir(ao,{recursive:!0}),await oo.promises.writeFile(lo(),a)}catch(t){Vs.error("failed saving cache",{err:t}),e=t}co(e?{success:!1,error:e}:{success:!0})},200);Ld=Sd,Dd=kd.bind(void 0,!1),ZI=kd.bind(void 0,!0),Md=()=>HT(!1)});function po(){return{cliLocation:lt(),userInfo:Hr.userInfo(),platform:Hr.platform(),release:Hr.release()}}var Hr,ac=T(()=>{"use strict";Hr=E(require("os"));B()});function qT(s){try{return mo.resolve(mo.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 Kt(s){let e=qT(s);return require(e)}var mo,Gs=T(()=>{"use strict";mo=E(require("path"))});async function Bd(s){return(await Ud(`npm view ${s} version`)).stdout.trim()}function lc(s){try{return Kt(s)}catch{return!1}}function jd(s,e){return require(qr.join(s,`./node_modules/${e}/package.json`)).version}async function go(s,e,t){function r(c){let m=/EACCES[^']+'(.+)'/.exec(c.stderr);return m===null?!1:m[1]}function n(c){return/The "to" argument must be of type string./.exec(c.stderr)}let o=qr.join(s,"npm-shrinkwrap.json"),i=qr.join(s,"npm-shrinkwrap-dummy.json"),a=!1;try{try{await ge(o)&&(await cc.promises.rename(o,i),a=!0)}catch{}return await Ud(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(c=>{let l=r(c),m=n(c);throw l||m?(Fd.info("Failed to install package due to insufficient write access",{...po(),package:e,path:l||s}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${e} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
@@ -17,7 +17,7 @@ Testim had missing write access to ${l||s}
17
17
  `).filter(y=>!t(y)&&!e(y)&&!s(y)&&!r(y)&&!n(y)&&!a(y)&&!i(y)&&!o(y)&&!c(y)&&!l(y)&&!m(y)&&!d(y)&&!u(y)&&!g(y)).join(`
18
18
  `))},kw=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Om.default.yellow(`
19
19
  WARNING: ${s} is deprecated. ${t}
20
- `))},yl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:bl,argv:wl,exit:fl,cwd:At}=global.process,Ow=["trace","debug","info","warn","error","silent"];Za(wl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Tl.description("Testim.io CLI").option("-h --help","output usage information",Dm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Pw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(bl.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,gl.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,gl.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${yl.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).parse(wl);p=Tl.opts(),_w=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Lw=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Dw=async()=>{var y,v,S,b,w,R,C,k;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!wl.slice(2).length)throw Dm(),new Dr;if(p.requireCredentials){let I=await Promise.resolve().then(()=>(Zr(),nn)),U=await I.getProjectId(),O=await I.getToken();(!U||!O)&&await I.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(Zr(),nn))).doLogin(),{loginMode:!0};if(p.version){let I="Testim CLI Version: ";bl.npm_package_version&&(console.log(I,bl.npm_package_version),fl(0));let U=ct();U&&(console.log(I,U),fl(0)),console.log("Could not find version, please check the package.json manually"),fl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Dd();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let I=Me.resolve(n);_d(I)}if(p.usePrefechedData&&Md(),p.playerRequirePath){let I=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",I);let U=Me.join(I,"tsconfig.node.json"),N=require("ts-node").register({project:U,ignore:[/node_modules/,new RegExp(`^${Bt.escapeRegExp(Me.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:N.config.options.paths,baseUrl:N.config.options.baseUrl}),(Te(),fe(Xt)).options.playerPath=I;let H=require("module"),J=H.prototype.require;H.prototype.require=function(de){return de==="rox-alias"?J.call(this,"rox-node"):J.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=hl.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(Im(p))return Rm(p);try{let I={};p.configFile?I=require(Me.join(At(),p.configFile)).config:p.optionsFile&&(I=require(Me.join(At(),p.optionsFile))),I&&typeof I.then=="function"&&(I=await I),Object.keys(I).forEach(U=>{let O=xw(U);p[O]=Cw(p[O],I[U])})}catch(I){throw I.message=`Unable to read options file: ${I.message}`,I}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((y=p.testConfig)==null?void 0:y.length)||((v=p.testConfigId)==null?void 0:v.length),i=((S=p.testPlan)==null?void 0:S.length)||((b=p.testPlanId)==null?void 0:b.length),a=((w=p.suite)==null?void 0:w.length)||((R=p.suiteId)==null?void 0:R.length);if(p.seleniumCapsFile)try{r=require(Me.join(At(),p.seleniumCapsFile))}catch(I){throw new P(`Failed to parse selenium caps file file error: ${I.message}`)}if((C=p.reporters)!=null&&C.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(At(),p.chromeExtraPrefs))}catch(I){throw new P(`Failed to read/open chrome extra prefs file error: ${I.message}`)}if(p.chromeExtraArgs){let I=p.chromeExtraArgs.split(",");for(let U of I){let[O]=U.split("=");km.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(U),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(km)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Me.join(At(),p.paramsFile)))}catch(I){throw new P(`Failed to read/open params file error: ${I.message}`)}if(p.params)try{s=Object.assign({},s,JSON.parse(p.params))}catch(I){throw new P(`Failed to parse params string error: ${I.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(_w(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let I=require(Me.join(At(),p.sauceOptions)),U=I.platformName&&["ios","android"].includes(I.platformName.toLowerCase());if(I.browserName){let N=I.browserName.toLowerCase();switch(N){case"microsoftedge":p.browser="edge";break;default:p.browser=N}}p.browser==="edge"&&parseFloat(I.version)>=wa&&(p.browser="edge-chromium");let O=parseFloat(I.version)<50&&!["dev","beta"].includes(I.version);if(!U&&p.browser==="chrome"&&O)throw new P("The minimum chrome supported version is 50.0");p.saucelabs=Object.assign({},p.saucelabs,I)}catch(I){throw new P(`Failed to parse saucelabs options file error: ${I.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Lw(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let I=require(Me.join(At(),p.browserstackOptions)),U=I.platform&&["mac","android"].includes(I.platform.toLowerCase());if(I.browserName&&(p.browser=I.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(I.browser_version)>=wa&&(p.browser="edge-chromium"),!U&&parseFloat(I.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack=Object.assign({},p.browserstack,I)}catch(I){throw new P(`Failed to parse browserstack options file error: ${I.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let I=require(Me.join(At(),p.perfectoOptions)),U={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},U,I)}catch(I){throw new P(`Failed to parse perfecto options file error: ${I.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let I=require(Me.join(At(),p.testobjectOptions)),U={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},U,I)}catch(I){throw new P(`Failed to parse test object options file error: ${I.message}`)}if(!p.project){let U=await(await Promise.resolve().then(()=>(Zr(),nn))).getProjectId();if(U)p.project=U;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Y.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let U=await(await Promise.resolve().then(()=>(Zr(),nn))).getToken();if(U)p.token=U;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let l=I=>I<=0||!Number.isInteger(I);if(l(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.mode!==Y.SELENIUM&&p.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!Ow.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((k=p.host)!=null&&k.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=_m.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(U=>U.trim()).filter(Boolean);let I=p.resultLabel.filter(U=>U.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&mr()&&p.resultLabel.unshift(mr()),I.length)throw new P("A result label cannot exceed 250 characters")}let d=bm(p),u=Oo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Bt.inRange(Bt.parseInt(p.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Bt.difference(p.codeCoverageReporter,yl).length){let I=Bt.difference(p.codeCoverageReporter,yl);throw new P(`invalid --code-coverage-reporter parameters ${I.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let f={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(f).filter(I=>Boolean(p[I]));if(p.mode!==Y.EXTENSION&&h.length){let I=h.length>1?"are":"is";throw new P(`${h.map(U=>f[U]).join(" and ")} ${I} only applicable in extension mode`)}if(p.tmsFieldFile)try{let I=hl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(I)}catch(I){throw new P(`failed to parse field file error: ${I.message}`)}if(p.highSpeed&&(kw("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.resetOnSessionStartOnly&&!p.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),p.lightweightMode)try{let I={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},U=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},I,U)}catch(I){throw new P(`failed to parse lightweightMode settings error: ${I.message}`)}else p.turboMode&&p.mode===Y.EXTENSION&&(p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),webpackConfig:p.webpackConfig,reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?mr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,isRegressionBaselineRun:p.isRegressionBaselineRun,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,resetOnSessionStartOnly:p.resetOnSessionStartOnly,ext:p.ext,extensionLocation:[p.extensionPath||d].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||u,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0},downloadBrowser:p.downloadBrowser}}});var jm={};V(jm,{installAllLazyDependencies:()=>Uw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=lc(s);if(t)return t;let r;e.silent||(r=(0,Um.default)(`Installing ${s} before first usage...`).start());try{let n=await Nw(s);return r&&r.succeed(),n}catch(n){Mw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Bm(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw r&&r.fail(l),n}}async function Nw(s){return es.has(s)||(es.set(s,Fm(s)),es.get(s).catch(()=>{es.delete(s)})),es.get(s)}async function Fm(s){let e=lc(s);if(e)return e;let t=Bm(s),r=`${s}@${t}`;return await go(lt(),r),Kt(s)}async function Uw(){let s=Object.keys(Ia);for(let e of s)await Fm(e)}function Bm(s){let e=Object.entries(Ia).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Um,Mw,es,wr=T(()=>{"use strict";Um=E(require("ora"));Hs();j();B();Vn();Gs();Mw=A("lazy-require"),es=new Map});var Wm={};V(Wm,{preloadTests:()=>on});async function on(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ut(async()=>{let t=await ae(s.testId,r=>Ac({...e,testId:r}),{concurrency:2});return $m.keyBy(t,"testData.id")},"loadTests",Fw,[e,s.testId])()}var $m,Fw,No=T(()=>{"use strict";$m=E(require("lodash"));zt();be();B();Fw=1e3*60*60*10});function vl(){return ct()}async function Hm(){if(!ke)try{let s=await ce(jw(),5e3,"The API call to NPM timed out"),e=vl();e&&Gm.lt(e,s)&&console.log(Vm.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){Bw.warn("Failed to get NPM version",{err:s})}}var Vm,Gm,Bw,jw,El=T(()=>{"use strict";Vm=E(require("chalk")),Gm=E(require("semver"));B();le();Hs();zt();j();Bw=A("npm-driver"),jw=ut(()=>Bd("@testim/testim-cli"),"getNpmVersion")});var Sl,Ww,ts,qm,zm,Il,Km,Jm=T(()=>{"use strict";B();z();j();wr();Sl=A("testimNgrok"),Ww=".whitelisted-ngrok.testim.io",ts="",zm=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${s.projectData.projectId}${Ww}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(Sl.info("replace https to http"),ts=o.replace("https://","http://")):ts=o,s.tunnelDiagnostics&&Il(),s.baseUrl=ts},Il=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ts);console.log("ngrok stats",n),Sl.info("ngrok stats",{tunnel:n})}catch(e){Sl.error("error collecting ngrok stats",{err:e})}s&&(qm=setTimeout(()=>Il(),1e4))},Km=async s=>{if(!ts)return;clearTimeout(qm),s.tunnelDiagnostics&&await Il(!1),await(await Ee("ngrok")).disconnect(ts)}});var Qt,Al,Ym,Gw,Hw,Rl,Uo,Bo,Fo,qw,Xm,Qm,Zm=T(()=>{"use strict";Qt=E(require("os")),Al=E(require("fs")),Ym=E(require("child_process"));B();be();Gw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Hw={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},Rl=Qt.tmpdir(),Uo=`${Rl}/cloudflared`,Bo=null,Fo=null,qw=async()=>{if(await ge(Uo))return;let e=Hw[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?Rl+e.path:Uo;await qe(`${Gw}/${e.path}`,t),e.extract&&await et(t,Rl),await Al.promises.chmod(Uo,"755")},Xm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Jc(s.company.companyId,t),qw()]);Bo=r._id,Fo=Ym.spawn(Uo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Yc(s.company.companyId,Bo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Al.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Qm=async s=>{let e=[];return Bo&&e.push(Xc(s.company.companyId,Bo)),Fo&&e.push(new Promise((t,r)=>{Fo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Fo.kill()})),await Promise.all(e)}});var G,tf,Kw,Jw,Yw,ef,jo,xl,M,he=T(()=>{"use strict";G=E(require("rox-node"));j();B();le();tf=A("FeatureFlagsService"),Kw=!ke&&!0&&!Dp,Jw=2e4,Yw=60*60*24,ef=["labs","disabled","enabled"],jo=class extends G.default.Variant{constructor(e="disabled"){super(e,ef)}getValue(){let e=super.getValue();return ef.includes(e)?e:(tf.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},xl=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,useJsInputCodeInSafari:new G.default.Flag,useJsInputCodeInFirefox:new G.default.Flag,useJsInputCodeInEdgeChromium:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new jo("labs"),highSpeedMode:new jo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),useLinkedomToParseHtml:new G.default.Flag,dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,removeEdgeChromeDefaultVersion:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Kw)return;let e={fetchIntervalInSec:Yw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(_p,e),Jw).catch(t=>tf.error("failed to get feature flag status",t))}},M=new xl});var sf,nf,Zt,of,af,rf,Xw,Qw,$o,Zw,ev,ne,Wo=T(()=>{"use strict";sf=E(require("ms")),nf=E(require("p-retry")),Zt=E(require("os")),of=E(require("portfinder")),af=E(require("child_process"));B();He();be();z();j();_o();oe();he();B();rf=A("lambdatestService"),Xw="https://downloads.lambdatest.com/tunnel/v3",Qw={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},$o=`${Zt.tmpdir()}/LT`,Zw=`${$o}/LT`,ev=(0,sf.default)("15m"),ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.LAMBDATEST||e.type===_.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=$c(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?ev:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Zw))return;let t=Qw[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let r=`${$o}.zip`;await qe(`${Xw}/${t}`,r),await et(r,$o)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await of.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=te();let l=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],i&&a)l=[...l,"--ntlm-user",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...ec(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)l=[...l,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),ne.tunnel=af.spawn("./LT",l,{cwd:$o});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,nf.default)(()=>Re(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});rf.info("LT tunnel info",u)}catch(u){throw rf.error("Failed to start LT tunnel",{err:u,stdoutResult:m,stderrResult:d}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=ne.lambdatestConfig.CAPABILITIES[t]||{},a={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},c=[],{mode:l,canary:m,ext:d,extensionPath:u,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!d){let f=cl({canary:m},!0);!u&&f[t]&&(c=[...c,f[t]]),u&&je(u)&&(c=[...c,u])}return g&&je(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:ne.lambdatestConfig.PLATFORM,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,resolution:ne.lambdatestConfig.RESOLUTION,timezone:ne.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:!0,ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var Pl={};V(Pl,{connect:()=>Go,disconnect:()=>Ho,serveTunneling:()=>rv});var Vo,cf,lf,tv,Go,Ho,rv,Cl=T(()=>{"use strict";Jm();tn();Zm();Rt();Vo=E(require("ora"));j();oe();Wo();cf=A("tunnel"),lf=s=>{var e;return[_.LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},tv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},Go=async s=>{if(!s.tunnel)return;let e=Nt(),t;try{lf(s)?(t=(0,Vo.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):tv(s)?(t=(0,Vo.default)("Starting testim cloudflare tunnel...").start(),await Xm(s)):(t=(0,Vo.default)("Starting testim ngrok tunnel...").start(),await zm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw cf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Ho=async s=>{if(s.tunnel)try{lf(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await Qm(s):await Km(s)}catch(e){let t="catch error - failed to close tunnel";throw cf.error(t,{err:e}),new Error(t)}},rv=async(s,e=new Promise(()=>{}))=>(await Go(s),Xr(()=>Ho(s)),await e)});function sv(s){if(s.protocol)return s.protocol;if([_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=uf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function nv(s){let e=uf.exec(s);return e==null?void 0:e[3]}function zo(s){var y,v,S,b,w,R,C,k,I;let e=s&&nv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&sv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(v=s==null?void 0:s.external)==null?void 0:v.user,l=(S=s==null?void 0:s.external)==null?void 0:S.key,m=s==null?void 0:s.type,d=m===_.HYBRID?a&&((R=(w=(b=s.hybrid)==null?void 0:b.external)==null?void 0:w[s.hybrid.tunnel])==null?void 0:R.user):c,u=m===_.HYBRID?a&&((I=(k=(C=s.hybrid)==null?void 0:C.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:I.key):l,g=s==null?void 0:s.name,f=s&&(s._id||s.gridId),h=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:m,name:g,provider:h,tunnelUser:d,tunnelKey:u}}async function df(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Ye.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Ye.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Ye.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=zo(o.grid);return ov(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new wt($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${r} - concurrency limit reached`):(Ye.error("invalid code error response - get grid",{res:o}),new wt($r.UNKNOWN))}function iv(s,e,t,r,n,o){return df(t,e,s,n,()=>Ro(e,t,r,n,o))}function av(s,e,t,r,n,o,i){return df(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(m=>(m.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Ro(e,t,c._id,n,o):Fc(e,t,r,n,o)})}function mf(s){return jc(s)}async function ff(s,e,t){let n=(t||await mf(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return zo(n)}async function cv(s,e,t){let n=(t||await mf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return zo(n)}async function kl(s,e){let t=an[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete an[s],!r){Ye.warn("failed to find grid slot id",{projectId:e});return}Ye.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Nc(i,e,r,n,o)}catch(a){Ye.error("failed to release slot",{projectId:e,err:a})}}async function lv(s){let e=Object.values(an).filter(Boolean);if(e.length!==0){Ye.info("keep alive worker slots",{projectId:s,slots:e});try{await Mc(s,e)}catch(t){Ye.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function uv(s){pf=global.setInterval(lv,1e4,s)}async function pv(s){let e=Object.keys(an);if(e.length){Ye.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>kl(Number(t),s))}catch(t){Ye.error("failed to release all slots",{err:t,projectId:s})}}}async function dv(s){await pv(s),clearInterval(pf)}function mv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function fv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>qo.isEmpty(s.testobjectSauce)?qo.isEmpty(s.saucelabs)?qo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=mv(t,s),c=fv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function hf(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function yf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return gf(s);let l=t==null?void 0:t.companyId;if(a)return ff(l,a,e);if(c)return cv(l,c,e);if(Fs(s)||s.tunnelOnlyMode){Ye.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new wt("Missing host or grid configuration")}async function bf(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:m,company:d}=t,u=d==null?void 0:d.companyId;if(l||m||c)return{mode:"local"};if(n)return gf(t);if(a)return iv(r,u,o,a,s,e);if(i)return av(r,u,o,i,s,e,t);throw new wt("Missing host or grid configuration")}var qo,Ye,an,uf,pf,ov,cn,Tf,rs=T(()=>{"use strict";qo=E(require("lodash"));be();j();B();oe();z();Ye=A("grid-service"),an={},uf=/(^(https?):\/{2})?(.*)/,pf=null;ov=(s,e,t,r,n)=>{an[s]={gridId:t,companyId:e,slotId:r,browser:n}};cn={start:uv,end:dv};Tf=async(s={},e={},t={},r={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:m,currentRetry:d}=n;if(!i||!a||(a===_.LAMBDATEST&&await((f=r.enableIfNeeded)==null?void 0:f.call(r,e)),a!==_.HYBRID||!o||!c||!m||!d))return e;let u=await Uc({companyId:o,gridId:i,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Ye.info("handling hybrid grid",{response:u,companyId:o});let g=zo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});function un(){return Ko||"master"}function wf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Ko="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){Ko=s.branch||s;return}Ko=e?"master":void 0}var Ko,Ol=T(()=>{"use strict";z()});var pn,_l,gv,Ll,hv,Jo,Yo,Xo,Qo,Zo,ei=T(()=>{"use strict";B();oe();pn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},_l=s=>{let{status:e}=s;return e===pe.ABORTED},gv=s=>{let{status:e}=s;return e===pe.PASSED},Ll=s=>s.runnerStatus===Ka.SKIPPED,hv=s=>s.testStatus===ze.EVALUATING,Jo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ll(t)&&(Ke(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Yo=s=>Object.values(s).filter(e=>pn(e)&&hv(e)).length,Xo=s=>Object.values(s).filter(pn),Qo=s=>Object.values(s).filter(gv),Zo=s=>Object.values(s).filter(_l)});function bv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Dl,ti,yv,ri,Ef=T(()=>{"use strict";Dl=E(require("lodash"));j();ei();ti=A("debug-reporter"),yv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ri=class{constructor(e){this.options=e}onTestStarted(e,t){ti.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;ti.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Dl.default.omit(this.options,yv),company:Dl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=bv(process.argv);ti.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=Qo(e).length,a=Object.keys(e).length-i;ti.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ml,xt,dn=T(()=>{"use strict";oe();Ml=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===_.DEVICE_FARM}},xt=new Ml});var Ul={};V(Ul,{Reporter:()=>Tv});var er,mn,vr,si,Sf,Nl,Tv,Fl=T(()=>{"use strict";er=E(require("chalk")),mn=E(require("lodash"));B();oe();dn();ei();vr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:si}=Dt,Sf="device",Nl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${er.default.underline(at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${to(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=at(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
20
+ `))},yl=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:bl,argv:wl,exit:fl,cwd:At}=global.process,Ow=["trace","debug","info","warn","error","silent"];Za(wl,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Tl.description("Testim.io CLI").option("-h --help","output usage information",Dm).option("-o --options-file [options-file.json]","").option("-c --config-file [config-file.js]","").option("--test-config [test-config]","test config name to override for all tests in current execution",De,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",De,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",De,[]).option("-w, --webpackConfig [webpack-configuration]","webpack configuration used to build the code based project").option("--test-id [test-id]","test ID to run",De,[]).option("-l, --label [label]","labels to search test by",De,[]).option("-n, --name [test-name]","test name to run",De,[]).option("--project [project-id]","project ID").option("-r, --report-file [report junit xml path]","where to save junit xml results file").option("--urls","add step urls to the junit report").option("--override-report-file-classname [override-report-file-classname]","custom junit class name for the junit reporter").option("--reporters [names]","report types",Pw).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--is-regression-baseline-run","save doms and run results as regression baseline data").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",De,[]).option("--test-plan-id [test-plan-id]","test plan to run",De,[]).option("--suite [suite-name]","suite to run",De,[]).option("--suite-id [suite-id]","suite ID to run",De,[]).option("--rerun-failed-by-run-id [run-id]","allows re-running failed tests from a specific run ID").option("--disable-grid-check [boolean]","disable checking if selenium grid is available",!1).option("--disable-native-events [boolean]","pass nativeEvents=false capability to the selenium browser (in selenium mode)",!1).option("--disable-timeout-retry [boolean]","disable retry after test pass test timeout",!1).option("--ca-file [ca-file-location]","ca certificate file location").option("--proxy [proxy-url]","proxy url to all requests").option("--proxy-for-grid [proxy-for-grid]","used together with --proxy to also router grid traffic through a proxy").option("--result-label [result-label]","result label",De,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("-roso --reset-on-session-start-only [reset-on-session-start-only]","set resetOnSessionStartOnly appium capability to true to avoid uninstall app on session end (ios run only)",!1).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(bl.TESTIM_TEST_START_TIMEOUT)||2*60*1e3).option("--timeout [test-timeout]","Test run timeout in milliseconds",Number).option("--browser-timeout [open-browser-timeout]","Get browser from grid timeout in milliseconds",Number).option("--new-browser-wait-timeout [max-wait-to-browser]","Maximum get browser wait in minutes",Number).option("--get-browser-timeout [get-browser-timeout]","Timeout for a single attempt to get browser from the grid configured in the project's plan",Number).option("--get-browser-retries [get-browser-retries]","Number of attempts to get browser from the grid configured in the project's plan",Number).option("--get-session-timeout [get-session-timeout]",'Timeout for "/session" request to the selenium server',Number,(0,gl.default)("90s")).option("--get-session-retries [get-session-retries]",'Retries for "/session" request to the selenium server',Number,3).option("--driver-request-timeout [driver-request-timeout]","Timeout for any WebDriver request to the grid server",Number,(0,gl.default)("90s")).option("--driver-request-retries [driver-request-retries]","Retries for any WebDriver request to the grid server",Number,3).option("--local-tma-url [local-tma-url]","use a local TMA instance for appium session").option("--use-local-chrome-driver [use-local-chrome-driver]","use a local ChromeDriver instance instead of a selenium grid").option("--chrome-binary-location [chrome-binary-location]","Chrome binary location").option("--use-chrome-launcher","use a local Chrome installation without selenium").option("-mnh --mock-network-har","use the HAR file configured in the Testim editor to mock network traffic").option("-mnp --mock-network-pattern [local file location path]","use a JSON rule file to mock network traffic (Rule file schema: https://help.testim.io/page/mocking-network-traffic)").option("-omf --override-mapping-file [local file location path]","pass map file location to override mock network (see schema: https://help.testim.io/page/mocking-network-traffic)").option("-dmn --disable-mock-network","Disable mock mode for the entire CLI run").option("--run-quarantined-tests","Run quarantine tests").option("--collect-code-coverage","collect code coverage for all js files under base url").option("--code-coverage-url-filter [url pattern]","collect code coverage for all js files matching url filter (url including asterisk)").option("--code-coverage-report-path [path]","where to save coverage report (default ./coverage)").option("--code-coverage-source-map-path [path]","path of source code").option("--code-coverage-reporter [reporter]",`set code coverage reporter (default html and text), options: ${yl.join("/")}`,De,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",De,[]).option("--sauce-user [sauce-lab-user]","user to connect to sauce labs").option("--sauce-key [sauce-lab-key]","key to use when connecting to sauce labs").option("--sauce-options [sauce-options]","json file of browser and os options for sauce").option("--browserstack-user [browserstack-user]","user to connect to browserStack").option("--browserstack-key [browserstack-key]","key to use when connecting to browserStack").option("--browserstack-options [browserstack-options]","json file of browser and os options for browserStack").option("--perfecto-token [perfecto-token]","security token to use when connecting to perfecto").option("--perfecto-options [perfecto-options]","json file of browser and os options for perfecto").option("--experitest-token [experitest-token]","security token to use when connecting to experitest").option("--testobject-key [testobject-key]","api key to use when connecting to testobject").option("--testobject-options [testobject-options]","json file of options for testobject").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--login","Log in to Testim").option("--require-credentials","Log in to Testim if not already logged in").option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",De,[]).option("--intersect-with-suite [suiteName]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite name)",De,[]).option("--intersect-with-suite-id [suiteId]","Out of the execution's test list, run only those tests that are included in the specified suite (by suite ID)",De,[]).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).parse(wl);p=Tl.opts(),_w=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},Lw=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Dw=async()=>{var y,v,S,b,w,R,C,k;p.inspect&&require("inspector").open(p.inspect);let s={},e={},t=[],r={};if(!wl.slice(2).length)throw Dm(),new Dr;if(p.requireCredentials){let I=await Promise.resolve().then(()=>(Zr(),nn)),U=await I.getProjectId(),O=await I.getToken();(!U||!O)&&await I.doLogin()}if(p.login)return await(await Promise.resolve().then(()=>(Zr(),nn))).doLogin(),{loginMode:!0};if(p.version){let I="Testim CLI Version: ";bl.npm_package_version&&(console.log(I,bl.npm_package_version),fl(0));let U=ct();U&&(console.log(I,U),fl(0)),console.log("Could not find version, please check the package.json manually"),fl(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Dd();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let I=Me.resolve(n);_d(I)}if(p.usePrefechedData&&Md(),p.playerRequirePath){let I=Me.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",I);let U=Me.join(I,"tsconfig.node.json"),N=require("ts-node").register({project:U,ignore:[/node_modules/,new RegExp(`^${Bt.escapeRegExp(Me.relative(At(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:N.config.options.paths,baseUrl:N.config.options.baseUrl}),(Te(),fe(Xt)).options.playerPath=I;let H=require("module"),J=H.prototype.require;H.prototype.require=function(de){return de==="rox-alias"?J.call(this,"rox-node"):J.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=hl.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent"),global.HttpsProxyAgent=require("https-proxy-agent")),p.proxyForGrid&&!p.proxy)throw new P("missing --proxy option");if(Im(p))return Rm(p);try{let I={};p.configFile?I=require(Me.join(At(),p.configFile)).config:p.optionsFile&&(I=require(Me.join(At(),p.optionsFile))),I&&typeof I.then=="function"&&(I=await I),Object.keys(I).forEach(U=>{let O=xw(U);p[O]=Cw(p[O],I[U])})}catch(I){throw I.message=`Unable to read options file: ${I.message}`,I}if(p.tunneld)return{tunnel:!0,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,tunnelOnlyMode:!0,token:p.token,project:p.project};let o=((y=p.testConfig)==null?void 0:y.length)||((v=p.testConfigId)==null?void 0:v.length),i=((S=p.testPlan)==null?void 0:S.length)||((b=p.testPlanId)==null?void 0:b.length),a=((w=p.suite)==null?void 0:w.length)||((R=p.suiteId)==null?void 0:R.length);if(p.seleniumCapsFile)try{r=require(Me.join(At(),p.seleniumCapsFile))}catch(I){throw new P(`Failed to parse selenium caps file file error: ${I.message}`)}if((C=p.reporters)!=null&&C.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new P("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new P("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new P("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(Me.join(At(),p.chromeExtraPrefs))}catch(I){throw new P(`Failed to read/open chrome extra prefs file error: ${I.message}`)}if(p.chromeExtraArgs){let I=p.chromeExtraArgs.split(",");for(let U of I){let[O]=U.split("=");km.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(U),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.cloudinary.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(km)}`)}}if(p.paramsFile)try{s=Object.assign({},s,require(Me.join(At(),p.paramsFile)))}catch(I){throw new P(`Failed to read/open params file error: ${I.message}`)}if(p.params)try{s=Object.assign({},s,JSON.parse(p.params))}catch(I){throw new P(`Failed to parse params string error: ${I.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new P("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(_w(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let I=require(Me.join(At(),p.sauceOptions)),U=I.platformName&&["ios","android"].includes(I.platformName.toLowerCase());if(I.browserName){let N=I.browserName.toLowerCase();switch(N){case"microsoftedge":p.browser="edge";break;default:p.browser=N}}p.browser==="edge"&&parseFloat(I.version)>=wa&&(p.browser="edge-chromium");let O=parseFloat(I.version)<50&&!["dev","beta"].includes(I.version);if(!U&&p.browser==="chrome"&&O)throw new P("The minimum chrome supported version is 50.0");p.saucelabs=Object.assign({},p.saucelabs,I)}catch(I){throw new P(`Failed to parse saucelabs options file error: ${I.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new P("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(Lw(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let I=require(Me.join(At(),p.browserstackOptions)),U=I.platform&&["mac","android"].includes(I.platform.toLowerCase());if(I.browserName&&(p.browser=I.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(I.browser_version)>=wa&&(p.browser="edge-chromium"),!U&&parseFloat(I.browser_version)<50&&p.browser==="chrome")throw new P("The minimum chrome supported version is 50.0");p.browserstack=Object.assign({},p.browserstack,I)}catch(I){throw new P(`Failed to parse browserstack options file error: ${I.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let I=require(Me.join(At(),p.perfectoOptions)),U={location:"US East",securityToken:p.perfectoToken};p.perfecto=Object.assign({},U,I)}catch(I){throw new P(`Failed to parse perfecto options file error: ${I.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let I=require(Me.join(At(),p.testobjectOptions)),U={testobjectApiKey:p.testobjectKey};p.testobjectSauce=Object.assign({},U,I)}catch(I){throw new P(`Failed to parse test object options file error: ${I.message}`)}if(!p.project){let U=await(await Promise.resolve().then(()=>(Zr(),nn))).getProjectId();if(U)p.project=U;else throw new P("missing project-id info, either --login to provide new credentials or use --project <project-id>")}p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),p.mode??="extension",p.retries=!p.retries||typeof p.retries=="boolean"?1:Number(p.retries)+1,p.browserTimeout=!p.browserTimeout||typeof p.browserTimeout=="boolean"?60*1e3:p.browserTimeout,p.newBrowserWaitTimeout=!p.newBrowserWaitTimeout||typeof p.newBrowserWaitTimeout=="boolean"?10*60*1e3:p.newBrowserWaitTimeout*60*1e3,p.getBrowserTimeout||(p.getBrowserTimeout=p.browserTimeout),p.getBrowserRetries||(p.getBrowserRetries=p.mode===Y.APPIUM?1:Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=p.browserTimeout<p.getSessionTimeout?p.getSessionTimeout:p.browserTimeout,p.driverRequestTimeout=p.browserTimeout<p.driverRequestTimeout?p.driverRequestTimeout:p.browserTimeout;let c=Boolean(p.timeout);if(p.timeout=!p.timeout||typeof p.timeout=="boolean"?10*60*1e3:p.timeout,p.beforeParallel=!p.beforeParallel||typeof p.beforeParallel=="boolean"?1:Number(p.beforeParallel),p.parallel=!p.parallel||typeof p.parallel=="boolean"?1:Number(p.parallel),p.afterParallel=!p.afterParallel||typeof p.afterParallel=="boolean"?1:Number(p.afterParallel),p.tunnelPort=!p.tunnelPort||typeof p.tunnelPort=="boolean"?"80":p.tunnelPort,p.port&&=Number(p.port),!p.token){let U=await(await Promise.resolve().then(()=>(Zr(),nn))).getToken();if(U)p.token=U;else throw new P("missing Testim Access Token, either --login to provide new credentials or use --token <testim-access-token>, contact info@testim.io if you need a new one.")}let l=I=>I<=0||!Number.isInteger(I);if(l(p.retries))throw new P("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new P("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(l(p.browserTimeout))throw new P("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(l(p.newBrowserWaitTimeout))throw new P("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(l(p.timeout))throw new P("test run timeout could not be a negative number, --timeout <run-timeout>");if(l(p.beforeParallel))throw new P("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(l(p.parallel))throw new P("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(l(p.afterParallel))throw new P("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(![Y.EXTENSION,Y.SELENIUM,Y.APPIUM].includes(p.mode))throw new P(`runner mode <${p.mode}> is not supported`);if(p.mode!==Y.SELENIUM&&p.disableNativeEvents)throw new P("disable-native-events is only applicable in selenium mode");if(!p.browser&&!o&&!i&&(p.browser="chrome"),p.appiumLogLevel||(p.appiumLogLevel="silent"),!Ow.includes(p.appiumLogLevel))throw new P(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData)throw new P("missing remote grid address parameter, specify --host <host-name-or-ip> or --grid <grid-name> or --grid-id <grid-id>")}else if(p.testId.length||p.label.length||p.name.length||o||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new P("cannot set --testId, --label, --name, --browser, --test-config, --test-config-id, --local-tma-url, --use-local-chrome-driver --use-chrome-launcher or --suite with --test-plan option");if(!i&&(p.beforeParallel!==1||p.afterParallel!==1))throw new P("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new P("please define exactly one of --grid or --grid-id or --host");if((k=p.host)!=null&&k.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=_m.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(U=>U.trim()).filter(Boolean);let I=p.resultLabel.filter(U=>U.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&mr()&&p.resultLabel.unshift(mr()),I.length)throw new P("A result label cannot exceed 250 characters")}let d=bm(p),u=Oo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new P("cannot set --w3c-capabilities and --old-capabilities options as false");if(p.protocol||=p.port===443?"https":"http",!["http","https"].includes(p.protocol))throw new P("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new P("It is not possible to use --branch with --rerun-failed-by-run-id. Tests will automatically run on the same branch that was used in the original run");if(p.rerunFailedByRunId&&(a||p.name.length||p.testId.length||p.label.length||i))throw new P("Re-running failed tests is not possible when suite (--suite), label (--label), plan (--test-plan), or other test flags (--test) are provided. Please remove these flags and try again");if(p.setRetention&&!Bt.inRange(Bt.parseInt(p.setRetention),1,11))throw new P("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let g="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new P(`--mock-network-har ${g}`);if(p.mockNetworkPattern)throw new P(`--mock-network-pattern ${g}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new P("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new P("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new P("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new P("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Bt.difference(p.codeCoverageReporter,yl).length){let I=Bt.difference(p.codeCoverageReporter,yl);throw new P(`invalid --code-coverage-reporter parameters ${I.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let f={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},h=Object.keys(f).filter(I=>Boolean(p[I]));if(p.mode!==Y.EXTENSION&&h.length){let I=h.length>1?"are":"is";throw new P(`${h.map(U=>f[U]).join(" and ")} ${I} only applicable in extension mode`)}if(p.tmsFieldFile)try{let I=hl.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(I)}catch(I){throw new P(`failed to parse field file error: ${I.message}`)}if(p.highSpeed&&(kw("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new P("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new P("It is not possible to use --osVersion or --deviceName with --device-udid. device-udid is unique and cannot be combined with another flag");if(p.setNoReset&&p.fullReset)throw new P("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.resetOnSessionStartOnly&&!p.fullReset&&console.warn("Ignoring --reset-on-session-start-only flag, should be used when --full-reset is provided for ios runs"),p.lightweightMode)try{let I={general:!0,disableLabs:!0,disableFeatureFlags:!0,disableAssets:!0,disablePixelValidation:!0,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!0,assumePreloadedSharedSteps:!0,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableAutoImprove:!0,disableQuotaBlocking:!0,onlyTestIdsNoSuite:!0,uploadAssetsAndResultsOnFailure:!0,preloadTests:!0,disableProjectDefaults:!0,type:"lightweight"},U=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode=Object.assign({},I,U)}catch(I){throw new P(`failed to parse lightweightMode settings error: ${I.message}`)}else p.turboMode&&p.mode===Y.EXTENSION&&(p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"});if(typeof p.baseUrl=="boolean")throw new P("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),webpackConfig:p.webpackConfig,reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?mr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userParamsData:s,mode:p.mode,isRegressionBaselineRun:p.isRegressionBaselineRun,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,resetOnSessionStartOnly:p.resetOnSessionStartOnly,ext:p.ext,extensionLocation:[p.extensionPath||d].flat(),extensionPath:p.extensionPath,playerLocation:p.playerPath||u,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:c,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0},downloadBrowser:p.downloadBrowser}}});var jm={};V(jm,{installAllLazyDependencies:()=>Uw,lazyRequire:()=>Ee});async function Ee(s,e={}){let t=lc(s);if(t)return t;let r;e.silent||(r=(0,Um.default)(`Installing ${s} before first usage...`).start());try{let n=await Nw(s);return r&&r.succeed(),n}catch(n){Mw.warn("failed to install dependency lazily",{dependency:s,err:n});let o=Bm(s),i=`${s}@${o}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${i}`;throw r&&r.fail(l),n}}async function Nw(s){return es.has(s)||(es.set(s,Fm(s)),es.get(s).catch(()=>{es.delete(s)})),es.get(s)}async function Fm(s){let e=lc(s);if(e)return e;let t=Bm(s),r=`${s}@${t}`;return await go(lt(),r),Kt(s)}async function Uw(){let s=Object.keys(Ia);for(let e of s)await Fm(e)}function Bm(s){let e=Object.entries(Ia).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Um,Mw,es,wr=T(()=>{"use strict";Um=E(require("ora"));Hs();j();B();Vn();Gs();Mw=A("lazy-require"),es=new Map});var Wm={};V(Wm,{preloadTests:()=>on});async function on(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await ut(async()=>{let t=await ae(s.testId,r=>Ac({...e,testId:r}),{concurrency:2});return $m.keyBy(t,"testData.id")},"loadTests",Fw,[e,s.testId])()}var $m,Fw,No=T(()=>{"use strict";$m=E(require("lodash"));zt();be();B();Fw=1e3*60*60*10});function vl(){return ct()}async function Hm(){if(!ke)try{let s=await ce(jw(),5e3,"The API call to NPM timed out"),e=vl();e&&Gm.lt(e,s)&&console.log(Vm.default.yellow(`Warning: You are using version ${e}, a newer version is available. To update please run npm install (npm install -g @testim/testim-cli)`))}catch(s){Bw.warn("Failed to get NPM version",{err:s})}}var Vm,Gm,Bw,jw,El=T(()=>{"use strict";Vm=E(require("chalk")),Gm=E(require("semver"));B();le();Hs();zt();j();Bw=A("npm-driver"),jw=ut(()=>Bd("@testim/testim-cli"),"getNpmVersion")});var Sl,Ww,ts,qm,zm,Il,Km,Jm=T(()=>{"use strict";B();z();j();wr();Sl=A("testimNgrok"),Ww=".whitelisted-ngrok.testim.io",ts="",zm=async(s,e={})=>{if(!e.ngrokToken)throw new P("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${te()}-${s.projectData.projectId}${Ww}`);let r={proto:"http",addr:s.tunnelPort||80,authtoken:e.ngrokToken,hostname:t};s.tunnelHostHeader&&(r.host_header=s.tunnelHostHeader),s.tunnelRegion&&(r.region=s.tunnelRegion);let o=await(await Ee("ngrok")).connect(r);s.tunnelUseHttpAddress&&o.startsWith("https://")?(Sl.info("replace https to http"),ts=o.replace("https://","http://")):ts=o,s.tunnelDiagnostics&&Il(),s.baseUrl=ts},Il=async(s=!0)=>{try{let t=(await Ee("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(o=>o.public_url===ts);console.log("ngrok stats",n),Sl.info("ngrok stats",{tunnel:n})}catch(e){Sl.error("error collecting ngrok stats",{err:e})}s&&(qm=setTimeout(()=>Il(),1e4))},Km=async s=>{if(!ts)return;clearTimeout(qm),s.tunnelDiagnostics&&await Il(!1),await(await Ee("ngrok")).disconnect(ts)}});var Qt,Al,Ym,Gw,Hw,Rl,Uo,Bo,Fo,qw,Xm,Qm,Zm=T(()=>{"use strict";Qt=E(require("os")),Al=E(require("fs")),Ym=E(require("child_process"));B();be();Gw="https://github.com/cloudflare/cloudflared/releases/download/2022.4.1/",Hw={win32ia32:{path:"cloudflared-windows-386.exe"},win32x64:{path:"cloudflared-windows-amd64.exe"},darwinx64:{path:"cloudflared-darwin-amd64.tgz",extract:!0},linuxia32:{path:"cloudflared-linux-386"},linuxx64:{path:"cloudflared-linux-amd64"}},Rl=Qt.tmpdir(),Uo=`${Rl}/cloudflared`,Bo=null,Fo=null,qw=async()=>{if(await ge(Uo))return;let e=Hw[Qt.platform()+Qt.arch()];if(!e)throw new Error(`tunnel on ${Qt.platform()+Qt.arch()} platform is not supported.`);let t=e.extract?Rl+e.path:Uo;await qe(`${Gw}/${e.path}`,t),e.extract&&await et(t,Rl),await Al.promises.chmod(Uo,"755")},Xm=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Jc(s.company.companyId,t),qw()]);Bo=r._id,Fo=Ym.spawn(Uo,["tunnel","--no-autoupdate","run","--force","--token",r.token],{stdio:"inherit"}),await Yc(s.company.companyId,Bo),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Al.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},Qm=async s=>{let e=[];return Bo&&e.push(Xc(s.company.companyId,Bo)),Fo&&e.push(new Promise((t,r)=>{Fo.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Fo.kill()})),await Promise.all(e)}});var G,tf,Kw,Jw,Yw,ef,jo,xl,M,he=T(()=>{"use strict";G=E(require("rox-node"));j();B();le();tf=A("FeatureFlagsService"),Kw=!ke&&!0&&!Dp,Jw=2e4,Yw=60*60*24,ef=["labs","disabled","enabled"],jo=class extends G.default.Variant{constructor(e="disabled"){super(e,ef)}getValue(){let e=super.getValue();return ef.includes(e)?e:(tf.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},xl=class{constructor(){this.flags={useNewWSCLI:new G.default.Flag,useSafariWebdriverVisibilityChecks:new G.default.Flag,useClickimVisibilityChecks:new G.default.Flag,runGetElementCodeInAut:new G.default.Flag,enableFrameSwitchOptimization:new G.default.Flag,maximumJsResultSize:new G.default.Configuration(2e3*1024),skipFileInputClicks:new G.default.Flag,errorMessageOnBadNetwork:new G.default.Flag(!0),warnOnBadNetwork:new G.default.Flag(!1),overrideAzureStorageUrl:new G.default.Flag,useJsInputCodeInSafari:new G.default.Flag,useJsInputCodeInFirefox:new G.default.Flag,useJsInputCodeInEdgeChromium:new G.default.Flag,autoSaveDownloadFileFireFox:new G.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new G.default.Flag(!0),experimentalPreCodeCompilation:new G.default.Flag(!0),experimentalAsyncCustomCode:new G.default.Flag,useSameBrowserForMultiTests:new jo("labs"),highSpeedMode:new jo,usePortedHtml5DragDrop:new G.default.Flag,testNamesToBeforeSuiteHook:new G.default.Flag,addCustomCapabilities:new G.default.Variant("{}"),addCustomLTtunnelNTLMOptions:new G.default.Variant("{}"),LTNetworkCapabilities:new G.default.Flag,downloadToBase64:new G.default.Flag,publicGridURL:new G.default.Configuration("public-grid.testim.io"),allowAppFromDeviceRuns:new G.default.Flag(!0),unsupportedCapsFields:new G.default.Variant("[]"),useLinkedomToParseHtml:new G.default.Flag,dontFocusOnInit:new G.default.Flag,retryOnSeleniumHubError:new G.default.Flag,removeEdgeChromeDefaultVersion:new G.default.Flag,enableLambdaTestTunnelNTLM:new G.default.Flag,enableLambdaTestTunnelSkipUpgrade:new G.default.Flag,tdcHsPreventNetworkCapture:new G.default.Flag,headSpinTdcEnableFlagCapability:new G.default.Flag,enableBatchTDC:new G.default.Flag,enableBatchHeadSpin:new G.default.Flag},G.default.register("default",this.flags)}setProjectId(e){G.default.setCustomStringProperty("projectId",e)}setProjectType(e){G.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){G.default.setCustomStringProperty("productType",e)}setCompanyId(e){G.default.setCustomStringProperty("companyId",e)}setPlanType(e){G.default.setCustomStringProperty("planType",e)}setIsPOC(e){G.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){G.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){G.default.setCustomStringProperty("runnerMode",e)}async fetch(){if(!Kw)return;let e={fetchIntervalInSec:Yw,disableNetworkFetch:!1};if(global.ProxyAgent){let t=new global.ProxyAgent(global.proxyUri);Object.assign(e,{httpsAgent:t,httpAgent:t})}return ce(G.default.setup(_p,e),Jw).catch(t=>tf.error("failed to get feature flag status",t))}},M=new xl});var sf,nf,Zt,of,af,rf,Xw,Qw,$o,Zw,ev,ne,Wo=T(()=>{"use strict";sf=E(require("ms")),nf=E(require("p-retry")),Zt=E(require("os")),of=E(require("portfinder")),af=E(require("child_process"));B();He();be();z();j();_o();oe();he();B();rf=A("lambdatestService"),Xw="https://downloads.lambdatest.com/tunnel/v3",Qw={win32ia32:"windows/32bit/LT_Windows.zip",win32x64:"windows/64bit/LT_Windows.zip",darwinia32:"mac/32bit/LT_Mac.zip",darwinx64:"mac/64bit/LT_Mac.zip",darwinarm64:"mac/64bit/LT_Mac.zip",linuxia32:"linux/32bit/LT_Linux.zip",linuxx64:"linux/64bit/LT_Linux.zip",freebsdia32:"freebsd/32bit/LT_Freebsd.zip",freebsdx64:"freebsd/64bit/LT_Freebsd.zip"},$o=`${Zt.tmpdir()}/LT`,Zw=`${$o}/LT`,ev=(0,sf.default)("15m"),ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.LAMBDATEST||e.type===_.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=$c(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?ev:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ge(Zw))return;let t=Qw[Zt.platform()+Zt.arch()];if(!t)throw new Error(`tunnel on ${Zt.platform()+Zt.arch()} platform is not supported.`);let r=`${$o}.zip`;await qe(`${Xw}/${t}`,r),await et(r,$o)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await of.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:o,externalLambdatestNTLMTunnelUsername:i,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=te();let l=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(M.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],i&&a)l=[...l,"--ntlm-user",i,"--ntlm-password",a];else{let u=JSON.parse(M.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...ec(u)])}if(M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io,res.cloudinary.com"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&o)l=[...l,"--user",n,"--key",o];else throw new P("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new P("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),ne.tunnel=af.spawn("./LT",l,{cwd:$o});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,nf.default)(()=>Re(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{retries:30,minTimeout:2e3});rf.info("LT tunnel info",u)}catch(u){throw rf.error("Failed to start LT tunnel",{err:u,stdoutResult:m,stderrResult:d}),u}}static async disconnectTunnel(e){if(!(e.externalLambdatestTunnelId||!ne.tunnel))return new Promise((t,r)=>{ne.tunnel.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),ne.tunnel.kill()})}getCapabilities(e,t,r,n,o){if(!this.isActive)return{};let i=ne.lambdatestConfig.CAPABILITIES[t]||{},a={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},c=[],{mode:l,canary:m,ext:d,extensionPath:u,installCustomExtension:g}=e;if(l===Y.EXTENSION&&!d){let f=cl({canary:m},!0);!u&&f[t]&&(c=[...c,f[t]]),u&&je(u)&&(c=[...c,u])}return g&&je(g)&&(c=[...c,g]),{build:r,name:`${n} - ${o}`,platform:ne.lambdatestConfig.PLATFORM,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,resolution:ne.lambdatestConfig.RESOLUTION,timezone:ne.lambdatestConfig.TIMEZONE,...i,loadExtension:c,...a,console:!0,queueTimeout:300,network:M.flags.LTNetworkCapabilities.isEnabled(),ntlm:M.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:M.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}}});var Pl={};V(Pl,{connect:()=>Go,disconnect:()=>Ho,serveTunneling:()=>rv});var Vo,cf,lf,tv,Go,Ho,rv,Cl=T(()=>{"use strict";Jm();tn();Zm();Rt();Vo=E(require("ora"));j();oe();Wo();cf=A("tunnel"),lf=s=>{var e;return[_.LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},tv=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},Go=async s=>{if(!s.tunnel)return;let e=Nt(),t;try{lf(s)?(t=(0,Vo.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):tv(s)?(t=(0,Vo.default)("Starting testim cloudflare tunnel...").start(),await Xm(s)):(t=(0,Vo.default)("Starting testim ngrok tunnel...").start(),await zm(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw cf.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(n)}},Ho=async s=>{if(s.tunnel)try{lf(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await Qm(s):await Km(s)}catch(e){let t="catch error - failed to close tunnel";throw cf.error(t,{err:e}),new Error(t)}},rv=async(s,e=new Promise(()=>{}))=>(await Go(s),Xr(()=>Ho(s)),await e)});function sv(s){if(s.protocol)return s.protocol;if([_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=uf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function nv(s){let e=uf.exec(s);return e==null?void 0:e[3]}function zo(s){var y,v,S,b,w,R,C,k,I;let e=s&&nv(s.host),t=s==null?void 0:s.port,r=s==null?void 0:s.path,n=s&&sv(s),o=s==null?void 0:s.token,i=s==null?void 0:s.slotId,a=(y=s==null?void 0:s.hybrid)==null?void 0:y.tunnel,c=(v=s==null?void 0:s.external)==null?void 0:v.user,l=(S=s==null?void 0:s.external)==null?void 0:S.key,m=s==null?void 0:s.type,d=m===_.HYBRID?a&&((R=(w=(b=s.hybrid)==null?void 0:b.external)==null?void 0:w[s.hybrid.tunnel])==null?void 0:R.user):c,u=m===_.HYBRID?a&&((I=(k=(C=s.hybrid)==null?void 0:C.external)==null?void 0:k[s.hybrid.tunnel])==null?void 0:I.key):l,g=s==null?void 0:s.name,f=s&&(s._id||s.gridId),h=s==null?void 0:s.provider;return{host:e,port:t,path:r,protocol:n,accessToken:o,slotId:i,gridId:f,tunnel:a,user:c,key:l,type:m,name:g,provider:h,tunnelUser:d,tunnelKey:u}}async function df(s,e,t,r,n){let o;try{o=await n()}catch(i){throw Ye.error("failed to get grid",{projectId:s,companyId:e,err:i}),new Error($r.UNKNOWN)}if(Ye.info("get grid info",Object.assign({},o,{projectId:s,companyId:e})),!o||!["success","error"].includes(o.status))throw Ye.error("invalid response - get grid",{res:o}),new Error($r.UNKNOWN);if(o.status==="success"){let i=zo(o.grid);return ov(t,e,i.gridId,i.slotId,r),i}throw o.code==="not-found"?new wt($r.NOT_FOUND):o.code==="no-available-slot"?new Nr(`Failed to run test on ${r} - concurrency limit reached`):(Ye.error("invalid code error response - get grid",{res:o}),new wt($r.UNKNOWN))}function iv(s,e,t,r,n,o){return df(t,e,s,n,()=>Ro(e,t,r,n,o))}function av(s,e,t,r,n,o,i){return df(t,e,s,n,()=>{var l;let c=(l=i.allGrids)==null?void 0:l.find(m=>(m.name||"").toLowerCase()===r.toLowerCase());return c!=null&&c._id?Ro(e,t,c._id,n,o):Fc(e,t,r,n,o)})}function mf(s){return jc(s)}async function ff(s,e,t){let n=(t||await mf(s)).find(o=>o._id===e);if(!n)throw new P(`Failed to find grid id: ${e}`);return zo(n)}async function cv(s,e,t){let n=(t||await mf(s)).find(o=>(o.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new P(`Failed to find grid name: ${e}`);return zo(n)}async function kl(s,e){let t=an[s];if(!t)return;let{slotId:r,gridId:n,browser:o,companyId:i}=t;if(delete an[s],!r){Ye.warn("failed to find grid slot id",{projectId:e});return}Ye.info("release slot id",{projectId:e,companyId:i,slotId:r,gridId:n,browser:o});try{await Nc(i,e,r,n,o)}catch(a){Ye.error("failed to release slot",{projectId:e,err:a})}}async function lv(s){let e=Object.values(an).filter(Boolean);if(e.length!==0){Ye.info("keep alive worker slots",{projectId:s,slots:e});try{await Mc(s,e)}catch(t){Ye.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function uv(s){pf=global.setInterval(lv,1e4,s)}async function pv(s){let e=Object.keys(an);if(e.length){Ye.warn("not all slots released before end runner flow",{projectId:s});try{await ae(e,t=>kl(Number(t),s))}catch(t){Ye.error("failed to release all slots",{err:t,projectId:s})}}}async function dv(s){await pv(s),clearInterval(pf)}function mv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function fv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>qo.isEmpty(s.testobjectSauce)?qo.isEmpty(s.saucelabs)?qo.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:o,protocol:i}=s,a=mv(t,s),c=fv(t,s);return{host:r,port:n,path:o,protocol:i,type:t,user:c,key:a}}async function hf(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function yf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:o,useChromeLauncher:i,gridId:a,grid:c}=s;if(n||i||o)return{mode:"local"};if(r)return gf(s);let l=t==null?void 0:t.companyId;if(a)return ff(l,a,e);if(c)return cv(l,c,e);if(Fs(s)||s.tunnelOnlyMode){Ye.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new wt("Missing host or grid configuration")}async function bf(s,e,t,r){let{host:n,project:o,grid:i,gridId:a,localTmaUrl:c,useLocalChromeDriver:l,useChromeLauncher:m,company:d}=t,u=d==null?void 0:d.companyId;if(l||m||c)return{mode:"local"};if(n)return gf(t);if(a)return iv(r,u,o,a,s,e);if(i)return av(r,u,o,i,s,e,t);throw new wt("Missing host or grid configuration")}var qo,Ye,an,uf,pf,ov,cn,Tf,rs=T(()=>{"use strict";qo=E(require("lodash"));be();j();B();oe();z();Ye=A("grid-service"),an={},uf=/(^(https?):\/{2})?(.*)/,pf=null;ov=(s,e,t,r,n)=>{an[s]={gridId:t,companyId:e,slotId:r,browser:n}};cn={start:uv,end:dv};Tf=async(s={},e={},t={},r={},n={})=>{var f,h,y;let{company:{companyId:o}={}}=s,{gridId:i,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:m,currentRetry:d}=n;if(!i||!a||(a===_.LAMBDATEST&&await((f=r.enableIfNeeded)==null?void 0:f.call(r,e)),a!==_.HYBRID||!o||!c||!m||!d))return e;let u=await Uc({companyId:o,gridId:i,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Ye.info("handling hybrid grid",{response:u,companyId:o});let g=zo({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((h=r.disable)==null||h.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,g)),g}});function un(){return Ko||"master"}function wf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Ko="master";return}if(s!=null&&s.isArchived)throw new P(`Branch ${s.branch} is archived, run aborted.`);if(s){Ko=s.branch||s;return}Ko=e?"master":void 0}var Ko,Ol=T(()=>{"use strict";z()});var pn,_l,gv,Ll,hv,Jo,Yo,Xo,Qo,Zo,ei=T(()=>{"use strict";B();oe();pn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===pe.FAILED},_l=s=>{let{status:e}=s;return e===pe.ABORTED},gv=s=>{let{status:e}=s;return e===pe.PASSED},Ll=s=>s.runnerStatus===Ka.SKIPPED,hv=s=>s.testStatus===ze.EVALUATING,Jo=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ll(t)&&(Ke(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,Yo=s=>Object.values(s).filter(e=>pn(e)&&hv(e)).length,Xo=s=>Object.values(s).filter(pn),Qo=s=>Object.values(s).filter(gv),Zo=s=>Object.values(s).filter(_l)});function bv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var Dl,ti,yv,ri,Ef=T(()=>{"use strict";Dl=E(require("lodash"));j();ei();ti=A("debug-reporter"),yv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ri=class{constructor(e){this.options=e}onTestStarted(e,t){ti.info("Test Started",{testId:e.testId,testName:e.name,resultId:e.resultId,workerId:t})}onTestFinished(e,t){let r=this.options.gridData||{},n=r.provider,o=r.host,i=r.gridId,a=r.type,c=r.failedGetBrowserAttempts;ti.info("Test Finished",{testId:e.testId,testName:e.name,resultId:e.resultId,success:e.success,duration:e.duration,browser:this.options.browser,companyId:this.options.company.companyId,grid:{provider:n,host:o,failedGetBrowserAttempts:c,id:i,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Dl.default.omit(this.options,yv),company:Dl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,o,i,a){let c=bv(process.argv);ti.info("Test Plan Started",{executionId:o,testPlanName:n,isAnonymous:i,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,o){let i=Qo(e).length,a=Object.keys(e).length-i;ti.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:o,passed:i,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ml,xt,dn=T(()=>{"use strict";oe();Ml=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===_.DEVICE_FARM}},xt=new Ml});var Ul={};V(Ul,{Reporter:()=>Tv});var er,mn,vr,si,Sf,Nl,Tv,Fl=T(()=>{"use strict";er=E(require("chalk")),mn=E(require("lodash"));B();oe();dn();ei();vr={success:er.default.green,warn:er.default.yellow,error:er.default.red},{CLI_MODE:si}=Dt,Sf="device",Nl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.config={showWorkerNames:e.parallel>1}}toWorkerIdPrefix(e){return this.config.showWorkerNames?`W:${e}`:""}printWorkerDivider(){console.log("-".repeat(process.stdout.columns||83))}onTestStarted(e,t){let r=`(${e.testId})`,n=`url: ${er.default.underline(at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?pe.PASSED:pe.FAILED,n=`(${e.testId})`,o=vr[e.success?"success":"error"];console.log(o(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${to(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=at(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
21
21
  \r`)))}onTestPlanFinished(e,t,r,n,o){let i=Xo(e),a=Qo(e),c=Zo(e),l=a.length,m=c.length,d=i.length,u="",g="";if(xt.isTestStatusEnabled){let S=Yo(e);u=` FAILED-EVALUATING: ${S}`,d-=S,g=` SKIPPED: ${Jo(e,this.options)}`}let f=this.buildTestPlanName(o,t),h,y=vr[d?"error":"success"],v=`PASSED: ${l} FAILED: ${d}${u} ABORTED: ${m}${g} Duration: ${to(r)}`;f.trim()===""||f.trim()==="Anonymous"?h=`Tests completed. ${v} (Execution ID: ${n})`:h=`Test plan${f} completed ${v} (${n})`,this.printWorkerDivider(),console.log(y(h)),this.printWorkerDivider(),this.printAllFailedTests(i)}buildTestPlanName(e,t){let r=mn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=mn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,o=mn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,i=mn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[o,n,r,i].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,o,i,a){let c=u=>{u.forEach((g,f)=>{var v;let h=(v=g.testData)!=null&&v.index?`- ${g.testData.index} / ${g.testData.total} Data set`:"",y=`(${g.testId})`;console.log(" ",f+1,":",`${g.name}${Ke(g,this.options)?"-quarantine":""}`,y,h)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(i,n)} test plan with ${d} (${o})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===si.APPIUM?Sf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${er.default.underline(n)} slot from ${er.default.underline(r)}`)}onGetSession(e,t,r){let n=r===si.APPIUM?Sf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${er.default.underline(t)}`)}onWaitToTestStart(e){console.log(this.toWorkerIdPrefix(e),"Wait for test start")}onWaitToTestComplete(e){console.log(this.toWorkerIdPrefix(e),"Wait for test complete")}onGetBrowserFailure(e,t,r){if(r!==2)return;let n=this.options.grid||this.options.gridId,o=this.options.mode===si.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${o} from the grid ${n}`));else if(this.options.useLocalChromeDriver)console.log(vr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let i=this.options.mode===si.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${i} grid at ${this.options.host}:${this.options.port||4444}`))}}},Tv=Nl});var $l={};V($l,{Reporter:()=>Rv});function wv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function vv(s){return s.visitedUrlsList||console.log("No URLs found:","Please contact our support team or remove the --urls flag from the CLI command"),`${s.visitedUrlsList||""}`}function Ev(s){return`${s.visitedUrlsJson||""}`}async function Sv(s,e,t,r,n,o){function i(u){let g=at(s,t,u.testId,u.resultId,r),f={$:{name:wv(u),classname:n,time:tc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":g};if(pn(u)||_l(u)){let h=`Step Failed: ${u.failureReason||u.reason}`,y=pn(u)?`${h} More info at: ${g}`:h;f.failure={$:{message:y}}}return Ll(u)&&Ke(u,o)&&xt.isTestStatusEnabled&&(f.skipped={}),o.urls&&(f["visited-urls-list"]=vv(u),f["visited-urls-json"]=Ev(u)),f}function a(u){let{results:g,testPlanName:f,configName:h}=u,y=g||{},S={name:(h&&f?`${f} with config '${h}'`:f)||"selenium run",tests:l(y),failure:m(y),timestamp:c(e)};if(xt.isTestStatusEnabled){S.skipped=Jo(y,o);let b=Yo(y);S.failure-=b,S["failure-evaluating"]=b}return{$:S,testcase:Object.keys(y).map(b=>i(y[b]))}}function c(u){let g=Object.keys(u).map(h=>u[h].startTime),f=Math.min.apply(null,g);return f?new Date(f).toISOString():new Date().toISOString()}function l(u){return Object.keys(u).length}function m(u){return Xo(u).length+Zo(u).length}let d={testsuites:{testsuite:e.map(u=>a(u))}};try{return new jl.Builder().buildObject(d)}catch(u){return Iv(u)}}function Iv(s){let e=new jl.Builder,t={testsuites:{testsuite:{$:{name:"selenium run",tests:1,failure:1,timestamp:Date.now()},testcase:{$:{name:"junit reporter generator failed",classname:"testim.io.jUnitXmlReporter"},error:{$:{message:s.message}}}}}};return e.buildObject(t)}var jl,If,Bl,Rv,Wl=T(()=>{"use strict";jl=E(require("xml2js"));B();If=require("fs");dn();ei();Bl=class{constructor(e,t){this.options=e;this.branchToUse=t;this.classname="testim.io.test",typeof e.reportFileClassname=="string"&&(this.classname=e.reportFileClassname),e.reportFileClassname===!0&&(this.classname="")}async createResultsReport(e){let t=this.options.reportFile,r=this.options.project,n=await Sv(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await If.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(o){return console.error("could not save report file",t,o),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Rv=Bl});var Rf={};V(Rf,{Reporter:()=>Av});function ss(s){return s?s.replace(/\|/g,"||").replace(/'/g,"|'").replace(/\n/g,"|n").replace(/\r/g,"|r").replace(/\u0085/g,"|x").replace(/\u2028/g,"|l").replace(/\u2029/g,"|p").replace(/\[/g,"|[").replace(/\]/g,"|]"):""}var Vl,Gl,Av,Af=T(()=>{"use strict";j();Vl=A("team-city-reporter");Gl=class{constructor(e){this.options=e}getPrintName(e){let t=e.config||{},r=typeof t.testDataTotal=="number"?` - ${t.testDataIndex} / ${t.testDataTotal} Data set`:"",n=`${e.name} (${e.testId})${r}`;return ss(n)}onTestStarted(e,t,r,n){if(r){Vl.debug("skip report test started because is rerun");return}let o=this.getPrintName(e);console.log(`##teamcity[testStarted name='${o}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,o,i){if(o){Vl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ss(t)}' details='${ss(r)}' flowId='${i}']`)}onTestFinished(e,t,r){if(r){Vl.debug("skip report test finished because is rerun");return}let n=this.getPrintName(e);console.log(`##teamcity[testFinished name='${n}' duration='${e.duration}' flowId='${e.resultId}']`)}onTestIgnored(e,t,r="ignore"){let n=this.getPrintName(t);console.log(`##teamcity[testIgnored name='${n}' message='${ss(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ss(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ss(t)}']`)}},Av=Gl});var xf={};V(xf,{Reporter:()=>xv});var Hl,xv,Pf=T(()=>{"use strict";Hl=class{constructor(e){this.options=e}onTestStarted(e,t){console.log(JSON.stringify({name:"testStarted",data:{test:e,workerId:t}}))}onTestFinished(e,t){console.log(JSON.stringify({name:"testFinished",data:{test:e,workerId:t}}))}onTestPlanStarted(e,t,r,n,o){let i={name:"suiteStarted",data:{projectId:this.options.project,executionId:o}};console.log(JSON.stringify(i))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},xv=Hl});var Cf={};V(Cf,{Reporter:()=>Pv});var ql,Pv,kf=T(()=>{"use strict";B();ll();ql=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=at(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return Do(t)}},Pv=ql});var kA,zl,X,Pt=T(()=>{"use strict";Ef();j();kA=A("reporter"),zl=class{constructor(){this.reporters=[];this.onGetBrowserFailure=this.generateHook("onGetBrowserFailure");this.onGetBrowserSuccess=this.generateHook("onGetBrowserSuccess");this.onTestPlanStarted=this.generateHook("onTestPlanStarted");this.onGetSlot=this.generateHook("onGetSlot");this.onGetSession=this.generateHook("onGetSession");this.onTestFinished=this.generateHook("onTestFinished");this.onTestFailed=this.generateHook("onTestFailed");this.onTestPassed=this.generateHook("onTestPassed");this.onTestStarted=this.generateHook("onTestStarted");this.onTestIgnored=this.generateHook("onTestIgnored");this.onWaitToTestStart=this.generateHook("onWaitToTestStart");this.onWaitToTestComplete=this.generateHook("onWaitToTestComplete");this.onTestPlanFinished=this.generateHook("onTestPlanFinished",this.onTestPlanFinishedMutator);this.onAllTestPlansFinished=this.generateHook("onAllTestPlansFinished",this.onAllTestPlansFinishedMutator)}async setOptions(e,t){this.reporters=[];let r=e.reporters;if(this.reporters.push(new ri(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Fl(),Ul));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:o}=await Promise.resolve().then(()=>(Wl(),$l));this.reporters.push(new o(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Af(),Rf)),r.includes("console")&&Promise.resolve().then(()=>(Fl(),Ul)),r.includes("junit")&&Promise.resolve().then(()=>(Wl(),$l)),r.includes("json")&&Promise.resolve().then(()=>(Pf(),xf)),r.includes("chrome")&&Promise.resolve().then(()=>(kf(),Cf))])).forEach(o=>{o&&this.reporters.push(new o.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,o){let i={};i=e;let a=Date.now()-(r||0);return[i,t,a,n,o]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var o;let n=t==null?void 0:t(...r);for(let i of this.reporters)await((o=i[e])==null?void 0:o.call(i,...n||r))}}},X=new zl});function _f(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Lf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:u,projectType:g,appSource:f,gridType:h}){let y=_f({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:o,companyName:i,projectName:a,companyPlan:c,source:Of(l,m),isStartUp:u,projectType:g,gridType:h,...["android","ios"].includes(g)&&f&&{appSource:f}},d);pt("test-run-ci",y)}function Df({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:u,logger:g,isStartUp:f,projectType:h,appSource:y,gridType:v}){try{let S=_f({executionId:s,projectId:e,testId:t,resultId:r,ucid:o,companyId:i,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:Of(m,d),isStartUp:f,projectType:h,gridType:v,...["android","ios"].includes(h)&&y&&{appSource:y}},u);if(n.success){pt("test-run-ci-success",S);return}pt("test-run-ci-fail",Object.assign({},S,{failureReason:n.failureReason}))}catch(S){g.error("failed to update test end analytics",{err:S})}}function Mf(s){pt("batch-run-ci",s)}var Of,Kl=T(()=>{"use strict";Qr();Eo();Of=(s,e)=>s!=="cli"&&s!=="cli-local"?s:Jr&&e?"ci-with-user":Jr?"ci":e?"cli-with-user":s});var Uf,ni,Ff=T(()=>{"use strict";Uf=require("istanbul-lib-report"),ni=class extends Uf.ReportBase{constructor(t){super();t||={},this.appendToObject=t.appendToObject||{}}onStart(t){let r=t.getCoverageSummary(!1);this.appendToObject=Object.assign(this.appendToObject,r.toJSON())}}});var Bf,jf,$f,fn,dt,Wf,oi,Jl,Vf,Cv,Gf,Hf,kv,Ov,qf,_v,Lv,Dv,Mv,Nv,zf,Kf=T(()=>{"use strict";Bf=E(require("ora")),jf=E(require("dayjs")),$f=E(require("test-exclude")),fn=E(require("fs")),dt=E(require("path")),Wf=E(require("istanbul-reports")),oi=E(require("istanbul-lib-report"));be();z();B();j();wr();Ff();Jl=A("test-run-status"),Vf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Cv=s=>!!Vf(s).search,Gf=s=>s?Vf(s).pathname.substring(1):"",Hf=(s,e)=>{let t=Gf(e);return!new $f.default({relativePath:!1,include:s}).shouldInstrument(t)},kv=s=>s.substring(0,s.indexOf("?")),Ov=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await Ee("convert-source-map");if(t==="file"&&!e)throw new P("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},qf=(s,e)=>`${dt.resolve(s,Gf(e))}.js`,_v=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await ae(Object.values(t),async n=>{if(!n)return;let o=n.toObject();await ae(o.sources,async(i,a)=>{if(Hf(r,i))return;let c=qf(e,i);await fn.promises.mkdir(dt.parse(c).dir,{recursive:!0}),await fn.promises.writeFile(c,o.sourcesContent[a])})})},Lv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Cv(e)&&(e=kv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=dt.dirname(this.getPath(s));return dt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Dv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,o={},i=oi.createContext({dir:t,coverageMap:e,watermarks:oi.getDefaultWatermarks(),sourceFinder:a=>{try{let c=qf(r,a);return fn.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new ni({appendToObject:o}).execute(i),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Lv}),Wf.create(a,c).execute(i)}),o},Mv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let i=(await Ee("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Hf(n,a));return await i.load(),i.applyCoverage(r),i.toIstanbul()},Nv=async(s,e)=>{let{mergeProcessCovs:r}=await Ee("@bcoe/v8-coverage"),n={result:[]},o=new Map,a=(await Vc(s,"testResult",`runId=${e}`)).data.docs;return await ae(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await Qs(c,9e4);await ae(l,async m=>{if(!o.has(m.url)){let d=m.text;m.sourceUrl&&(o.set(m.url,"TEMP"),d=await Ic(m.sourceUrl)),o.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:o,mergedCoverages:n}},zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Jl.info("start js coverage process");let n=(0,Bf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),o=dt.resolve(s.codeCoverageReportPath||"./coverage"),i=dt.resolve(o,`.js/${(0,jf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?dt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([Ee("istanbul-lib-coverage"),Nv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Jl.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),u={};await ae(l.result,async({url:f,functions:h})=>{let{text:y,sourceMapType:v}=m.get(f),S=await Ov({sourceMapType:v,source:y,sourceMapDir:a});u[f]=S;let b=await Mv(s,{source:y,sourceMap:S,functions:h});d.merge(b)}),await _v(s,i,u);let g=await Dv(s,d,o,i);return n.succeed(),g}catch(c){let l="Failed to report coverage information";c instanceof P?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Jl.error(l,{err:c})}}});var Jf={};V(Jf,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>jt});var xe,Uv,jt,ns=T(()=>{"use strict";B();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Uv=["ALL",...Object.values(xe)],jt=class{constructor(){this.marks=Object.fromEntries(Uv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=te();return this.startTimes[`${e}:${t}`]=Date.now(),t}markEnd(e,t){let r=Date.now()-this.startTimes[`${t}:${e}`];if(delete this.startTimes[`${t}:${e}`],!this.marks[t]){this.marks.ALL.push(r);return}this.marks[t].push(r)}getStats(){let e=Object.entries(this.marks).flatMap(([t,r])=>!Array.isArray(r)||!r.length?[]:[[`${t}_COUNT`,r.length],[`${t}_P50`,no(r,50)],[`${t}_P95`,no(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var Zf={};V(Zf,{initServer:()=>jv,mapFilesToLocalDrive:()=>Xl});function Xl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,ii[t.id]?{screenshot:ii[t.id]}:{})),Object.keys(ai).forEach(t=>{s.assets||={},s.assets[Qf[t]]=ai[t]}),s.assets||={},s.assets.screenshots=Object.values(ii)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function jv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await Ee("multer"),n=typeof t=="string"?t:Fv;await Yl.promises.mkdir(n,{recursive:!0});let o=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let u=gn.join(n,d.testResultId);try{await Yl.promises.mkdir(u,{recursive:!0})}catch(g){return m(g,"")}return m(null,u)},filename(c,l,m){let{fileName:d}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(u.stepId){let g=gn.extname(d);return m(null,`step_${u.stepId}_${u.stepName||""}${g}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),i=(0,Xf.default)();i.post("/",o.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(ii[m.stepId]=c.file.path),m.testResultId&&Bv.includes(m.subType)&&(ai[m.subType]||=[],ai[m.subType].push(c.file.path)),l.sendStatus(200)}),i.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(i);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new P(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new P(`Port ${s} is already in use`));default:return l(u)}}})}var Yl,Yf,gn,Xf,Fv,ii,ai,Qf,Bv,Ql=T(()=>{"use strict";Yl=E(require("fs")),Yf=E(require("os")),gn=E(require("path")),Xf=E(require("express"));z();wr();Fv=gn.join(Yf.tmpdir(),"testim/rca/"),ii={},ai={},Qf={"test-log":"consoleLogs","har-file":"networkLogs"},Bv=Object.keys(Qf)});var tr,Zl,ci,eg=T(()=>{"use strict";tr=E(require("lodash"));B();j();Zl=A("override-test-data-builder"),ci=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return tr.isObject(e)&&!Array.isArray(e)}isArrayOfObjects(e){return Array.isArray(e)&&e.filter(t=>!this.isObjectNotArray(t)).length===0}overrideTestData(){let{params:e,projectId:t}=this;return this.isObjectNotArray(e)&&e.overrideTestData!==void 0&&(this.isObjectNotArray(e.overrideTestData)&&!tr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Zl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(tr.isObject(e.overrideAllTestsData)&&!tr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Zl.error("invalid overrideAllTestsData",{overrideAllTestsData:e.overrideAllTestsData,projectId:t})),this.testInfoList}overrideSingleTest(e,t){let{projectId:r}=this;if(this.isObjectNotArray(t)||this.isArrayOfObjects(t)){this.replaceAndCreateOverrideTestData(e,t);return}Zl.error("skip override test data to test name",{testName:e,projectId:r}),console.error(`Invalid override test data provided to test '${e}'`)}replaceAndCreateOverrideTestData(e,t){let r=this.mapTestListToUniqueId(e);if(r.length!==0)return this.createNewTestPerOverrideTestData(r,t)}mapTestListToUniqueId(e){let{testInfoList:t}=this;return tr.chain(t).map(r=>{if(r.name.toLowerCase()===e.toLowerCase())return this.generateTestUniqId(r)}).compact().uniq().value()}createNewTestPerOverrideTestData(e,t){let{testInfoList:r}=this;return[...new Set(e)].map(n=>{let o=r.map(m=>this.generateTestUniqId(m)),i=o.indexOf(n),a=o.lastIndexOf(n),c=r[i],l=this.createNewTestItems(c,t);return r.splice(i,a-i+1,...l)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let o=te();return Object.assign({},e,{resultId:o,testData:{value:r,index:n+1,total:t.length||1}})})}getTestType(e){return e.isBeforeTestPlan?"before":e.isAfterTestPlan?"after":"test"}generateTestUniqId(e){return`${e.testId}:${e.testConfig.id}:${this.getTestType(e)}`}}});async function li(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Xe.warn("failed to run hook",{err:t}),new P(`failed to run hook promise ${t.message}`)}}var Er,Xe,$v,Wv,Vv,Gv,ui,tg=T(()=>{"use strict";Er=E(require("lodash"));B();oe();rs();be();z();j();Pt();tn();Kf();ns();Ql();le();he();eg();dn();Xe=A("test-run-status"),$v=mr(),Wv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Vv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Gv=ct();ui=class{constructor(e,t,r,n){this.testInfoList=e;this.options=t;this.branchToUse=n;this.exportsGlobal={};this.startTime=null;this.beforeSuiteParams={};this.executionStartedPromise=Promise.resolve();this.seleniumPerfStats=new jt;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let o=Us(t,e),i=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:zn||t.parallel||1,browser:o,gitBranch:$v,gitCommit:Wv,gitRepoUrl:Vv,runnerVersion:Gv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:i,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:o,retryCount:i=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:u,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:i,testStatus:d};return this.testRunStatus[e]=Object.assign({},b,{testCreatorName:u,testCreatorEmail:g,testOwnerName:f,testOwnerEmail:h,testLabels:y,testSuites:v,allLabels:S}),zc({projectId:n,runId:o,testId:l,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let o=this.getTestResult(r);return o.workerId=e,X.onTestStarted(o,e,n,r),o}async updateTestStatusRunning(e,t,r){var l;let{project:n,remoteRunId:o,projectData:i}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await xo(n,e.testId,e.resultId,e.config.testData,i.defaults)||""}catch(m){Xe.error("failed to upload test data artifact (runner)",{err:m})}let c=Er.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,br(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:o,testRetryKey:r})}async testStartReport(e,t,r){if(Ke(e,this.options))return;let n=this.exportsGlobal;try{let o=await li(this.options.beforeTest,Object.assign({},e,{exportsGlobal:n,globalParameters:n}),this.options.userData.loginData.token);return e.config.testData=Object.assign({},e.config.testData,this.exportsGlobal,this.fileUserParamsData,this.beforeSuiteParams,o),this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(o){throw Xe.error("Failed to start test",{err:o}),o}}testStartAndReport(e,t,r,n,o){let i=this.testStart(e,t,r,n);return this.testStartReport(i,t,o)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo=Object.assign({},t,{key:void 0,user:void 0}),Xe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:o,testId:i,testStatus:a}=r,{resultId:c,success:l}=t;if(a===ze.EVALUATING&&xt.isTestStatusEnabled){X.onTestIgnored(e,r,`test in ${ze.EVALUATING} status`);return}if(l){X.onTestPassed(o);return}X.onTestFailed(r,r.failureReason,at(this.options.editorUrl,this.options.project,i,c,this.branchToUse),i,n,c)}calcResultText(e){return e.success?pe.PASSED:pe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);X.onTestIgnored(e,r,`test in ${ze.QUARANTINE}`)}monitorMemoryUsage(e){let t=rc();if(t.isOverThreshold){let r=M.flags.useLinkedomToParseHtml.isEnabled()?"linkedom":"jsdom";Xe.info(`using ${r} to parse html`,{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}}testEnd(e,t,r,n,o){let i=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;i.sessionId=n,i.startTime=t.startTime||i.startTime||Date.now(),i.duration=a,t.duration=a,i.failureReason=t.failureReason||t.reason,t.failureReason=i.failureReason,i.failurePath=t.failurePath,i.resultId=t.resultId,i.success=t.success,this.options.saveRCALocally&&Xl(i,Xe),i.resultUrl=at(this.options.editorUrl,this.options.project,i.testId,i.resultId,this.branchToUse),i.status=this.calcResultText(t),t.status=i.status,t.name=i.name,t.testStatus=i.testStatus,t.testId||=i.testId,t.testCreatorName=i.testCreatorName,t.testCreatorEmail=i.testCreatorEmail,t.testOwnerName=i.testOwnerName,t.testOwnerEmail=i.testOwnerEmail,t.testData=i.config&&typeof i.config.testDataTotal=="number"?{total:i.config.testDataTotal,index:i.config.testDataIndex}:{},this.reportTestStatus(e,t,i,o),this.monitorMemoryUsage(i),X.onTestFinished(i,e,o);let c=Object.assign({},this.exportsGlobal,t.exportsGlobal);return this.exportsGlobal=c,i}async testEndReport(e,t,r,n){var i;let o=r.exportsGlobal;try{try{await li(this.options.afterTest,Object.assign({},e,{exportsGlobal:o,globalParameters:o}),this.options.userData.loginData.token)}catch(a){Xe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(i=this.options.lightweightMode)!=null&&i.onlyTestIdsNoSuite?void 0:await br(this.options.project,t,e.testId,e.resultId,"FINISHED",{startTime:e.startTime,endTime:r.endTime,success:e.success,failureReason:e.failureReason,remoteRunId:this.options.remoteRunId,...n},5)}catch(a){throw Xe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,o,i){let a=this.testEnd(e,t,r,n,o);return this.testEndReport(a,r,t,i)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:o,VIRTUAL_BUILD:i}=Xa;return e&&(n=o),Wr(t,r)&&(n=i),n}calcTestRunStatus(){var i;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(i=e.gridData)==null?void 0:i.type,o=t.map(a=>{var g,f,h;let c=e.browser?Ws(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=!M.flags.allowAppFromDeviceRuns.isEnabled()&&Bs(a.nativeApp),m=js(e)&&(Wr(a.nativeApp,n)||l),d=Ke(a,e)||m,u={testId:a.testId,status:d?pe.SKIPPED:pe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||ze.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...m&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:Object.assign({},this.execConfig,{companyId:r,testData:((g=a.testData)==null?void 0:g.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((f=a.testData)==null?void 0:f.total)||null,testDataIndex:((h=a.testData)==null?void 0:h.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:c.browserValue.toLowerCase()})};return[a.resultId,u]});return Object.fromEntries(o)}async executionStart(e,t,r,n,o){Xe.info("execution started",{executionId:e});let{options:i}=this,{remoteRunId:a,projectData:c}=i;Xr(()=>Promise.all([cn.end(t),Io("ABORTED",e,t,!1,void 0,a,void 0)])),this.startTime=r||Date.now();let l={projectId:t,executionId:e,...M.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:o}},m=await li(i.beforeSuite,l),d=new ci(m,Er.cloneDeep(this.testInfoList),t);this.testInfoList=d.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=m;let{testInfoList:u}=this,g=[],f=[],h=[];for(let v of u){if(v.isBeforeTestPlan){g.push(v);continue}if(v.isAfterTestPlan){h.push(v);continue}f.push(v)}let y=async()=>{let v=Er.cloneDeep(this.testRunStatus);await ae(Object.keys(v),async R=>{var O;let C=v[R],k=(O=C.config)==null?void 0:O.testData,I=C.testId,U=await xo(t,I,R,k,c.defaults);U&&(delete C.config.testData,C.config.testDataUrl=U)});let S=Boolean(i.useLocalChromeDriver||i.useChromeLauncher),b={executionId:e,projectId:t,labels:n||[],startTime:r,executions:v,config:this.execConfig,resultLabels:i.resultLabels,remoteRunId:i.remoteRunId,localRunUserId:i.user,isLocalRun:S,intersections:i.intersections},w=Cc(b);return this.executionStartedPromise=w,w.catch(R=>Xe.error(R)),w};try{await y()}catch(v){Xe.error("Failed to start suite",{err:v}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:f,afterTests:h}}concatSeleniumPerfMarks(e){Er.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var m;let t=nc(this.testRunStatus),r=t.length,n=0,o=0,i=0;for(let{status:d,testStatus:u}of t)d===pe.PASSED&&n++,d===pe.SKIPPED&&o++,d===pe.FAILED&&u===ze.EVALUATING&&i++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await li(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:o})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Xe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await zf(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Io("FINISHED",e,this.options.project,r===n+o+i,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Xe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let o=Object.keys(this.testRunStatus).filter(i=>this.getTestResult(i).status==="QUEUED");await Pc(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let i of o){let a=this.getTestResult(i);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function qv(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function nu(s){return ng.readFileSync(s,{encoding:"base64"})}function cg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&je(s))&&s){let r=nu(s);os.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${su(r)} current extension count: ${e.length}`),e.push(r)}}function lg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;if(s.ext||r){let c=typeof s.ext=="string"?s.ext:`${__dirname}/..`,l=r||c,m=`--load-extension=${l}`;os.info(`adding extension: testim unpacked , path: ${l}`),t.push(m);return}let o=s.canary?"-master.zip":".zip",i=ru.join(process.cwd(),`testim-headless${o}`),a=nu(i);os.info(`adding extension: testim zipped, path: ${i} length: ${a.length} hash: ${su(a)} current extension count: ${e.length}`),e.push(a)}function zv(s,e,t,r,n,o,i){var f,h;let a=t.seleniumName||t.browserValue,c=[],l=[...ag];e.headless&&l.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":eu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":eu.CONTENT_SETTING_ALLOW,"plugins.always_open_pdf_externally":!0,"safebrowsing.enabled":!0,"profile.content_settings.exceptions.clipboard":{"[*.],*":{last_modified:Date.now(),setting:1}},"download.allow_office_viewer_for_download":!1},w3c:!0};tu(n)&&(m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version="latest-1",s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60),tu(n)&&a==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(y=>l.push(`--${y}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=eu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&l.push(`--user-data-dir=${e.chromeUserDataDir}`),(h=(f=e.projectData)==null?void 0:f.defaults)!=null&&h.disableChromiumGpu&&l.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:a});function d(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Ja.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}d(),cg(r,c,i),e.mode===Y.EXTENSION&&lg(e,c,l,o,i),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=l;let u={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[a],g={MicrosoftEdge:"ms",chrome:"goog"}[a];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(i!=null&&i.isLambdatestRun())&&(s.desiredCapabilities[u]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${g}:${u}`]=m),s}function Jv(s,e,t){let r={"pdfjs.disabled":!0};if(M.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":sg.join(","),"browser.helperApps.neverAsk.openFile":sg.join(","),"browser.helperApps.alwaysAsk.force":!1,"browser.download.manager.useWindow":!1,"browser.download.manager.focusWhenStarting":!1,"browser.download.manager.alertOnEXEOpen":!1,"browser.download.manager.showWhenStarting":!1,"browser.download.manager.closeWhenDone":!0,"browser.download.manager.showAlertOnComplete":!1}),Object.assign(s.desiredCapabilities,{acceptInsecureCerts:!0,browserName:"firefox",marionette:!0,"moz:firefoxOptions":{prefs:r}},t!=null&&t.isLambdatestRun()?{enableCustomTranslation:!0}:{}),e.disableCookiesSameSiteNoneRequiresSecure&&(s.desiredCapabilities["moz:firefoxOptions"].prefs["network.cookie.sameSite.noneRequiresSecure"]=!1),e.mode===Y.EXTENSION)if(e.ext)s.desiredCapabilities.testim_firefox_profile=e.ext;else{let n=e.canary?"-master.zip":".zip",o=ru.join(process.cwd(),`testim-firefox-profile${n}`);s.desiredCapabilities.firefox_profile=nu(o)}return e.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function Yv(s,e,t){let{saucelabs:r}=s;if(r!=null&&r.browserVersion&&(r.version=r.browserVersion),r!=null&&r.username&&r.accessKey){let n={"sauce:options":{name:e}};if(t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let o=(0,ig.cloneDeep)(t.sl);return t.sl.screenResolution&&(n["sauce:options"].screenResolution=t.sl.screenResolution,delete o.screenResolution),rt.merge(o,n,r)}return rt.merge(n,r)}return{}}function Xv(s,e,t){return rt.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),Object.assign({},t.bs,s.browserstack,{name:e})):Object.assign({},s.browserstack,{name:e})}function Qv(s){return s.perfecto?s.perfecto:{}}function Zv(s,e,t){if(s.experitestToken){let r=e==="safari";return{accessKey:s.experitestToken,browserVersion:"latest",platformName:r?"MAC":"WIN10",seleniumScreenshot:r,newSessionWaitTimeout:t}}return{}}function eE(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,o=r||t.user||e.user,i=n||t.key||e.key,a={};return o&&i&&(a.Authorization=va(o,i)),a}function pi(s,e,t,r,n,o,i,a=null){var h,y;if(r.mode==="local"){let v=[],S=[...ag],b={};return s.headless&&S.push("--headless"),s.silentDebuggerExtensionApi&&S.push("--silent-debugger-extension-api"),s.remoteDebuggingPort!==void 0&&S.push(`--remote-debugging-port=${s.remoteDebuggingPort}`),s.chromeExtraArgs&&s.chromeExtraArgs.forEach(w=>S.push(`--${w}`)),s.chromeBinaryLocation&&(b.binary=s.chromeBinaryLocation),s.mode!=="selenium"&&lg(s,v,S,null,a),cg(n,v,a),{logLevel:rg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:S,extensions:v,...b},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:c,driverRequestRetries:l}=s,m=eE(s,r),d={hostname:r.host,host:r.host,port:r.port||4444,path:r.path||"/wd/hub",protocol:r.protocol||"http",logLevel:rg,connectionRetryTimeout:c,connectionRetryCount:l,getSessionTimeout:Math.max(a.getSessionTimeout,s.getSessionTimeout),getSessionRetries:a.getSessionRetries||s.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!rt.isEmpty(m)&&{headers:m},...s.proxyForGrid&&{agent:global.ProxyAgent(global.proxyUri)}};tu(r)&&(s.oldCapabilities=!1,s.w3cCapabilities=!0,d.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),s.disableNativeEvents&&(d.desiredCapabilities.nativeEvents=!1),r.user&&r.key&&(r.type==="saucelabs"&&(s.saucelabs||={},s.saucelabs.username||=r.user,s.saucelabs.accessKey||=r.key),r.type==="browserstack"&&(s.browserstack||={},s.browserstack["browserstack.user"]||=r.user,s.browserstack["browserstack.key"]||=r.key)),r.key&&r.type==="perfecto"&&(s.perfecto.securityToken=r.key);let u=Number(s.browserTimeout/1e3),g=s.browser||(t==null?void 0:t.browserValue);rt.merge(d.desiredCapabilities,Yv(s,e,t),Xv(s,e,t),Qv(s),Zv(s,g,u),a==null?void 0:a.getCapabilities(s,g,o,i,e));let f=null;switch(!s.ext&&!s.extensionPath&&((h=r.host)!=null&&h.endsWith(".testim.io"))&&!s.canary&&s.mode===Y.EXTENSION&&(g==="chrome"||g==="edge-chromium"&&M.flags.removeEdgeChromeDefaultVersion.isEnabled()?f="/opt/testim-headless":g==="edge-chromium"&&(f="C:/selenium/testim-headless")),!M.flags.removeEdgeChromeDefaultVersion.isEnabled()&&((y=r.host)!=null&&y.endsWith(".testim.io"))&&g==="edge-chromium"&&(d.desiredCapabilities.version="83"),g){case"chrome":case"edge-chromium":d=Kv(d,s,t,n,r,f,a);break;case"firefox":d=Jv(d,s,a);break;case"safari":case"safari technology preview":d=qv(d,g);break;default:break}rt.merge(d.desiredCapabilities,s.seleniumCapsFileContent);try{let v={"hub.lambdatest.com":"lambdatest",[M.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},S=C=>C[r.provider]||C[d.host]||C[v[d.host]],b=C=>{var k,I;return S(C)||C[(k=d.desiredCapabilities)==null?void 0:k.browserName]||C[(I=d.desiredCapabilities)==null?void 0:I.version]||C||{}},w=JSON.parse(M.flags.addCustomCapabilities.getValue()||"{}"),R=b(b(w));Object.keys(R).length&&(os.info(`Adding custom capabilities: ${JSON.stringify(R)}`),Object.assign(d.desiredCapabilities,R))}catch(v){os.error("Failed to load custom capabilities",{error:v,customCapabilities:M.flags.addCustomCapabilities.getValue()})}return d.desiredCapabilities&&!d.capabilities&&(Hv(d),d.capabilities={alwaysMatch:d.desiredCapabilities,firstMatch:[{}]},delete d.desiredCapabilities),d.hostname=d.host,d}var ng,ru,og,rt,ig,os,rg,eu,ag,su,tu,Hv,Kv,sg,ou=T(()=>{"use strict";ng=E(require("fs")),ru=E(require("path")),og=E(require("crypto")),rt=E(require("lodash"));B();le();j();he();oe();Wo();ig=require("lodash"),os=A("testim-desired-capabilities-builder"),rg=qn?"debug":"silent",eu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},ag=["--disable-popup-blocking","--ignore-gpu-blacklist","--auto-select-desktop-capture-source=Entire screen","--ignore-certificate-errors","--disable-features=TranslateUI","--disable-background-networking","--disable-sync","--metrics-recording-only","--disable-default-apps","--mute-audio","--no-first-run","--disable-back-forward-cache"],su=(...s)=>og.createHash("sha256").update(s.join("")).digest("hex"),tu=s=>s.type===_.DEVICE_FARM||s.type===_.HYBRID&&s.provider==="devicefarm",Hv=s=>{var r;let{desiredCapabilities:e}=s;Object.prototype.hasOwnProperty.call(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.prototype.hasOwnProperty.call(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.prototype.hasOwnProperty.call(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.prototype.hasOwnProperty.call(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.prototype.hasOwnProperty.call(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.prototype.hasOwnProperty.call(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.prototype.hasOwnProperty.call(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=M.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(o=>{delete e[o]})}catch{os.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};Kv=rt.memoize(zv,(s,e,t,r,n,o)=>{let i=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(rt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return su(i,a,c,r,l,o)}),sg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"]});function Ne(s){var e,t,r,n,o,i,a;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||s.message==="Unknown error"||((t=s.message)==null?void 0:t.match(/Unknown timeout type/))||s.name==="unknown command"||((r=s.message)==null?void 0:r.match(/did not match a known command/))||((n=s.message)==null?void 0:n.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((i=s.message)==null?void 0:i.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function pg(s,e,t){if(!e||!s)return s;if(s.includes("%"))return s.replace(/ /g,"%20");try{return decodeURI(s)!==s?s:encodeURI(s)}catch(r){return t&&t.warn("tried to encode url but failed",{err:r,url:s}),s}}var iu=T(()=>{"use strict"});function au(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,g){for(let f=u;f&&f!==u.ownerDocument;f=f.parentNode)if(g(f))return f;return null}function n(u,g){for(let f=u;f&&f!==u.ownerDocument;f=t(f))if(g(f))return f;return null}function o(u,g){if(!u||!g)return null;u instanceof DocumentFragment&&(u=u.host);let h=window.getComputedStyle(u).getPropertyValue(g);if(h&&h!=="inherit")return h;let y=t(u);return o(y,g)}function i(u){let g=u.getBoundingClientRect();if(g.width>0&&g.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&g.width+g.height>0){let h=o(u,"stroke-width");return!!h&&parseInt(h,10)>0}return o(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(h=>h.nodeType===Node.TEXT_NODE?!0:e(h)?i(h):!1)}function a(u){return o(u,"overflow")==="hidden"}function c(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(g=>g.nodeType===Node.TEXT_NODE?!1:!e(g)||!i(g)?!0:c(g))}function l(u){var g;return u?(g=u.parentNode)!=null&&g.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let g=r(s,f=>f.tagName.toUpperCase()==="SELECT");return au(g)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(o(s,"visibility")!=="visible")return!1;let m=!!n(s,u=>Number(o(u,"opacity"))===0),d=!!n(s,u=>o(u,"display")==="none");return!(m||d||!i(s)||c(s))}var dg=T(()=>{"use strict"});var mg,fg,$t,tE,rE,di,gg=T(()=>{"use strict";mg=E(require("promise-queue")),fg=E(require("webdriverio"));le();Be();B();j();Or();dg();iu();ns();$t=A("WebDriverApi"),tE=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},rE={implicit:0,pageLoad:1,script:2},di=class{constructor(){this.unsupportedActions=new Set}get capabilities(){var e;return(e=this.client)==null?void 0:e.capabilities}get browserName(){var e;return this.capabilities&&"browserName"in this.capabilities&&((e=this.capabilities.browserName)==null?void 0:e.toLocaleLowerCase())||void 0}windowHandleMaximize(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.maximizeWindow()})}async rejectWithLog(e,t){let{testName:r,testResultId:n}=this,o=t?t.toString().substr(0,2e3):"";throw $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:o}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),Ra!==void 0&&(e=Ra);let t=1/0;this.queue=new mg.default(e,t)}async addToQueue(e){var r,n;let t=(r=this.seleniumPerfStats)==null?void 0:r.markStart();try{return await this.queue.add(e)}catch(o){return this.rejectWithLog(o,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,i;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),D("right before addToQueue");let n=(o=this.seleniumPerfStats)==null?void 0:o.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t}),D("before this.client.init"),this.client=await fg.remote(e),this.logGridStatus(r)}),D("after client init")}finally{(i=this.seleniumPerfStats)==null||i.markEnd(n,xe.GET_BROWSER)}}async logGridStatus(e){var i;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",o;try{o=await this.client.status();for(let a of o.nodes||[])for(let c of a.slots||[])if(((i=c==null?void 0:c.session)==null?void 0:i.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){$t.info("grid status is not supported by the grid",{testResultId:e});return}$t.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),$t.info("grid status",{gridStatusMsg:o.message,ready:o.ready,browserNode:r,gridSlot:n,testResultId:e})}get isMobile(){var e;return(e=this.client)==null?void 0:e.isMobile}getSessionId(){var e;return(e=this.client)==null?void 0:e.sessionId}isChrome(){return this.browserName==="chrome"}isChromium(){return this.isChrome()||this.isEdgeChromium()}isFirefox(){return this.browserName==="firefox"}isSafari(){return this.browserName==="safari"||this.browserName==="safari technology preview"}isAndroid(){var e;return this.capabilities&&"platformName"in this.capabilities&&((e=this.capabilities.platformName)==null?void 0:e.toLocaleLowerCase())==="android"}isEdgeChromium(){let e=this.capabilities&&"_isOldEdge"in this.capabilities&&this.capabilities._isOldEdge;return this.browserName==="microsoftedge"&&!e}async execute(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=a=>{throw Object.assign(a,{executedScript:e}),a},o=()=>this.client.execute(e,t).catch(n),i=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return o();t=t.map(a=>{if(a===null){$t.warn('The function "executeScript" in webdriverio can no longer accept "null" as an argument, it was replaced with "undefined"',{script:e,args:t});return}return a});try{return await i()}catch(a){if(Ne(a))return this.unsupportedActions.add("execute"),o();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new Error("number or type of arguments don't agree with execute protocol command");typeof e=="function"&&(e=`return (${e}).apply(null, arguments)`);let n=()=>this.client.executeAsync(e,...t),o=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await o()}catch(i){if(Ne(i))return this.unsupportedActions.add("executeAsync"),n();throw i}})}}async executeCDP(e,t={}){var n;if(!this.isChromium())return;let r=await((n=this.client)==null?void 0:n.sendCommandAndGetResult(e,t));return r!=null&&r.targetInfos?r.targetInfos:[]}async takeScreenshot(){var t,r;let e=(t=this.seleniumPerfStats)==null?void 0:t.markStart(xe.GET_SCREENSHOT);try{return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.takeScreenshot()})}}finally{(r=this.seleniumPerfStats)==null||r.markEnd(e,xe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(xe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(_e(e)))}finally{this.seleniumPerfStats.markEnd(t,xe.GET_SCREENSHOT)}}async getElementBySelector(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e)})}}elementIdDisplayed(e){return this.addToQueue(async()=>{let t=()=>this.client.isElementDisplayed(e).then(n=>({value:n})),r=()=>this.execute(au,{ELEMENT:e,[Gt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ne(n))return this.unsupportedActions.add("elementIdDisplayed"),r();throw n}})}windowHandles(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandles().then(t=>({value:t}))})}async url(e){if(e)return await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.url(pg(e,this.isSafari(),$t))})}reloadTab(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.refresh()})}source(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getPageSource()})}timeouts(e,t){return this.addToQueue(async()=>{let r=()=>{let o=[];return o[rE[e]]=t,this.client.setTimeouts(...o)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(o){if(Ne(o))return this.unsupportedActions.add("timeouts"),n();throw o}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,o){window.scrollTo(n,o)};return this.execute(r,e,t)}async setValue(e,t){return await this.elementIdClear(_e(e)),await this.elementIdValue(_e(e),t)}async getViewportSize(e){let t=await this.execute(tE);if(typeof e=="string"&&e.match(/(width|height)/)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async keys(e){let t=i=>Ta.hasOwnProperty(i)?[Ta[i]]:i.split(""),r=[];if(typeof e=="string")r=t(e);else if(Array.isArray(e))for(let i of e)r=r.concat(t(i));else throw new Error("number or type of arguments don't agree with keys protocol command");let n=()=>{var i;return(i=this.client)==null?void 0:i.requestHandler.create("/session/:sessionId/keys",{value:r})},o=()=>{let i=r.map(c=>({type:"keyDown",value:c})),a=r.map(c=>({type:"keyUp",value:c}));return this.actions([{type:"key",id:"keys",actions:[...i,...a]}])};if(this.unsupportedActions.has("keys"))return o();try{return await this.addToQueue(()=>n())}catch(i){if(Ne(i))return this.unsupportedActions.add("keys"),o();throw i}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.elementSendKeys(e,r)})}}elementIdClear(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClear(e)})}submitForm(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementSubmit(_e(e))})}submitFormManually(e){return this.addToQueue(async()=>{var o;let t=await((o=this.client)==null?void 0:o.$(e)),r=await t.$('button[type="submit"]');return await r.isExisting()?r.click():(await t.$("input:last-of-type")).keys("Enter")})}async findElementAndPress(e,t,r){return{value:await this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.prototype.hasOwnProperty.call(n,"xoffset")&&(n.xOffset=1),this.addToQueue(()=>{var o;return(o=this.client)==null?void 0:o.$(e).moveTo(n)})}async uploadFile(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.uploadFile(e)})}}getUrl(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getUrl()})}getTitle(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getTitle()})}async windowHandleSize(e){return{value:await this.addToQueue(async()=>{let r=async()=>await this.client.getWindowSize(),n=async()=>await this.client._getWindowSize();if(e!=null&&e.width&&(e!=null&&e.height)){let o=Math.abs(e.width),i=Math.abs(e.height);r=async()=>await this.client.setWindowSize(o,i),n=async()=>await this.client._setWindowSize(o,i)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(o){if(Ne(o))return this.unsupportedActions.add("windowHandleSize"),r();throw o}})}}setCookie(e,t,r,n,o,i,a){return this.addToQueue(()=>{var c;return(c=this.client)==null?void 0:c.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:o,path:i,expiry:a&&Math.floor(a)})})}getCookie(e){return this.addToQueue(async()=>{var r;return(await((r=this.client)==null?void 0:r.getCookies(e))??[])||(typeof e=="string"?null:[])})}deleteCookie(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.deleteCookie(e)})}isVisibleWithinViewport(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.$(e).isDisplayedInViewport()})}getCurrentTabId(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.getWindowHandle()})}frame(e=null){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToFrame(e)})}switchTab(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchToWindow(e)})}alertAccept(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.acceptAlert()})}log(e="browser"){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getLogs(e)})}async end(){try{this.client&&await this.executeAsync(async e=>{var t,r;await((r=(t=window.TSTA)==null?void 0:t.gracefulShutdown)==null?void 0:r.call(t)),e(!0)})}catch(e){$t.warn("error while trying to shutdown gracefully",{error:e})}if(this.unsupportedActions.clear(),!!this.queue)return await this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.deleteSession()})}async forceEnd(){if(this.unsupportedActions.clear(),!!this.client)return await this.client.deleteSession()}touchPerform(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchPerform(e)})}touchAction(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.touchAction(e)})}pressKeycode(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.pressKeyCode(e)})}setImmediateValue(e,t){return this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.setValueImmediate(e,t)})}elementIdText(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementText(e)})}async isAppInstalled(e){let t=await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.isAppInstalled(e)});return $t.info(`is app (${e}) installed?`,{isInstalled:t}),{value:t}}launch(){return this.addToQueue(()=>{var e;return(e=this.client)==null?void 0:e.launchApp()})}context(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.switchContext(e)})}elementIdLocation(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.getElementLocation(e)})}}});var hg={};V(hg,{doubleClick:()=>sE});var sE,yg=T(()=>{"use strict";sE=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,o={status:"done",success:!0};window.__unloadNavigator=function(){e(o)};let i=function(u){function g(S,b,w){return w>S&&w<b}let f=u.pointerPosition||{},h=r.getBoundingClientRect(),y=f.originX&&g(h.left,h.left+h.width,f.originX)?f.originX:h.left+h.width/2,v=f.originY&&g(h.top,h.top+h.height,f.originY)?f.originY:h.top+h.height/2;return{x:y,y:v}},a=function(u,g){return{screenX:0,screenY:0,clientX:u,clientY:g,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},c=function(u,g,f){if(!window.PointerEvent)return;let h=a(g,f);return new window.PointerEvent(u,h)},l=function(u,g,f){let h=document.createEvent("MouseEvents");return h.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,g,f,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),h},m=function(){var g;let u=document.activeElement;for(;(g=u.shadowRoot)!=null&&g.activeElement;)u=u.shadowRoot.activeElement;return u},d=function(u){let g=i(u),f=u.event;return t.includes(f)?c(f,g.x,g.y):l(f,g.x,g.y)};try{n.map(g=>d(g)).filter(Boolean).forEach(g=>r.dispatchEvent(g));let u=m();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(o)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var hn={};V(hn,{dispatchFocus:()=>nE});function nE(s,e){function t(o){let i=document.createEvent("HTMLEvents");return i.initEvent(o,!0,!1),i}function r(){var i;let o=document.activeElement;for(;(i=o.shadowRoot)!=null&&i.activeElement;)o=o.shadowRoot.activeElement;return o}function n(o,i){i&&(i.dispatchEvent(t("focusout")),i.dispatchEvent(t("blur"))),o.dispatchEvent(t("focusin")),o.dispatchEvent(t("focus")),typeof o.focus=="function"&&o.focus();let a=r();i&&a===i&&typeof i.blur=="function"&&i.blur()}if(s){let o=getLocatedElement(s);if(o&&o!==e)try{n(o,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var yn=T(()=>{"use strict"});var Eg={};V(Eg,{WebDriver:()=>Ir});async function cE(s){var e,t;try{let r=(t=(e=s==null?void 0:s.value)==null?void 0:e["goog:chromeOptions"])==null?void 0:t.debuggerAddress;return r?await iE(r):void 0}catch(r){Ue.info("Error getting cdpAddress",r);return}}var is,wg,vg,Ue,rr,oE,bg,iE,sr,aE,Tg,Sr,Ir,bn=T(()=>{"use strict";is=E(require("lodash"));B();Be();ou();wg=E(require("p-retry")),vg=E(require("ua-parser-js"));Or();j();iu();gg();z();he();ns();Ue=A("webdriver"),[rr,oE]=[0,2],{extractElementId:bg,getCdpAddressForHost:iE}=K,sr=()=>(Te(),fe(Xt)).getSessionPlayer().codeSnippets,aE=()=>(Te(),fe(Xt)).getSessionPlayer().locatorBuilderUtils,Tg=()=>(Te(),fe(Xt)).getSessionPlayer().utils,Sr=()=>(Te(),fe(Xt)).getSessionPlayer().positionUtils;Ir=class extends di{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer))}}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t,r,n,o,i,a,c,l=new jt,m=!1,d=void 0){var h,y,v,S,b,w,R,C;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((v=(y=(h=t==null?void 0:t.company)==null?void 0:h.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:v.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let u=pi(t,r,n,o,i,a,c,d);u.desiredCapabilities&&delete u.desiredCapabilities.marionette,u.capabilities&&delete u.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(d==null?void 0:d.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=l;let g=m?0:1500,f=m?()=>null:()=>this.executeJS("window.focus()");try{D("before initClient in webdriver.js init");let k=await this.initClient(u,r,c);D("after initResult before getCdpAddress in init"),this.cdpUrl=await cE(k),D("after getCdpAddress in webdriver.js init"),Ue.info(`init new session testName: ${r}`,{sessionId:this.getSessionId(),testResultId:c}),await ie(g),M.flags.dontFocusOnInit.isEnabled()||await f(),D("after focus and delay in webdriver.js init")}catch(k){let I=JSON.stringify(is.omit(u,"capabilities.extensions","capabilities.capabilities.extensions"));Ue.error("failed to init webdriver",{err:k,capabilitiesAsString:I});let U=((b=(S=t==null?void 0:t.company)==null?void 0:S.activePlan)==null?void 0:b.plan)==="free";throw(w=k.stack)!=null&&w.includes("at startWebDriverSession")&&((R=k.message)!=null&&R.startsWith("Failed to create session"))&&((C=k.message)!=null&&C.includes("Timeout awaiting 'request'"))&&U?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):k.message.match(/Invalid username or password/)?new Mr(k.message):k.message.match(/capabilit(y|ies)/)?new Kn(k.message):new Error("failed to init client driver")}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=o=>is.zip(o.slice(0,-1),o.slice(1)),r=this._keepAliveRequests.map(({start:o})=>o).filter(Boolean),n=t(r).map(([o,i])=>i-o);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[a]=Date.now())};function o(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let i=te();r(i);try{await this.executeJS(o),this._isAlive=!0,n("end",i),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",i),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Ue.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Ue.warn("failed to click on alert",{err:c}));return}if(Ue.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Ue.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.browserClosedCallbacks.forEach(l=>{try{l(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=bg(r.value);return await this.switchToFrame({ELEMENT:n,[Gt]:n}),r}switchToFrame(t){return this.frame(t)}async switchToTopFrame(){var t;try{return await this.frame()}catch(r){throw(t=r.message)!=null&&t.includes("ECONNREFUSED")?new Jn:r}}async getElement(t){var o;let r=this.seleniumPerfStats.markStart(xe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}if(((o=t==null?void 0:t.shadowPath)==null?void 0:o.length)||M.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
22
22
  var fn = ${sr().getLocatedElementCode};
23
23
  return fn.apply(null, arguments);
@@ -404,7 +404,7 @@ Please make sure the CLI has stable access to the internet. ${Ha()?"(Internal: n
404
404
  `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw $i.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",g=n?n.message:"";if(g===m||g.startsWith(d)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(u)||g.includes(c)||g.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw $i.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(_e(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.useJsInputCodeInSafari.isEnabled(),o=M.flags.useJsInputCodeInFirefox.isEnabled(),i=M.flags.useJsInputCodeInEdgeChromium.isEnabled(),a=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:c,context:l,step:m,stepActionUtils:d,driver:u}=this,g=await c.utils.addTokenToFileUrl(l.project.id,m.fileUrls,d.testimServicesApi,r,$i),f=u.isSafari()&&(n||g.length>1),h=u.isFirefox()&&(o||g.length>1),y=u.isEdgeChromium()&&(i||g.length>1);if(a&&(g=await Promise.all(g.map(async({name:S,url:b})=>{let w=await Lt(b);return{name:S,url:`data:${w.type};base64,${Buffer.from(w.body).toString("base64")}`}}))),f||h||y){await this.driver.executeJS(`
405
405
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
406
406
  const downloadAndUploadFile = ${lS()};
407
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,g);return}let v=await ey(g,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var Vi,Gi,sy=T(()=>{"use strict";Vi=require("url");ue();Gi=class extends W{async updateBaseUrl(e){let t=new Vi.URL(e),r=new Vi.URL(this.context.recordedBaseUrl),n=new Vi.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 Hi,ny=T(()=>{"use strict";ue();B();Hi=class extends W{async performAction(){await ie(this.step.durationMS||0)}}});var qi,oy=T(()=>{"use strict";ue();qi=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var xn,iy=T(()=>{"use strict";ue();xn=class extends W{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var zi,ay=T(()=>{"use strict";ue();zi=class extends W{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var cy,Nu,Uu,ly=T(()=>{"use strict";cy=E(require("@applitools/spec-driver-webdriverio"));Vn();Te();Nu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Sp["@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:cy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Uu=new Nu});var py,uy,Pn,dy=T(()=>{"use strict";py=E(require("lodash"));ue();j();ly();uy=A("pixel-validation-step-action"),Pn=class extends W{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,c=await Uu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let g=await c.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};py.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),uy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){uy.error("Applitools SDK step failed",{err:g,info:g.info}),m={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Uu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var ys,Fu=T(()=>{"use strict";Rr();z();Di();ys=class extends ir{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await cs(o,i,a,d,c,l,m,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,my=T(()=>{"use strict";Fu();ar=class extends ys{isFailedResult(e){return e===!1}}});var Ki,fy=T(()=>{"use strict";Fu();Ki=class extends ys{isFailedResult(e){return!e}}});var Ji,gy=T(()=>{"use strict";Rr();ue();z();Ji=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await as(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof vt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Cr,hy=T(()=>{"use strict";ue();Cr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,yy=T(()=>{"use strict";ue();ve=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Yi,by=T(()=>{"use strict";ue();Yi=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Xi,Ty=T(()=>{"use strict";ue();Xi=class extends W{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function uS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Qi(s,e){uS(pS,e),e.registerLocateStepActionUtils(In.getUtils(s))}var pS,Bu=T(()=>{"use strict";hh();Th();Ph();Ch();Oh();Dh();Uh();Fh();Bh();Wh();Vh();Gh();zh();Yh();ry();sy();ny();oy();iy();ay();dy();my();fy();gy();hy();yy();by();Ty();pS={locate:In,scroll:Ci,mouse:ki,submit:Ui,text:_i,"special-key":Mi,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":hs,"skip-code-step":hs,"element-code-step":hs,"evaluate-expression":Oi,"text-validation":An,"wait-for-text-validation":An,"select-option":Ni,"drop-file":ji,"input-file":Wi,hover:Fi,navigation:Gi,wheel:Bi,sleep:Hi,refresh:qi,"api-validation":xn,"api-action":xn,"api-code-step":Wt,"extract-text":zi,"simple-ui-verification":Pn,"wait-for-simple-ui-verification":Pn,"cli-validation-download-file":Cr,"cli-wait-for-download-file":Cr,"network-validation-step":Cr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Ki,"node-package":Ji,"email-code-step":Wt,"cli-email-code-step":ar,"sfdc-internal-test-step":Xi,"sfdc-recorded-step":Yi,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Cr}});var wy,dS,bs,ju=T(()=>{"use strict";wy=["simple-ui-verification","wait-for-simple-ui-verification"],dS=[...wy,"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"],bs=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=dS.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 wy.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 Ey={};V(Ey,{SeleniumTestPlayer:()=>Cn});var vy,Cn,$u=T(()=>{"use strict";B();vy=require("@applitools/eyes-sdk-core");bn();z();Pu();ph();_u();Lu();fh();Du();Te();Bu();ju();Cn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new bs(Pi());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Ir;let m=new gs(this.driver);this.stepActionFactory=new l(m),Qi(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ai(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=mh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ms(this.driver),FrameLocator:d,portSelector:xi,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:vy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Sy={};V(Sy,{WorkerSelenium:()=>Wu});function fS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>D(`Got event ${t}`))}var Zi,mS,Wu,Iy=T(()=>{"use strict";B();Be();Sn();j();Pt();No();oe();Au();z();$u();Te();Zi=A("worker-selenium"),mS=1e9,Wu=class extends st{initPlayer(t){return new Cn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){D("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ds(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),D("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),D("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,mS),await this.windowUtils.validatePageIsAvailable(),D("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Tt||m||d?new Tt(`Page '${c}' is not available`):(Zi.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),fS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await on(this.options))[this.testId]);let m=async()=>ce(new Promise((u,g)=>{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(g)}),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Zi.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(Zi.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),D("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),D("right after super.runTestOnce in workerSelenium");let u=await m();return D("right after runSeleniumTest"),u}catch(u){throw Zi.error("failed to run test once",{err:u}),u}}}});var Ry,Ge,Vu,ht,ea=T(()=>{"use strict";j();oe();le();be();He();Ry=E(require("ora")),Ge=A("mobile-grid-service"),Vu=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.PCLOUDY]:({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)?`${t}/lock`:""}getBaseApiUrl(e){return e===_.TESTIM_HEADSPIN?`${$p}/devices`:e===_.TESTIM_TDC?`${Vp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:o})}catch(i){throw Ge.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Re(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Ge.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Ds(`${Aa}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.PCLOUDY)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:o,gridId:i}){var a,c;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let l=await Zc({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}return t===_.BROWSERSTACK?(c=e.mobile)==null?void 0:c.version.split("-")[0]:t===_.SAUCELABS?e.testobject_device_name:e.device}async updateDeviceOnRemoteTestResult(e,t,r){var y;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:m="",type:d=""}={}}=r,u=t.capabilities,g=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:d,projectId:a,projectType:c,companyId:l,gridId:m}),f=u.platformVersion;!f&&d===_.BROWSERSTACK&&(f=(y=u.mobile)==null?void 0:y.version.split("-")[1]),!f&&d===_.TESTIM_TVC&&(f=u.os_version);let h={name:g??"",model:u.deviceModel,osVersion:f,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:d===_.TESTIM_TVC};return await br(a,n,o,i,"RUNNING",{device:h}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h}),h}async getTmaDeviceDetails(e){let t=await Re(`${Jp}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await _c({appId:e,projectId:t});if(!i)throw Ge.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Ge.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(jp*60))+1)*60*1e3,Math.max(Bp,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[_.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[_.TESTIM_TVC]:{name:"Tricentis Virtual Cloud",appPath:"testimTvcAppId"},[_.PCLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,Ry.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await el({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});l.succeed(`app uploaded successfully to ${a}`);let d=i[o].appPath;return m[d]}catch(m){throw l.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={},projectData:u}=t,{gridId:g="",type:f="",host:h=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){Ge.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:i});let b=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m,executionId:i,testResultId:a});n=b.appUrl,o=b.mobileApp,e.nativeApp=o}else Ge.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let y=c||e.mobileApp.appId,v=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:h}),S=f===_.BROWSERSTACK||f===_.TESTIM_TVC;if(v){let b=await this.verifyAppStillExistsOnGrid({gridAppId:v,gridData:d,projectType:u==null?void 0:u.type});b&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:v,projectId:l,testResultId:a,executionId:i,mobileAppId:y}),n=v),!b&&S&&(Ge.info("app not exists on grid, uploading it",{gridAppId:v,projectId:l,testResultId:a,executionId:i,mobileAppId:y}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:g,gridType:f,mobileAppId:y})),!b&&!S&&Ge.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:i})}return!v&&S&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:g,gridType:f,mobileAppId:y})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){let{accessToken:n,user:o,host:i,key:a,type:c}=t;if(c===_.BROWSERSTACK){let l=`${qp}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:l,user:o,key:a})).some(d=>d.app_url===e)}if(c===_.SAUCELABS){let m=`${i.includes("eu-central-1")?Kp:zp}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).items.some(u=>u.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let l=c===_.TESTIM_HEADSPIN?`${Wp}/apps`:`${Gp}/apps`;return(await this.fetchWithTokenAuth({url:l,accessToken:n,authType:"Bearer"})).apps.some(d=>d.app_id===e)}if(c===_.TESTIM_TVC){let l=`${Hp}/versions/${e}/info`;try{return await this.fetchWithTokenAuth({url:l,accessToken:n,authType:"Upload-Token"}),!0}catch(m){return m.status!==404&&Ge.error("error while verifying app exists on TVC",{error:m}),!1}}if(c===_.PCLOUDY){let l=await this.getPCloudyAuthToken(o,a),m=`${Aa}/drive`,d=await $a({url:m,body:{token:l,filter:r==="android"?"apk":"ipa"},headers:{contentType:null}});return JSON.parse(d).files.some(g=>g.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 Re(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Re(e,void 0,n)}},ht=new Vu});function Gu({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"&&!gS.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function hS({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 yS(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function bS(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=i?"tdc":"headspin",l=a&&M.flags.enableBatchHeadSpin.isEnabled(),m=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${c}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...o&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:yS(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n}}}function ta(s){return"id"in s?s.id:s.packageName}function TS(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function wS({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a,resetOnSessionStartOnly:c}=t,l={"appium:app":n},m=n==null?void 0:n.startsWith("http");switch(n&&!m&&(l=TS(n,t.gridData.type)),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":!!i,...!!i&&{"appium:resetOnSessionStartOnly":c},...r&&{"appium:bundleId":ta(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...r&&{"appium:appPackage":ta(r),"appium:appActivity":r.activity},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Hu({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}){switch(s){case"ios":return{...e,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...t&&{bundleId:ta(t)},...r&&{app:r}};case"android":return{...e,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:n,...t&&{appPackage:ta(t),appActivity:t.activity},...r&&{app:r}};default:throw Error(`unsupported mobile project ${s}`)}}function xy({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=bS(i.type,o,n);return wS({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function qu({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 zu({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o,selectedGrid:i}=e;return s||(n!=null&&n.deviceName?n.deviceName:o!=null&&o.deviceNameRegex?o.deviceNameRegex:((i==null?void 0:i.type)===_.BROWSERSTACK||r===_.BROWSERSTACK)&&t==="ios"?"iPhone.*":".*")}function vS({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,u=qu({osVersion:c,mobileConfig:m}),f={device:zu({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),os_version:u,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:options":{token:o.accessToken}};return Hu({projectType:s,sessionCaps:f,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ES({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,gridType:g}=o,f=qu({osVersion:c,mobileConfig:m}),h=zu({deviceName:l,mobileConfig:m,projectType:s,gridType:g});return Hu({projectType:s,sessionCaps:{platformVersion:f,pCloudy_DurationInMinutes:2,pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_DeviceManufacturer:h},nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function SS({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,u=d===_.BROWSERSTACK?"browserstack":"saucelabs",g=qu({osVersion:c,mobileConfig:m}),f=zu({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h={...d===_.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===_.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0,[`${u}.appium_version`]:"1.20.2"};return Hu({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Py(s){return _.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type?xy(s):_.TESTIM_TVC===s.gridInfo.type?vS(s):_.PCLOUDY===s.gridInfo.type?ES(s):SS(s)}function IS(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,c={};return n==="dynamic"&&(!o&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!i&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function Cy(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Gu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=ht.getGridConnection(e),c=Py(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let m=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",d=IS(r,o==null?void 0:o.mobile);if(!(0,Ay.isEmpty)(d)){let u=Object.entries(d).map(([g,f])=>f.split(",").map(h=>h===".*"||h==="="?"":`${g}:${h}`).join(",")).join(" ").trim();c[`${m}:selector`]=u}}let l=e.type===_.TESTIM_TVC?{commonCapabilities:c}:c;return{...a,desiredCapabilities:c,capabilities:l,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ky(s){var f,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;Gu({nativeAppMetadata:r,appPath:o,gridInfo:t}),hS({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((h=(f=c.mobile)==null?void 0:f.staticAllocation)==null?void 0:h.deviceUdid),d=await ht.getGridDirectConnection(t,m),g=xy({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(g["appium:udid"]=m),{...d,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Oy(s){return Gu(s),Py(s)}function _y(s){let e=Object.assign({},s);return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],delete e.capabilities.key,delete e.capabilities.user,e}var Ay,gS,Ku=T(()=>{"use strict";he();oe();ea();Ay=require("lodash"),gS=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.PCLOUDY]});var ra,Dy=T(()=>{"use strict";ra=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ju,sa,My=T(()=>{"use strict";j();Ju=A("mobile-frame-locator-mock"),sa=class{foundFrameCallback(){return Ju.info("foundFrameCallback-mock invoked"),{}}locate(){return Ju.info("locate-mock invoked"),{}}async findFrame(){return Ju.info("findFrame-mock invoked"),{}}}});var RS,Uy,Ny,Ts,Yu=T(()=>{"use strict";RS=E(require("webdriverio")),Uy=require("@applitools/eyes-sdk-core");Dy();_u();j();Lu();Du();Te();Bu();My();ju();Ny=A("appium-test-player"),Ts=class{constructor(e,t,r,n=RS,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=ee(),d=new gs(this.driver);this.stepActionFactory=new l(d),Qi(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new bs(Pi()),this.sessionPlayer=new a(e,{tabService:new ra,cookieUtils:void 0,FrameLocator:sa,portSelector:xi,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Uy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{await(n==null?void 0:n.endSession()),Ny.info("appium session deleted",o)}catch(i){Ny.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=ee();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function AS(s){return await Re(`${s}/api/status`)}async function Fy(s,e){return await Re(`${s}/api/devices/${e}/status`)}async function By(s){if((await AS(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var jy=T(()=>{"use strict";He()});var $y={};V($y,{WorkerLocalTma:()=>ep});var kn,na,Xu,Qu,Zu,ep,Wy=T(()=>{"use strict";He();kn=E(require("semver"));Ku();Sn();B();j();Pt();Yu();Te();jy();ea();na=A("worker-appium"),Xu=class extends Error{},Qu=class extends Error{},Zu=class extends Error{},ep=class extends st{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}checkIfUpgradeIsNeeded(t,r,n){if(n)return!1;let[o,i]=[kn.coerce(t),kn.coerce(r)];return!o||!i?!1:kn.cmp(o,"!==",i)}async getBrowserOnce(t,r,n,o){var C;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await By(i);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,g=!1,f=this.options.appId;if(f){let{executionId:k,testResultId:I}=t,{mobileApp:U}=await ht.getMobileAppDataByAppId({appId:f,projectId:l,token:m,executionId:k,testResultId:I});t.nativeApp=U}let h=u==="android"?t.androidActivityWait:null,y=t.nativeAppMetadata,v=t.downloadableAppPublicLink,S=t.appPackageNameOrBundleId;if(!y)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!S)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:w},R]=await Promise.all([this.getAppStateFromDevice(i,a,S),Fy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&v&&await this.installApp(i,a,v),b&&(!t.isAppFromDevice||f)&&(g=this.checkIfUpgradeIsNeeded(w,y.version,R.isVirtual));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(C=this.options.projectData)==null?void 0:C.name}-${this.options.project}`},I=Oy({projectType:u,nativeAppMetadata:y,appPath:v,androidActivityWait:h,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),U={capabilities:{udid:a,...I}},O=await this.requestNewAppiumSessionFromTma(i,U,y);if(this.sessionData=O,g){let $=await this.initAndGetAppiumAPI(n);await $.removeApp(S),await this.installApp(i,a,v),await $.activateApp({[u==="ios"?"appId":"bundleId"]:S})}let N=await d.attach({sessionId:O.sessionId,capabilities:I});this.device=await ht.updateTmaDeviceDetails(a,this.options,t),na.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:N.sessionId,testResultId:this.testResultId,nativeAppMetadata:y,sessionCaps:N.capabilities})}catch(k){throw na.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Zu(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Re(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Lt(n);await Ls(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Qu(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Xu(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw na.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw na.error("failed to run test once",{err:l}),l}}}});var Gy={};V(Gy,{WorkerAppium:()=>tp});var Vy,On,tp,Hy=T(()=>{"use strict";Ku();Vy=require("linkedom");Sn();j();Pt();Yu();Te();ea();oe();On=A("worker-appium"),tp=class extends st{initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,c=await ht.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=a==="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 d={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag}},u={projectType:a,nativeAppMetadata:m,appPath:c,androidActivityWait:l,sessionTags:d,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await ht.lockDevice(o,this.options.deviceUdid),g=await ky(u)):g=Cy(u),On.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:d,nativeAppMetadata:m,capabilities:_y(g)}),this.activeSession=await i.remote(g),this.device=await ht.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),On.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(d){throw On.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:d}),d}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===_.TESTIM_HEADSPIN||o===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===_.TESTIM_TVC?`https://${t}/wd/hub`:o===_.PCLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:S}=await ht.getHeadSpinDeviceConnection(this.options.gridData,f);l=`${h}://${y}:${v}${S}`}else l=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(l,this.activeSession.sessionId,Vy.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let d=async()=>{try{let f=await new Promise((y,v)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(v)});return await i.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw On.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),f}};try{return await super.runTestOnce(t,r),await d()}catch(f){throw On.error("failed to run test once",{err:f}),f}}}});var oa,qy=T(()=>{"use strict";B();bn();z();oa=class{constructor(e){this.id=e;this.driver=new Ir}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var zy,ia,Ky=T(()=>{"use strict";zy=E(require("ws"));B();ia=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new zy.default(this._cdpUrl,{timeout:e}),r=qt(o=>{t.once("open",o)}),n=qt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var ca,rp,aa,Jy=T(()=>{"use strict";B();ca=E(require("chrome-launcher"));ou();Ky();tn();rp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ia}async init(e,t,r,n,o,i,a,c,l,m){var f,h,y,v;let d=pi(e,t,r,n,o,i,a),u=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...ca.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await ca.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Xr(()=>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}},aa=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new rp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Xy={};V(Xy,{WorkerExtension:()=>_n});function xS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Yy(s){return xS(s)?s:new Error(s)}var nt,_n,sp=T(()=>{"use strict";Be();z();Sn();B();j();Pt();oe();qy();Jy();nt=A("worker-ext"),_n=class extends st{initPlayer(){return this.options.useChromeLauncher?new aa(this.id):new oa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw nt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;D("WorkerExtension runTestOnce");let i=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(m.cdpTestRunner),d,Ve.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof re))throw u;return nt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let g=await m.url(d);return u.driverUrlFinished=!0,g}catch(g){throw nt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(D("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw nt.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,f,u),c(u)]),this.options.testStartTimeout,Ve.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;nt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),nt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),v.type=Ns.BROWSER_CLOSED,h.abort(v)};d.registerToClosedBrowser(y);try{let v=ce(e.onCompleted(),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG),S=await Na(v,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(R){nt.error("Could not update the grid about the test status",{err:R})}d.isAlive()||(nt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(nt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw nt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),Yy(v)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw nt.warn("failed to start url",{err:f}),Yy(f)}};t.driver.start();try{return await super.runTestOnce(e,t),D("WorkerExtension super.runTestOnce"),await l()}catch(m){throw nt.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Qy={};V(Qy,{WorkerExtensionSingleBrowser:()=>np});var PS,CS,np,Zy=T(()=>{"use strict";Be();B();j();vu();Pt();sp();PS=A("base-worker"),CS=500,np=class extends _n{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await vn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(PS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;D("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ie(CS)}}});function kS(s,e){e===0?s():setTimeout(s,e*Lp)}var op,la,eb=T(()=>{"use strict";bn();le();Be();Kl();Rt();uu();z();j();oe();Xg();op=A("parallel-worker-manager"),la=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Iy(),fe(Sy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Wy(),fe($y)).WorkerLocalTma:(Hy(),fe(Gy)).WorkerAppium;default:return mi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Zy(),fe(Qy)).WorkerExtensionSingleBrowser:(sp(),fe(Xy)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return D("before new Worker",n.mode),new o(t,...r)}finally{D("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let m=!1,d=0,u=g=>new Promise(f=>{var yt,kr,x,L,F,q,ot,ga;let h=o.project,y=new wi(r,n,e,o,i,t),v={},S=e.length,b=((yt=o.company)==null?void 0:yt.ucid)||"",w=(kr=o.company)==null?void 0:kr.companyId,R=(x=o.company)==null?void 0:x.name,C=o.source||"cli",k=o.user,I=(L=o.company)==null?void 0:L.planType,U=(F=o.company)==null?void 0:F.isStartUp,O=(q=o.projectData)==null?void 0:q.name,N=(ot=o.projectData)==null?void 0:ot.type,$=o.lightweightMode,H=(ga=o.gridData)==null?void 0:ga.type,J=(kt,it,ye,ha,Dn,ya)=>(d++,Lf({executionId:r,projectId:h,testId:it,resultId:ye,ucid:b,companyId:w,companyName:R,projectName:O,companyPlan:I,source:C,user:k,lightweightMode:$,isStartUp:U,projectType:N,appSource:ya,gridType:H}),t.testStartAndReport(kt,r,ye,ha,Dn)),Q=async(kt,it,ye,ha,Dn,ya)=>{var hp,yp,bp;d--;let Qe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...ye.seleniumStats&&{seleniumStats:ye.seleniumStats},...ye.gridIssues&&{gridIssues:ye.gridIssues},...ye.keepAliveIssue&&{keepAliveIssue:ye.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ye.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ye.seleniumPerfMarks),delete ye.seleniumPerfMarks),o.grid||o.gridId?(Qe.gridName=o.grid||((hp=o.gridData)==null?void 0:hp.name),Qe.gridType=(yp=o.gridData)==null?void 0:yp.type,Qe.gridProvider=(bp=o.gridData)==null?void 0:bp.provider):o.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):o.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):o.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):o.browserstack?Qe.gridName="browserstack-from-options":o.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(kt,ye,r,ha,Dn,Qe).catch(zb=>op.error("testEndAndReport threw an error",{err:zb})),Dn)return;v[ye.resultId]=ye,Df({executionId:r,projectId:h,testId:it,resultId:ye.resultId,result:ye,ucid:b,companyId:w,companyName:R,projectName:O,companyPlan:I,source:C,user:k,lightweightMode:$,logger:op,isStartUp:U,projectType:N,appSource:ya}),l&&!ye.success&&(y.stop(),m=!0),(Object.keys(v).length===S||m&&d===0)&&f(v)},de=(kt,it)=>{v[it.resultId]=it,t.onTestIgnored(kt,it.resultId),d--,(Object.keys(v).length===S||m&&d===0)&&f(v)},Vt=(kt,it)=>t.onGridSlot(kt,it);o.userData={loginData:Object.assign({},Nt(),{refreshToken:vo(),authData:Nt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},D("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,J,Q,Vt,de).forEach((kt,it)=>{D("before schedule worker.run after createWorkers"),kS(()=>{D("right before worker.run"),kt.run()},it)})});try{let g=await Jt(),f=await u(g);if(m)throw new Ht;return f}catch(g){throw op.error("failed running parallel workers",{executionId:r,err:g}),g}}}});async function rb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Oc({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 ip(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 ap(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=tb.difference(Us(s,e),t);if(r.length>0)throw pt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var tb,sb=T(()=>{"use strict";tb=E(require("lodash"));B();Qr();be();z()});var Ln,$_,cp,lp,ua,nb=T(()=>{"use strict";Ln=E(require("lodash"));B();j();le();oe();Be();rs();Ol();Kl();be();Rt();Pt();tg();z();eb();sb();({testRunStatus:$_,CLI_MODE:cp}=Dt),lp=A("test-plan-runner"),ua=class{constructor(e){this.startTime=Date.now();this.workerManager=new la(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},m=Nt(),d=async()=>{let h=o.beforeParallel||1,y=!0,v=await this.workerManager.runTests(e,c,i,a,o,n,m,h,y);Object.assign(l,v)},u=async()=>{let h=zn||o.parallel,y=!1;D("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,m,h,y);D("right after this.workerManager.runTests"),Object.assign(l,v)},g=async()=>{let h=o.afterParallel||1,y=!1,v=await this.workerManager.runTests(r,c,i,a,o,n,m,h,y);Object.assign(l,v)};Mf({executionId:i,projectId:o.project}),D("right before runBeforeTests");try{return await d(),D("right before runTestPlanTests"),await u(),D("right after runTestPlanTests"),await g(),l}catch(h){if(lp.error("error running test plan",{err:h}),h instanceof Ht)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await f()}async function f(){var y,v,S,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===cp.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),Xt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=w();await C.closeBatch(i,R);return}let h;try{if(!((b=(S=(v=o.company)==null?void 0:v.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(h=await Kc(o.project),Ln.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,w,R;let l=te(),m=n.project;Oa(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new ui(d,n,i,a),g=Ln.default.chain(d).map(C=>{var k;return((k=C.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(C=>C.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,o,h);D("before testListInfoPromise");let v=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||X.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,f),D("before runTestAllPhases");let S=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",u);return D("before executionEnd"),await u.executionEnd(l),D("after executionEnd"),{results:S,executionId:l,testPlanName:o,configName:f}}async runTestPlans(e,t){lp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(m){return Ln.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await kc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==cp.APPIUM&&await ap(e,r(l)),await ae(c,async m=>{var f;let d=m.testPlanId;n[d]={};let u=Object.assign({},e);u.baseUrl||=m.startUrl,u.appId||=((f=m.mobileApp)==null?void 0:f.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await hf(e,m);let g=u.overrideExecutionName||m.name;return await ae(l[d],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,g,d,t);X.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let v=Object.keys(n[d]).map(R=>({executionId:R,status:ip(n[d][R])})),S=Object.keys(n[d]).map(R=>n[d][R]).reduce((R,C)=>Object.assign(R,C),{}),b=ip(S);Object.assign(o,S);let w=b?v[0].executionId:v.find(R=>!R.status).executionId;return await xc(i,d,{success:b,executions:v,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;lp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),D("before getSuite");let r=await rb(e,t);if(D("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return D("Right before validateConfig + runAnonymousTestPlan tests map"),await ae(r.tests,async c=>{if(e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==cp.APPIUM&&await ap(e,c),D("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return D("right after runTestPlan"),await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=un(),r=[];Fs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Ln.default.flattenDeep(r);return D("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),D("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var cb={};V(cb,{init:()=>JS,run:()=>zS});async function _S(s){let e=s.project,t=await Lc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),rn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function LS(s,e){var i,a,c,l,m,d;let t=so(e.activePlan),r=s.parallel;if(t==="free"&&r>ib)throw new P(`The free plan allows only ${ib} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let u=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!u)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
407
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,g);return}let v=await ey(g,this.uploadFile);await this.uploadFilesAndForceVisibility(v,t)}}});var Vi,Gi,sy=T(()=>{"use strict";Vi=require("url");ue();Gi=class extends W{async updateBaseUrl(e){let t=new Vi.URL(e),r=new Vi.URL(this.context.recordedBaseUrl),n=new Vi.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 Hi,ny=T(()=>{"use strict";ue();B();Hi=class extends W{async performAction(){await ie(this.step.durationMS||0)}}});var qi,oy=T(()=>{"use strict";ue();qi=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var xn,iy=T(()=>{"use strict";ue();xn=class extends W{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var zi,ay=T(()=>{"use strict";ue();zi=class extends W{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var cy,Nu,Uu,ly=T(()=>{"use strict";cy=E(require("@applitools/spec-driver-webdriverio"));Vn();Te();Nu=class{constructor(){let{EyeSdkBuilder:e}=ee(),t=Sp["@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:cy.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=ee(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Uu=new Nu});var py,uy,Pn,dy=T(()=>{"use strict";py=E(require("lodash"));ue();j();ly();uy=A("pixel-validation-step-action"),Pn=class extends W{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,c=await Uu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let g=await c.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};py.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),uy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:h}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){uy.error("Applitools SDK step failed",{err:g,info:g.info}),m={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Uu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var ys,Fu=T(()=>{"use strict";Rr();z();Di();ys=class extends ir{async executeCliCode(){var f,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(f=t.company)==null?void 0:f.activePlan)==null?void 0:h.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await cs(o,i,a,d,c,l,m,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof re?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ar,my=T(()=>{"use strict";Fu();ar=class extends ys{isFailedResult(e){return e===!1}}});var Ki,fy=T(()=>{"use strict";Fu();Ki=class extends ys{isFailedResult(e){return!e}}});var Ji,gy=T(()=>{"use strict";Rr();ue();z();Ji=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await as(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof vt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof re?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Cr,hy=T(()=>{"use strict";ue();Cr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,yy=T(()=>{"use strict";ue();ve=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Yi,by=T(()=>{"use strict";ue();Yi=class extends W{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Xi,Ty=T(()=>{"use strict";ue();Xi=class extends W{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function uS(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Qi(s,e){uS(pS,e),e.registerLocateStepActionUtils(In.getUtils(s))}var pS,Bu=T(()=>{"use strict";hh();Th();Ph();Ch();Oh();Dh();Uh();Fh();Bh();Wh();Vh();Gh();zh();Yh();ry();sy();ny();oy();iy();ay();dy();my();fy();gy();hy();yy();by();Ty();pS={locate:In,scroll:Ci,mouse:ki,submit:Ui,text:_i,"special-key":Mi,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":hs,"skip-code-step":hs,"element-code-step":hs,"evaluate-expression":Oi,"text-validation":An,"wait-for-text-validation":An,"select-option":Ni,"drop-file":ji,"input-file":Wi,hover:Fi,navigation:Gi,wheel:Bi,sleep:Hi,refresh:qi,"api-validation":xn,"api-action":xn,"api-code-step":Wt,"extract-text":zi,"simple-ui-verification":Pn,"wait-for-simple-ui-verification":Pn,"cli-validation-download-file":Cr,"cli-wait-for-download-file":Cr,"network-validation-step":Cr,"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":Ki,"node-package":Ji,"email-code-step":Wt,"cli-email-code-step":ar,"sfdc-internal-test-step":Xi,"sfdc-recorded-step":Yi,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Cr}});var wy,dS,bs,ju=T(()=>{"use strict";wy=["simple-ui-verification","wait-for-simple-ui-verification"],dS=[...wy,"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"],bs=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=dS.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 wy.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 Ey={};V(Ey,{SeleniumTestPlayer:()=>Cn});var vy,Cn,$u=T(()=>{"use strict";B();vy=require("@applitools/eyes-sdk-core");bn();z();Pu();ph();_u();Lu();fh();Du();Te();Bu();ju();Cn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new bs(Pi());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=ee();this.driver=n??new Ir;let m=new gs(this.driver);this.stepActionFactory=new l(m),Qi(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ai(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=mh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ms(this.driver),FrameLocator:d,portSelector:xi,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:vy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=ee(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof re&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(c=>a.url.includes(c))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Sy={};V(Sy,{WorkerSelenium:()=>Wu});function fS(s){let{playback:e}=ee().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>D(`Got event ${t}`))}var Zi,mS,Wu,Iy=T(()=>{"use strict";B();Be();Sn();j();Pt();No();oe();Au();z();$u();Te();Zi=A("worker-selenium"),mS=1e9,Wu=class extends st{initPlayer(t){return new Cn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){D("in WorkerSelenium getBrowserOnce"),X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ds(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await i.init(this.options,this.testName,this.testRunConfig,o,r,this.executionId,this.testResultId,t.seleniumPerfStats,l,this.lambdatestService),D("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),D("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,mS),await this.windowUtils.validatePageIsAvailable(),D("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof Tt||m||d?new Tt(`Page '${c}' is not available`):(Zi.error("failed to navigate to page",{baseUrl:c,err:l}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:o}=ee(),{driver:i,sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),fS(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await on(this.options))[this.testId]);let m=async()=>ce(new Promise((u,g)=>{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(g)}),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof re&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Zi.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(Zi.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});i.start(),D("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),D("right after super.runTestOnce in workerSelenium");let u=await m();return D("right after runSeleniumTest"),u}catch(u){throw Zi.error("failed to run test once",{err:u}),u}}}});var Ry,Ge,Vu,ht,ea=T(()=>{"use strict";j();oe();le();be();He();Ry=E(require("ora")),Ge=A("mobile-grid-service"),Vu=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)?`${t}/lock`:""}getBaseApiUrl(e){return e===_.TESTIM_HEADSPIN?`${$p}/devices`:e===_.TESTIM_TDC?`${Vp}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:o})}catch(i){throw Ge.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e.type)}/device_id:${t}/automation-config`;try{let o=await Re(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw Ge.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Ds(`${Aa}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};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:o,gridId:i}){var a,c;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let l=await Zc({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=l==null?void 0:l[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return(c=e.mobile)==null?void 0:c.version.split("-")[0];if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let l=e.pCloudy_DeviceFullName.split("_");return`${l[0]} ${l[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var y;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:c}={},company:{companyId:l=""}={},gridData:{gridId:m="",type:d=""}={}}=r,u=t.capabilities,g=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:d,projectId:a,projectType:c,companyId:l,gridId:m}),f=u.platformVersion;!f&&d===_.BROWSERSTACK&&(f=(y=u.mobile)==null?void 0:y.version.split("-")[1]),!f&&d===_.TESTIM_TVC&&(f=u.os_version);let h={name:g??"",model:u.deviceModel,osVersion:f,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:d===_.TESTIM_TVC};return await br(a,n,o,i,"RUNNING",{device:h}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h}),h}async getTmaDeviceDetails(e){let t=await Re(`${Jp}/devices`),r=t==null?void 0:t.find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:c}=t;return await br(c,n,o,i,"RUNNING",{device:a}),Ge.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await _c({appId:e,projectId:t});if(!i)throw Ge.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw Ge.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(jp*60))+1)*60*1e3,Math.max(Bp,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[_.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[_.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,Ry.default)(`uploading app to ${a} please wait..`).start();try{Ge.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await el({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});l.succeed(`app uploaded successfully to ${a}`);let d=i[o].appPath;return m[d]}catch(m){throw l.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={}}=t,{gridId:u="",type:g="",host:f=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){Ge.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:i});let S=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m,executionId:i,testResultId:a});n=S.appUrl,o=S.mobileApp,e.nativeApp=o}else Ge.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,y=this.gridsAppIdGetter[g]({testRunHandler:e,mobileApp:o,gridHost:f}),v=g===_.BROWSERSTACK||g===_.TESTIM_TVC||g===_.P_CLOUDY;if(y){let S=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:d});S&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=y),!S&&v&&(Ge.info("app not exists on grid, uploading it",{gridAppId:y,projectId:l,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:g,mobileAppId:h})),!S&&!v&&Ge.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:i})}return!y&&v&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:g,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t}){var c,l;let{accessToken:r,user:n,host:o,key:i,type:a}=t;if(a===_.BROWSERSTACK){let m=`${qp}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:n,key:i})).some(u=>u.app_url===e)}if(a===_.SAUCELABS){let d=`${o.includes("eu-central-1")?Kp:zp}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:d,user:n,key:i})).items.some(g=>g.id===e)}if(a===_.TESTIM_HEADSPIN||a===_.TESTIM_TDC){let m=a===_.TESTIM_HEADSPIN?`${Wp}/apps`:`${Gp}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:r,authType:"Bearer"})).apps.some(u=>u.app_id===e)}if(a===_.TESTIM_TVC){let m=`${Hp}/versions/${e}/info`;try{return await this.fetchWithTokenAuth({url:m,accessToken:r,authType:"Upload-Token"}),!0}catch(d){return d.status!==404&&Ge.error("error while verifying app exists on TVC",{error:d}),!1}}if(a===_.P_CLOUDY){let m=await this.getPCloudyAuthToken(n,i),d=`${Aa}/drive`,u=await $a({url:d,body:{token:m,filter:"all"},headers:{contentType:null}});return(l=(c=JSON.parse(u).result)==null?void 0:c.files)==null?void 0:l.some(f=>f.file===e)}throw new Error(`grid type ${a} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Re(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Re(e,void 0,n)}},ht=new Vu});function Gu({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"&&!gS.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function hS({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 yS(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function bS(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=i?"tdc":"headspin",l=a&&M.flags.enableBatchHeadSpin.isEnabled(),m=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${c}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...o&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:yS(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n}}}function ta(s){return"id"in s?s.id:s.packageName}function TS(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function wS({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a,resetOnSessionStartOnly:c}=t,l={"appium:app":n},m=n==null?void 0:n.startsWith("http");switch(n&&!m&&(l=TS(n,t.gridData.type)),s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":!!i,...!!i&&{"appium:resetOnSessionStartOnly":c},...r&&{"appium:bundleId":ta(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2","appium:appWaitActivity":o,...r&&{"appium:appPackage":ta(r),"appium:appActivity":r.activity},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Hu({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}){switch(s){case"ios":return{...e,autoAcceptAlerts:!0,platformName:"iOS",automationName:"XCUITest",...t&&{bundleId:ta(t)},...r&&{app:r}};case"android":return{...e,autoGrantPermissions:!0,platformName:"Android",automationName:"UiAutomator2",appWaitActivity:n,...t&&{appPackage:ta(t),appActivity:t.activity},...r&&{app:r}};default:throw Error(`unsupported mobile project ${s}`)}}function xy({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=bS(i.type,o,n);return wS({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function qu({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 zu({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e;if(s)return s;if(n!=null&&n.deviceName)return r===_.P_CLOUDY?n.deviceUdid:n.deviceName;if(o!=null&&o.deviceNameRegex)return o.deviceNameRegex;if(t==="ios"){if(r===_.BROWSERSTACK)return"iPhone.*";if(r===_.P_CLOUDY)return"apple"}return".*"}function vS({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,u=qu({osVersion:c,mobileConfig:m}),f={device:zu({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),os_version:u,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:options":{token:o.accessToken}};return Hu({projectType:s,sessionCaps:f,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ES({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,type:g}=o,f=qu({osVersion:c,mobileConfig:m}),h=zu({deviceName:l,mobileConfig:m,projectType:s,gridType:g}),y=/^[a-zA-Z]+$/.test(h),v={...f!==".*"&&{pCloudy_DeviceVersion:f},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},S={pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:10,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",Hu({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function SS({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=o,u=d===_.BROWSERSTACK?"browserstack":"saucelabs",g=qu({osVersion:c,mobileConfig:m}),f=zu({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h={...d===_.BROWSERSTACK&&{os_version:g,device:f,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...d===_.SAUCELABS&&{platformVersion:g,deviceName:f,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return Hu({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Py(s){return _.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type?xy(s):_.TESTIM_TVC===s.gridInfo.type?vS(s):_.P_CLOUDY===s.gridInfo.type?ES(s):SS(s)}function IS(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,c={};return n==="dynamic"&&(!o&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!i&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),o&&(c.manufacturer=o),i&&(c.os_version=i),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}function Cy(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Gu({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=ht.getGridConnection(e),c=Py(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let m=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",d=IS(r,o==null?void 0:o.mobile);if(!(0,Ay.isEmpty)(d)){let u=Object.entries(d).map(([g,f])=>f.split(",").map(h=>h===".*"||h==="="?"":`${g}:${h}`).join(",")).join(" ").trim();c[`${m}:selector`]=u}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c;return{...a,desiredCapabilities:c,capabilities:l,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ky(s){var f,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;Gu({nativeAppMetadata:r,appPath:o,gridInfo:t}),hS({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((h=(f=c.mobile)==null?void 0:f.staticAllocation)==null?void 0:h.deviceUdid),d=await ht.getGridDirectConnection(t,m),g=xy({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(g["appium:udid"]=m),{...d,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Oy(s){return Gu(s),Py(s)}function _y(s){let e=Object.assign({},s);return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],delete e.capabilities.key,delete e.capabilities.user,e}var Ay,gS,Ku=T(()=>{"use strict";he();oe();ea();Ay=require("lodash"),gS=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var ra,Dy=T(()=>{"use strict";ra=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Ju,sa,My=T(()=>{"use strict";j();Ju=A("mobile-frame-locator-mock"),sa=class{foundFrameCallback(){return Ju.info("foundFrameCallback-mock invoked"),{}}locate(){return Ju.info("locate-mock invoked"),{}}async findFrame(){return Ju.info("findFrame-mock invoked"),{}}}});var RS,Uy,Ny,Ts,Yu=T(()=>{"use strict";RS=E(require("webdriverio")),Uy=require("@applitools/eyes-sdk-core");Dy();_u();j();Lu();Du();Te();Bu();My();ju();Ny=A("appium-test-player"),Ts=class{constructor(e,t,r,n=RS,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=ee(),d=new gs(this.driver);this.stepActionFactory=new l(d),Qi(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new bs(Pi()),this.sessionPlayer=new a(e,{tabService:new ra,cookieUtils:void 0,FrameLocator:sa,portSelector:xi,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Uy.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{await(n==null?void 0:n.endSession()),Ny.info("appium session deleted",o)}catch(i){Ny.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=ee();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function AS(s){return await Re(`${s}/api/status`)}async function Fy(s,e){return await Re(`${s}/api/devices/${e}/status`)}async function By(s){if((await AS(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var jy=T(()=>{"use strict";He()});var $y={};V($y,{WorkerLocalTma:()=>ep});var kn,na,Xu,Qu,Zu,ep,Wy=T(()=>{"use strict";He();kn=E(require("semver"));Ku();Sn();B();j();Pt();Yu();Te();jy();ea();na=A("worker-appium"),Xu=class extends Error{},Qu=class extends Error{},Zu=class extends Error{},ep=class extends st{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=ee(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}checkIfUpgradeIsNeeded(t,r,n){if(n)return!1;let[o,i]=[kn.coerce(t),kn.coerce(r)];return!o||!i?!1:kn.cmp(o,"!==",i)}async getBrowserOnce(t,r,n,o){var C;if(X.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:c}=this.options;await By(i);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,g=!1,f=this.options.appId;if(f){let{executionId:k,testResultId:I}=t,{mobileApp:U}=await ht.getMobileAppDataByAppId({appId:f,projectId:l,token:m,executionId:k,testResultId:I});t.nativeApp=U}let h=u==="android"?t.androidActivityWait:null,y=t.nativeAppMetadata,v=t.downloadableAppPublicLink,S=t.appPackageNameOrBundleId;if(!y)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!S)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:b,version:w},R]=await Promise.all([this.getAppStateFromDevice(i,a,S),Fy(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!b&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!b&&v&&await this.installApp(i,a,v),b&&(!t.isAppFromDevice||f)&&(g=this.checkIfUpgradeIsNeeded(w,y.version,R.isVirtual));try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(C=this.options.projectData)==null?void 0:C.name}-${this.options.project}`},I=Oy({projectType:u,nativeAppMetadata:y,appPath:v,androidActivityWait:h,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),U={capabilities:{udid:a,...I}},O=await this.requestNewAppiumSessionFromTma(i,U,y);if(this.sessionData=O,g){let $=await this.initAndGetAppiumAPI(n);await $.removeApp(S),await this.installApp(i,a,v),await $.activateApp({[u==="ios"?"appId":"bundleId"]:S})}let N=await d.attach({sessionId:O.sessionId,capabilities:I});this.device=await ht.updateTmaDeviceDetails(a,this.options,t),na.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:N.sessionId,testResultId:this.testResultId,nativeAppMetadata:y,sessionCaps:N.capabilities})}catch(k){throw na.error("failed to start application",{err:k}),k}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local"}}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new Zu(c):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,c=(await Re(i)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Lt(n);await Ls(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new Qu(l,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Xu(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=ee(),{sessionPlayer:i}=r,a=n||"runner";X.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw na.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw na.error("failed to run test once",{err:l}),l}}}});var Gy={};V(Gy,{WorkerAppium:()=>tp});var Vy,On,tp,Hy=T(()=>{"use strict";Ku();Vy=require("linkedom");Sn();j();Pt();Yu();Te();ea();oe();On=A("worker-appium"),tp=class extends st{initPlayer(t){return new Ts(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){X.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,c=await ht.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),l=a==="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 d={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag}},u={projectType:a,nativeAppMetadata:m,appPath:c,androidActivityWait:l,sessionTags:d,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await ht.lockDevice(o,this.options.deviceUdid),g=await ky(u)):g=Cy(u),On.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:d,nativeAppMetadata:m,capabilities:_y(g)}),this.activeSession=await i.remote(g),this.device=await ht.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options),On.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(d){throw On.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:d}),d}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===_.TESTIM_HEADSPIN||o===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===_.TESTIM_TVC?`https://${t}/wd/hub`:o===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=ee(),{sessionPlayer:a}=r,c=n||"runner";X.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let l;if(this.options.skipLoadBalancer){let f=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:v,path:S}=await ht.getHeadSpinDeviceConnection(this.options.gridData,f);l=`${h}://${y}:${v}${S}`}else l=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(l,this.activeSession.sessionId,Vy.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let d=async()=>{try{let f=await new Promise((y,v)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(v)});return await i.drain(),f.stepsResults=null,f.resultId=this.testResultId,{...f,...t.seleniumPerfStats.getStats()}}catch(f){throw On.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:f}),f}};try{return await super.runTestOnce(t,r),await d()}catch(f){throw On.error("failed to run test once",{err:f}),f}}}});var oa,qy=T(()=>{"use strict";B();bn();z();oa=class{constructor(e){this.id=e;this.driver=new Ir}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof re&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var zy,ia,Ky=T(()=>{"use strict";zy=E(require("ws"));B();ia=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new zy.default(this._cdpUrl,{timeout:e}),r=qt(o=>{t.once("open",o)}),n=qt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((c,l)=>{this._cdpCallbacks.set(o,{resolve:c,reject:l})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var ca,rp,aa,Jy=T(()=>{"use strict";B();ca=E(require("chrome-launcher"));ou();Ky();tn();rp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new ia}async init(e,t,r,n,o,i,a,c,l,m){var f,h,y,v;let d=pi(e,t,r,n,o,i,a),u=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((v=(y=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:v.args)??[],...ca.Launcher.defaultFlags().filter(S=>S!=="--disable-extensions")];this.chrome=await ca.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),Xr(()=>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}},aa=class{constructor(e){this.id=e;this.sessionId=te();this.driver=new rp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Xy={};V(Xy,{WorkerExtension:()=>_n});function xS(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Yy(s){return xS(s)?s:new Error(s)}var nt,_n,sp=T(()=>{"use strict";Be();z();Sn();B();j();Pt();oe();qy();Jy();nt=A("worker-ext"),_n=class extends st{initPlayer(){return this.options.useChromeLauncher?new aa(this.id):new oa(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init(this.options,this.testName,this.testRunConfig,n,t,this.executionId,this.testResultId,e.seleniumPerfStats,(i=this.options.lightweightMode)==null?void 0:i.general,this.lambdatestService)}catch(a){throw nt.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return X.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;D("WorkerExtension runTestOnce");let i=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(m.cdpTestRunner),d,Ve.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof re))throw u;return nt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let g=await m.url(d);return u.driverUrlFinished=!0,g}catch(g){throw nt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:d,urlLength:d.length}),g}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(D("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){X.onWaitToTestStart(this.id),X.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(f){throw nt.warn("failed to run test via CDP",{err:f}),f}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let f=await e.getRunTestUrl();X.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,f,u),c(u)]),this.options.testStartTimeout,Ve.TEST_START_TIMEOUT_MSG)}catch(v){if(!(v instanceof re))throw v;nt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}X.onWaitToTestComplete(this.id);let h=new AbortController,y=v=>{e.onCompletedCleanup(),nt.warn("on browser closed error detected",{err:v,testResultId:r,executionId:n,testId:o}),d.unregisterToClosedBrowser(y),v.type=Ns.BROWSER_CLOSED,h.abort(v)};d.registerToClosedBrowser(y);try{let v=ce(e.onCompleted(),this.testRunTimeout,Ve.TEST_COMPLETE_TIMEOUT_MSG),S=await Na(v,h.signal);d.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(R){nt.error("Could not update the grid about the test status",{err:R})}d.isAlive()||(nt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let b=d.maxKeepAliveGap();return b>=3e4&&(nt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=b),{...S,...e.seleniumPerfStats.getStats()}}catch(v){throw nt.warn("timeout wait until test completed",{err:v,testResultId:r,executionId:n,testId:o}),Yy(v)}finally{d.unregisterToClosedBrowser(y)}}catch(f){throw nt.warn("failed to start url",{err:f}),Yy(f)}};t.driver.start();try{return await super.runTestOnce(e,t),D("WorkerExtension super.runTestOnce"),await l()}catch(m){throw nt.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Qy={};V(Qy,{WorkerExtensionSingleBrowser:()=>np});var PS,CS,np,Zy=T(()=>{"use strict";Be();B();j();vu();Pt();sp();PS=A("base-worker"),CS=500,np=class extends _n{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await vn(this.id,this.releaseSlotOnTestFinished,t,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return X.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(PS.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;D("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ie(CS)}}});function kS(s,e){e===0?s():setTimeout(s,e*Lp)}var op,la,eb=T(()=>{"use strict";bn();le();Be();Kl();Rt();uu();z();j();oe();Xg();op=A("parallel-worker-manager"),la=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(Iy(),fe(Sy)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(Wy(),fe($y)).WorkerLocalTma:(Hy(),fe(Gy)).WorkerAppium;default:return mi.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Zy(),fe(Qy)).WorkerExtensionSingleBrowser:(sp(),fe(Xy)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return D("before new Worker",n.mode),new o(t,...r)}finally{D("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,c,l){if(e&&e.length===0)return;let m=!1,d=0,u=g=>new Promise(f=>{var yt,kr,x,L,F,q,ot,ga;let h=o.project,y=new wi(r,n,e,o,i,t),v={},S=e.length,b=((yt=o.company)==null?void 0:yt.ucid)||"",w=(kr=o.company)==null?void 0:kr.companyId,R=(x=o.company)==null?void 0:x.name,C=o.source||"cli",k=o.user,I=(L=o.company)==null?void 0:L.planType,U=(F=o.company)==null?void 0:F.isStartUp,O=(q=o.projectData)==null?void 0:q.name,N=(ot=o.projectData)==null?void 0:ot.type,$=o.lightweightMode,H=(ga=o.gridData)==null?void 0:ga.type,J=(kt,it,ye,ha,Dn,ya)=>(d++,Lf({executionId:r,projectId:h,testId:it,resultId:ye,ucid:b,companyId:w,companyName:R,projectName:O,companyPlan:I,source:C,user:k,lightweightMode:$,isStartUp:U,projectType:N,appSource:ya,gridType:H}),t.testStartAndReport(kt,r,ye,ha,Dn)),Q=async(kt,it,ye,ha,Dn,ya)=>{var hp,yp,bp;d--;let Qe={...($==null?void 0:$.onlyTestIdsNoSuite)&&{show:!0},...ye.seleniumStats&&{seleniumStats:ye.seleniumStats},...ye.gridIssues&&{gridIssues:ye.gridIssues},...ye.keepAliveIssue&&{keepAliveIssue:ye.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ye.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ye.seleniumPerfMarks),delete ye.seleniumPerfMarks),o.grid||o.gridId?(Qe.gridName=o.grid||((hp=o.gridData)==null?void 0:hp.name),Qe.gridType=(yp=o.gridData)==null?void 0:yp.type,Qe.gridProvider=(bp=o.gridData)==null?void 0:bp.provider):o.localTmaUrl?(Qe.gridName="local-tma-from-options",Qe.gridType="local-tma"):o.useLocalChromeDriver?(Qe.gridName="local-chrome-driver-from-options",Qe.gridType="local-chrome"):o.useChromeLauncher?(Qe.gridName="chrome-launcher-from-options",Qe.gridType="local-chrome"):o.browserstack?Qe.gridName="browserstack-from-options":o.saucelabs&&(Qe.gridName="saucelabs-from-options"),await t.testEndAndReport(kt,ye,r,ha,Dn,Qe).catch(zb=>op.error("testEndAndReport threw an error",{err:zb})),Dn)return;v[ye.resultId]=ye,Df({executionId:r,projectId:h,testId:it,resultId:ye.resultId,result:ye,ucid:b,companyId:w,companyName:R,projectName:O,companyPlan:I,source:C,user:k,lightweightMode:$,logger:op,isStartUp:U,projectType:N,appSource:ya}),l&&!ye.success&&(y.stop(),m=!0),(Object.keys(v).length===S||m&&d===0)&&f(v)},de=(kt,it)=>{v[it.resultId]=it,t.onTestIgnored(kt,it.resultId),d--,(Object.keys(v).length===S||m&&d===0)&&f(v)},Vt=(kt,it)=>t.onGridSlot(kt,it);o.userData={loginData:Object.assign({},Nt(),{refreshToken:vo(),authData:Nt(),token:g}),projectId:o.project,company:o.company,servicesUrl:me},D("in localStrategy before createWorker"),this.createWorkers(c,y,o,this.customExtensionLocalLocation,r,J,Q,Vt,de).forEach((kt,it)=>{D("before schedule worker.run after createWorkers"),kS(()=>{D("right before worker.run"),kt.run()},it)})});try{let g=await Jt(),f=await u(g);if(m)throw new Ht;return f}catch(g){throw op.error("failed running parallel workers",{executionId:r,err:g}),g}}}});async function rb(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:te()}))]}:await Oc({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 ip(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 ap(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=tb.difference(Us(s,e),t);if(r.length>0)throw pt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var tb,sb=T(()=>{"use strict";tb=E(require("lodash"));B();Qr();be();z()});var Ln,$_,cp,lp,ua,nb=T(()=>{"use strict";Ln=E(require("lodash"));B();j();le();oe();Be();rs();Ol();Kl();be();Rt();Pt();tg();z();eb();sb();({testRunStatus:$_,CLI_MODE:cp}=Dt),lp=A("test-plan-runner"),ua=class{constructor(e){this.startTime=Date.now();this.workerManager=new la(e)}async runTestAllPhases(e,t,r,n,o,i,a,c){let l={},m=Nt(),d=async()=>{let h=o.beforeParallel||1,y=!0,v=await this.workerManager.runTests(e,c,i,a,o,n,m,h,y);Object.assign(l,v)},u=async()=>{let h=zn||o.parallel,y=!1;D("right before this.workerManager.runTests");let v=await this.workerManager.runTests(t,c,i,a,o,n,m,h,y);D("right after this.workerManager.runTests"),Object.assign(l,v)},g=async()=>{let h=o.afterParallel||1,y=!1,v=await this.workerManager.runTests(r,c,i,a,o,n,m,h,y);Object.assign(l,v)};Mf({executionId:i,projectId:o.project}),D("right before runBeforeTests");try{return await d(),D("right before runTestPlanTests"),await u(),D("right after runTestPlanTests"),await g(),l}catch(h){if(lp.error("error running test plan",{err:h}),h instanceof Ht)return c.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await f()}async function f(){var y,v,S,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===cp.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),Xt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:C}=w();await C.closeBatch(i,R);return}let h;try{if(!((b=(S=(v=o.company)==null?void 0:v.activePlan)==null?void 0:S.premiumFeatures)!=null&&b.applitools)||(h=await Kc(o.project),Ln.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,c){var b,w,R;let l=te(),m=n.project;Oa(l),e.forEach(C=>Object.assign(C,{isBeforeTestPlan:!0})),r.forEach(C=>Object.assign(C,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new ui(d,n,i,a),g=Ln.default.chain(d).map(C=>{var k;return((k=C.overrideTestConfig)==null?void 0:k.name)||""}).uniq().compact().value(),f=(g==null?void 0:g.length)===1?g[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:d.map(C=>C.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,o,h);D("before testListInfoPromise");let v=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||X.onTestPlanStarted(v.beforeTests,v.tests,v.afterTests,o,l,c,f),D("before runTestAllPhases");let S=await this.runTestAllPhases(v.beforeTests,v.tests,v.afterTests,a,n,l,o||"All Tests",u);return D("before executionEnd"),await u.executionEnd(l),D("after executionEnd"),{results:S,executionId:l,testPlanName:o,configName:f}}async runTestPlans(e,t){lp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(m){return Ln.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await kc(i,e.testPlan,e.testPlanIds,t,e.intersections),c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==cp.APPIUM&&await ap(e,r(l)),await ae(c,async m=>{var f;let d=m.testPlanId;n[d]={};let u=Object.assign({},e);u.baseUrl||=m.startUrl,u.appId||=((f=m.mobileApp)==null?void 0:f.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await hf(e,m);let g=u.overrideExecutionName||m.name;return await ae(l[d],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,g,d,t);X.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let v=Object.keys(n[d]).map(R=>({executionId:R,status:ip(n[d][R])})),S=Object.keys(n[d]).map(R=>n[d][R]).reduce((R,C)=>Object.assign(R,C),{}),b=ip(S);Object.assign(o,S);let w=b?v[0].executionId:v.find(R=>!R.status).executionId;return await xc(i,d,{success:b,executions:v,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;lp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),D("before getSuite");let r=await rb(e,t);if(D("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;return D("Right before validateConfig + runAnonymousTestPlan tests map"),await ae(r.tests,async c=>{if(e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==cp.APPIUM&&await ap(e,c),D("right before runTestPlan");let l=await this.runTestPlan([],c,[],e,o,null,t,i);return D("right after runTestPlan"),await X.onTestPlanFinished(l.results,o,this.startTime,l.executionId,i),l})}async run(e){let t=un(),r=[];Fs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Ln.default.flattenDeep(r);return D("right before onAllTestPlansFinished"),await X.onAllTestPlansFinished(n),D("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var cb={};V(cb,{init:()=>JS,run:()=>zS});async function _S(s){let e=s.project,t=await Lc(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),rn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ps}function LS(s,e){var i,a,c,l,m,d;let t=so(e.activePlan),r=s.parallel;if(t==="free"&&r>ib)throw new P(`The free plan allows only ${ib} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let u=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!u)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let g=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
408
408
  Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}let n=s.retentionDays;if(!n)return;let o=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function DS(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await _S(s)}catch(t){if([P,Ps].some(r=>t instanceof r))throw t;OS.error("could not validate cli account",{err:t})}}function MS(s){let e=Nt();return Sm({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function NS(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return ft.connect(s);if(!t){let{remoteStepService:n}=await Promise.resolve().then(()=>(yi(),$g));await n.init(s)}if(!e){let{testResultService:n}=await Promise.resolve().then(()=>(bi(),Gg));n.init(s,r)}}function US(s,e){let{branch:t,autoDetect:r}=s;if(wf(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function FS(s){let{project:e}=s,t=un();ab.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await Rc({projectId:e,branch:t}))}function BS(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:d,extensionPath:u,ext:g,playerPath:f}=s;if([Y.SELENIUM].includes(d)&&!f)throw new P("in selenium on prem mode --player-path must be provided");if(d==="extension"&&!u&&!g)throw new P("In extension on prem mode --ext or --extension-path must be provided")}let c=Boolean(a.isPoc),l=Boolean(a.isStartUp),m=so(a);m==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ob?ob:s.newBrowserWaitTimeout),M.setCompanyId(r),M.setIsPOC(c),M.setIsStartUp(l),M.setPlanType(m),xt.setPlanType(m),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:m,isPOC:c,isStartUp:l,activePlan:a}}function jS(s,e){s.editorUrl=xs||e.editorUrl}function $S(s,e){s.allGrids=e}function WS(s,e){s.authData=e}function VS(s,e){let{id:t,name:r,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function GS(s){s.gridData=await yf(s)}async function HS(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(pt("user-override-file",t),s.mockNetworkRules=await pm(s.overrideMappingFile))}async function qS(s,e){D("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await Hm(),D("in runner.js after checkNpmVersion"),await DS(s),D("in runRunner before tunnel.connect"),await Go(s),D("in runRunner after tunnel.connect");let a=await new ua(e).run(s);return D("before tunnel.disconnect"),await Ho(s),await cn.end(t),D("after tunnel.disconnect and gridService.keepAlive.end"),a}function KS(s){var e;xt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
409
409
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
410
410
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m