@testim/testim-cli 4.147.0 → 4.149.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,20 +1,20 @@
1
1
  #! /usr/bin/env node
2
2
  "use strict";var jT=Object.create;var ii=Object.defineProperty;var $T=Object.getOwnPropertyDescriptor;var WT=Object.getOwnPropertyNames;var VT=Object.getPrototypeOf,GT=Object.prototype.hasOwnProperty;var v=(s,e)=>()=>(s&&(e=s(s=0)),e);var H=(s,e)=>{for(var t in e)ii(s,t,{get:e[t],enumerable:!0})},ld=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of WT(e))!GT.call(s,n)&&n!==t&&ii(s,n,{get:()=>e[n],enumerable:!(r=$T(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?jT(VT(s)):{},ld(e||!s||!s.__esModule?ii(t,"default",{value:s,enumerable:!0}):t,s)),He=s=>ld(ii({},"__esModule",{value:!0}),s);var Be={};H(Be,{log:()=>M,measure:()=>qT});function M(...s){if(!pd)return;let e=Date.now();console.log(`${e-HT} ${e-ud} `,...s),ud=e}function qT(s,e){if(!pd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var pd,HT,ud,je=v(()=>{"use strict";pd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,HT=Date.now(),ud=Date.now()});var Gt,jr=v(()=>{"use strict";Gt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function qe(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function tc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function Oe(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 rc=v(()=>{"use strict"});var nc,dd,md,mi=v(()=>{nc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"1.4.5-lts.1"},dd={"@applitools/eyes-sdk-core":"13.11.34-legacy.1","@applitools/spec-driver-webdriverio":"1.4.29","@segment/analytics-node":"2.1.3","@types/unzip-stream":"0.3.4",ajv:"6.12.6","body-parser":"1.20.3",chalk:"4.1.2","chrome-launcher":"0.15.0",commander:"10.0.0",compression:"1.7.4",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.1",fkill:"7.2.1","form-data":"3.0.0","https-proxy-agent":"7.0.2","istanbul-lib-report":"3.0.0","istanbul-reports":"3.1.5",jimp:"1.1.4",jsonwebtoken:"9.0.0",linkedom:"0.18.0",lodash:"4.17.21","memory-fs":"0.5.0",ms:"2.1.2","node-fetch":"2.7.0",npm:"10.5.0","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.40.6",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},md={node:">= 18.0.0"}});var Ls,JT,fd,Ht,YT,Ds,gd,hd,fi,Ns,yd,he,bd,Td,gi,$e,ic,wd,hi,vd,FR,BR,Sd,Ed,Ms,Id,Rd,xd,Ad,oc,ac,cc,lc,Cd,Us,Pd,uc,de=v(()=>{"use strict";Ls=process.env.SERVICES_HOST||"https://services.testim.io",JT="https://testimstatic.blob.core.windows.net",fd="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:Ls,Ls=process.env.SERVICES_HOST);Ht=process.env.RUNNER_ENVIRONMENT||"production",YT={production:"",staging:".staging",development:".dev"},Ds=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${YT[Ht]}.testim.io`,gd=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),hd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),fi=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),Ns=process.env.EDITOR_URL,yd=process.env.WEBSOCKET_HOST||`${Ls}/ws`,he=Ls,bd=parseInt(process.env.LOGGER_CONSOLE||"0",10),Td=parseInt(process.env.LOGGER_DEBUG||"0",10),gi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),$e=parseInt(process.env.IS_ON_PREM||"0",10),ic=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,wd=parseInt(process.env.DEBUG_MODE||"0",10),hi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,vd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",FR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),BR=process.env.APPIUM_VERSION||"1.10.1",Sd=process.env.GATEWAY_URL,Ed=process.env.EXTENSION_SERVICES_HOST||Ls,Ms=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/blob`:JT,Id=process.env.GATEWAY_URL?`${process.env.GATEWAY_URL}/testim/edge`:fd,Rd=fd,xd=5*60*1e3,Ad=40,oc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",ac=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",cc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",lc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Cd=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Us=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Pd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,uc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung"});var kd,yi,Od=v(()=>{"use strict";kd=I(require("superagent")),yi=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=process.env.CORALOGIX_PRIVATE_KEY||"d0eb01da-f966-1663-63c6-8871225d7c39",this.applicationName=e.applicationName,this.subsystemName=e.subsystemName,this.flushIntervalMs=e.flushIntervalMs||2e3,this.maxBufferedLogsCount=e.maxBufferedLogsCount||50,this.interval=setInterval(()=>this.flushLogs(),this.flushIntervalMs)}addLog(e){this.logs.push(e),this.logs.length>=this.maxBufferedLogsCount&&this.flushLogs()}setProxy(e){this.proxy=e}async waitForFlush(){clearInterval(this.interval),await this.flushLogs()}async flushLogs(){try{if(this.logs.length===0)return;let e={applicationName:this.applicationName,subsystemName:this.subsystemName,logEntries:[...this.logs]};this.logs=[];let t=kd.default.post(this.url).set("Content-Type","application/json; charset=UTF-8").set("Authorization",`Bearer ${this.token}`).send(e);this.proxy&&t.proxy(this.proxy),await t}catch{}}}});var Ld={};H(Ld,{CoralogixTransport:()=>pc});var _d,XT,QT,pc,Dd=v(()=>{"use strict";_d=I(require("winston-transport"));Od();XT={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},QT=["err","error","reason","e"],pc=class extends _d.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new yi({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...l}=t,c={...a,...l},d={severity:XT[i],text:o,category:n||this.category};c.className&&(d.className=c.className),c.methodName&&(d.methodName=c.methodName),c.threadId&&(d.threadId=c.threadId),delete c.className,delete c.methodName,delete c.threadId,delete c.category,delete c.level,delete c.message;let m=!1;a instanceof Error&&(m=!0,c.msg=a.message+a.stack,o&&(c.msg=`${o}
3
- ${c.msg}`));for(let u of QT)a[u]instanceof Error&&(c[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(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function tw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Dd(),He(Ld)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(bd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ti.inspect(n.meta,r)}`))}))}return[s,e,t]}function $d(s){dc=s}function Wd(s){jd=s}function Vd(s){$e||!s||nw(s)}function Md(s){return{projectId:jd,time:new Date().toISOString(),...dc&&!s&&{executionId:dc}}}function P(s){return new mc(aw.child({category:s}))}var Ud,mt,Ti,bi,Fd,ZT,ew,Nd,Bd,rw,sw,nw,iw,ow,aw,dc,jd,mc,W=v(()=>{"use strict";Ud=I(require("node:os")),mt=I(require("winston"));de();Ti=I(require("node:util")),bi=I(require("chalk")),Fd=I(require("dayjs"));F();ZT=Ud.hostname(),ew=tt();Nd={depth:5,colors:!0},Bd=(s,e,t)=>{let r=`[${(0,Fd.default)().format("HH:mm:ss:SSS")}]`,n=Ti.inspect(e,Nd),i=Ti.inspect(t,Nd);return`${bi.default.white(r)} ${bi.default.reset()}SessionPlayer-${bi.default.red(s)} ${n} ${i}`},[rw,sw,nw]=tw(),iw=Td?"debug":"info",ow={release:Boolean(!1),branch:"runner-v4.147.0"},aw=mt.createLogger({levels:mt.config.syslog.levels,level:iw,transports:rw,defaultMeta:{name:"runner",hostname:ZT,nodeVersion:process.version,runnerVersion:ew,...ow}}),dc=null,jd=null;mc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Md(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Md(n)})}catch{}}}waitForFlush(){return sw()}}});var Ei,$r,C,qt,pr,It,wi,Wr,oe,Fs,rt,zt,Rt,vi,Vr,Si,Bs,Y=v(()=>{"use strict";Ei=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ei.AbortError{},wi=class extends Ei.AbortError{},Wr=class extends Ei.AbortError{},oe=class extends Error{},Fs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},vi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Si=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Bs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function fc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,qd.setTimeout)(s)}function gc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){fi&&!Gd&&(Gd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=fi?Number(fi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Hd||=(await import("p-limit")).default;let r=Hd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var qd,Gd,Hd,hc=v(()=>{"use strict";qd=require("timers/promises");Y();de();Gd=!1});var $s,zd,lw,js,Kd,uw,pw,Jd,Yd=v(()=>{"use strict";$s=I(require("lodash"));de();zd=require("dns");W();hc();lw=P("http-request-counters"),js=!1,Kd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>zd.promises.lookup(t)));return e||(js=!0),e}catch{return lw.error("network connectivity test failed"),js=!0,!1}},uw=$s.throttle(Kd,10*1e3),pw=60*1e3*15,Jd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},pw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),js||uw(),a}}}async function r(){if(js||!await Kd())return!1;let n=$s.sum([...s.fail.values()]),i=$s.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>js,t}});var ze={};H(ze,{deleteReq:()=>Ws,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>Te,getFullRes:()=>hw,getText:()=>Gs,head:()=>yw,isNetworkHealthy:()=>Sc,post:()=>We,postForm:()=>Vs,postText:()=>Tc,put:()=>wc});function mw(){return global.caFileContent}function fw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function gw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=mw();t&&s.ca(t);let r=!e&&gw();r&&s.proxy(r)}async function Xd(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function bc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,yc,st,Gr,dw,Dt,Ws,We,Vs,Gs,Tc,Te,hw,yw,wc,vc,Sc,Ec,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();Yd();yc=P("http-request"),st=Jd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,dw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw yc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ws=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Xd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Gs=st(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Xd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),hw=st((s,e,t,r)=>bc(s,e,t,r)),yw=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),vc=st(async s=>{yc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(dw).buffer(!0).parse(fw);dr(e);try{let t=await e;return yc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=st.isNetworkHealthy,Ec=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ii(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return md.node}catch{return""}}async function em(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await em(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,Qd,Zd,nt,bw,Mt,Ke,Ri,Ic,it,Rc,tm=v(()=>{"use strict";Nt=I(require("node:path"));rc();mi();Qd=I(require("unzip-stream")),Zd=I(require("p-retry")),nt=require("node:fs"),bw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,Zd.default)(()=>e.download(s),{retries:bw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};Ri=async(s,e)=>{let t=Ii(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},Ic=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(Qd.Extract({path:e})),Rc=s=>(0,nt.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>xi,MOBILE_RUN_SKIP_REASON:()=>kc,X_HEADER_RUNNER_ID:()=>_c,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>Cc,runnerStatus:()=>Ac,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>qs,test:()=>Pc,testRunStatus:()=>Hs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,Hs,Ac,me,Je,ht,Cc,Pc,xt,q,L,qs,xi,kc,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Hs={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Cc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},qs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},xi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},kc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},_c="X-Testim-Runner-ID"});function zs(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(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function Tw(){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 Ks,rm,Ye,ww,vw,Sw,Ew,Iw,Lc,Dc,sm=v(()=>{"use strict";ie();Ks=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},rm=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!rm(e)&&!e.runQuarantinedTests;ww=s=>Boolean(s.loginMode),vw=s=>Boolean(s.tunnelOnlyMode),Sw=s=>Boolean(s.createPrefechedData),Ew=s=>Boolean(s.installLazyDepsMode),Iw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ci(s=0){return Ai.default.duration(s).format("HH:mm:ss.SSS")}function Nc(s=0){return Ai.default.duration(s).asSeconds()}var Ai,nm,im=v(()=>{"use strict";Ai=I(require("dayjs")),nm=I(require("dayjs/plugin/duration"));Ai.default.extend(nm.default)});var Js,Hr,Jt,om,qr,am=v(()=>{"use strict";ie();Js=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},om=s=>s===L.TESTIM_TVC,qr=(s,e)=>om(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Mc(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 cm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>tc,calcPercentile:()=>Oi,copyDir:()=>em,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>Tw,getBrowserInfo:()=>xw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Ci,getDurationSec:()=>Nc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Qs,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Mc,getPlanType:()=>ki,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>tt,getSource:()=>Ri,getSourceAsBuffer:()=>Ic,getSourcePath:()=>Ii,getTestUrl:()=>qe,getUniqBrowsers:()=>zs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Ks,isAgentMode:()=>Iw,isAppFromDevice:()=>Js,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>Sw,isInstallLazyDepsMode:()=>Ew,isLoginMode:()=>ww,isMobileProject:()=>Jt,isPromise:()=>fc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>rm,isTestimVirtualGrid:()=>om,isTunnelOnlyMode:()=>vw,isURL:()=>Oe,promiseAbort:()=>gc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Pi,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Xs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function xw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Pi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Pi(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function ki(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Xs(s){return dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Qs(s){return[...dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),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 lm,Kr,um,pm,Rw,Ft,zr,Uc,Oi,dm,F=v(()=>{"use strict";lm=I(require("os")),Kr=I(require("lodash")),um=I(require("path")),pm=require("linkedom");jr();tm();sm();im();rc();hc();am();cm();Rw=lm.homedir(),Ft=um.join(Rw,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{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"}];Oi=(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]};dm=new pm.DOMParser});var Bc={};H(Bc,{$schema:()=>Aw,default:()=>_w,definitions:()=>Cw,properties:()=>Ow,required:()=>kw,type:()=>Pw});var Aw,Cw,Pw,kw,Ow,_w,mm=v(()=>{Aw="http://json-schema.org/draft-07/schema#",Cw={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}}}},Pw="object",kw=["entries"],Ow={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},_w={$schema:Aw,definitions:Cw,type:Pw,required:kw,properties:Ow}});async function wm(){try{return await le(_i.promises.readFile(Mi()).then(async s=>{let e=await Tm;return Nw(e,s)}),3e4)}catch{return{}}}function Nw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Bt(s,e,t=Lw,r=void 0){return async()=>{if(!hm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Mw(e);if(i)return Zs.debug("cache hit:",{fnName:e}),i;if(Zs.debug("cache miss:",{fnName:e}),!ym)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Uw(e,o,t),o}}async function Mw(s){let t=(await Ui)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Uw(s,e,t){if(jc)throw Zs.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 Ui;r[s]={value:e,expiry:Date.now()+t},bm=new Promise(n=>{Ni=n}),Dw(r)}catch{Zs.error("failed updating cache")}}async function Xr(){let s=await Ui;Object.keys(s).forEach(e=>{delete s[e]})}function vm(s){hm=s}function Fw(s=!0){ym=s}async function Sm(){try{return jc=!0,await bm}finally{jc=!1}}function Em(s){Di=s,Ui=wm()}var _i,Li,Yr,fm,Zs,Di,gm,Ni,hm,ym,jc,bm,Tm,Lw,Mi,Ui,Dw,Im,Rm,gx,xm,Yt=v(()=>{"use strict";_i=I(require("fs")),Li=I(require("path")),Yr=I(require("crypto"));F();fm=require("lodash");W();Zs=P("local cache"),Di=Li.resolve(gt(),"testim-cache"),hm=!0,ym=!0,jc=!1,bm=new Promise(s=>{Ni=s}),Tm=new Promise(s=>{gm=s}),Lw=1e3*60*60*3,Mi=()=>Li.resolve(Li.resolve(Di,"testim.cache"));Ui=wm(),Dw=(0,fm.debounce)(async s=>{let e;try{let t=await Tm,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Di)||await _i.promises.mkdir(Di,{recursive:!0}),await _i.promises.writeFile(Mi(),a)}catch(t){Zs.error("failed saving cache",{err:t}),e=t}Ni(e?{success:!1,error:e}:{success:!0})},200);Im=gm,Rm=vm.bind(void 0,!1),gx=vm.bind(void 0,!0),xm=()=>Fw(!1)});function Fi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,$c=v(()=>{"use strict";Qr=I(require("node:os"));F()});function Bw(s){try{return Bi.resolve(Bi.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 Xt(s){let e=Bw(s);return require(e)}var Bi,en=v(()=>{"use strict";Bi=I(require("path"))});function jw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function $w(s){return/The "to" argument must be of type string./.exec(s)}function km(s,e,t){let r=jw(s),n=$w(s);return r||n?(Pm.info("Failed to install package due to insufficient write access",{...Fi(),package:t,path:r}),console.error(`
3
+ ${c.msg}`));for(let u of QT)a[u]instanceof Error&&(c[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(c).length>0&&(o&&!m&&(c.msg=o),d.text=JSON.stringify(c)),this.logger.addLog(d),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function tw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!$e){let{CoralogixTransport:r}=(Dd(),He(Ld)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(bd){let r={depth:5,colors:!0};s.push(new mt.transports.Console({format:mt.format.combine(mt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),mt.format.timestamp({format:"HH:mm:ss:SSS"}),mt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ti.inspect(n.meta,r)}`))}))}return[s,e,t]}function $d(s){dc=s}function Wd(s){jd=s}function Vd(s){$e||!s||nw(s)}function Md(s){return{projectId:jd,time:new Date().toISOString(),...dc&&!s&&{executionId:dc}}}function P(s){return new mc(aw.child({category:s}))}var Ud,mt,Ti,bi,Fd,ZT,ew,Nd,Bd,rw,sw,nw,iw,ow,aw,dc,jd,mc,W=v(()=>{"use strict";Ud=I(require("node:os")),mt=I(require("winston"));de();Ti=I(require("node:util")),bi=I(require("chalk")),Fd=I(require("dayjs"));F();ZT=Ud.hostname(),ew=tt();Nd={depth:5,colors:!0},Bd=(s,e,t)=>{let r=`[${(0,Fd.default)().format("HH:mm:ss:SSS")}]`,n=Ti.inspect(e,Nd),i=Ti.inspect(t,Nd);return`${bi.default.white(r)} ${bi.default.reset()}SessionPlayer-${bi.default.red(s)} ${n} ${i}`},[rw,sw,nw]=tw(),iw=Td?"debug":"info",ow={release:Boolean(!1),branch:"runner-v4.149.0"},aw=mt.createLogger({levels:mt.config.syslog.levels,level:iw,transports:rw,defaultMeta:{name:"runner",hostname:ZT,nodeVersion:process.version,runnerVersion:ew,...ow}}),dc=null,jd=null;mc=class{constructor(e){this._logger=e;this.debug=this.debug.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.fatal=this.fatal.bind(this)}debug(e,t={}){this.innerLog("debug",e,t)}info(e,t={}){this.innerLog("info",e,t)}warn(e,t={}){this.innerLog("warning",e,t)}error(e,t={}){this.innerLog("error",e,t)}fatal(e,t={}){this.innerLog("crit",e,t)}innerLog(e,t,r={}){let{executionId:n}=r;try{this._logger.log(e,{meta:r,message:t,...Md(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Md(n)})}catch{}}}waitForFlush(){return sw()}}});var Ei,$r,C,qt,pr,It,wi,Wr,oe,Fs,rt,zt,Rt,vi,Vr,Si,Bs,Y=v(()=>{"use strict";Ei=require("p-retry"),$r=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},qt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},pr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},It=class extends Ei.AbortError{},wi=class extends Ei.AbortError{},Wr=class extends Ei.AbortError{},oe=class extends Error{},Fs=class extends Error{},rt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},zt=class extends rt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Rt=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},vi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Vr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Si=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},Bs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function fc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function ce(s){return(0,qd.setTimeout)(s)}function gc(s,e){let t=new Promise((r,n)=>{e.onabort=()=>{n(e.reason)}});return Promise.race([s,t])}function le(s,e,t="Timeout Error"){fi&&!Gd&&(Gd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new oe(t);return e=fi?Number(fi)||6e5:e,Promise.race([s,ce(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Hd||=(await import("p-limit")).default;let r=Hd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Kt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var qd,Gd,Hd,hc=v(()=>{"use strict";qd=require("timers/promises");Y();de();Gd=!1});var $s,zd,lw,js,Kd,uw,pw,Jd,Yd=v(()=>{"use strict";$s=I(require("lodash"));de();zd=require("dns");W();hc();lw=P("http-request-counters"),js=!1,Kd=async()=>{if($e)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>zd.promises.lookup(t)));return e||(js=!0),e}catch{return lw.error("network connectivity test failed"),js=!0,!1}},uw=$s.throttle(Kd,10*1e3),pw=60*1e3*15,Jd=()=>{let s={call:new Map,success:new Map,fail:new Map};function e(n,i){let o=n.get(i)||0;n.set(i,o+1),setTimeout(()=>{let a=n.get(i)||1;n.set(i,a-1)},pw)}function t(n,i=n.name){return async function(...o){e(s.call,i);try{let a=await n.call(null,...o);return e(s.success,i),a}catch(a){throw e(s.fail,i),js||uw(),a}}}async function r(){if(js||!await Kd())return!1;let n=$s.sum([...s.fail.values()]),i=$s.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>js,t}});var ze={};H(ze,{deleteReq:()=>Ws,didNetworkConnectivityTestFail:()=>Ec,download:()=>vc,get:()=>Te,getFullRes:()=>hw,getText:()=>Gs,head:()=>yw,isNetworkHealthy:()=>Sc,post:()=>We,postForm:()=>Vs,postText:()=>Tc,put:()=>wc});function mw(){return global.caFileContent}function fw(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function gw(){return!ft.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ft.default),global.proxyUri}function dr(s,e=!1){let t=mw();t&&s.ca(t);let r=!e&&gw();r&&s.proxy(r)}async function Xd(s,e,t={},r=Gr,n=0){let i=ft.default.post(s).send(e).timeout(r).set(t);dr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function bc(s,e,t={},r=Gr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ft.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),dr(o,i),await o}var ft,yc,st,Gr,dw,Dt,Ws,We,Vs,Gs,Tc,Te,hw,yw,wc,vc,Sc,Ec,Ve=v(()=>{"use strict";ft=I(require("superagent"));W();Yd();yc=P("http-request"),st=Jd(),Gr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,dw=6e4;Dt=(s,e,t)=>{let r=e.response;e.response instanceof ft.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw yc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Ws=st(async(s,e={},t={},r=Gr)=>{try{let n=ft.default.delete(s).send(e).timeout(r).set(t);dr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Dt("failed to delete request",n,{url:s})}}),We=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await Xd(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Dt("failed to post request",i,{url:s})}});Vs=st(async(s,e,t,r={},n=Gr)=>{let i=ft.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),dr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Dt("failed to post request",o,{url:s})}});Gs=st(async(s,e,t)=>{try{return(await bc(s,e,t)).text}catch(r){return Dt("failed to getText request",r,{url:s,query:e})}}),Tc=st(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await Xd(s,e,t,r,n)).text}catch(i){return Dt("failed to post request",i,{url:s})}}),Te=st(async(s,e,t,r,n)=>{try{return(await bc(s,e,t,r,n)).body}catch(i){return Dt("failed to get request",i,{url:s,query:e})}}),hw=st((s,e,t,r)=>bc(s,e,t,r)),yw=st(async s=>{let e=ft.default.head(s).timeout(Gr);dr(e);try{return await e}catch(t){return Dt("failed to head request",t,{url:s})}}),wc=st(async(s,e,t={},r=Gr)=>{let n=ft.default.put(s).send(e).timeout(r).set(t);dr(n);try{return(await n).body}catch(i){return Dt("failed to put request",i,{url:s})}}),vc=st(async s=>{yc.info("start to download",{url:s});let e=ft.default.get(s).set("User-Agent","Testim.io").timeout(dw).buffer(!0).parse(fw);dr(e);try{let t=await e;return yc.info("finished to download",{url:s}),t}catch(t){return Dt("failed to download",t,{url:s})}}),Sc=st.isNetworkHealthy,Ec=st.didNetworkConnectivityTestFail});function gt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=Nt.resolve(__dirname,"../../"):s=Nt.resolve(__dirname,""),s):process.cwd()}function Ii(s,e){return Oe(s)?e||Nt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||Nt.basename(s)}function tt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function xc(){try{return md.node}catch{return""}}async function em(s,e,t=!0){let r=await nt.promises.readdir(s,{withFileTypes:!0});await nt.promises.mkdir(e,{recursive:t});for(let n of r){let i=Nt.join(s,n.name),o=Nt.join(e,n.name);n.isDirectory()?await em(i,o):await nt.promises.copyFile(i,o)}}async function ye(s){try{return await nt.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Nt,Qd,Zd,nt,bw,Mt,Ke,Ri,Ic,it,Rc,tm=v(()=>{"use strict";Nt=I(require("node:path"));rc();mi();Qd=I(require("unzip-stream")),Zd=I(require("p-retry")),nt=require("node:fs"),bw=3;Mt=async s=>{let e=await Promise.resolve().then(()=>(Ve(),ze));return(0,Zd.default)(()=>e.download(s),{retries:bw,factor:1})},Ke=async(s,e)=>{let t=await Mt(s);return nt.promises.writeFile(e,t.body)};Ri=async(s,e)=>{let t=Ii(s,e);return Oe(s)?Ke(s,t):nt.promises.copyFile(s,t)},Ic=async s=>Oe(s)?Mt(s):nt.promises.readFile(s),it=async(s,e)=>(0,nt.createReadStream)(s).pipe(Qd.Extract({path:e})),Rc=s=>(0,nt.statSync)(s).size/1e6});var Ut={};H(Ut,{APPIUM_SESSION_MESSAGE:()=>Oc,CLI_MODE:()=>q,MOBILE_APP_SOURCE:()=>xi,MOBILE_RUN_SKIP_REASON:()=>kc,X_HEADER_RUNNER_ID:()=>_c,gridMessages:()=>ht,gridTypes:()=>L,mobileWeb:()=>Cc,runnerStatus:()=>Ac,runnerTestStatus:()=>me,socketEventTypes:()=>xt,stepResult:()=>qs,test:()=>Pc,testRunStatus:()=>Hs,testStatus:()=>Je,timeoutMessages:()=>Me});var Me,Hs,Ac,me,Je,ht,Cc,Pc,xt,q,L,qs,xi,kc,Oc,_c,ie=v(()=>{"use strict";Me={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout"},Hs={COMPLETED:"completed"},Ac={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},me={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Je={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},ht={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Cc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},Pc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},xt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},q={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},L={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},qs={SETUP_TIMEOUT:"setup-timeout",NETWORK_ERROR:"network-error",GRID_ERROR:"grid-error",SELENIUM_ERROR:"selenium-error",BROWSER_CLOSED:"browser-closed",MOBILE_SESSION_ERROR:"mobile-session-error",UNKNOWN_ERROR:"unknown-error"},xi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},kc={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Oc={APP_NOT_EXIST_ON_DEVICE:"used to start the app doesn't exist or cannot be launched",APP_NEVER_STARTED:"never started",DEVICE_OS_VERSION_TOO_LOW:"DeviceOSVersionTooLow",TIMEOUT_ERROR:"Timeout awaiting 'request'",SAUCELABS_APP_IS_NOT_INSTALLED:"Original error: 'app' option is required for reinstall"},_c="X-Testim-Runner-ID"});function zs(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(i=>{var o;return(o=i.runConfig)==null?void 0:o.browserValue}))]:[(n=s.browser)==null?void 0:n.toLowerCase()]}function Tw(){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 Ks,rm,Ye,ww,vw,Sw,Ew,Iw,Lc,Dc,sm=v(()=>{"use strict";ie();Ks=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},rm=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Je.QUARANTINE&&!rm(e)&&!e.runQuarantinedTests;ww=s=>Boolean(s.loginMode),vw=s=>Boolean(s.tunnelOnlyMode),Sw=s=>Boolean(s.createPrefechedData),Ew=s=>Boolean(s.installLazyDepsMode),Iw=s=>Boolean(s.agentMode),Lc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Dc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Ci(s=0){return Ai.default.duration(s).format("HH:mm:ss.SSS")}function Nc(s=0){return Ai.default.duration(s).asSeconds()}var Ai,nm,im=v(()=>{"use strict";Ai=I(require("dayjs")),nm=I(require("dayjs/plugin/duration"));Ai.default.extend(nm.default)});var Js,Hr,Jt,om,qr,am=v(()=>{"use strict";ie();Js=s=>!(!s||"fileName"in s),Hr=(s,e)=>{if(e===L.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Jt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},om=s=>s===L.TESTIM_TVC,qr=(s,e)=>om(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Mc(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 cm=v(()=>{"use strict"});var J={};H(J,{OSS:()=>zr,TESTIM_BROWSER_DIR:()=>Ft,buildBasicHeader:()=>tc,calcPercentile:()=>Oi,copyDir:()=>em,delay:()=>ce,doesPathExist:()=>ye,download:()=>Mt,downloadAndSave:()=>Ke,extractElementId:()=>_e,getArgsOnRemoteRunFailure:()=>Tw,getBrowserInfo:()=>xw,getCdpAddressForHost:()=>gr,getCliLocation:()=>gt,getDuration:()=>Ci,getDurationSec:()=>Nc,getEnginesVersion:()=>xc,getEnvironmentGitBranch:()=>fr,getLinksFromUnescapeHTML:()=>Qs,getLocalFileSizeInMB:()=>Rc,getMemorySnapshot:()=>Mc,getPlanType:()=>ki,getRunConfigByBrowserName:()=>Ys,getRunnerVersion:()=>tt,getSource:()=>Ri,getSourceAsBuffer:()=>Ic,getSourcePath:()=>Ii,getTestUrl:()=>qe,getUniqBrowsers:()=>zs,groupTestsByRetries:()=>Fc,guid:()=>re,hasTestPlanFlag:()=>Ks,isAgentMode:()=>Iw,isAppFromDevice:()=>Js,isAppFromDeviceDisabled:()=>qr,isCreatePrefetchedDataMode:()=>Sw,isInstallLazyDepsMode:()=>Ew,isLoginMode:()=>ww,isMobileProject:()=>Jt,isPromise:()=>fc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>rm,isTestimVirtualGrid:()=>om,isTunnelOnlyMode:()=>vw,isURL:()=>Oe,promiseAbort:()=>gc,promiseFromCallback:()=>Kt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Pi,replaceArgsWithNoDashes:()=>Lc,sanitizeNumberValue:()=>mr,shouldBlockVirtualIosBuild:()=>Hr,spreadObjectToArgs:()=>Dc,unescapeHTML:()=>Xs,unzipFile:()=>it});function mr(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function xw(s){return s=s.toLowerCase(),Uc.find(e=>e.browserValue===s)}function Ys(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Uc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Uc[0],n=zr.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=zr.find(i=>i.sl.platform===e.platform):e.platformName&&(n=zr.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=zr.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=zr.find(i=>i.bs.platform===t.platform))),Kr.merge(r,n)}function fr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Pi(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Pi(s[r],e,t))}function _e(s){return s.ELEMENT||s[Gt]}function ki(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Fc(s=[]){return Kr.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,l=typeof o.retryCount=="number"?o.retryCount:1;return a===l?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=Kr.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function Xs(s){return dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function Qs(s){return[...dm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function gr(s,e){let t=await Promise.resolve().then(()=>(Ve(),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 lm,Kr,um,pm,Rw,Ft,zr,Uc,Oi,dm,F=v(()=>{"use strict";lm=I(require("os")),Kr=I(require("lodash")),um=I(require("path")),pm=require("linkedom");jr();tm();sm();im();rc();hc();am();cm();Rw=lm.homedir(),Ft=um.join(Rw,".testim-browser-profile"),zr=[{osName:"Linux",bs:{os:"LINUX"},sl:{platform:"Linux"},lt:{platform:"Linux"}},{osName:"Windows 11",bs:{os:"WINDOWS",os_version:"11"},sl:{platform:"Windows 11"},lt:{platform:"Windows 11"}},{osName:"Windows 10",bs:{os:"WINDOWS",os_version:"10"},sl:{platform:"Windows 10"},lt:{platform:"Windows 10"}},{osName:"Windows 8",bs:{os:"WINDOWS",os_version:"8"},sl:{platform:"Windows 8"}},{osName:"Windows 8.1",bs:{os:"WINDOWS",os_version:"8.1"},sl:{platform:"Windows 8.1"}},{osName:"Windows 7",bs:{os:"WINDOWS",os_version:"7"},sl:{platform:"Windows 7"}},{osName:"Windows XP",bs:{os:"WINDOWS",os_version:"XP"},sl:{platform:"Windows XP"}},{osName:"macOS Sonoma",bs:{os:"OS X",os_version:"Sonoma",safari_version:"17"},sl:{},lt:{platform:"macOS Sonoma",safari_version:"17"}},{osName:"macOS Ventura",bs:{os:"OS X",os_version:"Ventura",safari_version:"16.5"},sl:{platform:"macOS 13",safari_version:"latest"},lt:{platform:"macOS Ventura",safari_version:"16"}},{osName:"macOS Monterey",bs:{os:"OS X",os_version:"Monterey",safari_version:"15.6"},sl:{platform:"macOS 12",safari_version:"latest"},lt:{platform:"macOS Monterey",safari_version:"15"}},{osName:"macOS Big Sur",bs:{os:"OS X",os_version:"Big Sur",safari_version:"14.1"},sl:{platform:"macOS 11",safari_version:"latest"}},{osName:"macOS Catalina",bs:{os:"OS X",os_version:"Catalina",safari_version:"13.1"},sl:{platform:"macOS 10.15",safari_version:"latest"}},{osName:"macOS Mojave",bs:{os:"OS X",os_version:"Mojave",safari_version:"12.1"},sl:{platform:"macOS 10.14",safari_version:"latest"}},{osName:"macOS High Sierra",bs:{os:"OS X",os_version:"High Sierra",safari_version:"11.1"},sl:{platform:"macOS 10.13",safari_version:"latest"}},{osName:"macOS Sierra",bs:{os:"OS X",os_version:"Sierra",safari_version:"10.1"},sl:{platform:"macOS 10.12",safari_version:"latest"}},{osName:"OS X El Capitan",bs:{os:"OS X",os_version:"El Capitan",safari_version:"9.1"},sl:{platform:"OS X 10.11",safari_version:"latest"}},{osName:"OS X Yosemite",bs:{os:"OS X",os_version:"Yosemite",safari_version:"8"},sl:{platform:"OS X 10.10",safari_version:"latest"}},{osName:"OS X Mavericks",bs:{os:"OS X",os_version:"Mavericks",safari_version:"7.1"},sl:{platform:"OS X 10.9",safari_version:"latest"}},{osName:"OS X Mountain Lion",bs:{os:"OS X",os_version:"Mountain Lion",safari_version:"6.2"},sl:{platform:"OS X 10.8",safari_version:"latest"}},{osName:"OS X Lion",bs:{os:"OS X",os_version:"Lion",safari_version:"6"},sl:{}},{osName:"OS X Snow Leopard",bs:{os:"OS X",os_version:"Snow Leopard",safari_version:"5.1"},sl:{}},{osName:"iOS",bs:{platform:"MAC"},sl:{platformName:"iOS",appiumVersion:"1.6.4"}},{osName:"Android",bs:{platform:"ANDROID"},sl:{platformName:"Android",appiumVersion:"1.6.4"}}],Uc=[{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"}];Oi=(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]};dm=new pm.DOMParser});var Bc={};H(Bc,{$schema:()=>Aw,default:()=>_w,definitions:()=>Cw,properties:()=>Ow,required:()=>kw,type:()=>Pw});var Aw,Cw,Pw,kw,Ow,_w,mm=v(()=>{Aw="http://json-schema.org/draft-07/schema#",Cw={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}}}},Pw="object",kw=["entries"],Ow={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},_w={$schema:Aw,definitions:Cw,type:Pw,required:kw,properties:Ow}});async function wm(){try{return await le(_i.promises.readFile(Mi()).then(async s=>{let e=await Tm;return Nw(e,s)}),3e4)}catch{return{}}}function Nw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=Yr.createDecipheriv("aes-256-cbc",Buffer.concat([n,Buffer.alloc(32)],32),t),o=i.update(r);return JSON.parse(Buffer.concat([o,i.final()]))}function Bt(s,e,t=Lw,r=void 0){return async()=>{if(!hm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Mw(e);if(i)return Zs.debug("cache hit:",{fnName:e}),i;if(Zs.debug("cache miss:",{fnName:e}),!ym)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Uw(e,o,t),o}}async function Mw(s){let t=(await Ui)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Uw(s,e,t){if(jc)throw Zs.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 Ui;r[s]={value:e,expiry:Date.now()+t},bm=new Promise(n=>{Ni=n}),Dw(r)}catch{Zs.error("failed updating cache")}}async function Xr(){let s=await Ui;Object.keys(s).forEach(e=>{delete s[e]})}function vm(s){hm=s}function Fw(s=!0){ym=s}async function Sm(){try{return jc=!0,await bm}finally{jc=!1}}function Em(s){Di=s,Ui=wm()}var _i,Li,Yr,fm,Zs,Di,gm,Ni,hm,ym,jc,bm,Tm,Lw,Mi,Ui,Dw,Im,Rm,gx,xm,Yt=v(()=>{"use strict";_i=I(require("fs")),Li=I(require("path")),Yr=I(require("crypto"));F();fm=require("lodash");W();Zs=P("local cache"),Di=Li.resolve(gt(),"testim-cache"),hm=!0,ym=!0,jc=!1,bm=new Promise(s=>{Ni=s}),Tm=new Promise(s=>{gm=s}),Lw=1e3*60*60*3,Mi=()=>Li.resolve(Li.resolve(Di,"testim.cache"));Ui=wm(),Dw=(0,fm.debounce)(async s=>{let e;try{let t=await Tm,r=Yr.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=Yr.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Di)||await _i.promises.mkdir(Di,{recursive:!0}),await _i.promises.writeFile(Mi(),a)}catch(t){Zs.error("failed saving cache",{err:t}),e=t}Ni(e?{success:!1,error:e}:{success:!0})},200);Im=gm,Rm=vm.bind(void 0,!1),gx=vm.bind(void 0,!0),xm=()=>Fw(!1)});function Fi(){return{cliLocation:gt(),userInfo:Qr.userInfo(),platform:Qr.platform(),release:Qr.release()}}var Qr,$c=v(()=>{"use strict";Qr=I(require("node:os"));F()});function Bw(s){try{return Bi.resolve(Bi.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 Xt(s){let e=Bw(s);return require(e)}var Bi,en=v(()=>{"use strict";Bi=I(require("path"))});function jw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function $w(s){return/The "to" argument must be of type string./.exec(s)}function km(s,e,t){let r=jw(s),n=$w(s);return r||n?(Pm.info("Failed to install package due to insufficient write access",{...Fi(),package:t,path:r}),console.error(`
4
4
 
5
5
  Testim failed installing the package ${t||""} due to insufficient permissions.
6
6
  This is probably due to an installation of @testim/testim-cli with sudo, and running it without sudo.
7
7
  Testim had missing write access to ${r||e}
8
8
 
9
9
  `),!0):!1}function Gc(s){try{return Xt(s)}catch{return!1}}function Om(s,e){return require(yr.join(s,`./node_modules/${e}/package.json`)).version}function _m(s){if(typeof s=="string"&&s.endsWith(".cjs"))return s;if(typeof s=="object"&&s!==null)for(let e of Object.keys(s).filter(t=>t!=="browser")){let t=_m(s[e]);if(t)return t}}function Lm(s){let e=require(yr.join(s,"package.json"));if(!("exports"in e))return"";let t=_m(e);if(!t)throw new Si(e.name);return t}async function $i(s,e,t){let r=yr.join(s,"npm-shrinkwrap.json"),n=yr.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await Vc.promises.rename(r,n),i=!0)}catch{}return await Cm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw km(o.stderr,s,e)?new Vr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await Vc.promises.rename(n,r)}catch{}}}function Hc(s,e,t,r,n=!0){return new Promise((i,o)=>{let a=t?["--proxy",t]:[],l=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},c="",d="",m=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&m.push("--prefer-offline");let u=(0,ji.spawn)("node",[Wc,"i","--prefix",s,...m,...e,...a],l);u.stderr.pipe(process.stderr),u.stdout.pipe(process.stdout),u.stdout.on("data",f=>{c+=f}),u.stderr.on("data",f=>{d+=f}),u.on("close",f=>{var h,g;if(f){n&&Hc(s,e,t,r,!1).then(i).catch(o);let y;try{let T=(h=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(d))==null?void 0:h[1],w=(g=/No matching version found for (\S+)@/gm.exec(d))==null?void 0:g[1];T||w?y=`404 Not Found - GET https://registry.npmjs.org/${w??T} - Not found`:km(d,Wc)?y=`insufficient write access in location ${Wc}`:y=`Npm Installation closed with exit code ${f} with error: ${d}`}catch{y=`Npm Install closed with exit code ${f}
10
- stdout: ${c} stderr: ${d}`}Pm.info(`Npm Install closed with exit code ${f}`,{message:y,stderr:d}),o(new Rt(y))}else i(c)}),setTimeout(()=>{try{u.kill()}finally{o(new oe)}},r)})}async function Dm(){try{return(await Cm("npm -v")).stdout.trim()}catch{return""}}var Vc,yr,Am,ji,Cm,Pm,Wc,Zr=v(()=>{"use strict";Vc=I(require("fs")),yr=I(require("path"));F();Am=require("util"),ji=require("child_process");W();$c();en();Y();Cm=(0,Am.promisify)(ji.exec),Pm=P("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var U,Mm,Um,Fm,Ww,Vw,Gw,Nm,Wi,zc,_,ue=v(()=>{"use strict";U=I(require("rox-node")),Mm=I(require("node-fetch")),Um=require("eventsource");W();F();de();Fm=P("FeatureFlagsService"),Ww=!$e&&!0&&!Sd,Vw=2e4,Gw=60*60*24,Nm=["labs","disabled","enabled"],Wi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Nm)}getValue(){let e=super.getValue();return Nm.includes(e)?e:(Fm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},zc=class{constructor(){this.flags={useNewWSCLI:new U.default.Flag,useSafariWebdriverVisibilityChecks:new U.default.Flag,useClickimVisibilityChecks:new U.default.Flag,runGetElementCodeInAut:new U.default.Flag,enableFrameSwitchOptimization:new U.default.Flag,maximumJsResultSize:new U.default.RoxNumber(2e3*1024),skipFileInputClicks:new U.default.Flag,errorMessageOnBadNetwork:new U.default.Flag(!0),warnOnBadNetwork:new U.default.Flag(!1),overrideAzureStorageUrl:new U.default.Flag,autoSaveDownloadFileFireFox:new U.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new U.default.Flag(!0),experimentalPreCodeCompilation:new U.default.Flag(!0),experimentalAsyncCustomCode:new U.default.Flag,useSameBrowserForMultiTests:new Wi("labs"),highSpeedMode:new Wi,usePortedHtml5DragDrop:new U.default.Flag,testNamesToBeforeSuiteHook:new U.default.Flag,addCustomCapabilities:new U.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new U.default.RoxString("{}"),LTNetworkCapabilities:new U.default.Flag,downloadToBase64:new U.default.Flag,publicGridURL:new U.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new U.default.Flag(!0),unsupportedCapsFields:new U.default.RoxString("[]"),dontFocusOnInit:new U.default.Flag,retryOnSeleniumHubError:new U.default.Flag,enableLambdaTestTunnelNTLM:new U.default.Flag,enableLambdaTestTunnelSkipUpgrade:new U.default.Flag,tdcHsPreventNetworkCapture:new U.default.Flag,headSpinTdcEnableFlagCapability:new U.default.Flag,enableBatchTDC:new U.default.Flag,enableBatchHeadSpin:new U.default.Flag,clearRunnerFileCache:new U.default.Flag,forceTurboModeIfNeeded:new U.default.Flag,redisSlotManager:new U.default.Flag,tunnelBinaryNewVersion:new U.default.Flag(!1),encryptedCredentials:new U.default.Flag,computePackagePathFromPackageJsonExports:new U.default.Flag,sendExtensionOnEdgeNonLinux:new U.default.Flag,enableAppium2pCloudy:new U.default.Flag,reuseCliPkgInstallFolder:new U.default.Flag,getPublicIpFrom3rdPartyServices:new U.default.Flag,chromedriverCdnBinariesUrl:new U.default.RoxString(""),sfdcHybridCompany:new U.default.Flag,allowFixingAppIdStructure:new U.default.Flag,enableAppium2BrowserStack:new U.default.Flag,increaseTDCRequestTimeout:new U.default.Flag,accessTokenExpiryMargin:new U.default.RoxNumber(300*1e3),useMV3Extension:new U.default.Flag,testimHeadlessExtensionDownloadUrl:new U.default.RoxString("",[]),useStepResultIdForStepTransactions:new U.default.Flag,applyMobileRestrictionFromDate:new U.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new U.default.Flag,appiumConnectionRetryCount:new U.default.RoxNumber(0),appiumConnectionRequestTimeout:new U.default.RoxNumber(12e4),DFBrowserVersion:new U.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new U.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new U.default.Flag(!1),enableTestPlanAggregation:new U.default.Flag},U.default.register("default",this.flags)}setProjectId(e){U.default.setCustomStringProperty("projectId",e)}setProjectType(e){U.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){U.default.setCustomStringProperty("productType",e)}setCompanyId(e){U.default.setCustomStringProperty("companyId",e)}setPlanType(e){U.default.setCustomStringProperty("planType",e)}setIsPOC(e){U.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){U.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){U.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){U.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,n;if(!Ww)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,l)=>(0,Mm.default)(a,{...l,agent:o}),n=function(a){return new Um.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Gw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(vd,i),Vw).catch(o=>Fm.error("failed to get feature flag status",o))}},_=new zc});var Wm={};H(Wm,{install:()=>qw,isReady:()=>Kw,start:()=>zw});var Bm,jm,$m,Jc,Kc,Hw,qw,zw,Kw,Vm=v(()=>{"use strict";Bm=I(require("fkill")),jm=I(require("p-retry"));Zr();Ve();F();en();ue();$m="chromedriver",Jc=9515,Kc=`http://localhost:${Jc}/wd/hub`,Hw=[`--port=${Jc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],qw=async()=>{let s=_.flags.chromedriverCdnBinariesUrl.getValue(),e=Oe(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await $i(gt(),`${$m} --detect_chromedriver_version ${e}`)},zw=async()=>{process.env.NODE_OPTIONS="",await(0,Bm.default)(`:${Jc}`,{silent:!0}),await Xt($m).start(Hw,!0)},Kw=async({chromeBinaryLocation:s})=>{await(0,jm.default)(async()=>{var n;let e=await Te(`${Kc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${Kc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Ws(`${Kc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var rn={};H(rn,{getSessionPlayerFolder:()=>Zc,prepareChromeDriver:()=>tn,prepareCustomExtension:()=>Xc,prepareExtension:()=>Qc,preparePlayer:()=>br});async function Xc(s,e=!1){if(!s)return;if(Oe(s)){let n=es.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Jw(s)>Yc&&!e)throw new C(Gm);return await Ke(s,n),n}let t=es.resolve(s);if(!qm.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Yc&&!e)throw new C(Gm);return t}async function Jw(s){let e=(Ve(),He(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Vi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function Qc(s){Vi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ii(t)}));return Bt(()=>se(e,({location:t,path:r})=>Ri(t,r)),"prepareExtension",Km,e)()}async function tn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Vm(),Wm));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Vr||(Vi.error(a,{...s,...Fi(),error:(0,zm.serializeError)(o)}),console.log(`
10
+ stdout: ${c} stderr: ${d}`}Pm.info(`Npm Install closed with exit code ${f}`,{message:y,stderr:d}),o(new Rt(y))}else i(c)}),setTimeout(()=>{try{u.kill()}finally{o(new oe)}},r)})}async function Dm(){try{return(await Cm("npm -v")).stdout.trim()}catch{return""}}var Vc,yr,Am,ji,Cm,Pm,Wc,Zr=v(()=>{"use strict";Vc=I(require("fs")),yr=I(require("path"));F();Am=require("util"),ji=require("child_process");W();$c();en();Y();Cm=(0,Am.promisify)(ji.exec),Pm=P("cli-service");Wc=yr.resolve(require.resolve("npm").replace("index.js",""),"bin","npm-cli.js")});var U,Mm,Um,Fm,Ww,Vw,Gw,Nm,Wi,zc,_,ue=v(()=>{"use strict";U=I(require("rox-node")),Mm=I(require("node-fetch")),Um=require("eventsource");W();F();de();Fm=P("FeatureFlagsService"),Ww=!$e&&!0&&!Sd,Vw=2e4,Gw=60*60*24,Nm=["labs","disabled","enabled"],Wi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Nm)}getValue(){let e=super.getValue();return Nm.includes(e)?e:(Fm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},zc=class{constructor(){this.flags={useNewWSCLI:new U.default.Flag,useSafariWebdriverVisibilityChecks:new U.default.Flag,useClickimVisibilityChecks:new U.default.Flag,runGetElementCodeInAut:new U.default.Flag,enableFrameSwitchOptimization:new U.default.Flag,maximumJsResultSize:new U.default.RoxNumber(2e3*1024),skipFileInputClicks:new U.default.Flag,errorMessageOnBadNetwork:new U.default.Flag(!0),warnOnBadNetwork:new U.default.Flag(!1),overrideAzureStorageUrl:new U.default.Flag,autoSaveDownloadFileFireFox:new U.default.Flag(!0),safariSelectOptionDispatchEventOnSelectElement:new U.default.Flag(!0),experimentalPreCodeCompilation:new U.default.Flag(!0),experimentalAsyncCustomCode:new U.default.Flag,useSameBrowserForMultiTests:new Wi("labs"),highSpeedMode:new Wi,usePortedHtml5DragDrop:new U.default.Flag,testNamesToBeforeSuiteHook:new U.default.Flag,addCustomCapabilities:new U.default.RoxString("{}"),addCustomLTtunnelNTLMOptions:new U.default.RoxString("{}"),LTNetworkCapabilities:new U.default.Flag,downloadToBase64:new U.default.Flag,publicGridURL:new U.default.RoxString("public-grid.testim.io"),allowAppFromDeviceRuns:new U.default.Flag(!0),unsupportedCapsFields:new U.default.RoxString("[]"),dontFocusOnInit:new U.default.Flag,retryOnSeleniumHubError:new U.default.Flag,enableLambdaTestTunnelNTLM:new U.default.Flag,enableLambdaTestTunnelSkipUpgrade:new U.default.Flag,tdcHsPreventNetworkCapture:new U.default.Flag,headSpinTdcEnableFlagCapability:new U.default.Flag,enableBatchTDC:new U.default.Flag,enableBatchHeadSpin:new U.default.Flag,clearRunnerFileCache:new U.default.Flag,forceTurboModeIfNeeded:new U.default.Flag,redisSlotManager:new U.default.Flag,tunnelBinaryNewVersion:new U.default.Flag(!1),encryptedCredentials:new U.default.Flag,computePackagePathFromPackageJsonExports:new U.default.Flag,sendExtensionOnEdgeNonLinux:new U.default.Flag,enableAppium2pCloudy:new U.default.Flag,reuseCliPkgInstallFolder:new U.default.Flag,getPublicIpFrom3rdPartyServices:new U.default.Flag,chromedriverCdnBinariesUrl:new U.default.RoxString(""),sfdcHybridCompany:new U.default.Flag,allowFixingAppIdStructure:new U.default.Flag,enableAppium2BrowserStack:new U.default.Flag,increaseTDCRequestTimeout:new U.default.Flag,accessTokenExpiryMargin:new U.default.RoxNumber(300*1e3),useMV3Extension:new U.default.Flag,testimHeadlessExtensionDownloadUrl:new U.default.RoxString("",[]),applyMobileRestrictionFromDate:new U.default.RoxNumber(17235072e5),removeMobileTrialRestrictions:new U.default.Flag,appiumConnectionRetryCount:new U.default.RoxNumber(0),appiumConnectionRequestTimeout:new U.default.RoxNumber(12e4),DFBrowserVersion:new U.default.RoxString("latest",["latest","latest-1","latest-2"]),DFAcceptInsecureOrigins:new U.default.RoxString("http://jsbin.testim.io"),enableFixForCustomExtensionForLT:new U.default.Flag(!1),enableTestPlanAggregation:new U.default.Flag},U.default.register("default",this.flags)}setProjectId(e){U.default.setCustomStringProperty("projectId",e)}setProjectType(e){U.default.setCustomStringProperty("projectType",e)}setCompanyProductType(e){U.default.setCustomStringProperty("productType",e)}setCompanyId(e){U.default.setCustomStringProperty("companyId",e)}setPlanType(e){U.default.setCustomStringProperty("planType",e)}setIsPOC(e){U.default.setCustomBooleanProperty("isPOC",e)}setIsStartUp(e){U.default.setCustomBooleanProperty("isStartUp",e)}setRunnerMode(e){U.default.setCustomStringProperty("runnerMode",e)}setRunnerEnvironment(e){U.default.setCustomStringProperty("runnerEnvironment",e)}async fetch({proxy:e}){let t,r,n;if(!Ww)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,l)=>(0,Mm.default)(a,{...l,agent:o}),n=function(a){return new Um.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Gw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(vd,i),Vw).catch(o=>Fm.error("failed to get feature flag status",o))}},_=new zc});var Wm={};H(Wm,{install:()=>qw,isReady:()=>Kw,start:()=>zw});var Bm,jm,$m,Jc,Kc,Hw,qw,zw,Kw,Vm=v(()=>{"use strict";Bm=I(require("fkill")),jm=I(require("p-retry"));Zr();Ve();F();en();ue();$m="chromedriver",Jc=9515,Kc=`http://localhost:${Jc}/wd/hub`,Hw=[`--port=${Jc}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],qw=async()=>{let s=_.flags.chromedriverCdnBinariesUrl.getValue(),e=Oe(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await $i(gt(),`${$m} --detect_chromedriver_version ${e}`)},zw=async()=>{process.env.NODE_OPTIONS="",await(0,Bm.default)(`:${Jc}`,{silent:!0}),await Xt($m).start(Hw,!0)},Kw=async({chromeBinaryLocation:s})=>{await(0,jm.default)(async()=>{var n;let e=await Te(`${Kc}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await We({url:`${Kc}/session`,body:{desiredCapabilities:{browserName:"chrome",chromeOptions:t}},headers:{"Content-Type":"application/json"}});if(!r||r.status!==0||!r.sessionId)throw new Error("create session failed");await Ws(`${Kc}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var rn={};H(rn,{getSessionPlayerFolder:()=>Zc,prepareChromeDriver:()=>tn,prepareCustomExtension:()=>Xc,prepareExtension:()=>Qc,preparePlayer:()=>br});async function Xc(s,e=!1){if(!s)return;if(Oe(s)){let n=es.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await Jw(s)>Yc&&!e)throw new C(Gm);return await Ke(s,n),n}let t=es.resolve(s);if(!qm.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Rc(t)>Yc&&!e)throw new C(Gm);return t}async function Jw(s){let e=(Ve(),He(ze));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Vi.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function Qc(s){Vi.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Ii(t)}));return Bt(()=>se(e,({location:t,path:r})=>Ri(t,r)),"prepareExtension",Km,e)()}async function tn(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Vm(),Wm));try{await i.install(),await i.start(),t||await i.isReady(e),n.succeed("Chrome Driver initiated successfully")}catch(o){let a="Failed to initiate Chrome Driver";throw o instanceof Vr||(Vi.error(a,{...s,...Fi(),error:(0,zm.serializeError)(o)}),console.log(`
11
11
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
12
12
  2. If Chrome is installed, please verify it's binary directory:
13
13
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
14
14
  - exists in your PATH environment variables.
15
15
  3. Try adding --chrome-binary-location flag to Testim CLI specifying the exact location of chrome binary in your computer (e.g on Windows "C:/Program Files/Google/Chrome/Application/chrome.exe").
16
16
  4. You can always use a standalone Selenium grid and providing it's details with the --host and --port flags (see https://www.npmjs.com/package/selenium-standalone)`)),n.fail(a),o}}async function Yw(){let s=Ht==="staging"?`${Ds}/Staging-LATEST_VERSION`:`${Ms}/extension/sessionPlayer_LATEST_RELEASE`;return(await Mt(s)).body.toString("utf8")}function Xw(){return`${Ds}/dev-sessionPlayer.zip`}async function Qw(s,e){if(!Oe(s)||Oe(s)&&e||$e)return s;let t=await Yw();return`${s}-${t}${Ht==="staging"?".zip":""}`}function Zc(){let s=gt();return es.resolve(s,"testim-bin")}function Zw(){let s=Zc();return es.resolve(s,"sessionPlayer.zip")}async function Jm(s,e,t=!1){try{return await Ri(s,e),await it(e,Zc())}catch(r){if(t)throw r;return await Jm(s,e,!0)}}async function br(s,e){Vi.info("prepare player",{location:s,canary:e});let t=Zw();return Bt(async()=>{let r=Ht==="development"?Xw():await Qw(s,e);return await Jm(r,t),{}},"preparePlayer",Km,[s,e,t])()}var Hm,qm,es,zm,Vi,Km,Yc,Gm,sn=v(()=>{"use strict";Hm=I(require("ms")),qm=I(require("node:fs")),es=I(require("node:path"));de();Yt();zm=require("serialize-error");W();$c();Y();F();Vi=P("prepare runner and testim start"),Km=(0,Hm.default)("0.5 day"),Yc=16,Gm=`The size of the custom extension is more than ${Yc}MB`});function ev(){let s=nn.type().toLowerCase();return s==="darwin"?nn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?nn.arch()==="x64"?"win64":"win32":"linux"}async function Hi(){let s=ev(),e="https://storage.googleapis.com/chromium-browser-snapshots",t={linux:"Linux_x64",mac:"Mac",mac_arm:"Mac_Arm",win32:"Win",win64:"Win_x64"};if(!(s in t))throw new C(`Unsupported platform: ${s}`);let r=parseInt(on,10)>591479?"chrome-win":"chrome-win32",n={linux:"chrome-linux",mac:"chrome-mac",mac_arm:"chrome-mac",win32:r,win64:r},i={linux:"chrome",mac:"Chromium.app/Contents/MacOS/Chromium",mac_arm:"Chromium.app/Contents/MacOS/Chromium",win32:"chrome.exe",win64:"chrome.exe"},o=`${e}/${t[s]}/${on}/${n[s]}.zip`,a=Gi.join(el,n[s]),l=`${a}.zip`,c=Gi.join(a,i[s]);if(await ye(c))return c;if(!await ye(l)){let m=(0,tl.default)("Downloading Chromium").start();try{await Ym.promises.mkdir(el),await Ke(o,l)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw m.fail(f),new Error(f)}m.succeed()}let d=(0,tl.default)("Extracting Chromium").start();try{await it(l,el)}catch(m){let u=`Failed to extract Chromium: ${m.message}`;throw d.fail(u),new Error(u)}return d.succeed(),c}var Ym,nn,Gi,tl,on,el,rl=v(()=>{"use strict";Ym=I(require("fs")),nn=I(require("os")),Gi=I(require("path")),tl=I(require("ora"));Y();F();on="1000968",el=Gi.join(Ft,`chrome-${on}`)});async function Zm(s,e){return Tr=s,ol=e,await sl()}function ef(s,e){Tr=e.projectId,ol=e.token,an=e.userAccessKey,ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,Xm=e.publicIp,Qm=e.initializedFromCache}function rv(s=Tr,e=ol){return Bt(()=>(cn.info("request to get cli token from server"),We({url:`${he}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",tv*10,{projectId:s,token:e})()}async function sv(){cn.info("request to refresh JWT cli token from server");let s=await We({url:`${he}/auth/refreshToken`,body:{token:ot,refreshToken:un}});return ot=s.token,ln=al(ot),s.refreshToken&&(un=s.refreshToken),ot}async function sl(){try{let s=await rv();return cn.info("successfully get cli token from server"),ot=s.token,ln=al(ot),un=s.refreshToken,nl=s.ngrokToken,il=s.isNgrokWhitelisted,ot}catch(s){throw s.message.includes("Unauthorized")?new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file."):(cn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Tr}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function al(s){return require("jsonwebtoken").decode(s).exp*1e3}async function At(){if(!ln)return sl();let s=_.flags.accessTokenExpiryMargin.getValue();if(ln<Date.now()+4*s)try{return await sv()}catch(e){return cn.error("failed to refresh token, executing fallback",e),sl()}return ot}function qi(){return un}function wr(){return ot?{uid:require("jsonwebtoken").decode(ot).id,ngrokToken:nl,isNgrokWhitelisted:il}:{}}async function zi(){if(!an||!Tr)return;if(await cl({userAccessKey:an,projectId:Tr}))return an;let e=`user access key "${an}" is invalid for project "${Tr}"`;throw new C(e)}function Ki(){return Xm}function Ji(){return Qm}var cn,ot,ln,un,nl,il,Tr,ol,an,Xm,Qm,tv,at=v(()=>{"use strict";de();Ve();Yt();Y();W();ge();ue();cn=P("testim-custom-token"),Tr=null,ol=null,tv=5*60*1e3});function nv(s){if(s.protocol)return s.protocol;if([L.TESTIM_PRIVATE,L.TESTIM,L.BROWSERSTACK,L.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([L.TESTIM_ENTERPRISE,L.TESTIM_LAMBDATEST,L.DEVICE_FARM].includes(s.type)){let e=tf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function iv(s){let e=tf.exec(s);return e==null?void 0:e[3]}function Xi(s){var S,E,A,D,j,R,x,O,B,G,z;let e=s&&iv(s.host),t=s.port,r=s.path,n=s&&nv(s),i=s.token,o=s.slotId,a=(S=s.hybrid)==null?void 0:S.tunnel,l=(E=s.external)==null?void 0:E.user,c=(A=s.external)==null?void 0:A.key,d=s.type,m=d===L.HYBRID?a&&((R=(j=(D=s.hybrid)==null?void 0:D.external)==null?void 0:j[s.hybrid.tunnel])==null?void 0:R.user):l,u=d===L.HYBRID?a&&((B=(O=(x=s.hybrid)==null?void 0:x.external)==null?void 0:O[s.hybrid.tunnel])==null?void 0:B.key):c,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(z=s.mobileTokens)==null?void 0:z.iosToken,w=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:l,key:c,type:d,name:f,provider:g,tunnelUser:m,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:w,isSupportGrid:b}}async function av(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(l){throw Xe.error("failed to get grid",{projectId:s,companyId:e,err:l}),new Error(ht.UNKNOWN)}if(Xe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Xe.error("invalid response - get grid",{res:o}),new Error(ht.UNKNOWN);if(o.status==="success"){if(o.grid.mode==="local")return{mode:"local"};((a=o.grid)==null?void 0:a.mode)==="custom"&&Object.assign(o.grid,of(n));let l=Xi(o.grid);return ov(t,e,l.gridId,l.slotId,r,l.isSupportGrid),l}throw o.code==="not-found"?new rt(ht.NOT_FOUND):o.code==="no-available-slot"?new zt(`Failed to run test on ${r} - concurrency limit reached`):(Xe.error("invalid code error response - get grid",{res:o}),new rt(ht.UNKNOWN))}function sf(s){return fl(s)}async function nf(s,e,t){let n=(t||await sf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return Xi(n)}async function cv(s,e,t){let n=(t||await sf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return Xi(n)}async function ll(s,e){let t=pn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete pn[s],!a){if(!r){Xe.warn("failed to find grid slot id",{projectId:e});return}Xe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await pl(o,e,r,n,i)}catch(l){Xe.error("failed to release slot",{projectId:e,err:l})}}}async function lv(s){let e=Object.values(pn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Xe.info("keep alive worker slots",{projectId:s,slots:e});try{await ul(s,e)}catch(t){Xe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function uv(s){rf=global.setInterval(lv,1e4,s)}async function pv(s){let e=Object.keys(pn);if(e.length){Xe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>ll(Number(t),s))}catch(t){Xe.error("failed to release all slots",{err:t,projectId:s})}}}async function dv(s){await pv(s),clearInterval(rf)}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 of(s){let t=(()=>Yi.isEmpty(s.testobjectSauce)?Yi.isEmpty(s.saucelabs)?Yi.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=mv(t,s),l=fv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:l,key:a,gridId:re()}}async function af(s,e){let t=s.company.companyId;return await nf(t,e.gridId,s.allGrids)}async function cf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:l}=s;if(n||o||i)return{mode:"local"};if(r)return of(s);let c=t==null?void 0:t.companyId;if(a)return nf(c,a,e);if(l)return cv(c,l,e);if(Ks(s)||s.tunnelOnlyMode){Xe.info("skipping getting grid, as it is set on test plan",{companyId:c});return}throw new rt("Missing host or grid configuration")}async function lf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:l,localTmaUrl:c,useLocalChromeDriver:d,useChromeLauncher:m,company:u}=t,f=Boolean(d||m||c),h=u==null?void 0:u.companyId;return av(o,h,r,s,t,()=>ml({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:l,gridName:a,host:i,testResultId:n}))}var Yi,Xe,pn,tf,rf,ov,dn,uf,ts=v(()=>{"use strict";Yi=I(require("lodash"));ge();W();F();ie();Y();Xe=P("grid-service"),pn={},tf=/(^(https?):\/{2})?(.*)/,rf=null;ov=(s,e,t,r,n,i)=>{pn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};dn={start:uv,end:dv};uf=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,l=s.browser||t.browserValue,c=Boolean(s.tunnel),{maxRetries:d,currentRetry:m}=n;if(!o||!a||((a===L.TESTIM_LAMBDATEST||a===L.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e)),a!==L.HYBRID||!i||!l||!d||!m))return e;let u=await dl({companyId:i,gridId:o,maxRetries:d,currentRetry:m,browser:l,usingTunnel:c});Xe.info("handling hybrid grid",{response:u,companyId:i});let f=Xi({...e,...u.connectionDetails,provider:u.provider});return u.provider!=="lambdatest"&&((g=r.disable)==null||g.call(r)),u.provider==="lambdatest"&&await((y=r.enableIfNeeded)==null?void 0:y.call(r,f)),f}});function fn(){return Qi||"master"}function pf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){Qi="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){Qi=s.branch||s;return}Qi=e?"master":void 0}var Qi,gl=v(()=>{"use strict";Y()});function hf(s){$e||(s!=null&&s.userId||(s={anonymousId:gf}),ff.identify(s))}function yt(s,e){return gn("ci",s,e)}function gn(s,e,t){if($e)return;let r=s?{userId:s}:{anonymousId:gf};ff.track(Object.assign(r,{event:e,properties:t}))}var mf,ff,gf,rs=v(()=>{"use strict";de();mf=require("@segment/analytics-node"),ff=new mf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1}),gf=require("crypto").randomBytes(20).toString("hex")});var yf={};H(yf,{isCi:()=>ss});var ss,Zi=v(()=>{"use strict";ss=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Tf(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function wf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:c,user:d,lightweightMode:m,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Tf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:l,source:bf(c,d),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},m);yt("test-run-ci",y)}function vf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,source:d,user:m,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let w=Tf({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:l,companyPlan:c,mockNetworkEnabled:n.wasMockNetworkActivated,source:bf(d,m),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){yt("test-run-ci-success",w);return}yt("test-run-ci-fail",{...w,failureReason:n.failureReason})}catch(w){f.error("failed to update test end analytics",{err:w})}}function Sf(s){yt("batch-run-ci",s)}var bf,hl=v(()=>{"use strict";rs();Zi();bf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ss&&e?"ci-with-user":ss?"ci":e?"cli-with-user":s});var yn,yl,gv,bl,hv,eo,to,ro,so,no,io=v(()=>{"use strict";F();ie();yn=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===me.FAILED},yl=s=>{let{status:e}=s;return e===me.ABORTED},gv=s=>{let{status:e}=s;return e===me.PASSED},bl=s=>s.runnerStatus===Ac.SKIPPED,hv=s=>s.testStatus===Je.EVALUATING,eo=(s,e)=>Object.values(s).filter(t=>{var r,n;return bl(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,to=s=>Object.values(s).filter(e=>yn(e)&&hv(e)).length,ro=s=>Object.values(s).filter(yn),so=s=>Object.values(s).filter(gv),no=s=>Object.values(s).filter(yl)});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 Tl,oo,yv,ao,If=v(()=>{"use strict";Tl=I(require("lodash"));W();io();oo=P("debug-reporter"),yv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],ao=class{constructor(e){this.options=e}onTestStarted(e,t){oo.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,i=r.host,o=r.gridId,a=r.type,l=r.failedGetBrowserAttempts;oo.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:i,failedGetBrowserAttempts:l,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{...Tl.default.omit(this.options,yv),company:Tl.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let l=bv(process.argv);oo.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:l})}onTestPlanFinished(e,t,r,n,i){let o=so(e).length,a=Object.keys(e).length-o;oo.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var wl,Ct,bn=v(()=>{"use strict";ie();wl=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===L.DEVICE_FARM}},Ct=new wl});var Sl={};H(Sl,{Reporter:()=>Tv});var Zt,Tn,vr,co,Rf,vl,Tv,El=v(()=>{"use strict";Zt=I(require("chalk")),Tn=I(require("lodash"));F();ie();bn();io();vr={success:Zt.default.green,warn:Zt.default.yellow,error:Zt.default.red},{CLI_MODE:co}=Ut,Rf="device",vl=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: ${Zt.default.underline(qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse))}`;console.log(this.toWorkerIdPrefix(t),`Test "${e.name}" started ${r} ${n}`.trim())}onTestFinished(e,t){let r=e.success?me.PASSED:me.FAILED,n=`(${e.testId})`,i=vr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Ci(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=qe(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(vr.error("Failed runs are:")),console.log(vr.error(t.join(`
17
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ro(e),a=so(e),l=no(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=to(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${eo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ci(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Tn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var w;let g=(w=f.testData)!=null&&w.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===co.APPIUM?Rf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===co.APPIUM?Rf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.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,i=this.options.mode===co.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} 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 o=this.options.mode===co.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Tv=vl});var xl={};H(xl,{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 Sv(s){return`${s.visitedUrlsJson||""}`}async function Ev(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:wv(u),classname:n,time:Nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(yn(u)||yl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=yn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return bl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=vv(u),h["visited-urls-json"]=Sv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=eo(y,i);let b=to(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return ro(u).length+no(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Rl.Builder().buildObject(m)}catch(u){return Iv(u)}}function Iv(s){let e=new Rl.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 Rl,xf,Il,Rv,Al=v(()=>{"use strict";Rl=I(require("xml2js"));F();xf=require("fs");bn();io();Il=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 Ev(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await xf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Rv=Il});var Af={};H(Af,{Reporter:()=>xv});function ns(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 Cl,Pl,xv,Cf=v(()=>{"use strict";W();Cl=P("team-city-reporter");Pl=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 ns(n)}onTestStarted(e,t,r,n){if(r){Cl.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Cl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Cl.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='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},xv=Pl});var Pf={};H(Pf,{Reporter:()=>Av});var kl,Av,kf=v(()=>{"use strict";kl=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,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Av=kl});function uo(s){let{platform:e}=process;e==="win32"?(0,lo.exec)(`start chrome ${s}`):e==="darwin"?(0,lo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,lo.exec)(`google-chrome ${s}`)}var lo,Ol=v(()=>{"use strict";lo=require("child_process")});var Of={};H(Of,{Reporter:()=>Cv});var _l,Cv,_f=v(()=>{"use strict";F();Ol();_l=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return uo(t)}},Cv=_l});var Ll,Q,Pt=v(()=>{"use strict";If();Ll=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 ao(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(El(),Sl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Al(),xl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Cf(),Af)),r.includes("console")&&Promise.resolve().then(()=>(El(),Sl)),r.includes("junit")&&Promise.resolve().then(()=>(Al(),xl)),r.includes("json")&&Promise.resolve().then(()=>(kf(),Pf)),r.includes("chrome")&&Promise.resolve().then(()=>(_f(),Of))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new Ll});async function Dl(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Ml(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function Pv(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Fl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function kv(s,e){Lf=global.setInterval(()=>Pv(s,e),1e4)}async function Ov(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Dl(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function _v(s,e){await Ov(s,e),clearInterval(Lf)}async function Nf(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Df(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function Mf(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Df(r,n),await Ul(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,Lf,Df,wn,os=v(()=>{"use strict";ge();W();F();ie();Y();ct=P("slot-service"),is={},Lf=null,Df=(s,e)=>{is[s]=e};wn={start:kv,end:_v}});function Ff(s,e=process){async function t(r){await le(se(Uf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Sn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Sn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Sn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){Uf.push(s)}var Sn,Uf,En=v(()=>{"use strict";W();F();Sn=P("process-handler"),Uf=[]});var Wf={};H(Wf,{installAllLazyDependencies:()=>Mv,lazyRequire:()=>lt});async function lt(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,Bf.default)(`Installing ${s} before first usage...`).start());try{let n=await Nv(s);return r&&r.succeed(),n}catch(n){Dv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=$f(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function Nv(s){return cs.has(s)||(cs.set(s,jf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function jf(s){let e=Gc(s);if(e)return e;let t=$f(s),r=`${s}@${t}`;return await $i(gt(),r),Xt(s)}async function Mv(){let s=Object.keys(nc);for(let e of s)await jf(e)}function $f(s){let e=Object.entries(nc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Bf,Dv,cs,In=v(()=>{"use strict";Bf=I(require("ora"));Zr();W();F();mi();en();Dv=P("lazy-require"),cs=new Map});var Vf,po,Gf=v(()=>{"use strict";Vf=require("istanbul-lib-report"),po=class extends Vf.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 Hf,qf,zf,Rn,bt,Kf,mo,Bl,Jf,Uv,Yf,Xf,Fv,Bv,Qf,jv,$v,Wv,Vv,Gv,Zf,eg=v(()=>{"use strict";Hf=I(require("ora")),qf=I(require("dayjs")),zf=I(require("test-exclude")),Rn=I(require("fs")),bt=I(require("path")),Kf=I(require("istanbul-reports")),mo=I(require("istanbul-lib-report"));ge();Y();F();W();In();Gf();Bl=P("test-run-status"),Jf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Uv=s=>!!Jf(s).search,Yf=s=>s?Jf(s).pathname.substring(1):"",Xf=(s,e)=>{let t=Yf(e);return!new zf.default({relativePath:!1,include:s}).shouldInstrument(t)},Fv=s=>s.substring(0,s.indexOf("?")),Bv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Qf=(s,e)=>`${bt.resolve(s,Yf(e))}.js`,jv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(Xf(r,o))return;let l=Qf(e,o);await Rn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,i.sourcesContent[a])})})},$v={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Uv(e)&&(e=Fv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Wv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=mo.createContext({dir:t,coverageMap:e,watermarks:mo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Qf(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:$v}),Kf.create(a,l).execute(o)}),i},Vv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Xf(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Gv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await $l(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await xn(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await jl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bl.info("start js coverage process");let n=(0,Hf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),Gv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await Bv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await Vv(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await jv(s,o,u);let f=await Wv(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bl.error(c,{err:l})}}});var tg={};H(tg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,Hv,Sr,ls=v(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Hv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(Hv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();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`,Oi(r,50)],[`${t}_P95`,Oi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ig={};H(ig,{initServer:()=>Kv,mapFilesToLocalDrive:()=>Vl});function Vl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,fo[t.id]?{screenshot:fo[t.id]}:{})),Object.keys(go).forEach(t=>{s.assets||={},s.assets[ng[t]]=go[t]}),s.assets||={},s.assets.screenshots=Object.values(fo)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Kv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:qv;await Wl.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await Wl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,sg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(fo[d.stepId]=l.file.path),d.testResultId&&zv.includes(d.subType)&&(go[d.subType]||=[],go[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var Wl,rg,An,sg,qv,fo,go,ng,zv,Gl=v(()=>{"use strict";Wl=I(require("fs")),rg=I(require("os")),An=I(require("path")),sg=I(require("express"));Y();In();qv=An.join(rg.tmpdir(),"testim/rca/"),fo={},go={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},zv=Object.keys(ng)});var er,Hl,ho,og=v(()=>{"use strict";er=I(require("lodash"));F();W();Hl=P("override-test-data-builder"),ho=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Hl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Hl.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}Hl.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 er.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 i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,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 yo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Er,Qe,Jv,Yv,Xv,Qv,bo,ag=v(()=>{"use strict";Er=I(require("lodash"));F();ie();ts();os();ge();Y();W();Pt();En();eg();ls();Gl();de();ue();og();bn();Qe=P("test-run-status"),Jv=fr(),Yv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Xv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Qv=tt();bo=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 Sr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:hi||t.parallel||1,browser:i,gitBranch:Jv,gitCommit:Yv,gitRepoUrl:Xv,runnerVersion:Qv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Kl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await wo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await yo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Mc();t.isOverThreshold&&Qe.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Vl(o,Qe),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await yo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Ir(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 Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=kc;return e&&(n=i),Hr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Js(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await wn.end(r,t),e==="mongo"&&await dn.end(t)}async executionStart(e,t,r,n,i){Qe.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),To("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await yo(o.beforeSuite,m),f=new ho(u,Er.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let w=async()=>{let b=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await wo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=zl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(A=>Qe.error(A)),E};try{await w()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){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 d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Je.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await yo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Zf(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await To("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Qe.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ql(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Rd:Ms}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(Zv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function cg(s){let{chrome:e}=Jl(s,!1);return e}function vo(s){let e=Ht==="staging"?`${Ds}/staging-sessionPlayer`:`${Ms}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Zv,Cn=v(()=>{"use strict";de();ue();W();Zv=P("runOptionsUtils")});function ug(s,e){if(e){if(!iS.has(e)){Pn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var pg,dg,jt,mg,fg,gg,So,hg,Pn,eS,tS,kn,rS,sS,nS,ne,iS,Eo=v(()=>{"use strict";pg=I(require("ms")),dg=I(require("p-retry")),jt=I(require("node:os")),mg=I(require("portfinder")),fg=I(require("node:child_process"));F();Ve();ge();gg=I(require("node:fs")),So=I(require("node:fs/promises")),hg=require("node:path");Y();W();Cn();ie();ue();F();Pn=P("lambdatestService"),eS="https://downloads.lambdatest.com/tunnel/v3",tS={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"},kn=`${jt.tmpdir()}/LT`,rS=`${kn}/LT`,sS=(0,pg.default)("15m"),nS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Yl(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?sS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(rS))return;let t=tS[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${kn}.zip`;await Ke(`${eS}/${t}`,r),await it(r,kn)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await So.access(e,gg.constants.X_OK);return}catch{}try{await So.chmod(e,"777")}catch(r){throw Pn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await mg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,hg.join)(kn,"LT")),ne.tunnel=fg.spawn("./LT",c,{cwd:kn});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,dg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Pn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Pn.error("Failed to start LT tunnel",{err:u}),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,i,o,a,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:ug(n,a==null?void 0:a.os)||ug(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??nS,version:t==="safari"&&((w=o==null?void 0:o.lt)==null?void 0:w.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||Pn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},iS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function aS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Ig(s){return wg.readFileSync(s,{encoding:"base64"})}function Rg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=Ig(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Zl(r)} current extension count: ${e.length}`),e.push(r)}}function xg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Io.basename(i));let l=Io.join(process.cwd(),a),c=Ig(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Zl(c)} current extension count: ${e.length}`),e.push(c)}function cS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...Eg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Xl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Xl.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,"profile.password_manager_leak_detection":!1},w3c:!0};if(Ql(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Ql(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Xl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Cc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Rg(r,c,o),a===q.EXTENSION&&xg(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function uS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":bg.join(","),"browser.helperApps.neverAsk.openFile":bg.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.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function us(s){return`${s.width}x${s.height}`}function hS(s){let{platform:e}=s;if(!e)return us(Tg);let t=e.split(" ")[1];return e.startsWith("Windows")&&gS.has(t)?us(dS):e==="Linux"?us(pS):e.startsWith("macOS")?us(mS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?fS:Tg)}function yS(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(n["sauce:options"].screenResolution=hS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,Sg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function bS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function TS(s){return s.perfecto?s.perfecto:{}}function wS(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 vS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=tc(i,o)),a}function Ro(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...Eg],j={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&xg(t,A,D,null,c),Rg(o,A,c),{logLevel:yg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=vS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:yg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ql(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,yS(t,r,n),bS(t,r,n),TS(t),wS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=lS(h,t,n,o,i,T,c,d);break;case"firefox":h=uS(h,t,c);break;case"safari":case"safari technology preview":h=aS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(oS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var wg,Io,vg,ut,Sg,ps,yg,Xl,Eg,Zl,Ql,oS,lS,bg,Tg,pS,dS,mS,fS,gS,eu=v(()=>{"use strict";wg=I(require("node:fs")),Io=I(require("node:path")),vg=I(require("node:crypto")),ut=I(require("lodash"));F();de();W();ue();ie();Eo();Sg=require("lodash"),ps=P("testim-desired-capabilities-builder"),yg=gi?"debug":"silent",Xl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Eg=["--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"],Zl=(...s)=>vg.createHash("sha256").update(s.join("")).digest("hex"),Ql=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",oS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};lS=ut.memoize(cS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Zl(o,a,l,r,c,i)}),bg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Tg={width:1920,height:1080},pS={width:1920,height:1200},dS={width:2560,height:1600},mS={width:2360,height:1770},fS={width:2048,height:1536},gS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,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/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Cg(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 tu=v(()=>{"use strict"});function ru(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return ru(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var Pg=v(()=>{"use strict"});var kg,Og,$t,SS,ES,xo,_g=v(()=>{"use strict";kg=I(require("promise-queue")),Og=I(require("webdriverio"));de();je();F();W();jr();Pg();tu();ls();$t=P("WebDriverApi"),SS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},ES={implicit:0,pageLoad:1,script:2},xo=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,i=t?t.toString().slice(0,2e3):"";throw $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),ic!==void 0&&(e=ic);let t=1/0;this.queue=new kg.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(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Og.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;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:i.message,ready:i.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 TypeError("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},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();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 o()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("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),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ue(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}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 i;return(i=this.client)==null?void 0:i.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(ru,{ELEMENT:e,[Gt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(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(Cg(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 i=[];return i[ES[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ue(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};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(SS);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.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 i;let t=await((i=this.client)==null?void 0:i.$(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 i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}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 i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ue(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,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 tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>nu});var Ao,nu,su,Z,we=v(()=>{"use strict";Ao=require("path");W();nu={playerPath:void 0},Z=()=>{if(su)return su;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(sn(),He(rn)),t=e(),r=nu.playerPath?(0,Ao.resolve)(nu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ao.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),su=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Bd),n}});var Lg={};H(Lg,{doubleClick:()=>IS});var IS,Dg=v(()=>{"use strict";IS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,S){return S>w&&S<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>RS});function RS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var _n=v(()=>{"use strict"});var Bg={};H(Bg,{WebDriver:()=>Ar});async function PS(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 AS(r):void 0}catch(r){Fe.info("Error getting cdpAddress",r);return}}var ds,Ug,Fg,Fe,rr,xS,Ng,AS,Rr,CS,Mg,xr,Ar,Ln=v(()=>{"use strict";ds=I(require("lodash"));F();je();eu();Ug=I(require("p-retry")),Fg=I(require("ua-parser-js"));jr();W();tu();_g();Y();ue();ls();Fe=P("webdriver"),[rr,xS]=[0,2],{extractElementId:Ng,getCdpAddressForHost:AS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,CS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,Mg=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends xo{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))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Ro({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await PS(O),M("after getCdpAddress in webdriver.js init"),Fe.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Fe.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new wi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Fe.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Fe.warn("failed to click on alert",{err:l}));return}if(Fe.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Fe.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Ng(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 vi:r}}async getElement(t){var i;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(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
17
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ro(e),a=so(e),l=no(e),c=a.length,d=l.length,m=o.length,u="",f="";if(Ct.isTestStatusEnabled){let w=to(e);u=` FAILED-EVALUATING: ${w}`,m-=w,f=` SKIPPED: ${eo(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=vr[m?"error":"success"],T=`PASSED: ${c} FAILED: ${m}${u} ABORTED: ${d}${f} Duration: ${Ci(r)}`;h.trim()===""||h.trim()==="Anonymous"?g=`Tests completed. ${T} (Execution ID: ${n})`:g=`Test plan${h} completed ${T} (${n})`,this.printWorkerDivider(),console.log(y(g)),this.printWorkerDivider(),this.printAllFailedTests(o)}buildTestPlanName(e,t){let r=Tn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Tn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Tn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Tn.isEmpty(this.options.testId)?"":`Test Id: ${this.options.testId}`,a=[i,n,r,o].filter(Boolean).join(", ");return e?` anonymous (${a})`:` '${t}'`}onTestPlanStarted(e,t,r,n,i,o,a){let l=u=>{u.forEach((f,h)=>{var w;let g=(w=f.testData)!=null&&w.index?`- ${f.testData.index} / ${f.testData.total} Data set`:"",y=`(${f.testId})`,T="";f.testOptimization?T=` [${f.testOptimization.reason}]`:Ye(f,this.options)&&(T="-quarantine"),console.log(" ",h+1,":",`${f.name}${T}`,y,g)})},c=a?`config '${a}'`:"default configs",d=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",m=`${c}, Project: ${this.options.project}, Branch: ${this.branchToUse}${d}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${m} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),l(e)),console.log("Test list:"),l(t),r.length>0&&(console.log("After all:"),l(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===co.APPIUM?Rf:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${Zt.default.underline(n)} slot from ${Zt.default.underline(r)}`)}onGetSession(e,t,r){let n=r===co.APPIUM?Rf:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${Zt.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,i=this.options.mode===co.APPIUM?"device":"browser";if(n)console.log(vr.warn(this.toWorkerIdPrefix(e),`It is taking us some time to get a ${i} 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 o=this.options.mode===co.APPIUM?"Appium":"Selenium";console.log(vr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Tv=vl});var xl={};H(xl,{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 Sv(s){return`${s.visitedUrlsJson||""}`}async function Ev(s,e,t,r,n,i){function o(u){let f=qe(s,t,u.testId,u.resultId,r),h={$:{name:wv(u),classname:n,time:Nc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(yn(u)||yl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=yn(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return bl(u)&&Ye(u,i)&&Ct.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=vv(u),h["visited-urls-json"]=Sv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},w={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:c(y),failures:d(y),timestamp:l(e)};if(Ct.isTestStatusEnabled){w.skipped=eo(y,i);let b=to(y);w.failures-=b,w["failure-evaluating"]=b}return{$:w,testcase:Object.keys(y).map(b=>o(y[b]))}}function l(u){let f=Object.keys(u).map(g=>u[g].startTime),h=Math.min.apply(null,f);return h?new Date(h).toISOString():new Date().toISOString()}function c(u){return Object.keys(u).length}function d(u){return ro(u).length+no(u).length}let m={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Rl.Builder().buildObject(m)}catch(u){return Iv(u)}}function Iv(s){let e=new Rl.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 Rl,xf,Il,Rv,Al=v(()=>{"use strict";Rl=I(require("xml2js"));F();xf=require("fs");bn();io();Il=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 Ev(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await xf.promises.writeFile(t,n),console.log("JUnit XML file saved to",t),e}catch(i){return console.error("could not save report file",t,i),e}}async onAllTestPlansFinished(e){await this.createResultsReport(e)}};Rv=Il});var Af={};H(Af,{Reporter:()=>xv});function ns(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 Cl,Pl,xv,Cf=v(()=>{"use strict";W();Cl=P("team-city-reporter");Pl=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 ns(n)}onTestStarted(e,t,r,n){if(r){Cl.debug("skip report test started because is rerun");return}let i=this.getPrintName(e);console.log(`##teamcity[testStarted name='${i}' captureStandardOutput='true' flowId='${n}']`)}onTestFailed(e,t,r,n,i,o){if(i){Cl.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ns(t)}' details='${ns(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){Cl.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='${ns(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ns(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ns(t)}']`)}},xv=Pl});var Pf={};H(Pf,{Reporter:()=>Av});var kl,Av,kf=v(()=>{"use strict";kl=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,i){let o={name:"suiteStarted",data:{projectId:this.options.project,executionId:i}};console.log(JSON.stringify(o))}onTestPlanFinished(e){console.log(JSON.stringify({name:"suiteFinished",data:{testResults:e}}))}},Av=kl});function uo(s){let{platform:e}=process;e==="win32"?(0,lo.exec)(`start chrome ${s}`):e==="darwin"?(0,lo.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,lo.exec)(`google-chrome ${s}`)}var lo,Ol=v(()=>{"use strict";lo=require("child_process")});var Of={};H(Of,{Reporter:()=>Cv});var _l,Cv,_f=v(()=>{"use strict";F();Ol();_l=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=qe(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return uo(t)}},Cv=_l});var Ll,Q,Pt=v(()=>{"use strict";If();Ll=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 ao(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(El(),Sl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(Al(),xl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Cf(),Af)),r.includes("console")&&Promise.resolve().then(()=>(El(),Sl)),r.includes("junit")&&Promise.resolve().then(()=>(Al(),xl)),r.includes("json")&&Promise.resolve().then(()=>(kf(),Pf)),r.includes("chrome")&&Promise.resolve().then(()=>(_f(),Of))])).forEach(i=>{i&&this.reporters.push(new i.Reporter(e,t))})}onTestPlanFinishedMutator(e,t,r,n,i){let o={};o=e;let a=Date.now()-(r||0);return[o,t,a,n,i]}onAllTestPlansFinishedMutator(e){return[e]}generateHook(e,t){return async(...r)=>{var i;let n=t==null?void 0:t(...r);for(let o of this.reporters)await((i=o[e])==null?void 0:i.call(o,...n||r))}}},Q=new Ll});async function Dl(s,e,t){let r=is[s];if(!r)return;let{slotId:n}=r;if(delete is[s],!n){ct.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ct.info("release slot id",{companyId:e,slotId:n});try{await Ml(e,t,n)}catch(i){ct.error("failed to release slot",{companyId:e,err:i})}}async function Pv(s,e){let t=Object.values(is).filter(Boolean);if(t.length!==0){ct.info("keep alive worker slots",{companyId:s,slots:t});try{await Fl(s,e,t)}catch(r){ct.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function kv(s,e){Lf=global.setInterval(()=>Pv(s,e),1e4)}async function Ov(s,e){let t=Object.keys(is);if(t.length){ct.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>Dl(Number(r),s,e))}catch(r){ct.error("failed to release all slots",{err:r,companyId:s})}}}async function _v(s,e){await Ov(s,e),clearInterval(Lf)}async function Nf(s,e,t){let r;try{r=await Nl(s,e)}catch(n){throw ct.error("failed to get slot",{companyId:s,err:n}),new Error(ht.UNKNOWN)}if(ct.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ct.error("invalid response - get slot",{res:r}),new Error(ht.UNKNOWN);if(r.status==="success")return Df(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new rt(ht.NOT_FOUND):r.code==="no-available-slot"?new zt("Failed to run test - concurrency limit reached"):(ct.error("invalid code error response - get slot",{res:r}),new rt(ht.UNKNOWN))}async function Mf(s,e,t,r){let n=is[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Df(r,n),await Ul(s,e,n),ct.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ct,is,Lf,Df,wn,os=v(()=>{"use strict";ge();W();F();ie();Y();ct=P("slot-service"),is={},Lf=null,Df=(s,e)=>{is[s]=e};wn={start:kv,end:_v}});function Ff(s,e=process){async function t(r){await le(se(Uf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Sn.error("Caught exception",{err:r}),console.log("Uncaught exception"),r.message&&console.log("Message =",r.message),r.reason&&console.log("Reason =",r.reason),await t(r)}),e.on("unhandledRejection",r=>{var n;if(Sn.fatal("Caught unhandled promise rejection",r),!((n=r==null?void 0:r.message)!=null&&n.includes("ENOTFOUND x-api.rollout.io")))throw r}),e.on("rejectionHandled",()=>{Sn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Sn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function as(s){Uf.push(s)}var Sn,Uf,En=v(()=>{"use strict";W();F();Sn=P("process-handler"),Uf=[]});var Wf={};H(Wf,{installAllLazyDependencies:()=>Mv,lazyRequire:()=>lt});async function lt(s,e={}){let t=Gc(s);if(t)return t;let r;e.silent||(r=(0,Bf.default)(`Installing ${s} before first usage...`).start());try{let n=await Nv(s);return r&&r.succeed(),n}catch(n){Dv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=$f(s),o=`${s}@${i}`,l=process.argv.includes("npx")?"":"-g ",c=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${l}${o}`;throw r&&r.fail(c),n}}async function Nv(s){return cs.has(s)||(cs.set(s,jf(s)),cs.get(s).catch(()=>{cs.delete(s)})),cs.get(s)}async function jf(s){let e=Gc(s);if(e)return e;let t=$f(s),r=`${s}@${t}`;return await $i(gt(),r),Xt(s)}async function Mv(){let s=Object.keys(nc);for(let e of s)await jf(e)}function $f(s){let e=Object.entries(nc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Bf,Dv,cs,In=v(()=>{"use strict";Bf=I(require("ora"));Zr();W();F();mi();en();Dv=P("lazy-require"),cs=new Map});var Vf,po,Gf=v(()=>{"use strict";Vf=require("istanbul-lib-report"),po=class extends Vf.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 Hf,qf,zf,Rn,bt,Kf,mo,Bl,Jf,Uv,Yf,Xf,Fv,Bv,Qf,jv,$v,Wv,Vv,Gv,Zf,eg=v(()=>{"use strict";Hf=I(require("ora")),qf=I(require("dayjs")),zf=I(require("test-exclude")),Rn=I(require("fs")),bt=I(require("path")),Kf=I(require("istanbul-reports")),mo=I(require("istanbul-lib-report"));ge();Y();F();W();In();Gf();Bl=P("test-run-status"),Jf=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Uv=s=>!!Jf(s).search,Yf=s=>s?Jf(s).pathname.substring(1):"",Xf=(s,e)=>{let t=Yf(e);return!new zf.default({relativePath:!1,include:s}).shouldInstrument(t)},Fv=s=>s.substring(0,s.indexOf("?")),Bv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await lt("convert-source-map");if(t==="file"&&!e)throw new C("--code-coverage-source-map-path [path]");return e?r.fromMapFileSource(s,e):r.fromSource(s)},Qf=(s,e)=>`${bt.resolve(s,Yf(e))}.js`,jv=async(s,e,t)=>{let{codeCoverageInclude:r}=s;await se(Object.values(t),async n=>{if(!n)return;let i=n.toObject();await se(i.sources,async(o,a)=>{if(Xf(r,o))return;let l=Qf(e,o);await Rn.promises.mkdir(bt.parse(l).dir,{recursive:!0}),await Rn.promises.writeFile(l,i.sourcesContent[a])})})},$v={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Uv(e)&&(e=Fv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=bt.dirname(this.getPath(s));return bt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Wv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=mo.createContext({dir:t,coverageMap:e,watermarks:mo.getDefaultWatermarks(),sourceFinder:a=>{try{let l=Qf(r,a);return Rn.readFileSync(l,"utf8")}catch(l){throw new Error(`Unable to lookup source: ${a} (${l.message})`)}}});return new po({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let l={projectRoot:"/"};a==="html"&&(l={linkMapper:$v}),Kf.create(a,l).execute(o)}),i},Vv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await lt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>Xf(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Gv=async(s,e)=>{let{mergeProcessCovs:r}=await lt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await $l(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(l=>l.JSCoverageURLS||[]),async l=>{let c=await xn(l,9e4);await se(c,async d=>{if(!i.has(d.url)){let m=d.text;d.sourceUrl&&(i.set(d.url,"TEMP"),m=await jl(d.sourceUrl)),i.set(d.url,{text:m,url:d.url,sourceMapType:d.sourceMapType,hash:d.hash})}delete d.text,n=r([n,{result:[d]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},Zf=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Bl.info("start js coverage process");let n=(0,Hf.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=bt.resolve(s.codeCoverageReportPath||"./coverage"),o=bt.resolve(i,`.js/${(0,qf.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?bt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[l,{mergedCoverages:c,covUrlMap:d}]=await Promise.all([lt("istanbul-lib-coverage"),Gv(s.project,r)]);if(c.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Bl.info("start js coverage merge and remap",{numOfFiles:d.size,numMergedCoverages:c.result.length});let m=l.createCoverageMap({}),u={};await se(c.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=d.get(h),w=await Bv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=w;let b=await Vv(s,{source:y,sourceMap:w,functions:g});m.merge(b)}),await jv(s,o,u);let f=await Wv(s,m,i,o);return n.succeed(),f}catch(l){let c="Failed to report coverage information";l instanceof C?n.fail(`${c}, missing arg: ${l.message}`):n.fail(c),Bl.error(c,{err:l})}}});var tg={};H(tg,{SELENIUM_PERF_MARKS:()=>xe,SeleniumPerfStats:()=>Sr});var xe,Hv,Sr,ls=v(()=>{"use strict";F();xe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Hv=["ALL",...Object.values(xe)],Sr=class{constructor(){this.marks=Object.fromEntries(Hv.map(e=>[e,[]]));this.startTimes={}}markStart(e){let t=re();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`,Oi(r,50)],[`${t}_P95`,Oi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var ig={};H(ig,{initServer:()=>Kv,mapFilesToLocalDrive:()=>Vl});function Vl(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,fo[t.id]?{screenshot:fo[t.id]}:{})),Object.keys(go).forEach(t=>{s.assets||={},s.assets[ng[t]]=go[t]}),s.assets||={},s.assets.screenshots=Object.values(fo)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function Kv({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await lt("multer"),n=typeof t=="string"?t:qv;await Wl.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(l,c,d){let m=JSON.parse(l.body.metadata||"{}");if(!m.testResultId)return d(new Error("missing testResultId"),"");let u=An.join(n,m.testResultId);try{await Wl.promises.mkdir(u,{recursive:!0})}catch(f){return d(f,"")}return d(null,u)},filename(l,c,d){let{fileName:m}=l.body,u=JSON.parse(l.body.metadata||"{}");if(!u.stepId&&!m)return d(new Error("missing stepId or fileName"),"");if(u.stepId){let f=An.extname(m);return d(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return d(null,m)}})}),o=(0,sg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(l,c)=>{let d=JSON.parse(l.body.metadata||"{}");d.stepId&&(fo[d.stepId]=l.file.path),d.testResultId&&zv.includes(d.subType)&&(go[d.subType]||=[],go[d.subType].push(l.file.path)),c.sendStatus(200)}),o.use((l,c)=>c.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((l,c)=>{let d=a(o);d.listen(s,e),d.on("error",m),d.on("listening",()=>l(d.address()));function m(u){if(u.syscall!=="listen")return c(u);switch(u.code){case"EACCES":case"EPERM":return c(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return c(new C(`Port ${s} is already in use`));default:return c(u)}}})}var Wl,rg,An,sg,qv,fo,go,ng,zv,Gl=v(()=>{"use strict";Wl=I(require("fs")),rg=I(require("os")),An=I(require("path")),sg=I(require("express"));Y();In();qv=An.join(rg.tmpdir(),"testim/rca/"),fo={},go={},ng={"test-log":"consoleLogs","har-file":"networkLogs"},zv=Object.keys(ng)});var er,Hl,ho,og=v(()=>{"use strict";er=I(require("lodash"));F();W();Hl=P("override-test-data-builder"),ho=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return er.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)&&!er.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):Hl.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(er.isObject(e.overrideAllTestsData)&&!er.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):Hl.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}Hl.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 er.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 i=r.map(d=>this.generateTestUniqId(d)),o=i.indexOf(n),a=i.lastIndexOf(n),l=r[o],c=this.createNewTestItems(l,t);return r.splice(o,a-o+1,...c)})}createNewTestItems(e,t){return[].concat(t).map((r,n)=>{let i=re();return{...e,resultId:i,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 yo(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Qe.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Er,Qe,Jv,Yv,Xv,Qv,bo,ag=v(()=>{"use strict";Er=I(require("lodash"));F();ie();ts();os();ge();Y();W();Pt();En();eg();ls();Gl();de();ue();og();bn();Qe=P("test-run-status"),Jv=fr(),Yv=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,Xv=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,Qv=tt();bo=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 Sr;var a,l,c,d;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:hi||t.parallel||1,browser:i,gitBranch:Jv,gitCommit:Yv,gitRepoUrl:Xv,runnerVersion:Qv,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(m=>m.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((l=t.gridData)==null?void 0:l.gridId),gridName:t.grid||((c=t.gridData)==null?void 0:c.name),gridType:(d=t.gridData)==null?void 0:d.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:l,testId:c,name:d,testStatus:m,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w}=a,b={originalTestResultId:t,previousTestResultId:r,config:Er.cloneDeep(l),testId:c,status:"QUEUED",name:d,resultId:e,retryCount:o,testStatus:m};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:w},Kl({projectId:n,runId:i,testId:c,newResultId:e,originalTestResultId:t,previousTestResultId:r,testResult:b})}testStart(e,t,r,n){let i=this.getTestResult(r);return i.workerId=e,Q.onTestStarted(i,e,n,r),i}async updateTestStatusRunning(e,t,r){var c;let{project:n,remoteRunId:i,projectData:o}=this.options;if((c=this.options.lightweightMode)!=null&&c.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await wo(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(d){Qe.error("failed to upload test data artifact (runner)",{err:d})}let l=Er.cloneDeep(e.config);return delete l.testData,l.testDataUrl=a,await this.executionStartedPromise,Ir(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:l,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await yo(this.options.beforeTest,{...e,exportsGlobal:n,globalParameters:n},this.options.userData.loginData.token);return e.config.testData={...e.config.testData,...this.exportsGlobal,...this.fileUserParamsData,...this.beforeSuiteParams,...i},this.options.runParams[e.resultId]=e.config.testData,e.startTime=Date.now(),await this.updateTestStatusRunning(e,t,r),e}catch(i){throw Qe.error("Failed to start test",{err:i}),i}}testStartAndReport(e,t,r,n,i){let o=this.testStart(e,t,r,n);return this.testStartReport(o,t,i)}onGridSlot(e,t){let r=this.getTestResult(e);r.config.gridInfo={...t,key:void 0,user:void 0},Qe.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:l,success:c}=t;if(a===Je.EVALUATING&&Ct.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Je.EVALUATING} status`);return}if(c){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,qe(this.options.editorUrl,this.options.project,o,l,this.branchToUse),o,n,l)}calcResultText(e){return e.success?me.PASSED:me.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Je.QUARANTINE}`)}monitorMemoryUsage(e){let t=Mc();t.isOverThreshold&&Qe.info("memoryUsage is over threshold",{memoryUsage:t,testName:e.name,testId:e.testId,resultId:e.resultId,startTime:e.startTime,duration:e.duration,success:e.success,failureReason:e.failureReason,lightweightMode:this.options.lightweightMode,parallel:this.options.parallel,browser:this.options.browser})}testEnd(e,t,r,n,i){let o=this.getTestResult(t.resultId),a=t.endTime-t.startTime||0;o.sessionId=n,o.startTime=t.startTime||o.startTime||Date.now(),o.duration=a,t.duration=a,o.failureReason=t.failureReason||t.reason,t.failureReason=o.failureReason,o.failurePath=t.failurePath,o.resultId=t.resultId,o.success=t.success,this.options.saveRCALocally&&Vl(o,Qe),o.resultUrl=qe(this.options.editorUrl,this.options.project,o.testId,o.resultId,this.branchToUse),o.status=this.calcResultText(t),t.status=o.status,t.name=o.name,t.testStatus=o.testStatus,t.testId||=o.testId,t.testCreatorName=o.testCreatorName,t.testCreatorEmail=o.testCreatorEmail,t.testOwnerName=o.testOwnerName,t.testOwnerEmail=o.testOwnerEmail,t.testData=o.config&&typeof o.config.testDataTotal=="number"?{total:o.config.testDataTotal,index:o.config.testDataIndex}:{},this.reportTestStatus(e,t,o,i),this.monitorMemoryUsage(o),Q.onTestFinished(o,e,i);let l={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=l,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await yo(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Qe.error("HOOK threw an error",{test:e.testId,err:a}),console.error("HOOK threw an error",a)}return(o=this.options.lightweightMode)!=null&&o.onlyTestIdsNoSuite?void 0:await Ir(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 Qe.error("Failed to update test finished",{err:a}),a}}testEndAndReport(e,t,r,n,i,o){let a=this.testEnd(e,t,r,n,i);return this.testEndReport(a,r,t,o)}getMobileRunSkippedReason(e,t,r){let n="",{APP_FROM_DEVICE:i,VIRTUAL_BUILD:o}=kc;return e&&(n=i),Hr(t,r)&&(n=o),n}calcTestRunStatus(){var o;let{options:e,testInfoList:t}=this,r=e.company.companyId,n=(o=e.gridData)==null?void 0:o.type,i=t.map(a=>{var f,h,g;let l=e.browser?Ys(e.browser,e.saucelabs,e.browserstack):a.runConfig,c=qr(_,n)&&Js(a.nativeApp)&&!e.appId,d=Jt(e)&&(Hr(a.nativeApp,n)||c),m=Ye(a,e)||d,u={testId:a.testId,testOptimization:a.testOptimization,status:m?me.SKIPPED:me.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Je.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...d&&{reason:this.getMobileRunSkippedReason(c,a.nativeApp,n)},config:{...this.execConfig,companyId:r,testData:((f=a.testData)==null?void 0:f.value)||null,isBeforeTestPlan:a.isBeforeTestPlan,isAfterTestPlan:a.isAfterTestPlan,testDataTotal:((h=a.testData)==null?void 0:h.total)||null,testDataIndex:((g=a.testData)==null?void 0:g.index)||null,baseUrl:e.baseUrl||a.baseUrl||a.testConfig.baseUrl,testConfig:a.overrideTestConfig||a.testConfig,browser:l.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await wn.end(r,t),e==="mongo"&&await dn.end(t)}async executionStart(e,t,r,n,i){Qe.info("execution started",{executionId:e,gridId:this.execConfig.gridId,gridHost:this.execConfig.gridHost,gridName:this.execConfig.gridName,gridType:this.execConfig.gridType,parallel:this.execConfig.parallel,runnerVersion:this.execConfig.runnerVersion,source:this.execConfig.source});let{options:o}=this,{remoteRunId:a,projectData:l,company:{companyId:c}={},slotService:d}=o;as(()=>Promise.all([this.endKeepAlive(d,t,c),To("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let m={projectId:t,executionId:e,..._.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await yo(o.beforeSuite,m),f=new ho(u,Er.cloneDeep(this.testInfoList),t);this.testInfoList=f.overrideTestData(),this.testRunStatus=this.calcTestRunStatus(),this.beforeSuiteParams=u;let{testInfoList:h}=this,g=[],y=[],T=[];for(let b of h){if(b.isBeforeTestPlan){g.push(b);continue}if(b.isAfterTestPlan){T.push(b);continue}y.push(b)}let w=async()=>{let b=Er.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var O;let D=b[A],j=(O=D.config)==null?void 0:O.testData,R=D.testId,x=await wo(t,R,A,j,l.defaults);x&&(delete D.config.testData,D.config.testDataUrl=x)});let S=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),E=zl({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:S,intersections:o.intersections});return this.executionStartedPromise=E,E.catch(A=>Qe.error(A)),E};try{await w()}catch(b){Qe.error("Failed to start suite",{err:b}),console.error("Failed to start test run. Please contact support@testim.io")}return{beforeTests:g,tests:y,afterTests:T}}concatSeleniumPerfMarks(e){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 d;let t=Fc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:m,testStatus:u}of t)m===me.PASSED&&n++,m===me.SKIPPED&&i++,m===me.FAILED&&u===Je.EVALUATING&&o++;let{seleniumPerfMarks:a,...l}=this.seleniumPerfStats.getStats();try{await yo(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(m){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:m,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let c=await Zf(this.options,this.branchToUse,r,e);if(Object.assign(l,{coverageSummary:c}),!((d=this.options.lightweightMode)!=null&&d.onlyTestIdsNoSuite))try{return await To("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,l)}catch(m){throw Qe.error("Failed to update suite finished",{err:m}),m}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await ql(e,["QUEUED"],t,r,n,this.startTime,null,this.options.project);for(let o of i){let a=this.getTestResult(o);a.status=t,a.failureReason=r,a.success=n}return this.testRunStatus}}});function Jl(s,e){var o;let t=s.canary?"-master.zip":".zip",r=`${e?Rd:Ms}/extension/testim-headless${t}`,n=_.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(o=s.company)==null?void 0:o.companyId,projectId:s.project,runnerEnvironment:Ht});return n||(Zv.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),n="https://testimstatic.blob.core.windows.net/extension/testim-headless.zip"),!(s.ext||s.extensionPath)&&n&&(r=n,s.testimHeadlessExtensionDownloadUrl=n),{chrome:r,"edge-chromium":r}}function cg(s){let{chrome:e}=Jl(s,!1);return e}function vo(s){let e=Ht==="staging"?`${Ds}/staging-sessionPlayer`:`${Ms}/extension/sessionPlayer`;return s.canary?`${e}-master`:e}var Zv,Cn=v(()=>{"use strict";de();ue();W();Zv=P("runOptionsUtils")});function ug(s,e){if(e){if(!iS.has(e)){Pn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var pg,dg,jt,mg,fg,gg,So,hg,Pn,eS,tS,kn,rS,sS,nS,ne,iS,Eo=v(()=>{"use strict";pg=I(require("ms")),dg=I(require("p-retry")),jt=I(require("node:os")),mg=I(require("portfinder")),fg=I(require("node:child_process"));F();Ve();ge();gg=I(require("node:fs")),So=I(require("node:fs/promises")),hg=require("node:path");Y();W();Cn();ie();ue();F();Pn=P("lambdatestService"),eS="https://downloads.lambdatest.com/tunnel/v3",tS={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"},kn=`${jt.tmpdir()}/LT`,rS=`${kn}/LT`,sS=(0,pg.default)("15m"),nS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===L.TESTIM_LAMBDATEST||e.type===L.LAMBDATEST||e.type===L.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=Yl(),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?sS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(rS))return;let t=tS[jt.platform()+jt.arch()];if(!t)throw new Error(`tunnel on ${jt.platform()+jt.arch()} platform is not supported.`);let r=`${kn}.zip`;await Ke(`${eS}/${t}`,r),await it(r,kn)}static async chmodLtTunnel(e){if(!(jt.platform()==="win32"||!await ye(e))){try{await So.access(e,gg.constants.X_OK);return}catch{}try{await So.chmod(e,"777")}catch(r){throw Pn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await ce(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await mg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,l=global.proxyUri;ne.tunnelName=re();let c=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(_.flags.enableLambdaTestTunnelNTLM.isEnabled())if(c=[...c,"--ntlm"],o&&a)c=[...c,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(_.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(c=[...c,...Dc(u)])}if(_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(c=[...c,"--skip-upgrade"]),e.externalLambdatestUseWss&&(c=[...c,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(c=[...c,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)c=[...c,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)c=[...c,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(l)try{let u=new URL(l);c=[...c,"--proxy-host",u.hostname],u.port&&(c=[...c,"--proxy-port",u.port]),u.username&&u.password&&(c=[...c,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(c=[...c,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,hg.join)(kn,"LT")),ne.tunnel=fg.spawn("./LT",c,{cwd:kn});let d="",m="";ne.tunnel.stdout.on("data",u=>{d+=u.toString()}),ne.tunnel.stderr.on("data",u=>{m+=u.toString()});try{let u=await(0,dg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(d.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Pn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:d,stderrResult:m}),Pn.error("Failed to start LT tunnel",{err:u}),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,i,o,a,l){var T,w;if(!this.isActive)return{};let c=ne.lambdatestConfig.CAPABILITIES[t]||{},d={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},m=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:ug(n,a==null?void 0:a.os)||ug(n,(T=o==null?void 0:o.lt)==null?void 0:T.platform)||c.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??nS,version:t==="safari"&&((w=o==null?void 0:o.lt)==null?void 0:w.safari_version)||c.version};if(l!==q.APPIUM&&l!==q.SELENIUM&&!f){let b=Jl({canary:u},!0);!h&&b[t]&&(m=[...m,b[t]]),h&&Oe(h)&&(m=[...m,h]),m.length||Pn.warn("No extension was loaded in LambdaTestService",{extUrls:b,extensionPath:h})}return _.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&Oe(g)&&(m=[...m,g]),{build:r,name:`${n} - ${i}`,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...c,...y,loadExtension:m,...d,console:!0,queueTimeout:300,network:_.flags.LTNetworkCapabilities.isEnabled(),ntlm:_.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:_.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},iS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey"])});function aS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Ig(s){return wg.readFileSync(s,{encoding:"base64"})}function Rg(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&Oe(s))&&s){let r=Ig(s);ps.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${Zl(r)} current extension count: ${e.length}`),e.push(r)}}function xg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let d=typeof s.ext=="string"?s.ext:`${__dirname}/..`,m=r||d,u=`--load-extension=${m}`;ps.info(`adding extension: testim unpacked , path: ${m}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=Io.basename(i));let l=Io.join(process.cwd(),a),c=Ig(l);ps.info(`adding extension: testim zipped, path: ${l} length: ${c.length} hash: ${Zl(c)} current extension count: ${e.length}`),e.push(c)}function cS(s,e,t,r,n,i,o,a){var g,y;let l=t.seleniumName||t.browserValue,c=[],d=[...Eg];e.headless&&d.push("--headless");let m={prefs:{"profile.default_content_setting_values.popups":Xl.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":Xl.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,"profile.password_manager_leak_detection":!1},w3c:!0};if(Ql(n)){let T=_.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&d.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),m.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=_.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}Ql(n)&&l==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(m.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>d.push(`--${T}`)),e.chromeBlockLocation&&(m.prefs["profile.default_content_setting_values.geolocation"]=Xl.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&d.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&d.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:l});function u(){t.mobileEmulation&&(m.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Cc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Rg(r,c,o),a===q.EXTENSION&&xg(e,c,d,i,o),c.length>0&&(m.extensions=c),e.disableCookiesSameSiteNoneRequiresSecure&&(m.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),m.args=d;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[l],h={MicrosoftEdge:"ms",chrome:"goog"}[l];return ne.isLambdatestGrid(n)&&delete m.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=m),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=m),s}function uS(s,e,t){let r={"pdfjs.disabled":!0};return _.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":bg.join(","),"browser.helperApps.neverAsk.openFile":bg.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.headless&&(s.desiredCapabilities["moz:firefoxOptions"].args||(s.desiredCapabilities["moz:firefoxOptions"].args=[]),s.desiredCapabilities["moz:firefoxOptions"].args.push("-headless")),s}function us(s){return`${s.width}x${s.height}`}function hS(s){let{platform:e}=s;if(!e)return us(Tg);let t=e.split(" ")[1];return e.startsWith("Windows")&&gS.has(t)?us(dS):e==="Linux"?us(pS):e.startsWith("macOS")?us(mS):us(e==="OS X El Capitan"||e==="OS X Yosemite"?fS:Tg)}function yS(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(n["sauce:options"].screenResolution=hS(t.sl),t){t.sl.version=t.browserValue==="safari"?t.sl.safari_version:t.sl.version,t.sl.appiumVersion=r.appiumVersion||t.sl.appiumVersion;let i=(0,Sg.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,ut.merge(i,n,r)}return ut.merge(n,r)}return{}}function bS(s,e,t){return ut.isEmpty(s.browserstack)?{}:t?(t.bs.browser_version=t.browserValue==="safari"?t.bs.safari_version:t.bs.browser_version,t.browserValue==="safari"&&t.bs.safari_version==="10"&&Object.assign(t.bs,{"safari.options":{technologyPreview:!0}}),{...t.bs,...s.browserstack,name:e}):{...s.browserstack,name:e}}function TS(s){return s.perfecto?s.perfecto:{}}function wS(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 vS(s,e={}){let{gridData:t={},gridUsername:r,gridPassword:n}=s,i=r||t.user||e.user,o=n||t.key||e.key,a={};return i&&o&&(a.Authorization=tc(i,o)),a}function Ro(s){var w,b,S,E;let{overrideConfiguration:e,browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,lambdatestService:c,mode:d}=s;if(i.mode==="local"){let A=[],D=[...Eg],j={};return t.headless&&D.push("--headless"),t.silentDebuggerExtensionApi&&D.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&D.push(`--remote-debugging-port=${t.remoteDebuggingPort}`),t.chromeExtraArgs&&t.chromeExtraArgs.forEach(R=>D.push(`--${R}`)),t.chromeBinaryLocation&&(j.binary=t.chromeBinaryLocation),d!==q.SELENIUM&&xg(t,A,D,null,c),Rg(o,A,c),{logLevel:yg,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:D,extensions:A,...j},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:m,driverRequestRetries:u}=t,f=vS(t,i),h={hostname:i.host,host:i.host,port:i.port||4444,path:i.path||"/wd/hub",protocol:i.protocol||"http",logLevel:yg,connectionRetryTimeout:m,connectionRetryCount:u,getSessionTimeout:Math.max(c.getSessionTimeout,t.getSessionTimeout),getSessionRetries:c.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!ut.isEmpty(f)&&{headers:f},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};Ql(i)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,h.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(h.desiredCapabilities.nativeEvents=!1),i.user&&i.key&&(i.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=i.user,t.saucelabs.accessKey||=i.key),i.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=i.user,t.browserstack["browserstack.key"]||=i.key)),i.key&&i.type==="perfecto"&&(t.perfecto.securityToken=i.key);let g=Number(t.browserTimeout/1e3),y=t.browser||(n==null?void 0:n.browserValue);ut.merge(h.desiredCapabilities,yS(t,r,n),bS(t,r,n),TS(t),wS(t,y,g),c==null?void 0:c.getCapabilities(t,y,a,l,r,n,e,d));let T=null;switch(!t.ext&&!t.extensionPath&&((w=i.host)!=null&&w.endsWith(".testim.io"))&&!t.canary&&d===q.EXTENSION&&(y==="chrome"||y==="edge-chromium"&&_.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(T="/opt/testim-headless"),y){case"chrome":case"edge-chromium":h=lS(h,t,n,o,i,T,c,d);break;case"firefox":h=uS(h,t,c);break;case"safari":case"safari technology preview":h=aS(h,y);break;default:break}ut.merge(h.desiredCapabilities,t.seleniumCapsFileContent);try{let A={"hub.lambdatest.com":"lambdatest",[_.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},D=O=>O[i.provider]||O[h.host]||O[A[h.host]],j=O=>{var B,G;return D(O)||O[(B=h.desiredCapabilities)==null?void 0:B.browserName]||O[(G=h.desiredCapabilities)==null?void 0:G.version]||O||{}},R=JSON.parse(_.flags.addCustomCapabilities.getValue()||"{}"),x=j(j(R));Object.keys(x).length&&(ps.info(`Adding custom capabilities: ${JSON.stringify(x)}`),Object.assign(h.desiredCapabilities,x))}catch(A){ps.error("Failed to load custom capabilities",{error:A,customCapabilities:_.flags.addCustomCapabilities.getValue()})}if(h.desiredCapabilities&&!h.capabilities&&(oS(h),h.capabilities={alwaysMatch:h.desiredCapabilities,firstMatch:[{}]},delete h.desiredCapabilities),h.hostname=h.host,s.printFinalCaps){let A=(b=h.capabilities)==null?void 0:b.alwaysMatch,D=JSON.parse(JSON.stringify(h)),j=(S=D==null?void 0:D.capabilities)==null?void 0:S.alwaysMatch,R=O=>O.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(O=>{var B,G;j!=null&&j[O]&&(j[O].extensions=(G=(B=A==null?void 0:A[O])==null?void 0:B.extensions)==null?void 0:G.map(R))}),j!=null&&j.loadExtension&&(j.loadExtension=(E=A==null?void 0:A.loadExtension)==null?void 0:E.map(R));let x=require("node:util");console.log(x.inspect(D,{showHidden:!1,depth:null,colors:!0}))}return h}var wg,Io,vg,ut,Sg,ps,yg,Xl,Eg,Zl,Ql,oS,lS,bg,Tg,pS,dS,mS,fS,gS,eu=v(()=>{"use strict";wg=I(require("node:fs")),Io=I(require("node:path")),vg=I(require("node:crypto")),ut=I(require("lodash"));F();de();W();ue();ie();Eo();Sg=require("lodash"),ps=P("testim-desired-capabilities-builder"),yg=gi?"debug":"silent",Xl={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Eg=["--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"],Zl=(...s)=>vg.createHash("sha256").update(s.join("")).digest("hex"),Ql=s=>s.type===L.DEVICE_FARM||s.type===L.HYBRID&&s.provider==="devicefarm",oS=s=>{var r;let{desiredCapabilities:e}=s;Object.hasOwn(e,"version")&&(e.browserVersion=e.version,delete e.version),Object.hasOwn(e,"platform")&&(e.platformName=e.platform,delete e.platform),Object.hasOwn(e,"acceptSslCerts")&&(e.acceptInsecureCerts=e.acceptSslCerts,delete e.acceptSslCerts),Object.hasOwn(e,"unexpectedAlertBehaviour")&&(e.unhandledPromptBehavior=e.unexpectedAlertBehaviour,delete e.unexpectedAlertBehaviour),Object.hasOwn(e,"chromeOptions")&&(e["goog:chromeOptions"]??=e.chromeOptions,delete e.chromeOptions),Object.hasOwn(e,"edgeOptions")&&(e["ms:edgeOptions"]??=e.edgeOptions,delete e.edgeOptions),Object.hasOwn(e,"firefoxOptions")&&(e["moz:firefoxOptions"]??=e.firefoxOptions,delete e.firefoxOptions),((r=e["goog:chromeOptions"])==null?void 0:r.w3c)===!1&&(e["goog:chromeOptions"].w3c=!0),"username"in s.desiredCapabilities&&(s.user=s.desiredCapabilities.username,delete s.desiredCapabilities.username),"accessKey"in s.desiredCapabilities&&(s.key=s.desiredCapabilities.accessKey,delete s.desiredCapabilities.accessKey);let t;try{t=_.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ps.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};lS=ut.memoize(cS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(ut.omit(e,"runParams")),l=JSON.stringify(t),c=JSON.stringify(n.type);return Zl(o,a,l,r,c,i)}),bg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Tg={width:1920,height:1080},pS={width:1920,height:1200},dS={width:2560,height:1600},mS={width:2360,height:1770},fS={width:2048,height:1536},gS=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,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/))||((i=s.seleniumStack)==null?void 0:i.message)==="The arguments passed to a command are either invalid or malformed."||((o=s.message)==null?void 0:o.match(/Invalid timeout type specified: ms/))||((a=s.message)==null?void 0:a.match(/\.\w* is not a function/))}function Cg(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 tu=v(()=>{"use strict"});function ru(s){function e(u){return u?[Node.ELEMENT_NODE,Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE].includes(u.nodeType):!1}function t(u){return u?r(u.parentNode,e):null}function r(u,f){for(let h=u;h&&h!==u.ownerDocument;h=h.parentNode)if(f(h))return h;return null}function n(u,f){for(let h=u;h&&h!==u.ownerDocument;h=t(h))if(f(h))return h;return null}function i(u,f){if(!u||!f)return null;u instanceof DocumentFragment&&(u=u.host);let g=window.getComputedStyle(u).getPropertyValue(f);if(g&&g!=="inherit")return g;let y=t(u);return i(y,f)}function o(u){let f=u.getBoundingClientRect();if(f.width>0&&f.height>0)return!0;if(u.tagName.toUpperCase()==="PATH"&&f.width+f.height>0){let g=i(u,"stroke-width");return!!g&&parseInt(g,10)>0}return i(u,"overflow")==="hidden"?!1:Array.from(u.childNodes).some(g=>g.nodeType===Node.TEXT_NODE?!0:e(g)?o(g):!1)}function a(u){return i(u,"overflow")==="hidden"}function l(u){return!u||!a(u)||!u.childNodes.length?!1:Array.from(u.childNodes).every(f=>f.nodeType===Node.TEXT_NODE?!1:!e(f)||!o(f)?!0:l(f))}function c(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:c(u.parentNode):!1}if(!s||!c(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return ru(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let d=!!n(s,u=>Number(i(u,"opacity"))===0),m=!!n(s,u=>i(u,"display")==="none");return!(d||m||!o(s)||l(s))}var Pg=v(()=>{"use strict"});var kg,Og,$t,SS,ES,xo,_g=v(()=>{"use strict";kg=I(require("promise-queue")),Og=I(require("webdriverio"));de();je();F();W();jr();Pg();tu();ls();$t=P("WebDriverApi"),SS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},ES={implicit:0,pageLoad:1,script:2},xo=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,i=t?t.toString().slice(0,2e3):"";throw $t.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),ic!==void 0&&(e=ic);let t=1/0;this.queue=new kg.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(i){return this.rejectWithLog(i,e)}finally{(n=this.seleniumPerfStats)==null||n.markEnd(t)}}async initClient(e,t,r){var o,a,l,c,d,m,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),M("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((m=(d=(c=(l=e.capabilities.alwaysMatch)==null?void 0:l["goog:chromeOptions"])==null?void 0:c.extensions)==null?void 0:d[0])==null?void 0:m.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(xe.GET_BROWSER);try{await this.addToQueue(async()=>{$t.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),M("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await Og.remote(e),this.logGridStatus(r)}),M("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,xe.GET_BROWSER)}}async logGridStatus(e){var o;if(!this.client)return;let{sessionId:t}=this.client,r="N/A",n="N/A",i;try{i=await this.client.status();for(let a of i.nodes||[])for(let l of a.slots||[])if(((o=l==null?void 0:l.session)==null?void 0:o.sessionId)===t){r=a,n=l;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:i.message,ready:i.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 TypeError("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},i=()=>this.client.execute(e,t).catch(n),o=()=>this.client.executeScript(e,t).catch(n);if(this.unsupportedActions.has("execute"))return i();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 o()}catch(a){if(Ue(a))return this.unsupportedActions.add("execute"),i();throw a}})}}async executeAsync(e,...t){return{value:await this.addToQueue(async()=>{if(typeof e!="string"&&typeof e!="function")throw new TypeError("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),i=()=>this.client.executeAsyncScript(e,t);if(this.unsupportedActions.has("executeAsync"))return n();try{return await i()}catch(o){if(Ue(o))return this.unsupportedActions.add("executeAsync"),n();throw o}})}}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 i;return(i=this.client)==null?void 0:i.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(ru,{ELEMENT:e,[Gt]:e});if(this.unsupportedActions.has("elementIdDisplayed"))return r();try{return await t()}catch(n){if(Ue(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(Cg(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 i=[];return i[ES[e]]=t,this.client.setTimeouts(...i)},n=()=>this.client.setTimeout({[e]:t});if(this.unsupportedActions.has("timeouts"))return n();try{return await r()}catch(i){if(Ue(i))return this.unsupportedActions.add("timeouts"),n();throw i}})}scroll(e,t){e=typeof e=="number"?e:0,t=typeof t=="number"?t:0;let r=function(n,i){window.scrollTo(n,i)};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(SS);if(typeof e=="string"&&/(width|height)/.test(e)){let r=`screen${e.slice(0,1).toUpperCase()}${e.slice(1)}`;return t.value[r]}return{width:t.value.screenWidth||0,height:t.value.screenHeight||0}}async elementIdValue(e,t){let r=Array.isArray(t)?t.join():t;return{value:await this.addToQueue(()=>{var i;return(i=this.client)==null?void 0:i.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 i;let t=await((i=this.client)==null?void 0:i.$(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 i;return(i=this.client)==null?void 0:i.$(e).click({x:Math.floor(t.clickOffset.x),y:Math.floor(t.clickOffset.y),button:r})})}}_rightClick(e,t){return this.findElementAndPress(e,t,"right")}_leftClick(e,t){return this.findElementAndPress(e,t,"left")}elementIdClick(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.elementClick(e)})}sendKeyboardShortcut(e){return this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.keys(e)})}async actions(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.performActions(e)})}}async doDoubleClick(e){return{value:await this.addToQueue(()=>{var r;return(r=this.client)==null?void 0:r.$(e).doubleClick()})}}async _dragAndDrop(e,t){return{value:await this.addToQueue(()=>{var n;return(n=this.client)==null?void 0:n.$(e).dragAndDrop(t)})}}async buttonDown(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonDown()})}}async buttonUp(){return{value:await this.addToQueue(()=>{var t;return(t=this.client)==null?void 0:t.buttonUp()})}}moveTo(e,t,r){let n={...typeof t=="number"&&{xOffset:t},...typeof r=="number"&&{yOffset:r}};return this.isSafari()&&!Object.hasOwn(n,"yoffset")&&(n.yOffset=1),this.isSafari()&&!Object.hasOwn(n,"xoffset")&&(n.xOffset=1),this.addToQueue(async()=>{if(!this.client)throw new Error("The client is not initialized");let i=await this.client.$(e);await this.client.action("pointer").move({origin:i}).perform()})}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 i=Math.abs(e.width),o=Math.abs(e.height);r=async()=>await this.client.setWindowSize(i,o),n=async()=>await this.client._setWindowSize(i,o)}if(this.unsupportedActions.has("windowHandleSize"))return r();try{return await n()}catch(i){if(Ue(i))return this.unsupportedActions.add("windowHandleSize"),r();throw i}})}}setCookie(e,t,r,n,i,o,a){return this.addToQueue(()=>{var l;return(l=this.client)==null?void 0:l.setCookies({name:e,value:t,domain:r,httpOnly:n,secure:i,path:o,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()}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 tr={};H(tr,{getSessionPlayer:()=>Z,options:()=>nu});var Ao,nu,su,Z,we=v(()=>{"use strict";Ao=require("path");W();nu={playerPath:void 0},Z=()=>{if(su)return su;let s=(je(),He(Be));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(sn(),He(rn)),t=e(),r=nu.playerPath?(0,Ao.resolve)(nu.playerPath,"src/background/sessionPlayerInit.ts"):(0,Ao.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),su=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(Bd),n}});var Lg={};H(Lg,{doubleClick:()=>IS});var IS,Dg=v(()=>{"use strict";IS=function(s,e){let t=["pointerup","pointerdown","pointermove"],r=getLocatedElement(s.locatedElement);if(!r)throw new Error("element not found");let n=s.events,i={status:"done",success:!0};window.__unloadNavigator=function(){e(i)};let o=function(u){function f(w,b,S){return S>w&&S<b}let h=u.pointerPosition||{},g=r.getBoundingClientRect(),y=h.originX&&f(g.left,g.left+g.width,h.originX)?h.originX:g.left+g.width/2,T=h.originY&&f(g.top,g.top+g.height,h.originY)?h.originY:g.top+g.height/2;return{x:y,y:T}},a=function(u,f){return{screenX:0,screenY:0,clientX:u,clientY:f,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,bubbles:!0,cancelable:!0,button:0,pointerType:"mouse",isPrimary:!0}},l=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},c=function(u,f,h){let g=document.createEvent("MouseEvents");return g.initMouseEvent(u,!0,!0,document.defaultView,1,0,0,f,h,!1,!1,!1,!1,0,document.body?document.body.parentNode:document.documentElement),g},d=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},m=function(u){let f=o(u),h=u.event;return t.includes(h)?l(h,f.x,f.y):c(h,f.x,f.y)};try{n.map(f=>m(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=d();dispatchFocus(s.elementToFocusLocatedElement,u),window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e(i)}catch(u){window.__unloadNavigator&&(window.removeEventListener("unload",window.__unloadNavigator),window.__unloadNavigator=null),e({status:"done",result:u.toString(),success:!1})}}});var On={};H(On,{dispatchFocus:()=>RS});function RS(s,e){function t(i){let o=document.createEvent("HTMLEvents");return o.initEvent(i,!0,!1),o}function r(){var o;let i=document.activeElement;for(;(o=i.shadowRoot)!=null&&o.activeElement;)i=i.shadowRoot.activeElement;return i}function n(i,o){o&&(o.dispatchEvent(t("focusout")),o.dispatchEvent(t("blur"))),i.dispatchEvent(t("focusin")),i.dispatchEvent(t("focus")),typeof i.focus=="function"&&i.focus();let a=r();o&&a===o&&typeof o.blur=="function"&&o.blur()}if(s){let i=getLocatedElement(s);if(i&&i!==e)try{n(i,e)}catch{}}else e&&typeof e.blur=="function"&&e.blur()}var _n=v(()=>{"use strict"});var Bg={};H(Bg,{WebDriver:()=>Ar});async function PS(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 AS(r):void 0}catch(r){Fe.info("Error getting cdpAddress",r);return}}var ds,Ug,Fg,Fe,rr,xS,Ng,AS,Rr,CS,Mg,xr,Ar,Ln=v(()=>{"use strict";ds=I(require("lodash"));F();je();eu();Ug=I(require("p-retry")),Fg=I(require("ua-parser-js"));jr();W();tu();_g();Y();ue();ls();Fe=P("webdriver"),[rr,xS]=[0,2],{extractElementId:Ng,getCdpAddressForHost:AS}=J,Rr=()=>(we(),He(tr)).getSessionPlayer().codeSnippets,CS=()=>(we(),He(tr)).getSessionPlayer().locatorBuilderUtils,Mg=()=>(we(),He(tr)).getSessionPlayer().utils,xr=()=>(we(),He(tr)).getSessionPlayer().positionUtils;Ar=class extends xo{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))}}getIgnoreVisibility(){return this.ignoreVisibility}setIgnoreVisibility(t){this.ignoreVisibility=t}registerToClosedBrowser(t){this.browserClosedCallbacks.push(t)}unregisterToClosedBrowser(t){this.browserClosedCallbacks=this.browserClosedCallbacks.filter(r=>r!==t)}async init(t){var b,S,E,A,D,j,R,x;let{overrideConfiguration:r,browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,seleniumPerfStats:m,fastInit:u,lambdatestService:f,printFinalCaps:h,mode:g}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((E=(S=(b=n==null?void 0:n.company)==null?void 0:b.activePlan)==null?void 0:S.premiumFeatures)==null?void 0:E.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let y=Ro({browserOptions:n,testName:i,testRunConfig:o,gridInfo:a,customExtensionLocalLocation:l,executionId:c,testResultId:d,lambdatestService:f,overrideConfiguration:r,printFinalCaps:h,mode:g});y.desiredCapabilities&&delete y.desiredCapabilities.marionette,y.capabilities&&delete y.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(f==null?void 0:f.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=m;let T=u?0:1500,w=u?()=>null:()=>this.executeJS("window.focus()");try{M("before initClient in webdriver.js init");let O=await this.initClient(y,i,d);M("after initResult before getCdpAddress in init"),this.cdpUrl=await PS(O),M("after getCdpAddress in webdriver.js init"),Fe.info(`init new session testName: ${i}`,{sessionId:this.getSessionId(),testResultId:d}),await ce(T),_.flags.dontFocusOnInit.isEnabled()||await w(),M("after focus and delay in webdriver.js init")}catch(O){let B=JSON.stringify(ds.omit(y,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Fe.error("failed to init webdriver",{err:O,capabilitiesAsString:B});let G=((D=(A=n==null?void 0:n.company)==null?void 0:A.activePlan)==null?void 0:D.plan)==="free";throw(j=O.stack)!=null&&j.includes("at startWebDriverSession")&&((R=O.message)!=null&&R.startsWith("Failed to create session"))&&((x=O.message)!=null&&x.includes("Timeout awaiting 'request'"))&&G?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(O.message)?new Wr(O.message):/capabilit(y|ies)/.test(O.message)?new wi(O.message):/403 Forbidden/.test(O.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(O.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${O.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>ds.zip(i.slice(0,-1),i.slice(1)),r=this._keepAliveRequests.map(({start:i})=>i).filter(Boolean),n=t(r).map(([i,o])=>o-i);return Math.max(...n)}isClosedBrowserError(t){return["session-not-found","no such window","invalid session id"].includes(t==null?void 0:t.name)?!0:["CLIENT_STOPPED_SESSION","BROWSER_TIMEOUT","was terminated due to TIMEOUT","window was already closed","chrome not reachable","not connected to DevTools"].some(n=>t.message.includes(n))}start(){if(this.started)return;this.started=!0;let t=async()=>{let r=a=>this._keepAliveRequests.push({start:Date.now(),id:a}),n=(a,l)=>{let c=this._keepAliveRequests.find(d=>d.id===l);c&&(c[a]=Date.now())};function i(){var a;return(a=window.getTestimStatus)==null?void 0:a.call(window)}if(this.queue.getQueueLength()>0)return;let o=re();r(o);try{await this.executeJS(i),this._isAlive=!0,n("end",o),this.browserClosedFailedKeepAlives=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,Fe.warn("close unexpected alert open"),await this.alertAccept().catch(l=>Fe.warn("failed to click on alert",{err:l}));return}if(Fe.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let l=3;Fe.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:l,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=l&&this.browserClosedCallbacks.forEach(c=>{try{c(a)}catch{}})}else this.browserClosedFailedKeepAlives=0}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Ng(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 vi:r}}async getElement(t){var i;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(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||_.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
18
18
  var fn = ${Rr().getLocatedElementCode};
19
19
  return fn.apply(null, arguments);
20
20
  `,t)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,xe.GET_ELEMENT)}}executeJS(t,...r){return this.execute(t,...r)}async executeCodeAsync(t,r,...n){return await this.timeouts("script",r),await this.executeAsync(t,...n)}async markDynamicParent(t,r){function n({attributeName:i,attributeValue:o,locatedElement:a}){let l=getLocatedElement(a);if(!l)throw new Error("could not find dynamic parent");l.setAttribute(i,o)}await this.executeJS(`
@@ -258,7 +258,7 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
258
258
  var eventData = arguments[0];
259
259
  var funcToRun = ${a};
260
260
  return runCode.call(null, eventData, funcToRun);
261
- `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(zn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),_.flags.useStepResultIdForStepTransactions.isEnabled()&&("stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:zn.warn("useStepResultIdForStepTransactions is enabled but stepResultId is not present in context",{step:t,context:r})),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Wt,ny=v(()=>{"use strict";ta();Wt=class extends ir{isFailedResult(e){return e===!1}}});var vs,iy=v(()=>{"use strict";ta();vs=class extends ir{isFailedResult(e){return!e}}});var ra,oy=v(()=>{"use strict";pe();F();Ko();ra=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(_e(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Vn[t]),this.setWithValueApi(e)}}});var sa,ay=v(()=>{"use strict";pe();Ko();sa=class extends V{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Vn[n])t.push(Vn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var cy={};H(cy,{selectOption:()=>vE});function vE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var ly=v(()=>{"use strict"});var na,uy=v(()=>{"use strict";pe();F();ue();na=class extends V{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(_e(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(ly(),cy)),c=_.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
261
+ `;if(!r)return this.driver.executeJS(d,i);try{return await this.driver.executeJS(d,i)}catch(m){return this.handleExecutionError(m)}}codeExecDone(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this,{result:i={},tstConsoleLogs:o,nodeVersion:a,navigateToDifferentDomain:l}=t;i.exports&&(n.data.exports=i.exports);let c={nodeVersion:a,tstConsoleLogs:o,data:n.data};return this.isFailedResult(i.resultValue)?{...c,success:!1,errorType:r.JS_ASSERTION_FAILED}:this.isExceedingMaxResultSize({result:i,tstConsoleLogs:o},n)?{...c,success:!1,errorType:r.JS_RESULT_MAX_SIZE_EXCEEDED}:{...c,success:!0,exportsTest:i.exportsTest,exportsGlobal:i.exportsGlobal,...l&&{navigateToDifferentDomain:l}}}codeExecFailed(t){let{stepResult:r}=this.sessionPlayerInit.commonConstants,{context:n}=this;if(t.type==="promise")return{data:n.data,success:!1,shouldRetry:!0,isPendingPromise:!0,errorType:r.JS_ASSERTION_FAILED};if(t.reason==="stopped")return{...t,errorType:r.STOPPED};let{result:i={},tstConsoleLogs:o}=t;return{tstConsoleLogs:o,data:n.data,exportsGlobal:i.exportsGlobal,exportsTest:i.exportsTest,success:!1,errorType:r.UNWRAPPED_AUT_REJECT,resultInfo:{error:i.resultValue}}}checkCodeResponse(t){return t!=null&&t.success?this.codeExecDone(t):this.codeExecFailed(t)}getTransactionId(t,r){var i;let n=t.id;return t.id||(zn.warn("step.id doesn't exist on step",{step:t,context:r}),n=r.stepResultId),"stepResultId"in r&&((i=r.stepResultId)!=null&&i.length)?n=r.stepResultId:zn.warn("stepResultId is not present in context",{step:t,context:r}),`${r.testResultId}:${n}`}async performAction(){let{step:t,context:r}=this;this.startTimestamp=Date.now();let n=await this.driver.getBrowserAndOS(),i={transactionId:this.getTransactionId(t,r),id:t.id,eventType:t.type,code:t.code,incomingParams:r.incomingParams,exportsGlobal:this.exportsGlobal,exportsTest:this.exportsTest,context:{config:r.config,data:r.data},testResultId:r.testResultId,browser:n.browser,browserMajor:n.browserMajor};r.isPendingPromise||await this.executeInAut(i);let o=await this.checkStatus(i.transactionId);return this.checkCodeResponse(o)}handleExecutionError(t){throw(t==null?void 0:t.name)==="javascript error"?new Error(t.message):t}}});var Wt,ny=v(()=>{"use strict";ta();Wt=class extends ir{isFailedResult(e){return e===!1}}});var vs,iy=v(()=>{"use strict";ta();vs=class extends ir{isFailedResult(e){return!e}}});var ra,oy=v(()=>{"use strict";pe();F();Ko();ra=class extends V{setWithValueApi(e){let t=this.getTarget();return t!=null&&t.seleniumElement?this.driver.elementIdValue(_e(t.seleniumElement),e):Promise.reject(new Error("missing selenium element"))}performAction(){let e=[],t=this.step.events[0].eventData.keyCode;return t>=32&&t<=127?e.push(String.fromCharCode(t)):e.push(Vn[t]),this.setWithValueApi(e)}}});var sa,ay=v(()=>{"use strict";pe();Ko();sa=class extends V{async performAction(){var i,o;let e=this.context.config.os.startsWith("Mac");if(e&&!((i=this.step.keys)!=null&&i.mac)||!e&&!((o=this.step.keys)!=null&&o.windows))return;let t=[],r=e?this.step.keys.mac:this.step.keys.windows;r.altKey&&t.push("\uE052"),r.ctrlKey&&t.push("\uE051"),r.metaKey&&t.push("\uE03D"),r.shiftKey&&t.push("\uE050");let n=r.keyCode;if(n>=32&&n<=127)t.push(r.key);else if(Vn[n])t.push(Vn[n]);else throw new Error(`Invalid key with keyCode ${n}.`);return await this.driver.sendKeyboardShortcut(t)}}});var cy={};H(cy,{selectOption:()=>vE});function vE(s,e){function t(r,n){let i=Element.prototype.matches,o=i&&isNativeFunction(i)?i:document.createElement(r.tagName).__proto__.matches;do{if(o.call(r,n))return r;r=r.parentElement||r.parentNode}while(r!==null&&r.nodeType===1);return null}try{let r=getLocatedElement(s);if(!r)return{success:!1,status:"failed",result:"option element not found"};let n=t(r,"select");return n?(n.focus(),r.selected?{success:!0,status:"done"}:(r.selected=!0,["input","change"].map(o=>{let a=document.createEvent("HTMLEvents");return a.initEvent(o,!0,!1),a}).forEach(o=>{if(e){n.dispatchEvent(o);return}r.dispatchEvent(o)}),{success:!0,status:"done"})):{success:!1,status:"failed",result:"select element not found"}}catch(r){return{success:!1,status:"failed",result:r.toString()}}}var ly=v(()=>{"use strict"});var na,uy=v(()=>{"use strict";pe();F();ue();na=class extends V{async performAction(){var u,f;let e=this.getTarget(),{seleniumElement:t,locatedElement:r}=e,i=(await this.driver.getBrowserAndOS()).browserMajor,o=this.driver.isSafari(),a=Boolean((u=this.step.element)==null?void 0:u.isShadowed);if(!o||o&&i>=13&&!a)try{return await this.driver.elementIdClick(_e(t))}catch(h){if(!h.message.includes("Cannot check the displayedness of a non-Element argument"))throw h}let{selectOption:l}=await Promise.resolve().then(()=>(ly(),cy)),c=_.flags.safariSelectOptionDispatchEventOnSelectElement.isEnabled(),d=`
262
262
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
263
263
  const isNativeFunction = ${this.sessionPlayerInit.utils.isNativeFunction.toString()};
264
264
  const selectOption = ${l.toString()};
@@ -400,11 +400,11 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
400
400
  `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw la.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw la.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=_.flags.overrideAzureStorageUrl.isEnabled(),n=_.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:l,driver:c}=this,d=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,l.testimServicesApi,r,la);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let h=await Mt(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
401
401
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
402
402
  const downloadAndUploadFile = ${OE()};
403
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Sy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Ry=v(()=>{"use strict";pa=require("url");pe();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.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 ma,xy=v(()=>{"use strict";pe();F();ma=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var fa,Ay=v(()=>{"use strict";pe();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,Cy=v(()=>{"use strict";pe();Kn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ga,Py=v(()=>{"use strict";pe();ga=class extends V{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 ky,Fu,Bu,Oy=v(()=>{"use strict";ky=I(require("@applitools/spec-driver-webdriverio"));mi();we();Fu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=dd["@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:ky.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Bu=new Fu});var Ly,_y,Jn,Dy=v(()=>{"use strict";Ly=I(require("lodash"));pe();W();Oy();_y=P("pixel-validation-step-action"),Jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Bu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Ly.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),_y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){_y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Bu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,ju=v(()=>{"use strict";hs();Y();ta();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,Ny=v(()=>{"use strict";ju();or=class extends Ss{isFailedResult(e){return e===!1}}});var ha,My=v(()=>{"use strict";ju();ha=class extends Ss{isFailedResult(e){return!e}}});var ya,Uy=v(()=>{"use strict";hs();pe();Y();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,Fy=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,By=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,jy=v(()=>{"use strict";pe();ba=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ta,$y=v(()=>{"use strict";pe();Ta=class extends V{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 _E(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){_E(LE,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var LE,$u=v(()=>{"use strict";Uh();jh();Jh();Yh();Qh();ty();ny();iy();oy();ay();uy();py();dy();gy();by();Iy();Ry();xy();Ay();Cy();Py();Dy();Ny();My();Uy();Fy();By();jy();$y();LE={locate:Gn,scroll:Yo,mouse:Xo,submit:ia,text:Zo,"special-key":ra,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":Qo,"text-validation":qn,"wait-for-text-validation":qn,"select-option":na,"drop-file":ca,"input-file":ua,hover:oa,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":ga,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ha,"node-package":ya,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Wy,DE,Es,Wu=v(()=>{"use strict";Wy=["simple-ui-verification","wait-for-simple-ui-verification"],DE=[...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","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Es=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=DE.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 Gy={};H(Gy,{SeleniumTestPlayer:()=>Yn});var Vy,NE,Yn,Vu=v(()=>{"use strict";F();Vy=require("@applitools/eyes-sdk-core");Ln();Y();W();_u();_h();Mu();Ko();Nh();Uu();we();$u();Wu();NE=P("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Jo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new zo(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ho(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Dh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK: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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){NE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Hu={};H(Hu,{WorkerSelenium:()=>Gu});function UE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var va,ME,Gu,qu=v(()=>{"use strict";F();je();Wn();W();Pt();Po();ie();ku();Y();Vu();we();at();va=P("worker-selenium"),ME=1e9,Gu=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,ME),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ki(),initializedFromCache:Ji()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),UE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Mn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(va.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw va.error("failed to run test once",{err:u}),u}}}});var Hy,qy,Ge,FE,BE,zu,vt,Sa=v(()=>{"use strict";Hy=I(require("ora")),qy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),FE="https://tdc.tricentis-cloud.com",BE="https://ui.headspin.io",zu=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||oc}/${cc}/devices`:t===L.TESTIM_TDC?`${r||ac}/${cc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Gs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Qn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await qy.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Us}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?BE:FE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ju({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await Xn({appId:e,projectId:t});return{appUrl:`${he}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Ad*60))+1)*60*1e3,Math.max(xd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Hy.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 d=await Ku({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Us}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${lc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?oc:ac}/${lc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Cd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new zu});function zy({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"&&!jE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function $E({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function WE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function VE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:WE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ea(s){return"id"in s?s.id:s.packageName}function GE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function HE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=GE(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Ea(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Ea(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Ea(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ky({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=VE(o.type,i,n);return HE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Ra({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 xa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?uc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":uc:".*")}function qE(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function zE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Is)}}function Jy(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function KE(s){return Jy(s,e=>e.startsWith("browserstack."),"browserstack.")}function JE(s){return Jy(s,e=>!e.startsWith("browserstack."))}function Yy(s){return!s||!Xy(s)?"2.0.0":s}function Xy(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Qy({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Xy(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function YE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=qE(i,s),h=await Qn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Ra({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??xa({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function XE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Pd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=zE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function QE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Qy({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Yy(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ZE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=KE(n.browserstack),g=(0,Dr.omit)(JE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||Qy({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Yy(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function eI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Ky(s);if(L.TESTIM_TVC===s.gridInfo.type)return await YE(s);if(L.P_CLOUDY===s.gridInfo.type)return XE(s);if(L.SAUCELABS===s.gridInfo.type)return QE(s);if(L.BROWSERSTACK===s.gridInfo.type)return ZE(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function tI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function Zy(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);zy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await eI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=tI(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Yu.default)("2m"),f=(0,Yu.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function eb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;zy({nativeAppMetadata:r,appPath:i,gridInfo:t}),$E({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Ky({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function tb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function rb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Yu,Dr,Is,jE,Xu=v(()=>{"use strict";Yu=I(require("ms"));ue();ie();Sa();Dr=require("lodash");F();de();ge();Is="appium:",jE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Aa,nb=v(()=>{"use strict";Aa=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 Ca,ib=v(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Qu,Pa,ob=v(()=>{"use strict";W();Qu=P("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var rI,cb,ab,Rs,Zu=v(()=>{"use strict";rI=I(require("webdriverio")),cb=require("@applitools/eyes-sdk-core");nb();Mu();W();ib();Uu();we();$u();ob();Wu();ab=P("appium-test-player"),Rs=class{constructor(e,t,r,n=rI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Jo()),this.sessionPlayer=new a(e,{tabService:new Aa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:cb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),ab.info("appium session deleted",{...i}))}catch(o){ab.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function sI(s){return await Te(`${s}/api/status`)}async function lb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function ub(s){if((await sI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var pb=v(()=>{"use strict";Ve()});var db={};H(db,{WorkerLocalTma:()=>sp});var Mr,ep,tp,rp,sp,mb=v(()=>{"use strict";Ve();Xu();Wn();F();W();Pt();Zu();we();pb();Sa();Mr=P("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await ub(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),lb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=tb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new rp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Vs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new tp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new ep(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var gb={};H(gb,{WorkerAppium:()=>np});var fb,Ur,np,hb=v(()=>{"use strict";F();Xu();fb=require("linkedom");Wn();W();Pt();Zu();we();Sa();ie();os();Ur=P("worker-appium"),np=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await eb(f)):h=await Zy({...f,shouldRunInEnhancedMode:a}),Ur.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:rb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Ur.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Ur.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Ur.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Mf(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Ur.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,fb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Ur.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),c)}catch(y){throw Ur.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.147.0"}}});var ka,yb=v(()=>{"use strict";F();Ln();Y();ka=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var bb,Oa,Tb=v(()=>{"use strict";bb=I(require("ws"));F();Oa=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 bb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var La,ip,_a,wb=v(()=>{"use strict";F();La=I(require("chrome-launcher"));eu();Tb();En();ip=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Ro({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...La.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await La.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},_a=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new ip(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var op={};H(op,{WorkerExtension:()=>Zn});function nI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function vb(s){return nI(s)?s:new Error(s)}var dt,Zn,Da=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();yb();wb();at();dt=P("worker-ext"),Zn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ki(),initializedFromCache:Ji(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await gc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),vb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),vb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var cp={};H(cp,{WorkerExtensionSingleBrowser:()=>ap});var iI,oI,ap,lp=v(()=>{"use strict";je();F();W();xu();Pt();Da();iI=P("base-worker"),oI=500,ap=class extends Zn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(iI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(oI)}}});var up,Na,Sb=v(()=>{"use strict";Ln();de();je();hl();at();au();Y();W();ie();gh();Mo();up=P("worker-manager"),Na=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(mb(),db))).WorkerLocalTma:(await Promise.resolve().then(()=>(hb(),gb))).WorkerAppium;default:return Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension;case Bn.find(n=>n===r):return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new No(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,Qa,ni,Za)=>(d++,wf({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:Za,gridType:O}),t.testStartAndReport(Pe,r,ve,Qa,ni)),G=async(Pe,Et,ve,Qa,ni,Za)=>{var od,ad,cd;d--;let et={...(x==null?void 0:x.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((od=i.gridData)==null?void 0:od.name),et.gridType=(ad=i.gridData)==null?void 0:ad.type,et.gridProvider=(cd=i.gridData)==null?void 0:cd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,ve,r,Qa,ni,et).catch(BT=>up.error("testEndAndReport threw an error",{err:BT})),ni)return;this.combinedTestResults[ve.resultId]=ve,vf({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:up,isStartUp:D,projectType:R,appSource:Za}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:qi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await zi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw up.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var pp,ae,Eb=v(()=>{"use strict";pp=class{static colorString(e,t){return`${e}${t}${pp.Reset}`}},ae=pp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ei,Ib,Ma,dp,mp,Fr,fp=v(()=>{"use strict";ei=I(require("lodash"));F();W();de();ie();je();ts();gl();hl();ge();ue();Pt();ag();Y();Sb();Mo();Ib=require("uuid");Eb();({CLI_MODE:Ma}=Ut),dp=P("test-plan-runner"),mp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return mp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Na(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=hi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Sf({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(dp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ma.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await bp(i.project),ei.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;$d(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new bo(m,n,o,a),f=ei.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await gp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await hp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){dp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ei.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ti(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ti(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ti(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ma.APPIUM&&await Iu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await af(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Eu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Eu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await yp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;dp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await yh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Ma.APPIUM&&(a=await Xn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Ma.APPIUM&&await Iu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=fn(),r=[];await this.reportTestRunnerStarted(e.project,e),Ks(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ei.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Fr=mp;Fr._id=(0,Ib.v4)()});var Re={};H(Re,{addTestRetry:()=>Kl,clearTestResult:()=>vu,deleteCloudflareTunnel:()=>xp,fetchLambdatestConfig:()=>Yl,fixGridAppIDStructure:()=>Ju,forceUpdateCloudflareTunnelRoutes:()=>Rp,getAllGrids:()=>fl,getAppDetails:()=>Xn,getApplitoolsIntegrationData:()=>bp,getBrowserStackSessionMetaData:()=>hI,getCloudflareTunnel:()=>Ip,getEditorUrl:()=>mI,getGridSlot:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>cu,getMobileDevicesFromGrid:()=>Qn,getRealData:()=>$l,getS3Artifact:()=>xn,getS3ArtifactText:()=>jl,getSuiteTestList:()=>Ru,getTestPlan:()=>dI,getTestPlanTestList:()=>ti,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>Sp,initializeUserWithAuth:()=>Ep,isTestResultCompleted:()=>wu,keepAliveCompanySlots:()=>Fl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>vp,loadTest:()=>Un,releaseCompanySlot:()=>Ml,releaseGridSlot:()=>pl,reportExecutionFinished:()=>To,reportExecutionStarted:()=>zl,reportRunnerFinished:()=>hp,reportRunnerStarted:()=>gp,requestCompanySlot:()=>Nl,saveRemoteStep:()=>uu,saveTestPlanResult:()=>yp,updateCompanySlot:()=>Ul,updateExecutionTests:()=>ql,updateRemoteRunFailure:()=>Ap,updateTestDataArtifact:()=>wo,updateTestResult:()=>jo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Ku,uploadRunDataArtifact:()=>Su,validateUserAccessKey:()=>cl});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[_c]:Fr.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function uI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Vs(`${he}${s||""}`,e,t,o,n)}async function ri(s,e){let t=await xs();return await wc(`${he}${s||""}`,e,t)}async function xb(s,e){let t=await xs();return await Ws(`${he}${s||""}`,e,t)}async function pI(s,e){let t=await xs();return await Gs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function xn(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function jl(s){return(0,ee.default)(()=>pI(`/storage${s}`))}async function gp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function hp(s){return await xb("/test-runner",{projectId:s})}async function dI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function vp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Un({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function yp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ri("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:aI,...i}),{retries:o,factor:1})}function ql(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ri("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function zl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Zi(),yf));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function To(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ri("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ti(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Ru({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Xn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Sp(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function wu(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function ul(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function ml(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Ep({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Tp.default[y](Tp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function mI(){if(Ns)return{editorUrl:Ns};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function fl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function $l(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function jo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function vu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function uu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function fI(s){return s.startsWith("/")?s:`/${s}`}function gI(s,e,t){let r=fI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ab(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=gI(l,lI,s),d=Buffer.from(Rb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>uI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Kl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function bp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Ip(s,e){try{return await ri("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Rp(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function xp(s,e){try{return await xb(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Ap(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Qn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${cI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Ku({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ju(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ml(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,ee.default)(()=>ri("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Fl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function hI(s,e){return await Te(`${Us}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function cl(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var Tp,ar,Rb,ee,wp,aI,_t,te,cI,lI,Yl,cu,Su,wo,ge=v(()=>{"use strict";Tp=I(require("chalk")),ar=I(require("lodash")),Rb=I(require("pako"));F();de();ie();Ve();at();ee=I(require("p-retry")),wp=I(require("object-hash"));Y();W();fp();aI=tt(),_t=P("testim service api"),te=3,cI="/grid",lI="test-result-artifacts";Yl=async()=>(0,ee.default)(()=>Ae("/grid/lt/config"),{retries:te,factor:1}),cu=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Su=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await Ab(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`),wo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await Ab(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Pc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`)});async function Cb(){let s=await Promise.any(yI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var yI,Pb=v(()=>{"use strict";Ve();yI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ua(){return tt()}var Cp=v(()=>{"use strict";F()});function wI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function vI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Pp.default[i](Pp.default[n](r.text)))})}async function si(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?TI:bI,f=Ua(),h=xc(),g=await Dm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Cb()}catch(b){kb.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(wI(a),T=!1,await Ep({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return vI(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(kb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),ef(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Pp,kb,bI,TI,Ob=v(()=>{"use strict";Pp=I(require("chalk"));je();ge();Yt();at();Pb();ie();W();ue();Cp();F();Zr();kb=P("initializeUserWithAuth"),bI=1e3*60*5,TI=1e3*60*60*10});async function Db(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Hi():s.chromeBinaryLocation,e=tn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Qc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Xc(s.installCustomExtension,n)}return await e,t}async function Nb(s){var o;SI.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>_b*1e6)throw new Error(`${kp} exceeded ${_b}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${kp} cannot be parsed.${Fa.EOL}${a}`)}let n=new Lb.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Fa.EOL);throw new Error(`${kp} is malformed.${Fa.EOL}${a}`)}return r.entries}var Fa,Lb,_b,kp,SI,Op=v(()=>{"use strict";Fa=I(require("node:os"));F();mm();sn();Lb=I(require("ajv"));ie();rl();W();Ob();_b=1,kp="JSON file supplied to --mock-network-pattern",SI=P("prepare runner")});function jb(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function $b(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=vo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Wb=v(()=>{"use strict";Cn();rs();Y()});var Vb,CI,PI,Np,Gb=v(()=>{"use strict";Vb="TST_CREDS",CI=["username","password"],PI="$encrypted",Np={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of CI)t[r]={[PI]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(Vb)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[Vb]:this.proxyPlaceholder})}}});var jp={};H(jp,{doLogin:()=>Bp,getProjectId:()=>kI,getToken:()=>OI});async function kI(){return zb("projectId")}async function OI(){return zb("token")}function qb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function _I(){let s=(await import("express")).default(),e=async function(){return qb(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Re)),{editorUrl:n}=await r();uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Bp({overwriteExisting:s=!0,projects:e=null}={}){let t=Mp.homedir(),r=Up.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await qb(_I(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Hb(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Hb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Hb(s,e){await Fp.promises.writeFile(s,ja.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function zb(s){let e=Mp.homedir(),t=Up.join(e,".testim"),r=await ye(t),n={};if(r)try{n=ja.parse((await Fp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Mp,Up,ja,Fp,$a=v(()=>{"use strict";Mp=I(require("os")),Up=I(require("path")),ja=I(require("yaml"));F();Fp=require("fs");Y();Ol()});var tT={};H(tT,{process:()=>jI,program:()=>p});var Wp,Xb,Wa,Qb,Vt,De,Zb,LI,Le,Hp,DI,NI,Jb,eT,MI,Vp,Gp,qp,$p,Lt,UI,p,FI,BI,Yb,jI,zp=v(()=>{"use strict";Wp=I(require("ms")),Xb=I(require("chalk")),Wa=I(require("node:fs")),Qb=I(require("node:url")),Vt=I(require("lodash")),De=I(require("node:path"));F();Cn();Wb();Yt();Zb=require("commander");ie();Y();jr();F();ue();Gb();Mo();LI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),Hp=new Zb.Command,DI=s=>s.split(","),NI=(s,e)=>!s||s.length===0?e:s,Jb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],eT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Hp.help(g=>g.split(`
403
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Sy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Ry=v(()=>{"use strict";pa=require("url");pe();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.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 ma,xy=v(()=>{"use strict";pe();F();ma=class extends V{async performAction(){await ce(this.step.durationMS||0)}}});var fa,Ay=v(()=>{"use strict";pe();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Kn,Cy=v(()=>{"use strict";pe();Kn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ga,Py=v(()=>{"use strict";pe();ga=class extends V{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 ky,Fu,Bu,Oy=v(()=>{"use strict";ky=I(require("@applitools/spec-driver-webdriverio"));mi();we();Fu=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=dd["@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:ky.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:i}=Z(),o=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return i.rememberCreatedBatch(r,n),o}},Bu=new Fu});var Ly,_y,Jn,Dy=v(()=>{"use strict";Ly=I(require("lodash"));pe();W();Oy();_y=P("pixel-validation-step-action"),Jn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,l=await Bu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Ly.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),_y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){_y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Bu.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Ss,ju=v(()=>{"use strict";hs();Y();ta();Ss=class extends ir{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await gs(i,o,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var or,Ny=v(()=>{"use strict";ju();or=class extends Ss{isFailedResult(e){return e===!1}}});var ha,My=v(()=>{"use strict";ju();ha=class extends Ss{isFailedResult(e){return!e}}});var ya,Uy=v(()=>{"use strict";hs();pe();Y();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await fs(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Lr,Fy=v(()=>{"use strict";pe();Lr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,By=v(()=>{"use strict";pe();be=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,jy=v(()=>{"use strict";pe();ba=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ta,$y=v(()=>{"use strict";pe();Ta=class extends V{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 _E(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){_E(LE,e),e.registerLocateStepActionUtils(Gn.getUtils(s))}var LE,$u=v(()=>{"use strict";Uh();jh();Jh();Yh();Qh();ty();ny();iy();oy();ay();uy();py();dy();gy();by();Iy();Ry();xy();Ay();Cy();Py();Dy();Ny();My();Uy();Fy();By();jy();$y();LE={locate:Gn,scroll:Yo,mouse:Xo,submit:ia,text:Zo,"special-key":ra,"user-code":Wt,"validation-code-step":Wt,"wait-for-code-step":Wt,"action-code-step":Wt,"condition-step":vs,"skip-code-step":vs,"element-code-step":vs,"evaluate-expression":Qo,"text-validation":qn,"wait-for-text-validation":qn,"select-option":na,"drop-file":ca,"input-file":ua,hover:oa,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":Kn,"api-action":Kn,"api-code-step":Wt,"extract-text":ga,"simple-ui-verification":Jn,"wait-for-simple-ui-verification":Jn,"cli-validation-download-file":Lr,"cli-wait-for-download-file":Lr,"network-validation-step":Lr,"cli-validation-code-step":or,"cli-wait-for-code-step":or,"cli-action-code-step":or,"cli-api-code-step":or,"cli-condition-step":ha,"node-package":ya,"email-code-step":Wt,"cli-email-code-step":or,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"sfdc-step-login":be,"sfdc-step-loginas":be,"sfdc-step-logout":be,"sfdc-step-sobjectcreate":be,"sfdc-step-sobjectdelete":be,"sfdc-step-findrecord":be,"sfdc-step-quickaction":be,"sfdc-step-sobjectedit":be,"sfdc-step-sobjectvalidate":be,"sfdc-step-launchapp":be,"sfdc-step-wait-for-page-load":be,"sfdc-step-closeconsoletabs":be,"sfdc-step-relatedlistaction":be,"sfdc-step-permission-validation":be,"sfdc-step-convert-lead-to-opportunity":be,"sfdc-step-quotelineeditor":be,"sfdc-document-validation":Lr,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var Wy,DE,Es,Wu=v(()=>{"use strict";Wy=["simple-ui-verification","wait-for-simple-ui-verification"],DE=[...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","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Es=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=i=>{let o=this.getTotalStepTimeLeftToPlay(e,i),a=5e3;return o<=a?[a]:[Math.max(a,o/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=DE.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 Gy={};H(Gy,{SeleniumTestPlayer:()=>Yn});var Vy,NE,Yn,Vu=v(()=>{"use strict";F();Vy=require("@applitools/eyes-sdk-core");Ln();Y();W();_u();_h();Mu();Ko();Nh();Uu();we();$u();Wu();NE=P("SeleniumTestPlayer"),Yn=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new Es(Jo());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new zo(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ho(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Dh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new ws(this.driver),FrameLocator:m,portSelector:qo,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK: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=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){NE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=["app.testim.io"].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Hu={};H(Hu,{WorkerSelenium:()=>Gu});function UE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>M(`Got event ${t}`))}var va,ME,Gu,qu=v(()=>{"use strict";F();je();Wn();W();Pt();Po();ie();ku();Y();Vu();we();at();va=P("worker-selenium"),ME=1e9,Gu=class extends Ot{initPlayer(t){return new Yn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){M("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Ts(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await o.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),M("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),M("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,ME),await this.windowUtils.validatePageIsAvailable(),M("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Ki(),initializedFromCache:Ji()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),UE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await Mn(this.options))[this.testId]);let d=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(f)}),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof oe&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(va.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=o.maxKeepAliveGap();f>=3e4&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await o.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});o.start(),M("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),M("right after super.runTestOnce in workerSelenium");let u=await d();return M("right after runSeleniumTest"),u}catch(u){throw va.error("failed to run test once",{err:u}),u}}}});var Hy,qy,Ge,FE,BE,zu,vt,Sa=v(()=>{"use strict";Hy=I(require("ora")),qy=require("jimp");de();Ve();ge();W();ie();we();ue();Ge=P("mobile-grid-service"),FE="https://tdc.tricentis-cloud.com",BE="https://ui.headspin.io",zu=class{constructor(){this.gridsAppIdGetter={[L.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[L.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[L.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[L.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[L.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[L.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===L.TESTIM_TDC||e===L.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===L.TESTIM_HEADSPIN?`${r||oc}/${cc}/devices`:t===L.TESTIM_TDC?`${r||ac}/${cc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await We({url:r,headers:n,body:i})}catch(o){throw Ge.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw Ge.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Gs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===L.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===L.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([L.BROWSERSTACK,L.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,l,c;if(t===L.TESTIM_HEADSPIN||t===L.TESTIM_TDC){let d=await Qn({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===L.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===L.SAUCELABS)return e.testobject_device_name;if(t===L.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:l}=e,{project:c,projectData:{type:d}={},company:{companyId:m=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===L.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:w}=Z();y=w(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,c,d,m,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Ir(c,o,a,l,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),Ge.info("device details updated on testResult",{testResultId:l,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===L.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),l=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:l}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[l,c]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),d=Buffer.from(l,"base64"),m=await qy.Jimp.fromBuffer(d),u=m.bitmap.width,f=m.bitmap.height;return{scaleFactor:u/c.width,width:u,height:f}}catch(o){return Ge.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,l,c,d){let[m,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,d),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:l,gridId:c})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...m}}async buildRemoteResultLink(e,t,r){return e.type===L.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Us}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===L.SAUCELABS?r.testobject_test_report_url:e.type===L.TESTIM_TVC?r.replayUrl:e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC?`${e.type===L.TESTIM_HEADSPIN?BE:FE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:l}=t,c=await this.getTmaDeviceDetails(l,e);return await Ir(a,n,i,o,"RUNNING",{device:c}),Ge.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:c}),c}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(_.flags.allowFixingAppIdStructure.isEnabled()&&(Ge.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ju({gridAppId:o,gridId:e.gridId,projectId:r,gridType:n,appId:i.appId,gridHost:e.host})),o):t.getAppPathByGridType(n,e.gridId,i)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await Xn({appId:e,projectId:t});return{appUrl:`${he}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Ad*60))+1)*60*1e3,Math.max(xd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[L.BROWSERSTACK]:{name:"Browserstack"},[L.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[L.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Hy.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 d=await Ku({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),Ge.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){Ge.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else Ge.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===L.BROWSERSTACK||f===L.TESTIM_TVC||f===L.P_CLOUDY;if(g){let T=t.projectData.type,w=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});w&&(Ge.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=g),!w&&y&&(Ge.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!w&&!y&&Ge.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:i,host:o,key:a,type:l,apiUrl:c}=t;if(l===L.BROWSERSTACK){let u=`${Us}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===L.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(l===L.TESTIM_HEADSPIN||l===L.TESTIM_TDC){let u=`${c}/${lc}/apps`;return c||(u=`${l===L.TESTIM_HEADSPIN?oc:ac}/${lc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===L.TESTIM_TVC){let u=`${Cd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&Ge.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===L.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await Tc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},vt=new zu});function zy({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"&&!jE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function $E({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==L.TESTIM_TDC&&e.type!==L.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function WE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function VE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===L.TESTIM_TDC,a=s===L.TESTIM_HEADSPIN,l=o?"tdc":"headspin",c=a&&_.flags.enableBatchHeadSpin.isEnabled(),d=o&&(_.flags.enableBatchTDC.isEnabled()||_.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=_.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture.video`]:!0,..._.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...i&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:WE(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function Ea(s){return"id"in s?s.id:s.packageName}function GE(s,e){return{[`${e===L.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function HE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=GE(n,t.gridData.type));let m=()=>o===void 0&&n?!0:typeof o=="string"?o!=="false":o;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":Ea(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Nr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:Ea(t)},...r&&{[`${i}app`]:r},...e};case"android":return{platformName:"Android",[`${i}autoGrantPermissions`]:!0,[`${i}automationName`]:o?"WaldoTestim":"UiAutomator2",...n&&{[`${i}appWaitActivity`]:`${n}, *`},...t&&{[`${i}appPackage`]:Ea(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Ky({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let l=VE(o.type,i,n);return HE({projectType:s,sessionCaps:l,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Ra({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 xa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===L.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?uc:i.deviceNameRegex:t==="ios"&&r===L.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":uc:".*")}function qE(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function zE(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Is)}}function Jy(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function KE(s){return Jy(s,e=>e.startsWith("browserstack."),"browserstack.")}function JE(s){return Jy(s,e=>!e.startsWith("browserstack."))}function Yy(s){return!s||!Xy(s)?"2.0.0":s}function Xy(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Qy({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&o.test(s),d=l||c;if(t){let m=Xy(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function YE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:l}){let{osVersion:c,deviceName:d}=n,m=(a==null?void 0:a.mobile)||{},{type:u}=i,f=qE(i,s),h=await Qn({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:S})=>{var E;return((E=m.staticAllocation)==null?void 0:E.deviceUdid)===S}),y=(g==null?void 0:g.osVersion)??Ra({osVersion:c,mobileConfig:m}),T=(g==null?void 0:g.name)??xa({deviceName:d,mobileConfig:m,projectType:s,gridType:u}),w=qe(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":w,...l&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:l})}function XE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=i,h=_.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),w={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...w,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Pd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=zE(b)),t="",Nr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Is}})}function QE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Dr.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Qy({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},w={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:Yy(g.appiumVersion),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Is),"sauce:options":{...T,...w,...(0,Dr.omit)(g,"appiumVersion")}};return Nr({projectType:s,sessionCaps:b,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return Nr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ZE({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=i,u=Ra({osVersion:l,mobileConfig:d}),f=xa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=KE(n.browserstack),g=(0,Dr.omit)(JE(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:w}=n.browserstack||{},b=_.flags.enableAppium2BrowserStack.isEnabled();if(b||Qy({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:i.user,accessKey:i.key,appiumVersion:b?"2.0.1":Yy(h.appiumVersion),projectName:y||o.project,buildName:T||o.executionId,debug:!0,networkLogs:!0},A={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Is),"bstack:options":{...E,...(0,Dr.omit)(h,"appiumVersion")}};return Nr({projectType:s,sessionCaps:A,appiumPrefix:Is,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let S={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:w||o.testResultId,project:y||o.project,build:T||o.executionId,buildTags:Object.values(o).join(","),"browserstack.user":i.user,"browserstack.key":i.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Nr({projectType:s,sessionCaps:S,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}async function eI(s){if(L.TESTIM_TDC===s.gridInfo.type||L.TESTIM_HEADSPIN===s.gridInfo.type)return Ky(s);if(L.TESTIM_TVC===s.gridInfo.type)return await YE(s);if(L.P_CLOUDY===s.gridInfo.type)return XE(s);if(L.SAUCELABS===s.gridInfo.type)return QE(s);if(L.BROWSERSTACK===s.gridInfo.type)return ZE(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function tI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,l={};return n==="dynamic"&&(!i&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!o&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),i&&(l.manufacturer=i),o&&(l.os_version=o),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}async function Zy(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);zy({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=await eI(s);if(e.type===L.TESTIM_HEADSPIN||e.type===L.TESTIM_TDC){let y=e.type===L.TESTIM_HEADSPIN?"headspin":"tdc",T=tI(r,i==null?void 0:i.mobile);if(!(0,Dr.isEmpty)(T)){let w=Object.entries(T).map(([b,S])=>S.split(",").map(E=>E===".*"||E==="="?"":`${b}:${E}`).join(",")).join(" ").trim();l[`${y}:selector`]=w}}let c=e.type===L.TESTIM_TVC?{alwaysMatch:l}:l,d=_.flags.increaseTDCRequestTimeout.isEnabled(),m=0,u=(0,Yu.default)("2m"),f=(0,Yu.default)("12m"),h=mr(_.flags.appiumConnectionRetryCount.getValue(),m),g=mr(_.flags.appiumConnectionRequestTimeout.getValue(),u);return d&&g<f&&(g=f),{...a,desiredCapabilities:l,connectionRetryTimeout:g,capabilities:c,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function eb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;zy({nativeAppMetadata:r,appPath:i,gridInfo:t}),$E({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=Ky({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function tb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=Nr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function rb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Yu,Dr,Is,jE,Xu=v(()=>{"use strict";Yu=I(require("ms"));ue();ie();Sa();Dr=require("lodash");F();de();ge();Is="appium:",jE=[L.BROWSERSTACK,L.SAUCELABS,L.TESTIM_HEADSPIN,L.TESTIM_TDC,L.TESTIM_TVC,L.P_CLOUDY]});var Aa,nb=v(()=>{"use strict";Aa=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 Ca,ib=v(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Xs;this.getLinksFromUnescapeHTML=Qs}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Qu,Pa,ob=v(()=>{"use strict";W();Qu=P("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Qu.info("foundFrameCallback-mock invoked"),{}}locate(){return Qu.info("locate-mock invoked"),{}}async findFrame(){return Qu.info("findFrame-mock invoked"),{}}}});var rI,cb,ab,Rs,Zu=v(()=>{"use strict";rI=I(require("webdriverio")),cb=require("@applitools/eyes-sdk-core");nb();Mu();W();ib();Uu();we();$u();ob();Wu();ab=P("appium-test-player"),Rs=class{constructor(e,t,r,n=rI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Es(Jo()),this.sessionPlayer=new a(e,{tabService:new Aa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qo,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:cb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),ab.info("appium session deleted",{...i}))}catch(o){ab.error("error while deleting appium session",{...i,error:o})}finally{let{commonConstants:o}=Z();e.off(o.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function sI(s){return await Te(`${s}/api/status`)}async function lb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function ub(s){if((await sI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var pb=v(()=>{"use strict";Ve()});var db={};H(db,{WorkerLocalTma:()=>sp});var Mr,ep,tp,rp,sp,mb=v(()=>{"use strict";Ve();Xu();Wn();F();W();Pt();Zu();we();pb();Sa();Mr=P("worker-appium"),ep=class extends Error{},tp=class extends Error{},rp=class extends Error{},sp=class extends Ot{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),i=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n,!1);return t.sessionPlayer.playbackManager.appiumApi=i,i}async getBrowserOnce(t,r,n,i){var E;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:l}=this.options;await ub(o);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:A}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=A}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:w,version:b},S]=await Promise.all([this.getAppStateFromDevice(o,a,T),lb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if(Mr.info("device status and app state",{deviceStatus:S,appInstalled:w,version:b,executionId:this.executionId,testResultId:this.testResultId}),!w&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!w&&y&&(await this.installApp(o,a,y),Mr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let A={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=tb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),j={capabilities:{udid:a,...D}};Mr.info("requesting new appium session from TMA",{tmaSessionSettings:j,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(o,j,g);this.sessionData=R;let x=await m.attach({sessionId:R.sessionId,capabilities:D,options:{capabilities:D}});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Mr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:x.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:x.capabilities})}catch(A){throw Mr.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await We({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new rp(l):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,l=(await Te(o)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await Mt(n);await Vs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new tp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new ep(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Mr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Mr.error("failed to run test once",{err:c}),c}}}});var gb={};H(gb,{WorkerAppium:()=>np});var fb,Ur,np,hb=v(()=>{"use strict";F();Xu();fb=require("linkedom");Wn();W();Pt();Zu();we();Sa();ie();os();Ur=P("worker-appium"),np=class extends Ot{initPlayer(t){return new Rs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==L.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:l}=n,c=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),d=o==="android"?t.androidActivityWait:null,m=t.nativeAppMetadata;if(!m)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectType:o,nativeAppMetadata:m,appPath:c,androidActivityWait:d,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(i,this.options.deviceUdid),h=await eb(f)):h=await Zy({...f,shouldRunInEnhancedMode:a}),Ur.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:m,capabilities:rb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await l.remote(h),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Ur.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Ur.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Ur.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Mf(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Ur.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===L.TESTIM_HEADSPIN||i===L.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===L.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,l=n||"runner",c=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let d;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:w,port:b,path:S}=await vt.getHeadSpinDeviceConnection(this.options.gridData,y);d=`${T}://${w}:${b}${S}`}else d=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let m=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:m,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device},a.playbackManager.appiumApi=new i(d,this.activeSession.sessionId,fb.DOMParser,((g=this.device)==null?void 0:g.domMode)==="enhanced"),this.startKeepAlive(a.playbackManager.appiumApi),o.initialize({serverUrl:this.options.localRCASaver});let u=async()=>{try{let y=await new Promise((w,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:w,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Ur.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),c)}catch(y){throw Ur.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:runner-v4.149.0"}}});var ka,yb=v(()=>{"use strict";F();Ln();Y();ka=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var bb,Oa,Tb=v(()=>{"use strict";bb=I(require("ws"));F();Oa=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 bb.default(this._cdpUrl,{timeout:e}),r=Kt(i=>{t.once("open",i)}),n=Kt(i=>{t.once("error",i)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",i=>this.onCDPMessage(i)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((l,c)=>{this._cdpCallbacks.set(i,{resolve:l,reject:c})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var La,ip,_a,wb=v(()=>{"use strict";F();La=I(require("chrome-launcher"));eu();Tb();En();ip=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Ro({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=m.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...La.Launcher.defaultFlags().filter(w=>w!=="--disable-extensions")];this.chrome=await La.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let f=await gr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),as(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},_a=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new ip(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var op={};H(op,{WorkerExtension:()=>Zn});function nI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function vb(s){return nI(s)?s:new Error(s)}var dt,Zn,Da=v(()=>{"use strict";je();Y();Wn();F();W();Pt();ie();yb();wb();at();dt=P("worker-ext"),Zn=class extends Ot{initPlayer(){return this.options.useChromeLauncher?new _a(this.id):new ka(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw dt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Ki(),initializedFromCache:Ji(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Q.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var i;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((i=this.options.browserstack)!=null&&i["browserstack.user"])){let o={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(o)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:i}=this;M("WorkerExtension runTestOnce");let o=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(d.cdpTestRunner),m,Me.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return dt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw dt.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(M("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await o(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw dt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Me.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;dt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),dt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:i}),m.unregisterToClosedBrowser(y),T.type=qs.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=le(e.onCompleted(),this.testRunTimeout,Me.TEST_COMPLETE_TIMEOUT_MSG),w=await gc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(w.success),w.reason)}catch(E){dt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(dt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(dt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),w.keepAliveIssue=b),{...w,...e.seleniumPerfStats.getStats()}}catch(T){throw dt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:i}),vb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw dt.warn("failed to start url",{err:h}),vb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),M("WorkerExtension super.runTestOnce"),await c()}catch(d){throw dt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var cp={};H(cp,{WorkerExtensionSingleBrowser:()=>ap});var iI,oI,ap,lp=v(()=>{"use strict";je();F();W();xu();Pt();Da();iI=P("base-worker"),oI=500,ap=class extends Zn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await jn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,i){return Q.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,i)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(iI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let i=this.handleQuarantine(t);if(i)return i;M("before runTest onTestStarted single browser");let o=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=o.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ce(oI)}}});var up,Na,Sb=v(()=>{"use strict";Ln();de();je();hl();at();au();Y();W();ie();gh();Mo();up=P("worker-manager"),Na=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(mb(),db))).WorkerLocalTma:(await Promise.resolve().then(()=>(hb(),gb))).WorkerAppium;default:return Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension}else switch(r){case(Or.find(n=>n===r)&&Dn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(lp(),cp))).WorkerExtensionSingleBrowser;case Or.find(n=>n===r):return(await Promise.resolve().then(()=>(Da(),op))).WorkerExtension;case Bn.find(n=>n===r):return(await Promise.resolve().then(()=>(qu(),Hu))).WorkerSelenium;default:throw new C(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return M("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{M("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,f)=>new Promise(h=>{var fe,Ze,St,Br,k,N,$,K;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new No(r,n,e,i,o,t),this.combinedTestResults={};let T=((fe=i.company)==null?void 0:fe.ucid)||"",w=(Ze=i.company)==null?void 0:Ze.companyId,b=(St=i.company)==null?void 0:St.name,S=i.source||"cli",E=i.user,A=(Br=i.company)==null?void 0:Br.planType,D=(k=i.company)==null?void 0:k.isStartUp,j=(N=i.projectData)==null?void 0:N.name,R=($=i.projectData)==null?void 0:$.type,x=i.lightweightMode,O=(K=i.gridData)==null?void 0:K.type,B=(Pe,Et,ve,Qa,ni,Za)=>(d++,wf({executionId:r,projectId:g,testId:Et,resultId:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,isStartUp:D,projectType:R,appSource:Za,gridType:O}),t.testStartAndReport(Pe,r,ve,Qa,ni)),G=async(Pe,Et,ve,Qa,ni,Za)=>{var od,ad,cd;d--;let et={...(x==null?void 0:x.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((od=i.gridData)==null?void 0:od.name),et.gridType=(ad=i.gridData)==null?void 0:ad.type,et.gridProvider=(cd=i.gridData)==null?void 0:cd.provider):i.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):i.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):i.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):i.browserstack?et.gridName="browserstack-from-options":i.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,ve,r,Qa,ni,et).catch(BT=>up.error("testEndAndReport threw an error",{err:BT})),ni)return;this.combinedTestResults[ve.resultId]=ve,vf({executionId:r,projectId:g,testId:Et,resultId:ve.resultId,result:ve,ucid:T,companyId:w,companyName:b,projectName:j,companyPlan:A,source:S,user:E,lightweightMode:x,logger:up,isStartUp:D,projectType:R,appSource:Za}),l&&!ve.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},z=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(i.userData={loginData:{...wr(),refreshToken:qi(),authData:wr(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he},M("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,B,G,X,z)});try{let u=await At(),f=await zi(),h=await m(u,f);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw up.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var pp,ae,Eb=v(()=>{"use strict";pp=class{static colorString(e,t){return`${e}${t}${pp.Reset}`}},ae=pp;ae.Reset="\x1B[0m",ae.Bright="\x1B[1m",ae.Dim="\x1B[2m",ae.Underscore="\x1B[4m",ae.Blink="\x1B[5m",ae.Reverse="\x1B[7m",ae.Hidden="\x1B[8m",ae.FgBlack="\x1B[30m",ae.FgRed="\x1B[31m",ae.FgGreen="\x1B[32m",ae.FgYellow="\x1B[33m",ae.FgBlue="\x1B[34m",ae.FgMagenta="\x1B[35m",ae.FgCyan="\x1B[36m",ae.FgWhite="\x1B[37m",ae.FgGray="\x1B[90m",ae.BgBlack="\x1B[40m",ae.BgRed="\x1B[41m",ae.BgGreen="\x1B[42m",ae.BgYellow="\x1B[43m",ae.BgBlue="\x1B[44m",ae.BgMagenta="\x1B[45m",ae.BgCyan="\x1B[46m",ae.BgWhite="\x1B[47m",ae.BgGray="\x1B[100m"});var ei,Ib,Ma,dp,mp,Fr,fp=v(()=>{"use strict";ei=I(require("lodash"));F();W();de();ie();je();ts();gl();hl();ge();ue();Pt();ag();Y();Sb();Mo();Ib=require("uuid");Eb();({CLI_MODE:Ma}=Ut),dp=P("test-plan-runner"),mp=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return mp._id}async runTestAllPhases(e,t,r,n,i,o,a,l){let c={},d=new Na(this.customExtensionLocalLocation),m=async()=>{let g=i.beforeParallel||1,y=!0,T=await d.runTests(e,l,o,a,i,n,g,y);Object.assign(c,T)},u=async()=>{let g=hi||i.parallel,y=!1;M("right before this.workerManager.runTests");let T=await d.runTests(t,l,o,a,i,n,g,y);M("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await d.runTests(r,l,o,a,i,n,g,y);Object.assign(c,T)};Sf({executionId:o,projectId:i.project}),M("right before runBeforeTests");try{return await m(),M("right before runTestPlanTests"),await u(),M("right after runTestPlanTests"),await f(),c}catch(g){if(dp.error("error running test plan",{err:g}),g instanceof qt)return l.markAllQueuedTests(o,me.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,w,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===Ma.SELENIUM){let[{getSessionPlayer:S},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=S();await A.closeBatch(o,E);return}let g;try{if(!((b=(w=(T=i.company)==null?void 0:T.activePlan)==null?void 0:w.premiumFeatures)!=null&&b.applitools)||(g=await bp(i.project),ei.default.isEmpty(g)||!o))return;let{runKey:S,url:E}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[o],serverUrl:E,apiKey:S}})}catch{}}}async runTestPlan(e,t,r,n,i,o,a,l){var b,S,E;let c=re(),d=n.project;$d(c),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new bo(m,n,o,a),f=ei.default.chain(m).map(A=>{var D;return((D=A.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(A=>A.name),y=(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,i,g);M("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,c,l,h),M("before runTestAllPhases");let w=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,i||"All Tests",u);return M("before executionEnd"),await u.executionEnd(c),M("after executionEnd"),{results:w,executionId:c,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ae.colorString(ae.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await gp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await hp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){dp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return ei.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};_.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async d=>{let m=await ti(o,e.testPlan,[d],t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})}),await se(e.testPlan,async d=>{let m=await ti(o,[d],e.testPlanIds,t,e.intersections);m.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=m.testPlansData[f]})})):a=await ti(o,e.testPlan,e.testPlanIds,t,e.intersections);let l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ma.APPIUM&&await Iu(e,r(c)),await se(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await af(e,d);let f=u.overrideExecutionName||d.name;return await se(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Eu(n[m][E])})),w=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,A)=>Object.assign(E,A),{}),b=Eu(w);Object.assign(i,w);let S=b?T[0].executionId:T.find(E=>!E.status).executionId;return await yp(o,m,{success:b,executions:T,executionId:S}),y})})}async runAnonymousTestPlan(e,t){var l;dp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),M("before getSuite");let r=await yh(e,t);if(M("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let i=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),o=!0;M("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===Ma.APPIUM&&(a=await Xn({appId:e.appId,projectId:e.project})),await se(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Ma.APPIUM&&await Iu(e,c),M("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,i,null,t,o);return M("right after runTestPlan"),await Q.onTestPlanFinished(d.results,i,this.startTime,d.executionId,o),d})}async run(e){let t=fn(),r=[];await this.reportTestRunnerStarted(e.project,e),Ks(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ei.default.flattenDeep(r);return M("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),M("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Fr=mp;Fr._id=(0,Ib.v4)()});var Re={};H(Re,{addTestRetry:()=>Kl,clearTestResult:()=>vu,deleteCloudflareTunnel:()=>xp,fetchLambdatestConfig:()=>Yl,fixGridAppIDStructure:()=>Ju,forceUpdateCloudflareTunnelRoutes:()=>Rp,getAllGrids:()=>fl,getAppDetails:()=>Xn,getApplitoolsIntegrationData:()=>bp,getBrowserStackSessionMetaData:()=>hI,getCloudflareTunnel:()=>Ip,getEditorUrl:()=>mI,getGridSlot:()=>ml,getHybridGridProvider:()=>dl,getLabFeaturesByProjectId:()=>cu,getMobileDevicesFromGrid:()=>Qn,getRealData:()=>$l,getS3Artifact:()=>xn,getS3ArtifactText:()=>jl,getSuiteTestList:()=>Ru,getTestPlan:()=>dI,getTestPlanTestList:()=>ti,getTestResults:()=>kr,getUsageForCurrentBillingPeriod:()=>Sp,initializeUserWithAuth:()=>Ep,isTestResultCompleted:()=>wu,keepAliveCompanySlots:()=>Fl,keepAliveGrid:()=>ul,loadSfdcCredential:()=>vp,loadTest:()=>Un,releaseCompanySlot:()=>Ml,releaseGridSlot:()=>pl,reportExecutionFinished:()=>To,reportExecutionStarted:()=>zl,reportRunnerFinished:()=>hp,reportRunnerStarted:()=>gp,requestCompanySlot:()=>Nl,saveRemoteStep:()=>uu,saveTestPlanResult:()=>yp,updateCompanySlot:()=>Ul,updateExecutionTests:()=>ql,updateRemoteRunFailure:()=>Ap,updateTestDataArtifact:()=>wo,updateTestResult:()=>jo,updateTestStatus:()=>Ir,uploadAppToGrid:()=>Ku,uploadRunDataArtifact:()=>Su,validateUserAccessKey:()=>cl});async function xs(){let s=await At();if(!s)throw new Error("Failed to get token from server");return{[_c]:Fr.id,Authorization:`Bearer ${s}`}}async function Ee({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await xs(),o={...t,...i};return We({url:`${he}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function uI(s,e,t,r={},n=void 0){let i=await xs(),o={...r,...i};return await Vs(`${he}${s||""}`,e,t,o,n)}async function ri(s,e){let t=await xs();return await wc(`${he}${s||""}`,e,t)}async function xb(s,e){let t=await xs();return await Ws(`${he}${s||""}`,e,t)}async function pI(s,e){let t=await xs();return await Gs(`${he}${s||""}`,e||void 0,t)}async function Ae(s,e,t,r){let n=await xs();return await Te(`${he}${s||""}`,e||void 0,n,r,t)}function xn(s,e){return(0,ee.default)(()=>Ae(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function jl(s){return(0,ee.default)(()=>pI(`/storage${s}`))}async function gp(s,e){return await Ee({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function hp(s){return await xb("/test-runner",{projectId:s})}async function dI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>Ae("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...l})=>Object.assign(l,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function vp({branch:s,projectId:e}){let t=await(0,ee.default)(()=>Ae(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Un({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>Ae(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function yp(s,e,t){return(0,ee.default)(()=>Ee({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Ir(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ri("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:aI,...i}),{retries:o,factor:1})}function ql(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ri("/result/run/tests",{runId:s,runnerStatuses:e,status:t,reason:r,success:n,startTime:i,endTime:o,projectId:a}),{retries:te,factor:1})}async function zl({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:l,isLocalRun:c,intersections:d}){let{isCi:m}=await Promise.resolve().then(()=>(Zi(),yf));return Ee({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:d,metadata:{isCiRun:m,localRunUserId:l,isLocalRun:c}},retry:3})}function To(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ri("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function ti(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Ru({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}){return(0,ee.default)(()=>Ee({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:l,testConfigIds:c,intersections:d}}),{retries:te,factor:1})}async function Xn({appId:s,projectId:e}){try{return await(0,ee.default)(()=>Ae(`/mobile-app/app/${s}?projectId=${e}`),{retries:te,factor:1})}catch(t){throw new Error(`Could not load app with the ID ${s}`,{cause:t})}}async function Sp(s){try{return await(0,ee.default)(()=>Ae(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){_t.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function wu(s,e,t){return(0,ee.default)(()=>Ae(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function kr(s,e,t,r){return(0,ee.default)(()=>Ae(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function ul(s,e){return Ee({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function pl(s,e,t,r,n){return Ee({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function dl(s){return Ee({url:"/grid/hybrid/provider",body:s})}function ml(s){return(0,ee.default)(()=>Ae("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Ep({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d}){var m,u;try{return await(0,ee.default)(()=>We({url:`${he}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:l,clientNodeVersion:c,clientNpmVersion:d},timeout:6e4}),{retries:te,factor:1})}catch(f){if(_t.error("error initializing info from server",f),(m=f.message)!=null&&m.includes("Bad Request"))throw new C("Error trying to retrieve CLI token. Your CLI token and project might not match. Please make sure to pass `--project` and `--token` that match to each other or make sure they match in your ~/.testim file.");if((u=f.code)!=null&&u.includes("ENOTFOUND"))throw new C("Due to network connectivity issues, Testim CLI has been unable to connect to the Testim backend.");if(f.text)try{let h=JSON.parse(f.text),g=h.clientMessage.color||"red",y=h.clientMessage.bgColor||"bgBlack";console.log(Tp.default[y](Tp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{_t.error("Error parsing error message from server",f)}throw f}}async function mI(){if(Ns)return{editorUrl:Ns};try{return await(0,ee.default)(()=>Ae("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return _t.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function fl(s){return(0,ee.default)(()=>Ae("/grid",{companyId:s}),{retries:te,factor:1})}function $l(s,e,t){return(0,ee.default)(()=>Ae(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function jo(s,e,t,r,n){return(0,ee.default)(()=>Ee({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function vu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function uu(s,e,t,r){return(0,ee.default)(()=>Ee({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function fI(s){return s.startsWith("/")?s:`/${s}`}function gI(s,e,t){let r=fI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Ab(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,l=`${e}/${t}/${a}`,c=gI(l,lI,s),d=Buffer.from(Rb.gzip(r,{level:3})),m={file:{fileName:a,buffer:d}};return await(0,ee.default)(()=>uI(`/storage${c}`,{},m,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),c}function Kl({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Ee({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function bp(s){try{return await Ae(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return _t.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Ip(s,e){try{return await ri("/tunnel",{companyId:s,routes:e})}catch(t){return _t.warn("could'nt get tunnel.",{err:t}),{}}}async function Rp(s,e){try{return await Ee({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}async function xp(s,e){try{return await xb(`/tunnel/${e}`,{companyId:s})}catch(t){_t.warn("could'nt get tunnel.",{err:t});return}}function Ap(s){return We({url:`${he}/result/remoteRunFailure`,body:s})}async function Qn({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${cI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>Ae(i,{projectId:s}),{retries:te,factor:1})}catch(o){return _t.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function Ku({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Ee({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function Ju(s){return(0,ee.default)(()=>Ee({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Nl(s,e){return(0,ee.default)(()=>Ee({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Ml(s,e,t){return(0,ee.default)(()=>Ee({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Ul(s,e,t){return(0,ee.default)(()=>ri("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Fl(s,e,t){return Ee({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function hI(s,e){return await Te(`${Us}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function cl(s){try{return await Ae("/v2/project/validateUserAccessKey",s),!0}catch(e){return _t.error("error validating user access key",{error:e}),!1}}var Tp,ar,Rb,ee,wp,aI,_t,te,cI,lI,Yl,cu,Su,wo,ge=v(()=>{"use strict";Tp=I(require("chalk")),ar=I(require("lodash")),Rb=I(require("pako"));F();de();ie();Ve();at();ee=I(require("p-retry")),wp=I(require("object-hash"));Y();W();fp();aI=tt(),_t=P("testim service api"),te=3,cI="/grid",lI="test-result-artifacts";Yl=async()=>(0,ee.default)(()=>Ae("/grid/lt/config"),{retries:te,factor:1}),cu=async s=>(0,ee.default)(()=>Ae(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Su=ar.memoize(async(s,e,t,r)=>{if(!ar.isEmpty(r))return await Ab(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`),wo=ar.memoize(async(s,e,t,r,n)=>!r||ar.isEmpty(r)?void 0:await Ab(s,e,t,JSON.stringify((()=>{let o=ar.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(c=>{o[c]&&Object.assign(o,{[c]:Pc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,wp.default)(r)}:${e}:${t}`)});async function Cb(){let s=await Promise.any(yI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var yI,Pb=v(()=>{"use strict";Ve();yI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"]});function Ua(){return tt()}var Cp=v(()=>{"use strict";F()});function wI(s){q.EXTENSION!==s&&process.nextTick(()=>{try{(we(),He(tr)).getSessionPlayer()}catch{}})}function vI(s){var e,t;(t=(e=s.clientConfig)==null?void 0:e.clientMessages)!=null&&t.length&&s.clientConfig.clientMessages.forEach(r=>{let n=r.color||"yellow",i=r.bgColor||"bgBlack";console.log(Pp.default[i](Pp.default[n](r.text)))})}async function si(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:l,grid:c}=s,d=Boolean(n==null?void 0:n.general),m=Boolean(i||o),u=d?TI:bI,f=Ua(),h=xc(),g=await Dm(),y=null;if(_.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!m)try{y=await Cb()}catch(b){kb.error("failed to get public ip",b)}let T=!0;M("before initializeUserWithAuth");let w=await Bt(async()=>(wI(a),T=!1,await Ep({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:m,publicIp:y,gridId:l,grid:c,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:d,localGrid:m,gridId:l,grid:c,publicIp:y})();return vI(w),s.publicIps=[w.clientPublicIp],M("after initializeUserWithAuth"),y&&w.clientPublicIp&&w.clientPublicIp!==y&&(kb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:w.clientPublicIp}),s.publicIps.push(y)),ef(w.authData,{projectId:e,token:t,userAccessKey:r,publicIp:w.clientPublicIp,initializedFromCache:T}),w}var Pp,kb,bI,TI,Ob=v(()=>{"use strict";Pp=I(require("chalk"));je();ge();Yt();at();Pb();ie();W();ue();Cp();F();Zr();kb=P("initializeUserWithAuth"),bI=1e3*60*5,TI=1e3*60*60*10});async function Db(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Hi():s.chromeBinaryLocation,e=tn({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==q.EXTENSION&&await br(s.playerLocation,s.canary),s.mode!==q.SELENIUM&&s.mode!==q.APPIUM&&!s.ext&&await Qc(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await Xc(s.installCustomExtension,n)}return await e,t}async function Nb(s){var o;SI.info("prepare MockNetwork",{location:s});let e=await Ic(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>_b*1e6)throw new Error(`${kp} exceeded ${_b}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${kp} cannot be parsed.${Fa.EOL}${a}`)}let n=new Lb.default;if(!n.validate(Bc,r)){let a=(o=n.errors)==null?void 0:o.map((l,c)=>`${++c}) ${l.dataPath} ${l.message}`).join(Fa.EOL);throw new Error(`${kp} is malformed.${Fa.EOL}${a}`)}return r.entries}var Fa,Lb,_b,kp,SI,Op=v(()=>{"use strict";Fa=I(require("node:os"));F();mm();sn();Lb=I(require("ajv"));ie();rl();W();Ob();_b=1,kp="JSON file supplied to --mock-network-pattern",SI=P("prepare runner")});function jb(s){return s.start&&gn(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function $b(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=vo(s);return console.log("Start Testim CLI on Agent mode"),{project:s.project,token:s.token,agentMode:!0,agentPort:s.agentPort,agentBind:s.agentBind,openEditor:s.openEditor,startTestimBrowser:e,ext:s.ext,extensionPath:s.extensionPath,playerLocation:s.playerPath||t,canary:s.canary,playerPath:s.playerPath,playerRequirePath:s.playerRequirePath,downloadBrowser:Boolean(s.downloadBrowser)}}var Wb=v(()=>{"use strict";Cn();rs();Y()});var Vb,CI,PI,Np,Gb=v(()=>{"use strict";Vb="TST_CREDS",CI=["username","password"],PI="$encrypted",Np={get proxyPlaceholder(){return new Proxy({},{get(s,e){let t={};for(let r of CI)t[r]={[PI]:`${e}.${r}`};return t}})},containsEncryptedCredentials(s){return s.includes(Vb)},injectProxyCredentialsStoreToGlobal(){Object.assign(globalThis,{[Vb]:this.proxyPlaceholder})}}});var jp={};H(jp,{doLogin:()=>Bp,getProjectId:()=>kI,getToken:()=>OI});async function kI(){return zb("projectId")}async function OI(){return zb("token")}function qb(s,e){return Promise.race([s,ce(e).then(()=>{throw new oe("timeout")})])}async function _I(){let s=(await import("express")).default(),e=async function(){return qb(new Promise(n=>{s.get("/loginInfo",(i,o)=>{n(JSON.parse(Buffer.from(i.query.info,"base64").toString())),o.status(200).end()})}),6e4).catch(()=>null)}();await new Promise((r,n)=>{let i=s.listen(42543,o=>{o&&n(o),r(i.address().port)})});try{let{getEditorUrl:r}=await Promise.resolve().then(()=>(ge(),Re)),{editorUrl:n}=await r();uo(`${n}/#/new-test`)}catch{console.log("Unable to open Testim automatically - please manually go to https://app.testim.io")}return await e}async function Bp({overwriteExisting:s=!0,projects:e=null}={}){let t=Mp.homedir(),r=Up.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),l=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await qb(_I(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,l.succeed(),await Hb(r,i);return}if(e!=null&&e.length){l.succeed();let c=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(d=>({title:d.name,value:d}))});i.token=c.project.ci.token,i.projectId=c.project.id,await Hb(r,i);return}l.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function Hb(s,e){await Fp.promises.writeFile(s,ja.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function zb(s){let e=Mp.homedir(),t=Up.join(e,".testim"),r=await ye(t),n={};if(r)try{n=ja.parse((await Fp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var Mp,Up,ja,Fp,$a=v(()=>{"use strict";Mp=I(require("os")),Up=I(require("path")),ja=I(require("yaml"));F();Fp=require("fs");Y();Ol()});var tT={};H(tT,{process:()=>jI,program:()=>p});var Wp,Xb,Wa,Qb,Vt,De,Zb,LI,Le,Hp,DI,NI,Jb,eT,MI,Vp,Gp,qp,$p,Lt,UI,p,FI,BI,Yb,jI,zp=v(()=>{"use strict";Wp=I(require("ms")),Xb=I(require("chalk")),Wa=I(require("node:fs")),Qb=I(require("node:url")),Vt=I(require("lodash")),De=I(require("node:path"));F();Cn();Wb();Yt();Zb=require("commander");ie();Y();jr();F();ue();Gb();Mo();LI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Le=(s,e)=>(e.push(s),e),Hp=new Zb.Command,DI=s=>s.split(","),NI=(s,e)=>!s||s.length===0?e:s,Jb=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],eT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function l(g){return g.includes("--save-rca-locally")}function c(g){return g.includes("--exit-code-ignore-failing-tests")}function d(g){return g.includes("--high-speed")}function m(g){return g.includes("--urls")}function u(g){return g.includes("--test-start-timeout")}function f(g){return g.includes("--install-lazy-deps")}function h(g){return g.includes("--print-final-caps")||g.includes("--print-grids")}Hp.help(g=>g.split(`
404
404
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!l(T)&&!c(T)&&!d(T)&&!m(T)&&!u(T)&&!f(T)&&!h(T)).join(`
405
405
  `))},MI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(Xb.default.yellow(`
406
406
  WARNING: ${s} is deprecated. ${t}
407
- `))},Vp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Gp,argv:qp,exit:$p,cwd:Lt}=global.process,UI=new Set(["trace","debug","info","warn","error","silent"]);Lc(qp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Hp.description("Testim.io CLI").option("-h --help","output usage information",eT).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",DI).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Gp.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,Wp.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,Wp.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: ${Vp.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Le,[]).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)",Le,[]).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)",Le,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(qp);p=Hp.opts(),FI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},BI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Yb=s=>{var r;if(!_.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Wa.readFileSync(s);(r=Np)!=null&&r.containsEncryptedCredentials(t.toString())&&Np.injectProxyCredentialsStoreToGlobal()},jI=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!qp.slice(2).length)throw eT(),new $r;if(p.version){let R="Testim CLI Version: ";Gp.npm_package_version&&(console.log(R,Gp.npm_package_version),$p(0));let x=tt();x&&(console.log(R,x),$p(0)),console.log("Could not find version, please check the package.json manually"),$p(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Rm(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=De.resolve(n);Em(R)}if(p.usePrefechedData&&xm(),p.playerRequirePath){let R=De.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=De.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(De.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Wa.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(jb(p))return $b(p);try{let R={};p.configFile?(Yb(p.configFile),R=require(De.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(De.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=LI(x);p[O]=NI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}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 i=((T=p.testConfig)==null?void 0:T.length)||((w=p.testConfigId)==null?void 0:w.length),o=((b=p.testPlan)==null?void 0:b.length)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(De.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(De.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");Jb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(Jb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Yb(p.paramsFile),s={...s,...require(De.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(FI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(De.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(BI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(De.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(De.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(De.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>($a(),jp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),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=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let d=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 x=await(await Promise.resolve().then(()=>($a(),jp))).getToken();if(x)p.token=x;else throw new C("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 m=R=>R<=0||!Number.isInteger(R);if(m(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...Bn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!UI.has(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new C("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||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("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(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Qb.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=vo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("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 C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("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||o))throw new C("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&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,Vp).length){let R=Vt.difference(p.codeCoverageReporter,Vp);throw new C(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=Wa.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(MI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("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 C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={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"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
407
+ `))},Vp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:Gp,argv:qp,exit:$p,cwd:Lt}=global.process,UI=new Set(["trace","debug","info","warn","error","silent"]);Lc(qp,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));Hp.description("Testim.io CLI").option("-h --help","output usage information",eT).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",Le,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Le,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Le,[]).option("--test-id [test-id]","test ID to run",Le,[]).option("-l, --label [label]","labels to search test by",Le,[]).option("-n, --name [test-name]","test name to run",Le,[]).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",DI).option("-h, --host [host-name]","host name or ip containing the selenium grid").option("-p, --port [host-port]","host port").option("-g, --grid [grid-name]","grid name").option("--path [grid-path]","grid path").option("--protocol [grid-protocol]","grid protocol http or https").option("--grid-username [grid-username]","grid http basic auth username").option("--grid-password [grid-password]","grid http basic auth password").option("-gi --grid-id [grid-id]","grid ID").option("-b, --browser [browser-type]","browser type (chrome/firefox)").option("-h, --headless [headless]","run in headless mode").option("-m, --mode [runner-mode]","use extension or selenium mode (extension/selenium/appium)").option("--branch [branch]","branch name",void 0).option("--base-url [base-url]","change base-url to a specified url for all tests in current execution").option("--token [token]","identification token to testim").option("--parallel [number-of-tests]","number of tests to run in parallel").option("--before-parallel [number-of-tests]","number of tests to run in parallel during the before phase of a test plan").option("--after-parallel [number-of-tests]","number of tests to run in parallel during the after phase of a test plan").option("--canary [canary-mode]","enable canary mode",!1).option("--test-plan [test-plan-name]","test plan to run",Le,[]).option("--test-plan-id [test-plan-id]","test plan to run",Le,[]).option("--suite [suite-name]","suite to run",Le,[]).option("--suite-id [suite-id]","suite ID to run",Le,[]).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",Le,[]).option("-oen --override-execution-name [execution-name]","override the default execution name","").option("--retries [max_num_of_retries]","number of retries on test failure, defaults to 0 (no retries)",Number,0).option("--set-retention [retention-in-days]","set the number of days for results retention").option("--user [user-id]","user ID for local Testim-CLI").option("--user-access-key [user-access-key]","EXPERIMENTAL").option("--pass-zero-tests","don't fail the run if no tests were found").option("--device-name [device-name]","The device name to use, iPhone 12, Nexus 5X, SM-G900P etc....").option("--device-udid [device-udid]","Unique Device Identifier").option("--custom-tag [custom-tag]","tag grid result with custom tag").option("-slb --skip-load-balancer","skipping automatic allocation (AppiumLB) for mobile runs on mobile gird that support it",!1).option("--no-lock-device","skipping locking device internal use for TDC grid").option("--os-version [os-version]","The operating system version number").option("--app-id [app-id]","The application id from app library on Testim Editor App").option("--appium-log-level [appium-log-level]","Level of logging verbosity").option("--set-no-reset [set-no-reset]","set noReset appium capability, by default set to false",!1).option("-fr --full-reset [full-reset]","set fullReset appium capability to true to reinstall application on session start and session end").option("--duration [duration]","The duration of the test run in minutes",Number).option("-str --suppress-tms-reporting [suppress-tms-reporting]","disable test management reporting",!1).option("-tsr --tms-suppress-reporting [tms-suppress-reporting]","disable test management reporting",!1).option("-tid --tms-run-id [tms-run-id]","update existing result in test management","").option("-tff --tms-field-file [tms-field-file.json]","pass field file location to add custom result field to the tms result report","").option("--disable-file-cache","disable internal CLI file caching").option("--clear-file-cache","clear internal CLI file cache").option("--file-cache-location [directory]"," internal CLI file caching location").option("--test-start-timeout [test-start-timeout]","The time to wait for a test to start after getting a browser session",Number,Number(Gp.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,Wp.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,Wp.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: ${Vp.join("/")}`,Le,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Le,[]).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("--sealights-lab-id [sealights-lab-id]","SeaLight Lab ID").option("--sealights-build-session-id [sealights-build-session-id]","SeaLight Session Build ID").option("--ext [extension src path]","use extension from path (default it '/..')").option("--extension-path [path to extension archived file]","override the used extension").option("--install-custom-extension [chrome extension zipped file url or local path]","chrome extension to be installed in the browser").option("--player-path [path to player file]").option("--player-require-path [path to unminified player - development only]").option("--inspect [port]","Opens node inspector at given port",Number).option("--tunneld","run a tunnel daemon only").option("--tunnel [tunnel]","enable tunnel").option("--tunnel-routes [routes]","tunnel routes for cloudflare tunnels").option("--tunnel-port [tunnel-port]","tunnel port address").option("--tunnel-host-header [tunnel-host-header]","tunnel host header").option("--tunnel-region [tunnel-region]","ngrok tunnel region").option("--tunnel-diagnostics","collect ngrok tunnel diagnostics").option("--tunnel-use-http-address [tunnel-use-http-address]","use http:// address instead of https://",!1).option("--external-lambdatest-tunnel-id [tunnel-id]","use existing lambdatest tunnel ID").option("--external-lambdatest-use-wss","use wss instead of ssh for LT",!1).option("--external-lambdatest-disable-automation-tunneling","don't tunnel Testim calls in LT tunnel",!0).option("--external-lambdatest-mitm","Turn on LT Man in the middle",!1).option("--external-lambdatest-NTLM-tunnel-username [tunnel-NTLM-username]","Tunnel NTLM username").option("--external-lambdatest-NTLM-tunnel-password [tunnel-NTLM-password]","Tunnel NTLM password").option("--w3c-capabilities [enable-w3c-caps-mode]","enable/disable w3c capabilities format (default enable)",JSON.parse,!0).option("--old-capabilities [enable-old-caps-mode]","enable/disable old capabilities format (default enable)",JSON.parse,!0).option("--disable-sockets","Disable CLI sockets",!1).option("--executionId [execution-id]","","").option("--remoteRunId [remote-run-id]","","").option("--schedulerId [scheduler-id]","","").option("--source [source]","","cli").option("--resultId [result-id]","","").option("--connect, --agent [enable-agent-mode]","enable Testim CLI agent mode",!1).option("--start [enable-start]","Connect to testim and open the editor in a standalone browser",!1).option("--download-browser","when used with the start option, downloads a fixed version to run Testim editor in",!1).option("--agent-port [agent-port]","set agent port",Number,42543).option("--agent-bind [agent-host-bind]","set agent host bind","127.0.0.1").option("--chrome-extra-prefs [chrome-extra-prefs]","add extra chrome preferences","").option("--chrome-extra-args [chrome-extra-args]","add extra chrome arguments separated by ','","").option("--chrome-block-location [chrome-block-location]","block chrome geolocation",!1).option("--chrome-user-data-dir [chrome-user-data-dir]","use custom chrome user date dir",!1).option("--disable-cookies-same-site-none-requires-secure [disable-same-site-none-requires-secure]","Disable cookies without SameSite must be secure",!1).option("--selenium-caps-file [selenium-caps-file.json]","json file to merge into Testim selenium desired capabilities").option("--version [version]","print the current version of the Testim CLI and exit",!1).option("--monitor-performance","collect test playback performance data").option("--high-speed","DEPRECATED: use --turbo-mode instead").option("--turbo-mode","run in turbo mode (providing that tests are configured with browsers that use extension mode [chrome, edge chromium])").option("--lightweight-mode [settings]","run lightweight mode").option("--create-prefeched-data [location]","prefetch data into local cache file").option("--use-prefeched-data [location]","use prefetched data from local cache file, and force using only cached data").option("--save-rca-locally [path]","save root cause analysis assets locally").option("--exit-code-ignore-failing-tests","return exit code of zero when tests fail. non zero exit code will mean a real error occurred").option("--intersect-with-label [label]","Out of the execution's test list, run only those tests that have the specified label",Le,[]).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)",Le,[]).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)",Le,[]).option("--apply-intersections-to-before-and-after-sections [boolean]","For a test plan's before/after tests, run tests that intersect with specified intersection flags",void 0).option("--install-lazy-deps [install-lazy-deps]","Install all lazy dependencies from package.json",!1).option("--bypass-node-version-check [bypass-node-version-check]","Allow running with incompatible Node.js versions",!1).option("--print-grids","Print available grids and exit",!1).option("--print-final-caps","Print the final calculated capabilities",!1).option("--headless-extension-download-path [headless-extension-download-path]","Path to download headless extension","").parse(qp);p=Hp.opts(),FI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},BI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},Yb=s=>{var r;if(!_.flags.encryptedCredentials.isEnabled({projectId:p.project}))return;let t=Wa.readFileSync(s);(r=Np)!=null&&r.containsEncryptedCredentials(t.toString())&&Np.injectProxyCredentialsStoreToGlobal()},jI=async()=>{var T,w,b,S,E,A,D,j;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!qp.slice(2).length)throw eT(),new $r;if(p.version){let R="Testim CLI Version: ";Gp.npm_package_version&&(console.log(R,Gp.npm_package_version),$p(0));let x=tt();x&&(console.log(R,x),$p(0)),console.log("Could not find version, please check the package.json manually"),$p(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Rm(),p.clearFileCache&&Xr();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let R=De.resolve(n);Em(R)}if(p.usePrefechedData&&xm(),p.playerRequirePath){let R=De.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",R);let x=De.join(R,"tsconfig.node.json"),B=require("ts-node").register({project:x,ignore:[/node_modules/,new RegExp(`^${Vt.escapeRegExp(De.relative(Lt(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:B.config.options.paths,baseUrl:B.config.options.baseUrl}),(we(),He(tr)).options.playerPath=R;let z=require("node:module"),X=z.prototype.require;z.prototype.require=function(Ze){return Ze==="rox-alias"?X.call(this,"rox-node"):Ze==="canvas"?{}:X.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Wa.readFileSync(p.caFile)),p.proxy&&(global.proxyUri=p.proxy,global.SuperagentProxy=require("superagent-proxy"),global.ProxyAgent=require("proxy-agent").ProxyAgent,global.HttpsProxyAgent=require("https-proxy-agent").HttpsProxyAgent),p.proxyForGrid&&!p.proxy)throw new C("missing --proxy option");if(jb(p))return $b(p);try{let R={};p.configFile?(Yb(p.configFile),R=require(De.join(Lt(),p.configFile)).config):p.optionsFile&&(R=require(De.join(Lt(),p.optionsFile))),R&&typeof R.then=="function"&&(R=await R),Object.keys(R).forEach(x=>{let O=LI(x);p[O]=NI(p[O],R[x])})}catch(R){throw R.message=`Unable to read options file: ${R.message}`,R}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 i=((T=p.testConfig)==null?void 0:T.length)||((w=p.testConfigId)==null?void 0:w.length),o=((b=p.testPlan)==null?void 0:b.length)||((S=p.testPlanId)==null?void 0:S.length),a=((E=p.suite)==null?void 0:E.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(De.join(Lt(),p.seleniumCapsFile))}catch(R){throw new C(`Failed to parse selenium caps file file error: ${R.message}`)}if((D=p.reporters)!=null&&D.includes("junit")&&!p.reportFile&&console.log("Warning: please define --report-file option for JUnit reporter"),!p.tunnel&&p.externalLambdatestTunnelId)throw new C("missing --tunnel parameter");if(!p.tunnel&&p.externalLambdatestUseWss)throw new C("missing --tunnel parameter");if(!p.tunnel&&[p.tunnelPort,p.tunnelHostHeader,p.tunnelRegion,p.tunnelDiagnostics].some(Boolean))throw new C("missing --tunnel parameter");if(p.chromeExtraPrefs)try{e=require(De.join(Lt(),p.chromeExtraPrefs))}catch(R){throw new C(`Failed to read/open chrome extra prefs file error: ${R.message}`)}if(p.chromeExtraArgs){let R=p.chromeExtraArgs.split(",");for(let x of R){let[O]=x.split("=");Jb.includes(O)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(x),O==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${O}), allowed values: ${JSON.stringify(Jb)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&Yb(p.paramsFile),s={...s,...require(De.join(Lt(),p.paramsFile))}}catch(R){throw new C(`Failed to read/open params file error: ${R.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(R){throw new C(`Failed to parse params string error: ${R.message}`)}if(p.sauceUser&&!p.sauceKey||!p.sauceUser&&p.sauceKey)throw new C("missing --sauce-user <sauce-user> or --sauce-key <sauce-key>");if(p.sauceUser&&p.sauceKey&&(FI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let R=require(De.join(Lt(),p.sauceOptions)),x=R.platformName&&["ios","android"].includes(R.platformName.toLowerCase());if(R.browserName){let B=R.browserName.toLowerCase();switch(B){case"microsoftedge":p.browser="edge";break;default:p.browser=B}}p.browser==="edge"&&parseFloat(R.version)>=79&&(p.browser="edge-chromium");let O=parseFloat(R.version)<50&&!["dev","beta"].includes(R.version);if(!x&&p.browser==="chrome"&&O)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...R}}catch(R){throw new C(`Failed to parse saucelabs options file error: ${R.message}`)}if(p.browserstackUser&&!p.browserstackKey||!p.browserstackUser&&p.browserstackKey)throw new C("missing --browserstack-user <browserstack-user> or --browserstack-key <browserstack-key>");if(p.browserstackUser&&p.browserstackKey&&(BI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let R=require(De.join(Lt(),p.browserstackOptions)),x=R.platform&&["mac","android"].includes(R.platform.toLowerCase());if(R.browserName&&(p.browser=R.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(R.browser_version)>=79&&(p.browser="edge-chromium"),!x&&parseFloat(R.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...R}}catch(R){throw new C(`Failed to parse browserstack options file error: ${R.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let R=require(De.join(Lt(),p.perfectoOptions)),x={location:"US East",securityToken:p.perfectoToken};p.perfecto={...x,...R}}catch(R){throw new C(`Failed to parse perfecto options file error: ${R.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let R=require(De.join(Lt(),p.testobjectOptions)),x={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...x,...R}}catch(R){throw new C(`Failed to parse test object options file error: ${R.message}`)}let l={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId}};if(p.testOptimization=l,!p.project){let x=await(await Promise.resolve().then(()=>($a(),jp))).getProjectId();if(x)p.project=x;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}_.flags.forceTurboModeIfNeeded.isEnabled({projectId:p.project})&&(p.turboMode=!0),p.testConfig&&(p.testConfig=[p.testConfig].flat()),p.testConfigId&&(p.testConfigId=[p.testConfigId].flat()),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=Math.round(p.newBrowserWaitTimeout/p.browserTimeout)),p.getSessionTimeout=Math.max(p.browserTimeout,p.getSessionTimeout),p.driverRequestTimeout=Math.max(p.browserTimeout,p.driverRequestTimeout);let d=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 x=await(await Promise.resolve().then(()=>($a(),jp))).getToken();if(x)p.token=x;else throw new C("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 m=R=>R<=0||!Number.isInteger(R);if(m(p.retries))throw new C("test failure retry count could not be a negative number or string, --retries <max_num_of_retries>");if(p.retries>21)throw new C("Max number of retries exceeded. Number cannot be greater than 20, --retries <max_num_of_retries>");if(m(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(m(p.newBrowserWaitTimeout))throw new C("max new browser wait timeout could not be a negative number, --new-browser-wait-timeout <max-wait-to-browser>");if(m(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(m(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(m(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(m(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![q.EXTENSION,q.SELENIUM,q.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Or,...Bn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==q.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!UI.has(p.appiumLogLevel))throw new C(`runner appium-log-level <${p.appiumLogLevel}> is not supported`);if(p.testPlan&&p.testPlan.length===0&&p.testPlanId&&p.testPlanId.length===0){if(typeof p.host!="string"&&typeof p.grid!="string"&&typeof p.gridId!="string"&&!p.localTmaUrl&&!p.useLocalChromeDriver&&!p.useChromeLauncher&&!p.createPrefechedData&&!p.printGrids)throw new C("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||i||p.browser||a||p.localTmaUrl||p.useLocalChromeDriver||p.useChromeLauncher)throw new C("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(!o&&(p.beforeParallel!==1||p.afterParallel!==1))throw new C("cannot set --before-parallel or --after-parallel without --test-plan option");if([p.host,p.grid,p.gridId].filter(Boolean).length>1)throw new C("please define exactly one of --grid or --grid-id or --host");if((j=p.host)!=null&&j.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=Qb.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(x=>x.trim()).filter(Boolean);let R=p.resultLabel.filter(x=>x.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&fr()&&p.resultLabel.unshift(fr()),R.length)throw new C("A result label cannot exceed 250 characters")}let f=vo(p);if(!p.w3cCapabilities&&!p.oldCapabilities)throw new C("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 C("invalid --protocol value, allow --protocol http or https");if(p.rerunFailedByRunId&&p.branch)throw new C("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||o))throw new C("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&&!Vt.inRange(Vt.parseInt(p.setRetention),1,11))throw new C("Please provide the number of days that the test results will be retained for (--set-retention must be a whole number between 1 to 10)");p.setRetention&&=Number(p.setRetention);let h="is no longer supported, please use --override-mapping-file";if(p.mockNetworkHar)throw new C(`--mock-network-har ${h}`);if(p.mockNetworkPattern)throw new C(`--mock-network-pattern ${h}`);if(p.disableMockNetwork&&p.overrideMappingFile)throw new C("You can either use --disable-mock-network or --override-mapping-file");if(!p.collectCodeCoverage&&p.codeCoverageSourceMapPath)throw new C("cannot set --code-coverage-source-map-path without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageReporter.length)throw new C("cannot set --code-coverage-reporter without passing --collect-code-coverage");if(!p.collectCodeCoverage&&p.codeCoverageInclude.length)throw new C("cannot set --code-coverage-include without passing --collect-code-coverage");if(p.collectCodeCoverage&&p.codeCoverageReporter&&Vt.difference(p.codeCoverageReporter,Vp).length){let R=Vt.difference(p.codeCoverageReporter,Vp);throw new C(`invalid --code-coverage-reporter parameters ${R.join("/")}`)}p.codeCoverageReporter=p.codeCoverageReporter.length===0?["html","text"]:p.codeCoverageReporter,p.codeCoverageInclude=p.codeCoverageInclude.length===0?["src/**"]:p.codeCoverageInclude;let g={mockNetworkHar:"--mock-network-har",mockNetworkPattern:"--mock-network-pattern",overrideMappingFile:"--override-mapping-file",codeCoverageUrlFilter:"--code-coverage-url-filter",collectCodeCoverage:"--collect-code-coverage",disableMockNetwork:"--disable-mock-network",useChromeLauncher:"--use-chrome-launcher"},y=Object.keys(g).filter(R=>Boolean(p[R]));if([q.APPIUM,q.SELENIUM].includes(p.mode)&&y.length){let R=y.length>1?"are":"is";throw new C(`${y.map(x=>g[x]).join(" and ")} ${R} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let R=Wa.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(R)}catch(R){throw new C(`failed to parse field file error: ${R.message}`)}if(p.applyIntersectionsToBeforeAndAfterSections&&!p.intersectWithLabel&&!p.intersectWithSuite&&!p.intersectWithSuiteId)throw new C("--apply-intersections-to-before-and-after-sections flag must be combined with at least one of the available --intersect-with flags");if(p.highSpeed&&(MI("--high-speed","--turbo-mode"),p.turboMode=!0),p.skipLoadBalancer&&!p.deviceUdid)throw new C("It is not possible to skip load balancer without specifying deviceUdid");if(p.deviceUdid&&(p.deviceName||p.osVersion))throw new C("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 C("It is not possible to set both --set-no-reset and --full-reset capabilities to true at the same time!");if(p.lightweightMode)try{let R={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"},x=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...R,...x}}catch(R){throw new C(`failed to parse lightweightMode settings error: ${R.message}`)}else p.turboMode&&![q.APPIUM,q.SELENIUM].includes(p.mode)?p.lightweightMode={general:!0,disableLabs:!1,disableFeatureFlags:!1,disableAssets:!0,disablePixelValidation:!1,disableResults:!0,disableStepDelay:!0,disableRemoteStep:!1,assumePreloadedSharedSteps:!1,disableVisibilityCheck:!1,disableLocators:!1,bypassSetup:!1,disableQuotaBlocking:!1,disableAutoImprove:!1,onlyTestIdsNoSuite:!1,uploadAssetsAndResultsOnFailure:!0,preloadTests:!1,disableProjectDefaults:!1,type:"turboMode"}:p.turboMode&&[q.APPIUM,q.SELENIUM].includes(p.mode)&&console.warn(`
408
408
  When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they are not compatible concurrently`);if(typeof p.baseUrl=="boolean")throw new C("base url cannot be used as a flag, and must contain a string value");return{testId:[p.testId].flat(),name:[p.name].flat(),label:[p.label].flat(),suites:[p.suite].flat(),suiteIds:[p.suiteId].flat(),testPlan:[p.testPlan].flat(),testPlanIds:[p.testPlanId].flat(),reportFile:p.reportFile,urls:p.urls,reportFileClassname:p.overrideReportFileClassname,reporters:p.reporters,project:p.project,host:p.host,headless:p.headless,localTmaUrl:p.localTmaUrl,useLocalChromeDriver:p.useLocalChromeDriver,chromeBinaryLocation:p.chromeBinaryLocation,useChromeLauncher:p.useChromeLauncher,port:p.port,grid:p.grid,gridId:p.gridId,disableNativeEvents:p.disableNativeEvents,saucelabs:p.saucelabs,browserstack:p.browserstack,baseUrl:p.baseUrl,branch:(p.branch==="auto-detect"?fr():p.branch)||"master",autoDetect:p.branch==="auto-detect",token:p.token,userAccessKey:p.userAccessKey,userParamsData:s,mode:p.mode,browser:p.browser,beforeParallel:p.beforeParallel,parallel:p.parallel,afterParallel:p.afterParallel,canary:p.canary,rerunFailedByRunId:p.rerunFailedByRunId,disableGridCheck:p.disableGridCheck,disableTimeoutRetry:p.disableTimeoutRetry,resultLabels:p.resultLabel,path:p.path,protocol:p.protocol,perfecto:p.perfecto,experitestToken:p.experitestToken,testobjectSauce:p.testobjectSauce,testOptimization:p.testOptimization,gridUsername:p.gridUsername,gridPassword:p.gridPassword,overrideExecutionName:p.overrideExecutionName,tmsSuppressReporting:Boolean(p.suppressTmsReporting)||Boolean(p.tmsSuppressReporting),tmsRunId:p.tmsRunId,tmsCustomFields:p.tmsCustomFields,proxyForGrid:p.proxyForGrid,retentionDays:p.setRetention,passZeroTests:Boolean(p.passZeroTests),runQuarantinedTests:Boolean(p.runQuarantinedTests),deviceName:p.deviceName,deviceUdid:p.deviceUdid,customTag:p.customTag,osVersion:p.osVersion,duration:p.duration,skipLoadBalancer:p.skipLoadBalancer,lockDevice:p.lockDevice,appId:p.appId,appiumLogLevel:p.appiumLogLevel,setNoReset:p.setNoReset,fullReset:p.fullReset,ext:p.ext,extensionPath:p.extensionPath,extensionLocation:[p.extensionPath].filter(Boolean),playerLocation:p.playerPath||f,playerPath:p.playerPath,playerRequirePath:p.playerRequirePath,tunnel:p.tunnel,tunnelPort:p.tunnelPort,tunnelRoutes:p.tunnelRoutes,tunnelRoutesOutput:p.tunnelRoutesOutput,tunnelHostHeader:p.tunnelHostHeader,tunnelRegion:p.tunnelRegion,tunnelDiagnostics:p.tunnelDiagnostics,tunnelUseHttpAddress:p.tunnelUseHttpAddress,externalLambdatestTunnelId:p.externalLambdatestTunnelId,externalLambdatestNTLMTunnelUsername:p.externalLambdatestNTLMTunnelUsername,externalLambdatestNTLMTunnelPassword:p.externalLambdatestNTLMTunnelPassword,externalLambdatestUseWss:p.externalLambdatestUseWss||!1,externalLambdatestDisableAutomationTunneling:Boolean(p.externalLambdatestDisableAutomationTunneling),externalLambdatestMitm:Boolean(p.externalLambdatestMitm),beforeTest:p.beforeTest,afterTest:p.afterTest,beforeSuite:p.beforeSuite,afterSuite:p.afterSuite,timeout:p.timeout,timeoutWasGiven:d,browserTimeout:p.browserTimeout,newBrowserWaitTimeout:p.newBrowserWaitTimeout,getBrowserTimeout:p.getBrowserTimeout,getBrowserRetries:p.getBrowserRetries,getSessionTimeout:p.getSessionTimeout,getSessionRetries:p.getSessionRetries,driverRequestTimeout:p.driverRequestTimeout,driverRequestRetries:p.driverRequestRetries,testStartTimeout:p.testStartTimeout,testConfigNames:p.testConfig,testConfigIds:p.testConfigId,overrideMappingFile:p.overrideMappingFile,disableMockNetwork:p.disableMockNetwork,codeCoverageUrlFilter:p.codeCoverageUrlFilter,collectCodeCoverage:p.collectCodeCoverage,codeCoverageReportPath:p.codeCoverageReportPath,codeCoverageSourceMapPath:p.codeCoverageSourceMapPath,codeCoverageReporter:p.codeCoverageReporter,codeCoverageInclude:p.codeCoverageInclude,executionId:p.executionId,remoteRunId:p.remoteRunId,schedulerId:p.schedulerId,source:p.source,resultId:p.resultId,installCustomExtension:p.installCustomExtension,w3cCapabilities:p.w3cCapabilities,oldCapabilities:p.oldCapabilities,chromeBlockLocation:p.chromeBlockLocation,chromeUserDataDir:p.chromeUserDataDir,retries:p.retries,chromeExtraPrefs:e,chromeExtraArgs:t,disableCookiesSameSiteNoneRequiresSecure:p.disableCookiesSameSiteNoneRequiresSecure,seleniumCapsFileContent:r,shouldMonitorPerformance:p.monitorPerformance,user:p.user,lightweightMode:p.lightweightMode,createPrefechedData:p.createPrefechedData,saveRCALocally:p.saveRcaLocally,exitCodeIgnoreFailingTests:p.exitCodeIgnoreFailingTests,disableSockets:p.disableSockets,intersections:{labels:p.intersectWithLabel.length?[p.intersectWithLabel].flat():void 0,suiteNames:p.intersectWithSuite.length?[p.intersectWithSuite].flat():void 0,suiteIds:p.intersectWithSuiteId.length?[p.intersectWithSuiteId].flat():void 0,applyIntersectionsToBeforeAndAfterSections:p.applyIntersectionsToBeforeAndAfterSections},downloadBrowser:p.downloadBrowser,slotService:"mongo",printGrids:p.printGrids,printFinalCaps:p.printFinalCaps}}});var Kp,$I,As,rT,sT,Jp,nT,iT=v(()=>{"use strict";F();Y();W();In();Kp=P("testimNgrok"),$I=".whitelisted-ngrok.testim.io",As="",sT=async(s,e={})=>{if(!e.ngrokToken)throw new C("tunnel feature is not enabled, please contact support - info@testim.io.");let t;e.isNgrokWhitelisted&&(t=`${re()}-${s.projectData.projectId}${$I}`);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 i=await(await lt("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(Kp.info("replace https to http"),As=i.replace("https://","http://")):As=i,s.tunnelDiagnostics&&Jp(),s.baseUrl=As},Jp=async(s=!0)=>{try{let t=(await lt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===As);console.log("ngrok stats",n),Kp.info("ngrok stats",{tunnel:n})}catch(e){Kp.error("error collecting ngrok stats",{err:e})}s&&(rT=setTimeout(()=>Jp(),1e4))},nT=async s=>{if(!As)return;clearTimeout(rT),s.tunnelDiagnostics&&await Jp(!1),await(await lt("ngrok")).disconnect(As)}});var cr,Xp,oT,VI,GI,Yp,Va,Ha,Ga,HI,aT,cT,lT=v(()=>{"use strict";cr=I(require("os")),Xp=I(require("fs")),oT=I(require("child_process"));F();ge();VI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",GI={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"}},Yp=cr.tmpdir(),Va=`${Yp}/cloudflared`,Ha=null,Ga=null,HI=async()=>{if(await ye(Va))return;let e=GI[cr.platform()+cr.arch()];if(!e)throw new Error(`tunnel on ${cr.platform()+cr.arch()} platform is not supported.`);let t=e.extract?Yp+e.path:Va;await Ke(`${VI}/${e.path}`,t),e.extract&&await it(t,Yp),await Xp.promises.chmod(Va,"755")},aT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Ip(s.company.companyId,t),HI()]);Ha=r._id,Ga=oT.spawn(Va,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Rp(s.company.companyId,Ha),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await Xp.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},cT=async s=>{let e=[];return Ha&&e.push(xp(s.company.companyId,Ha)),Ga&&e.push(new Promise((t,r)=>{Ga.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),Ga.kill()})),await Promise.all(e)}});var Qp={};H(Qp,{connect:()=>za,disconnect:()=>Ka,serveTunneling:()=>KI});var qa,uT,pT,zI,za,Ka,KI,Zp=v(()=>{"use strict";iT();En();lT();at();qa=I(require("ora"));W();ie();Eo();uT=P("tunnel"),pT=s=>{var e;return[L.TESTIM_LAMBDATEST,L.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},zI=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===L.HYBRID&&s.gridData.tunnel==="cloudflare"},za=async s=>{if(!s.tunnel)return;let e=wr(),t;try{pT(s)?(t=(0,qa.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):zI(s)?(t=(0,qa.default)("Starting testim cloudflare tunnel...").start(),await aT(s)):(t=(0,qa.default)("Starting testim ngrok tunnel...").start(),await sT(s,e)),t.succeed()}catch(r){let n="Failed to start tunnel. Please contact support@testim.io";throw r.isInvalidCredsForLT&&(n="Could not connect to LambdaTest. Check your credentials and then try again."),uT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
409
409
  ${r.stdoutResult}`:n)}},Ka=async s=>{if(s.tunnel)try{pT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await cT(s):await nT(s)}catch(e){let t="catch error - failed to close tunnel";throw uT.error(t,{err:e}),new Error(t)}},KI=async(s,e=new Promise(()=>{}))=>(await za(s),as(()=>Ka(s)),await e)});var gT={};H(gT,{init:()=>hR,run:()=>dR});async function JI(s){let e=s.project,t=await Sp(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"),gn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Fs}function XI(s,e){var i,o,a,l,c,d,m,u,f,h,g,y,T;let t=ki(e.activePlan),r=s.parallel;if(t==="free"&&r>mT)throw new C(`The free plan allows only ${mT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let w=(i=s.projectData)!=null&&i.type?YI[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&w?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[w]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
410
410
  We'll use the maximum of ${b} for now. To use more, you can adjust your command or upgrade your plan.`),s.parallel=b);let S=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.tunnel;if(s.tunnel&&!S)throw new C("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 E=(m=(d=e.activePlan)==null?void 0:d.premiumFeatures)==null?void 0:m.runInTurboMode;s.lightweightMode&&!E&&(console.warn(`
@@ -419,5 +419,5 @@ Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Ce.rea
419
419
  `):""}overrideMimeType(t){if([Ie.LOADING,Ie.DONE].includes(this.readyState))throw new ur("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new ks("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new ui("The file protocol only supports GET"):new Error("Protocol file: not implemented")}_sendHttp(t){if(this._sync)throw new Error("Synchronous XHR processing not implemented");t!=null&&(this._method==="GET"||this._method==="HEAD")?t=null:t||="",this.upload._setData(t),this._finalizeHeaders(t),this._sendHxxpRequest(t)}_sendHxxpRequest(t){let r=this._url.protocol==="http:"?this.nodejsHttpAgent:this.nodejsHttpsAgent,i=(this._url.protocol==="http:"?_s:ec).request({hostname:this._url.hostname,port:this._url.port,path:this._url.path,auth:this._url.auth,method:this._method,headers:this._headers,agent:r});typeof t=="object"&&t instanceof oi.default&&t.pipe(i),this._request=i,this.timeout&&i.setTimeout(this.timeout,()=>this._onHttpTimeout(i)),i.on("response",o=>this._onHttpResponse(i,o)),i.on("error",()=>this._onHttpRequestError(i)),this.upload._startUpload(i),this._request===i&&this._dispatchProgress("loadstart")}_finalizeHeaders(t){typeof t=="object"&&t instanceof oi.default&&Object.assign(this._headers,t.getHeaders()),this._headers.Connection="keep-alive",this._headers.Host=this._url.host,this._anonymous&&(this._headers.Referer="about:blank"),this._headers["User-Agent"]=this._userAgent,this.upload._finalizeHeaders(this._headers,this._loweredHeaders)}_onHttpResponse(t,r){if(this._request!==t)return;if([301,302,303,307,308].includes(r.statusCode)){this._url=this._parseUrl(r.headers.location),this._method="GET","content-type"in this._loweredHeaders&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),"Content-Type"in this._headers&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),this._sendHxxpRequest();return}this._response=r,this._response.on("data",i=>this._onHttpResponseData(r,i)),this._response.on("end",()=>this._onHttpResponseEnd(r)),this._response.on("close",()=>this._onHttpResponseClose(r)),this.status=this._response.statusCode,this.statusText=_s.STATUS_CODES[this.status],this._parseResponseHeaders(r);let n=this._responseHeaders["content-length"];n?(this._totalBytes=parseInt(n,10),this._lengthComputable=!0):this._lengthComputable=!1,this._setReadyState(Ie.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==Ie.LOADING&&this._setReadyState(Ie.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(Ie.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend")}_onHttpResponseClose(t){if(this._response!==t)return;let r=this._request;return this._setError(),r.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(Ie.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new ks(t);r.lengthComputable=this._lengthComputable,r.loaded=this._loadedBytes,r.total=this._totalBytes,this.dispatchEvent(r)}_setError(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null}_parseUrl(t){let r,n,i,o=this.nodejsBaseUrl===null?t:Os.resolve(this.nodejsBaseUrl,t),a=Os.parse(o,!1,!0);return a.hash=null,a.auth&&(i!=null||n!=null)&&(r=a.auth.indexOf(":"),r===-1?i||(i=a.auth):(i||(i=a.substring(0,r)),n||(n=a.substring(r+1)))),(i||n)&&(a.auth=`${i}:${n}`),a}_parseResponseHeaders(t){this._responseHeaders={},Object.entries(t.headers).forEach(([r,n])=>{let i=r.toLowerCase();this._privateHeaders[i]||(this._mimeOverride!==null&&i==="content-type"&&(n=this._mimeOverride),this._responseHeaders[i]=n)}),this._mimeOverride!==null&&!("content-type"in this._responseHeaders)&&(this._responseHeaders["content-type"]=this._mimeOverride)}_parseResponse(){let t=Buffer.concat(this._responseParts);switch(this._responseHeaders["content-encoding"]==="gzip"&&(t=require("zlib").gunzipSync(t)),this._responseParts=null,this.responseType){case"text":this._parseTextResponse(t);break;case"json":this.responseText=null;try{this.response=JSON.parse(t.toString("utf-8"))}catch{this.response=null}break;case"buffer":this.responseText=null,this.response=t;break;case"arraybuffer":{this.responseText=null;let r=new ArrayBuffer(t.length),n=new Uint8Array(r);for(let i=0;i<t.length;i++)n[i]=t[i];this.response=r;break}default:this._parseTextResponse(t)}}_parseTextResponse(t){try{this.responseText=t.toString(this._parseResponseEncoding())}catch{this.responseText=t.toString("binary")}this.response=this.responseText}_parseResponseEncoding(){let t=this._responseHeaders["content-type"],r=/;\s*charset=(.*)$/.exec(t);return t&&r?r[1]:"utf-8"}},ke=Ie;ke.SyntaxError=li,ke.ProgressEvent=ks,ke.SecurityError=pi,ke.XMLHttpRequest=Ie,ke.InvalidStateError=ur,ke.XMLHttpRequestUpload=ci,ke.UNSENT=0,ke.OPENED=1,ke.HEADERS_RECEIVED=2,ke.LOADING=3,ke.DONE=4;Object.assign(global,{xhr2:ke,XMLHttpRequest:ke});var UT=I(require("semver"));je();Op();Yt();sn();var id=I(require("chalk")),FT=require("node:events");ie();En();Y();ie();Zi();W();var Mb=I(require("os")),_p=I(require("path")),Lp=I(require("chalk")),Ba=require("fs");de();function Ub(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=Mb.homedir();(0,Ba.mkdirSync)(_p.resolve(n,".testim_logs"),{recursive:!0});let i=_p.resolve(n,".testim_logs",`${new Date().toISOString().replace(/:|\./g,"_")}.log`);console.log("Oops :( The test runner has encountered an unexpected error. A complete log of this run can be found in:"),console.log(` ${i}`),wd&&console.log(`Call stack: ${s==null?void 0:s.stack}`),(t=s==null?void 0:s.message)!=null&&t.includes("Unable to compile TypeScript")&&((r=s.stack)!=null&&r.includes("runner/src"))&&process.argv.some(o=>o.includes("player-require-path"))&&(console.log(Lp.default.red("Looks like you got a TypeScript compile error champ - but it's not a very good one because we use TypeScript in transpile-only mode")),console.log(Lp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Ba.writeFileSync)(i,`${s}
420
420
  ${s==null?void 0:s.stack}
421
421
 
422
- ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}en();var II=P("process-handler"),Fb=!1;function RI(s){return s instanceof Error?1:Fb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Je.EVALUATING?!1:r!==!0)?1:0)}function xI(){try{Xt("chromedriver").stop()}catch{}}function Bb(){Fb=!0}async function Dp(s){s!=null&&s.stack&&(ss?console.error(s,s.stack):Ub(s)),xI(),await II.waitForFlush(),process.exit(RI(s))}ge();W();ue();zp();var kR=P("cli-entry");function OR(s){if(!UT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=20,r=Number(process.versions.node.split(".")[0]),n=new Date("2025-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(id.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function _R(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),J)),Promise.resolve().then(()=>(zp(),tT))]);M("Starting Testim.io CLI"),Ff(Dp);try{OR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await _.fetch({proxy:p.proxy});let t=await e.process();if(M("in main, after options.process"),Vd(global.proxyUri),FT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,Wd(t.project),Im("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(In(),Wf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await si(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Po(),Zg));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await Sm();o.success?console.log(`created prefetched data at ${Mi()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(hT(),gT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(Zp(),Qp));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(rd(),MT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Gl(),ig)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Bb(),M("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Db(t);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof $r)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ap({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(id.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),kR.error("runner ended with unexpected error",{err:t}),t)}}_R().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Dp(s)});
422
+ ${JSON.stringify(s,Object.getOwnPropertyNames(s),2)}`)}catch{}}en();var II=P("process-handler"),Fb=!1;function RI(s){return s instanceof Error?1:Fb?0:(s||={},Object.values(s).some(({runnerStatus:t,success:r,testStatus:n,status:i})=>[t,i].includes(me.SKIPPED)||[t,i].includes(me.FAILED)&&n===Je.EVALUATING?!1:r!==!0)?1:0)}function xI(){try{Xt("chromedriver").stop()}catch{}}function Bb(){Fb=!0}async function Dp(s){s!=null&&s.stack&&(ss?console.error(s,s.stack):Ub(s)),xI(),await II.waitForFlush(),process.exit(RI(s))}ge();W();ue();zp();var kR=P("cli-entry");function OR(s){if(!UT.satisfies(process.version,s))throw new C(`Testim.io CLI supports Node.js ${s}. This condition was not satisfied with current version: ${process.version}`);let e=18,t=22,r=Number(process.versions.node.split(".")[0]),n=new Date("2026-04-30T00:00:00.000Z"),i=n<=new Date,o=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"}).format(n);if(r<e)throw new C(`Testim.io CLI supports Node.js ${e} and above, please upgrade to a newer Node.js version`);if(r<t&&i)throw new C(`Testim.io CLI supports Node.js ${t} and above, please upgrade to a newer Node.js version`);r<t&&console.log(id.default.yellow(`Testim.io CLI will stop supporting Node.js < ${t} on ${o}. please upgrade to a newer Node.js version.`))}async function _R(){console.log("Starting Testim.io CLI");let[s,e]=await Promise.all([Promise.resolve().then(()=>(F(),J)),Promise.resolve().then(()=>(zp(),tT))]);M("Starting Testim.io CLI"),Ff(Dp);try{OR(s.getEnginesVersion())}catch(t){console.log("Argument Error:",t.message),process.exit(1)}try{await _.fetch({proxy:p.proxy});let t=await e.process();if(M("in main, after options.process"),Vd(global.proxyUri),FT.EventEmitter.defaultMaxListeners="parallel"in t&&t.parallel>10?t.parallel*3:30,Wd(t.project),Im("token"in t&&typeof t.token=="string"?t.token:"anonymous_encrypt_key"),s.isInstallLazyDepsMode(t)){console.log("Lazy dependency installation started");let{installAllLazyDependencies:i}=await Promise.resolve().then(()=>(In(),Wf));return await i()}if(s.isLoginMode(t))return;if(s.isCreatePrefetchedDataMode(t)){await Xr(),await si(t);let{preloadTests:i}=await Promise.resolve().then(()=>(Po(),Zg));await i(t),!t.playerRequirePath&&t.mode!==q.EXTENSION&&await br(t.playerLocation,t.canary);let o=await Sm();o.success?console.log(`created prefetched data at ${Mi()}`):console.error("failed to create prefetch data",o.error);return}let r=await Promise.resolve().then(()=>(hT(),gT));if(s.isTunnelOnlyMode(t)){await r.init(t);let{serveTunneling:i}=await Promise.resolve().then(()=>(Zp(),Qp));await i(t);return}if(s.isAgentMode(t)){let{runAgentMode:i}=await Promise.resolve().then(()=>(rd(),MT));return i(t)}if(t.saveRCALocally){let{initServer:i}=await Promise.resolve().then(()=>(Gl(),ig)),{port:o}=await i(t);t.localRCASaver=`http://localhost:${o}`}t.exitCodeIgnoreFailingTests&&Bb(),M("right before testRunner.init/prepareRunner.prepare"),await r.init(t);let n=await Db(t);return M("right after testRunner.init/prepareRunner.prepare"),await r.run(t,n)}catch(t){if(t instanceof $r)return;let r=s.getArgsOnRemoteRunFailure();return r&&await Ap({...r,error:t.message}).catch(()=>{}),t instanceof C?(console.log(id.default.red("Argument Error:",t.message)),t):(console.log("Error:",t.message),kR.error("runner ended with unexpected error",{err:t}),t)}}_R().then(s=>{Array.isArray(s)&&s.length===0&&console.log("No tests ran"),Dp(s)});
423
423
  //# sourceMappingURL=cli.js.map