@testim/testim-cli 4.164.1 → 4.164.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var XT=Object.create;var ui=Object.defineProperty;var YT=Object.getOwnPropertyDescriptor;var QT=Object.getOwnPropertyNames;var ZT=Object.getPrototypeOf,ew=Object.prototype.hasOwnProperty;var E=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)ui(s,t,{get:e[t],enumerable:!0})},bd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of QT(e))!ew.call(s,n)&&n!==t&&ui(s,n,{get:()=>e[n],enumerable:!(r=YT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?XT(ZT(s)):{},bd(e||!s||!s.__esModule?ui(t,"default",{value:s,enumerable:!0}):t,s)),qe=s=>bd(ui({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>F,measure:()=>rw});function F(...s){if(!wd)return;let e=Date.now();console.log(`${e-tw} ${e-Td} `,...s),Td=e}function rw(s,e){if(!wd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var wd,tw,Td,$e=E(()=>{"use strict";wd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,tw=Date.now(),Td=Date.now()});var Jt,Hr=E(()=>{"use strict";Jt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ze(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function mc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function De(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 fc=E(()=>{"use strict"});var hc,vd,Sd,bi=E(()=>{hc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"2.0.1"},vd={"@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.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.2",fkill:"7.2.1","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","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.44.1",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},Sd={node:">= 18.0.0"}});var fr,gr,Ed,xt,iw,ft,Id,Rd,Ti,rt,xd,he,Ad,Cd,wi,We,yc,Pd,vi,kd,Od,zR,KR,_d,Ld,Dd,Nd,bc,Tc,wc,vc,Md,Vs,Fd,Sc,Gs,oe=E(()=>{"use strict";fr=process.env.SERVICES_HOST||"",gr="https://app.testim.io";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:fr,fr=process.env.SERVICES_HOST);Ed=process.env.TESTIM_REGION||"us-west-2",xt=process.env.RUNNER_ENVIRONMENT||"production",iw={production:"",staging:".staging",development:".dev"},ft=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${iw[xt]||""}.testim.io`,Id=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Rd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Ti=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),rt=process.env.EDITOR_URL,xd=process.env.WEBSOCKET_HOST||`${fr}/ws`,he=()=>fr,Ad=parseInt(process.env.LOGGER_CONSOLE||"0",10),Cd=parseInt(process.env.LOGGER_DEBUG||"0",10),wi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),yc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Pd=parseInt(process.env.DEBUG_MODE||"0",10),vi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,kd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Od=process.env.CORALOGIX_PRIVATE_KEY||"",zR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),KR=process.env.APPIUM_VERSION||"1.10.1",_d=process.env.GATEWAY_URL,Ld=()=>process.env.EXTENSION_SERVICES_HOST||fr,Dd=5*60*1e3,Nd=40,bc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",Tc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",wc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",vc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Md=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Vs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Fd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Sc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Gs=s=>{fr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:fr}});var Ud,Si,Bd=E(()=>{"use strict";Ud=I(require("superagent"));oe();Si=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Od,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=Ud.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 $d={};z($d,{CoralogixTransport:()=>Ec});var jd,ow,aw,Ec,Wd=E(()=>{"use strict";jd=I(require("winston-transport"));Bd();ow={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},aw=["err","error","reason","e"],Ec=class extends jd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Si({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},m={severity:ow[i],text:o,category:n||this.category};l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
- ${l.msg}`));for(let u of aw)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(o&&!d&&(l.msg=o),m.text=JSON.stringify(l)),this.logger.addLog(m),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function uw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Wd(),qe($d)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Ad){let r={depth:5,colors:!0};s.push(new gt.transports.Console({format:gt.format.combine(gt.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),gt.format.timestamp({format:"HH:mm:ss:SSS"}),gt.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ii.inspect(n.meta,r)}`))}))}return[s,e,t]}function Jd(s){Ic=s}function Xd(s){Kd=s}function Yd(s){We||!s||mw(s)}function Gd(s){return{projectId:Kd,time:new Date().toISOString(),region:Ut.getRegion(),...Ic&&!s&&{executionId:Ic}}}function P(s){return new Ut(hw.child({category:s}))}var Hd,gt,Ii,Ei,qd,cw,lw,Vd,zd,pw,dw,mw,fw,gw,hw,Ic,Kd,Ut,$=E(()=>{"use strict";Hd=I(require("node:os")),gt=I(require("winston"));oe();Ii=I(require("node:util")),Ei=I(require("chalk")),qd=I(require("dayjs"));B();cw=Hd.hostname(),lw=st();Vd={depth:5,colors:!0},zd=(s,e,t)=>{let r=`[${(0,qd.default)().format("HH:mm:ss:SSS")}]`,n=Ii.inspect(e,Vd),i=Ii.inspect(t,Vd);return`${Ei.default.white(r)} ${Ei.default.reset()}SessionPlayer-${Ei.default.red(s)} ${n} ${i}`},[pw,dw,mw]=uw(),fw=Cd?"debug":"info",gw={release:Boolean(!1),branch:"test"},hw=gt.createLogger({levels:gt.config.syslog.levels,level:fw,transports:pw,defaultMeta:{name:"runner",hostname:cw,nodeVersion:process.version,runnerVersion:lw,...gw}}),Ic=null,Kd=null;Ut=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)}static setRegion(e){Ut.region=e}static getRegion(){return Ut.region}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,...Gd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Gd(n)})}catch{}}}waitForFlush(){return dw()}}});var Ci,qr,C,Xt,hr,At,Ri,zr,ce,Hs,nt,Yt,Ct,xi,Kr,Ai,qs,Y=E(()=>{"use strict";Ci=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Xt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},hr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},At=class extends Ci.AbortError{},Ri=class extends Ci.AbortError{},zr=class extends Ci.AbortError{},ce=class extends Error{},Hs=class extends Error{},nt=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends nt{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Ct=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},xi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ai=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},qs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Rc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,em.setTimeout)(s)}function xc(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"){Ti&&!Qd&&(Qd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=Ti?Number(Ti)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Zd||=(await import("p-limit")).default;let r=Zd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var em,Qd,Zd,Ac=E(()=>{"use strict";em=require("timers/promises");Y();oe();Qd=!1});var Ks,tm,bw,zs,rm,Tw,ww,sm,nm=E(()=>{"use strict";Ks=I(require("lodash"));oe();tm=require("dns");$();Ac();bw=P("http-request-counters"),zs=!1,rm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>tm.promises.lookup(t)));return e||(zs=!0),e}catch{return bw.error("network connectivity test failed"),zs=!0,!1}},Tw=Ks.throttle(rm,10*1e3),ww=60*1e3*15,sm=()=>{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)},ww)}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),zs||Tw(),a}}}async function r(){if(zs||!await rm())return!1;let n=Ks.sum([...s.fail.values()]),i=Ks.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>zs,t}});var Ke={};z(Ke,{deleteReq:()=>Js,didNetworkConnectivityTestFail:()=>Dc,download:()=>_c,get:()=>Te,getFullRes:()=>Rw,getText:()=>Ys,head:()=>xw,isNetworkHealthy:()=>Lc,post:()=>Ve,postForm:()=>Xs,postText:()=>kc,put:()=>Oc});function Sw(){return global.caFileContent}function Ew(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Iw(){return!ht.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(ht.default),global.proxyUri}function yr(s,e=!1){let t=Sw();t&&s.ca(t);let r=!e&&Iw();r&&s.proxy(r)}async function im(s,e,t={},r=Jr,n=0){let i=ht.default.post(s).send(e).timeout(r).set(t);yr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Pc(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=ht.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),yr(o,i),await o}var ht,Cc,it,Jr,vw,Bt,Js,Ve,Xs,Ys,kc,Te,Rw,xw,Oc,_c,Lc,Dc,Ge=E(()=>{"use strict";ht=I(require("superagent"));$();nm();Cc=P("http-request"),it=sm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,vw=6e4;Bt=(s,e,t)=>{let r=e.response;e.response instanceof ht.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 Cc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Js=it(async(s,e={},t={},r=Jr)=>{try{let n=ht.default.delete(s).send(e).timeout(r).set(t);yr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Bt("failed to delete request",n,{url:s})}}),Ve=it(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await im(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Bt("failed to post request",i,{url:s})}});Xs=it(async(s,e,t,r={},n=Jr)=>{let i=ht.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)}),yr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Bt("failed to post request",o,{url:s})}});Ys=it(async(s,e,t)=>{try{return(await Pc(s,e,t)).text}catch(r){return Bt("failed to getText request",r,{url:s,query:e})}}),kc=it(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await im(s,e,t,r,n)).text}catch(i){return Bt("failed to post request",i,{url:s})}}),Te=it(async(s,e,t,r,n)=>{try{return(await Pc(s,e,t,r,n)).body}catch(i){return Bt("failed to get request",i,{url:s,query:e})}}),Rw=it((s,e,t,r)=>Pc(s,e,t,r)),xw=it(async s=>{let e=ht.default.head(s).timeout(Jr);yr(e);try{return await e}catch(t){return Bt("failed to head request",t,{url:s})}}),Oc=it(async(s,e,t={},r=Jr)=>{let n=ht.default.put(s).send(e).timeout(r).set(t);yr(n);try{return(await n).body}catch(i){return Bt("failed to put request",i,{url:s})}}),_c=it(async s=>{Cc.info("start to download",{url:s});let e=ht.default.get(s).set("User-Agent","Testim.io").timeout(vw).buffer(!0).parse(Ew);yr(e);try{let t=await e;return Cc.info("finished to download",{url:s}),t}catch(t){return Bt("failed to download",t,{url:s})}}),Lc=it.isNetworkHealthy,Dc=it.didNetworkConnectivityTestFail});function yt(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=jt.resolve(__dirname,"../../"):s=jt.resolve(__dirname,""),s):process.cwd()}function Pi(s,e){return De(s)?e||jt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||jt.basename(s)}function st(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Fc(){try{return Sd.node}catch{return""}}async function cm(s,e,t=!0){let r=await ot.promises.readdir(s,{withFileTypes:!0});await ot.promises.mkdir(e,{recursive:t});for(let n of r){let i=jt.join(s,n.name),o=jt.join(e,n.name);n.isDirectory()?await cm(i,o):await ot.promises.copyFile(i,o)}}async function ye(s){try{return await ot.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var jt,om,am,ot,Aw,$t,Je,ki,Nc,at,Mc,lm=E(()=>{"use strict";jt=I(require("node:path"));fc();bi();om=I(require("unzip-stream")),am=I(require("p-retry")),ot=require("node:fs"),Aw=3;$t=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,am.default)(()=>e.download(s),{retries:Aw,factor:1})},Je=async(s,e)=>{let t=await $t(s);return ot.promises.writeFile(e,t.body)};ki=async(s,e)=>{let t=Pi(s,e);return De(s)?Je(s,t):ot.promises.copyFile(s,t)},Nc=async s=>De(s)?$t(s):ot.promises.readFile(s),at=async(s,e)=>(0,ot.createReadStream)(s).pipe(om.Extract({path:e})),Mc=s=>(0,ot.statSync)(s).size/1e6});var Wt={};z(Wt,{APPIUM_SESSION_MESSAGE:()=>Wc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>Oi,MOBILE_RUN_SKIP_REASON:()=>$c,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>Vc,gridMessages:()=>bt,gridTypes:()=>_,mobileWeb:()=>Bc,runnerStatus:()=>Uc,runnerTestStatus:()=>fe,socketEventTypes:()=>Pt,stepResult:()=>Xr,test:()=>jc,testRunStatus:()=>Qs,testStatus:()=>Xe,timeoutMessages:()=>Ae});var Ae,Qs,Uc,fe,Xe,bt,Bc,jc,Pt,K,_,Xr,Oi,$c,Wc,Vc,Yr,ae=E(()=>{"use strict";Ae={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},Qs={COMPLETED:"completed"},Uc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},bt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Bc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},jc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Pt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Xr={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",KEEP_ALIVE_FAILED:"keep-alive-failed"},Oi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},$c={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Wc={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"},Vc="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"}});function Zs(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Cw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var en,um,Ye,Pw,kw,Ow,_w,Lw,Gc,Hc,pm=E(()=>{"use strict";ae();en=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},um=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Xe.QUARANTINE&&!um(e)&&!e.runQuarantinedTests;Pw=s=>Boolean(s.loginMode),kw=s=>Boolean(s.tunnelOnlyMode),Ow=s=>Boolean(s.createPrefechedData),_w=s=>Boolean(s.installLazyDepsMode),Lw=s=>Boolean(s.agentMode),Gc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Hc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Li(s=0){return _i.default.duration(s).format("HH:mm:ss.SSS")}function qc(s=0){return _i.default.duration(s).asSeconds()}var _i,dm,zc,mm=E(()=>{"use strict";_i=I(require("dayjs")),dm=I(require("dayjs/plugin/duration"));_i.default.extend(dm.default);zc=s=>{let e=Math.floor(s.asMinutes()),t=s.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var tn,Qr,Zt,fm,Zr,gm=E(()=>{"use strict";ae();tn=s=>!(!s||"fileName"in s),Qr=(s,e)=>{if(e===_.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},fm=s=>s===_.TESTIM_TVC,Zr=(s,e)=>fm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Kc(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 hm=E(()=>{"use strict"});var X={};z(X,{OSS:()=>es,TESTIM_BROWSER_DIR:()=>Vt,buildBasicHeader:()=>mc,calcPercentile:()=>Mi,copyDir:()=>cm,delay:()=>pe,doesPathExist:()=>ye,download:()=>$t,downloadAndSave:()=>Je,extractElementId:()=>Ne,formatTimeoutDuration:()=>zc,getArgsOnRemoteRunFailure:()=>Cw,getBrowserInfo:()=>Nw,getCdpAddressForHost:()=>wr,getCliLocation:()=>yt,getDuration:()=>Li,getDurationSec:()=>qc,getEnginesVersion:()=>Fc,getEnvironmentGitBranch:()=>Tr,getLinksFromUnescapeHTML:()=>nn,getLocalFileSizeInMB:()=>Mc,getMemorySnapshot:()=>Kc,getPlanType:()=>Ni,getRunConfigByBrowserName:()=>rn,getRunnerVersion:()=>st,getSource:()=>ki,getSourceAsBuffer:()=>Nc,getSourcePath:()=>Pi,getTestUrl:()=>ze,getUniqBrowsers:()=>Zs,groupTestsByRetries:()=>Xc,guid:()=>re,hasTestPlanFlag:()=>en,isAgentMode:()=>Lw,isAppFromDevice:()=>tn,isAppFromDeviceDisabled:()=>Zr,isCreatePrefetchedDataMode:()=>Ow,isInstallLazyDepsMode:()=>_w,isLoginMode:()=>Pw,isMobileProject:()=>Zt,isPromise:()=>Rc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>um,isTestimVirtualGrid:()=>fm,isTunnelOnlyMode:()=>kw,isURL:()=>De,promiseAbort:()=>xc,promiseFromCallback:()=>Qt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Di,replaceArgsWithNoDashes:()=>Gc,sanitizeNumberValue:()=>br,shouldBlockVirtualIosBuild:()=>Qr,spreadObjectToArgs:()=>Hc,unescapeHTML:()=>sn,unzipFile:()=>at});function br(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Nw(s){return s=s.toLowerCase(),Jc.find(e=>e.browserValue===s)}function rn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Jc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Jc[0],n=es.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=es.find(i=>i.sl.platform===e.platform):e.platformName&&(n=es.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=es.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=es.find(i=>i.bs.platform===t.platform))),ts.merge(r,n)}function Tr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Di(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Di(s[r],e,t))}function Ne(s){return s.ELEMENT||s[Jt]}function Ni(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Xc(s=[]){return ts.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ts.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function sn(s){return vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function nn(s){return[...vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function wr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var bm,ts,Tm,wm,Dw,Vt,ym,es,Jc,Mi,vm,B=E(()=>{"use strict";bm=I(require("os")),ts=I(require("lodash")),Tm=I(require("path")),wm=require("linkedom");Hr();lm();pm();mm();fc();Ac();gm();hm();Dw=bm.homedir(),Vt=Tm.join(Dw,".testim-browser-profile"),ym="133",es=[{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"}}],Jc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:ym},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:ym},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"}];Mi=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};vm=new wm.DOMParser});var Yc={};z(Yc,{$schema:()=>Mw,default:()=>$w,definitions:()=>Fw,properties:()=>jw,required:()=>Bw,type:()=>Uw});var Mw,Fw,Uw,Bw,jw,$w,Sm=E(()=>{Mw="http://json-schema.org/draft-07/schema#",Fw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Uw="object",Bw=["entries"],jw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},$w={$schema:Mw,definitions:Fw,type:Uw,required:Bw,properties:jw}});async function Pm(){try{return await le(Fi.promises.readFile($i()).then(async s=>{let e=await Cm;return Gw(e,s)}),3e4)}catch{return{}}}function Gw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=ss.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 kt(s,e,t=Ww,r=void 0){return async()=>{if(!Rm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Zc(e);if(i)return on.debug("cache hit:",{fnName:e}),i;if(on.debug("cache miss:",{fnName:e}),!xm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Hw(e,o,t),o}}async function Zc(s){let t=(await Wi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Hw(s,e,t){if(Qc)throw on.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await Wi;r[s]={value:e,expiry:Date.now()+t},Am=new Promise(n=>{ji=n}),Vw(r)}catch{on.error("failed updating cache")}}async function ns(){let s=await Wi;Object.keys(s).forEach(e=>{delete s[e]})}function km(s){Rm=s}function qw(s=!0){xm=s}async function Om(){try{return Qc=!0,await Am}finally{Qc=!1}}function _m(s){Bi=s,Wi=Pm()}var Fi,Ui,ss,Em,on,Bi,Im,ji,Rm,xm,Qc,Am,Cm,Ww,$i,Wi,Vw,Lm,Dm,Ix,Nm,er=E(()=>{"use strict";Fi=I(require("fs")),Ui=I(require("path")),ss=I(require("crypto"));B();Em=require("lodash");$();on=P("local cache"),Bi=Ui.resolve(yt(),"testim-cache"),Rm=!0,xm=!0,Qc=!1,Am=new Promise(s=>{ji=s}),Cm=new Promise(s=>{Im=s}),Ww=1e3*60*60*3,$i=()=>Ui.resolve(Ui.resolve(Bi,"testim.cache"));Wi=Pm(),Vw=(0,Em.debounce)(async s=>{let e;try{let t=await Cm,r=ss.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=ss.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Bi)||await Fi.promises.mkdir(Bi,{recursive:!0}),await Fi.promises.writeFile($i(),a)}catch(t){on.error("failed saving cache",{err:t}),e=t}ji(e?{success:!1,error:e}:{success:!0})},200);Lm=Im,Dm=km.bind(void 0,!1),Ix=km.bind(void 0,!0),Nm=()=>qw(!1)});function Vi(){return{cliLocation:yt(),userInfo:is.userInfo(),platform:is.platform(),release:is.release()}}var is,el=E(()=>{"use strict";is=I(require("node:os"));B()});function zw(s){try{return Gi.resolve(Gi.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 tr(s){let e=zw(s);return require(e)}var Gi,an=E(()=>{"use strict";Gi=I(require("path"))});function Kw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Jw(s){return/The "to" argument must be of type string./.exec(s)}function Bm(s,e,t){let r=Kw(s),n=Jw(s);return r||n?(Um.info("Failed to install package due to insufficient write access",{...Vi(),package:t,path:r}),console.error(`
2
+ "use strict";var XT=Object.create;var ui=Object.defineProperty;var YT=Object.getOwnPropertyDescriptor;var QT=Object.getOwnPropertyNames;var ZT=Object.getPrototypeOf,ew=Object.prototype.hasOwnProperty;var E=(s,e)=>()=>(s&&(e=s(s=0)),e);var z=(s,e)=>{for(var t in e)ui(s,t,{get:e[t],enumerable:!0})},bd=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of QT(e))!ew.call(s,n)&&n!==t&&ui(s,n,{get:()=>e[n],enumerable:!(r=YT(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?XT(ZT(s)):{},bd(e||!s||!s.__esModule?ui(t,"default",{value:s,enumerable:!0}):t,s)),qe=s=>bd(ui({},"__esModule",{value:!0}),s);var je={};z(je,{log:()=>F,measure:()=>rw});function F(...s){if(!wd)return;let e=Date.now();console.log(`${e-tw} ${e-Td} `,...s),Td=e}function rw(s,e){if(!wd)return;let t=Date.now();try{s()}finally{console.log(e||s.name,"took",Date.now()-t)}}var wd,tw,Td,$e=E(()=>{"use strict";wd=process.env.MEASURE_TESTIM_CLI_PERFORMANCE,tw=Date.now(),Td=Date.now()});var Jt,Hr=E(()=>{"use strict";Jt="element-6066-11e4-a52e-4f735466cecf"});function re(s=16){let e="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t}function ze(s,e,t,r,n){let i="";return n=n?encodeURIComponent(n):"master",e&&t&&(i=`${s}/#/project/${e}/branch/${n}/test/${t}`,r&&(i+=`?result-id=${r}`)),i}function mc(s,e){return`Basic ${Buffer.from(`${s}:${e}`).toString("base64")}`}function De(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 fc=E(()=>{"use strict"});var hc,vd,Sd,bi=E(()=>{hc={ngrok:"4.3.3","v8-to-istanbul":"9.1.0","istanbul-lib-coverage":"3.2.0","@bcoe/v8-coverage":"0.2.3","convert-source-map":"1.7.0",multer:"2.0.1"},vd={"@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.8.1",cors:"2.8.5","data-uri-to-buffer":"2.0.2",dayjs:"1.11.8",eventsource:"3.0.6",express:"4.21.2",fkill:"7.2.1","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","object-hash":"3.0.0",ora:"5.4.1","p-limit":"4.0.0","p-retry":"4.6.2",pako:"1.0.11",portfinder:"1.0.28","promise-queue":"2.2.5",prompts:"2.4.2","proxy-agent":"6.3.1","rox-node":"5.4.12",semver:"7.6.0","serialize-error":"7.0.1","socket.io-client":"4.8.0","source-map-support":"0.5.19",superagent:"9.0.1","superagent-proxy":"3.0.0","test-exclude":"7.0.0","ua-parser-js":"0.7.39","unzip-stream":"0.3.4",uuid:"11.0.5","validate-npm-package-name":"3.0.0",webdriverio:"8.44.1",winston:"3.11.0","winston-transport":"4.6.0",ws:"8.17.1",xml2js:"0.6.2",yaml:"2.2.2"},Sd={node:">= 18.0.0"}});var fr,gr,Ed,xt,iw,mt,Id,Rd,Ti,tt,xd,he,Ad,Cd,wi,We,yc,Pd,vi,kd,Od,zR,KR,_d,Ld,Dd,Nd,bc,Tc,wc,vc,Md,Vs,Fd,Sc,Gs,oe=E(()=>{"use strict";fr=process.env.SERVICES_HOST||"",gr="https://app.testim.io";process.env.GATEWAY_URL&&(process.env.CORALOGIX_URL=`${process.env.GATEWAY_URL}/testim/coralogix/api/v1/logs`,process.env.SERVICES_HOST=`${process.env.GATEWAY_URL}/testim/services`,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:fr,fr=process.env.SERVICES_HOST);Ed=process.env.TESTIM_REGION||"us-west-2",xt=process.env.RUNNER_ENVIRONMENT||"production",iw={production:"",staging:".staging",development:".dev"},mt=process.env.EXTENSION_SP_S3_HOST||`https://playback-components${iw[xt]||""}.testim.io`,Id=parseInt(process.env.DISABLE_AGENT_ORIGIN_CHECK||"0",10),Rd=parseInt(process.env.DISABLE_DEBUGGER_INFINITE_TIMEOUT||"0",10),Ti=parseInt(process.env.OVERRIDE_TIMEOUTS||"0",10),tt=process.env.EDITOR_URL,xd=process.env.WEBSOCKET_HOST||`${fr}/ws`,he=()=>fr,Ad=parseInt(process.env.LOGGER_CONSOLE||"0",10),Cd=parseInt(process.env.LOGGER_DEBUG||"0",10),wi=parseInt(process.env.WEBDRIVER_DEBUG||"0",10),We=parseInt(process.env.IS_ON_PREM||"0",10),yc=process.env.REQUESTS_QUEUE_SIZE?parseInt(process.env.REQUESTS_QUEUE_SIZE,10):void 0,Pd=parseInt(process.env.DEBUG_MODE||"0",10),vi=process.env.TESTIM_CONCURRENT_WORKER_COUNT?parseInt(process.env.TESTIM_CONCURRENT_WORKER_COUNT,10):null,kd=process.env.ROLLOUT_KEY||"5b5560729601aa6484276518",Od=process.env.CORALOGIX_PRIVATE_KEY||"",zR=parseInt(process.env.DF_ENABLE_VIDEO||"0",10),KR=process.env.APPIUM_VERSION||"1.10.1",_d=process.env.GATEWAY_URL,Ld=()=>process.env.EXTENSION_SERVICES_HOST||fr,Dd=5*60*1e3,Nd=40,bc=process.env.HEADSPIN_MOBILE_API_BASE_URL||"https://api-dev.headspin.io",Tc=process.env.TDC_MOBILE_API_BASE_URL||"https://api.tdc.tricentis-cloud.com",wc=process.env.HEADSPIN_TDC_DEVICES_API_PATH||"v0",vc=process.env.HEADSPIN_TDC_APPS_API_PATH||"v1",Md=process.env.TVC_MOBILE_API_URL||"https://api.waldo.com",Vs=process.env.BROWSERSTACK_APPS_API_URL||"https://api-cloud.browserstack.com/app-automate",Fd=process.env.P_CLOUDY_DEFAULT_TEST_DURATION||60,Sc=process.env.P_CLOUDY_DEFAULT_ANDROID_DEVICE_NAME||"samsung",Gs=s=>{fr=s,process.env.SERVICES_HOST=s,process.env.EXTENSION_SERVICES_HOST=process.env.TUNNEL_GATEWAY?process.env.SERVICES_HOST:fr}});var Ud,Si,Bd=E(()=>{"use strict";Ud=I(require("superagent"));oe();Si=class{constructor(e){this.logs=[];this.url=process.env.CORALOGIX_URL||"https://ingress.coralogix.com/logs/v1/bulk",this.token=Od,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=Ud.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 $d={};z($d,{CoralogixTransport:()=>Ec});var jd,ow,aw,Ec,Wd=E(()=>{"use strict";jd=I(require("winston-transport"));Bd();ow={debug:1,silly:2,verbose:2,silent:2,info:3,http:3,warn:4,warning:4,error:5,critical:6,crit:6},aw=["err","error","reason","e"],Ec=class extends jd.default{constructor(t){super(t);this.name="Coralogix Transport",this.category=t.category,this.logger=new Si({applicationName:"testim",subsystemName:"runner"})}log(t,r){let{category:n,level:i,message:o,meta:a={},...c}=t,l={...a,...c},m={severity:ow[i],text:o,category:n||this.category};l.className&&(m.className=l.className),l.methodName&&(m.methodName=l.methodName),l.threadId&&(m.threadId=l.threadId),delete l.className,delete l.methodName,delete l.threadId,delete l.category,delete l.level,delete l.message;let d=!1;a instanceof Error&&(d=!0,l.msg=a.message+a.stack,o&&(l.msg=`${o}
3
+ ${l.msg}`));for(let u of aw)a[u]instanceof Error&&(l[u]={message:a[u].message,stack:a[u].stack,name:a[u].name,type:a[u].type,cause:a[u].cause,...a[u]});Object.keys(l).length>0&&(o&&!d&&(l.msg=o),m.text=JSON.stringify(l)),this.logger.addLog(m),r(null,!0)}setProxy(t){this.logger.setProxy(t)}async waitForFlush(){return await this.logger.waitForFlush()}}});function uw(){let s=[],e=()=>Promise.resolve(),t=r=>{};if(!We){let{CoralogixTransport:r}=(Wd(),qe($d)),n=new r({category:"ROOT"});s.push(n),e=()=>n.waitForFlush(),t=i=>n.setProxy(i)}if(Ad){let r={depth:5,colors:!0};s.push(new ft.transports.Console({format:ft.format.combine(ft.format.colorize({all:!0,colors:{info:"blue",error:"red",warning:"yellow"}}),ft.format.timestamp({format:"HH:mm:ss:SSS"}),ft.format.printf(n=>`[${n.timestamp}] ${n.level} ${n.category}: ${n.message} ${Ii.inspect(n.meta,r)}`))}))}return[s,e,t]}function Jd(s){Ic=s}function Xd(s){Kd=s}function Yd(s){We||!s||mw(s)}function Gd(s){return{projectId:Kd,time:new Date().toISOString(),region:Ut.getRegion(),...Ic&&!s&&{executionId:Ic}}}function P(s){return new Ut(hw.child({category:s}))}var Hd,ft,Ii,Ei,qd,cw,lw,Vd,zd,pw,dw,mw,fw,gw,hw,Ic,Kd,Ut,$=E(()=>{"use strict";Hd=I(require("node:os")),ft=I(require("winston"));oe();Ii=I(require("node:util")),Ei=I(require("chalk")),qd=I(require("dayjs"));B();cw=Hd.hostname(),lw=rt();Vd={depth:5,colors:!0},zd=(s,e,t)=>{let r=`[${(0,qd.default)().format("HH:mm:ss:SSS")}]`,n=Ii.inspect(e,Vd),i=Ii.inspect(t,Vd);return`${Ei.default.white(r)} ${Ei.default.reset()}SessionPlayer-${Ei.default.red(s)} ${n} ${i}`},[pw,dw,mw]=uw(),fw=Cd?"debug":"info",gw={release:Boolean(!1),branch:"test"},hw=ft.createLogger({levels:ft.config.syslog.levels,level:fw,transports:pw,defaultMeta:{name:"runner",hostname:cw,nodeVersion:process.version,runnerVersion:lw,...gw}}),Ic=null,Kd=null;Ut=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)}static setRegion(e){Ut.region=e}static getRegion(){return Ut.region}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,...Gd(n)})}catch(i){try{this._logger.log("crit",{message:`failed to log message ${i.message}, ${i.stack}`,...Gd(n)})}catch{}}}waitForFlush(){return dw()}}});var Ci,qr,C,Xt,hr,At,Ri,zr,ce,Hs,st,Yt,Ct,xi,Kr,Ai,qs,Y=E(()=>{"use strict";Ci=require("p-retry"),qr=class extends Error{constructor(){super(...arguments);this.name="NoArgsError"}},C=class extends Error{constructor(){super(...arguments);this.name="ArgError"}},Xt=class extends Error{constructor(){super(...arguments);this.name="StopRunOnError"}},hr=class extends Error{constructor(t,r){super(t instanceof Error?t.message:t,{cause:t});this.type=r}},At=class extends Ci.AbortError{},Ri=class extends Ci.AbortError{},zr=class extends Ci.AbortError{},ce=class extends Error{},Hs=class extends Error{},st=class extends Error{constructor(){super(...arguments);this.name="GridError"}toString(){return this.message}},Yt=class extends st{constructor(){super(...arguments);this.name="GridConcurrencyError"}},Ct=class extends Error{constructor(){super(...arguments);this.name="NpmPackageError"}},xi=class extends Error{constructor(){super(...arguments);this.message="selenium driver crashed";this.name="SeleniumCrashError"}},Kr=class extends Error{constructor(t){super(`Testim had missing write access to ${t}`);this.path=t}},Ai=class extends Error{constructor(e){super(`Package for CLI action need to have a CommonJS export which the package ${e} does not have`)}},qs=class extends Error{constructor(e=!1){let t="not implemented";e&&(t="should be implemented on descendant"),super(t)}}});function Rc(s){return!!s&&(typeof s=="object"||typeof s=="function")&&typeof s.then=="function"&&typeof s.catch=="function"}function pe(s){return(0,em.setTimeout)(s)}function xc(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"){Ti&&!Qd&&(Qd=!0,console.log("Debugger connected - timeouts were overridden to 10 minutes to improve debugging"));let r=new ce(t);return e=Ti?Number(Ti)||6e5:e,Promise.race([s,pe(e).then(()=>{throw r})])}async function se(s,e,{concurrency:t}={}){if(t){Zd||=(await import("p-limit")).default;let r=Zd(t);return await Promise.all(Array.from(s,(n,i)=>r(()=>e(n,i))))}return await Promise.all(Array.from(s,e))}function Qt(s){return new Promise((e,t)=>{s((r,n)=>r?t(r):e(n))})}var em,Qd,Zd,Ac=E(()=>{"use strict";em=require("timers/promises");Y();oe();Qd=!1});var Ks,tm,bw,zs,rm,Tw,ww,sm,nm=E(()=>{"use strict";Ks=I(require("lodash"));oe();tm=require("dns");$();Ac();bw=P("http-request-counters"),zs=!1,rm=async()=>{if(We)return!0;let s=["www.google.com","www.facebook.com","www.microsoft.com","testim.io"];try{let e=Boolean(await se(s,t=>tm.promises.lookup(t)));return e||(zs=!0),e}catch{return bw.error("network connectivity test failed"),zs=!0,!1}},Tw=Ks.throttle(rm,10*1e3),ww=60*1e3*15,sm=()=>{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)},ww)}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),zs||Tw(),a}}}async function r(){if(zs||!await rm())return!1;let n=Ks.sum([...s.fail.values()]),i=Ks.sum([...s.call.values()]);return n<i*.1}return r.counters=s,t.counters=s,t.isNetworkHealthy=r,t.didNetworkConnectivityTestFail=()=>zs,t}});var Ke={};z(Ke,{deleteReq:()=>Js,didNetworkConnectivityTestFail:()=>Dc,download:()=>_c,get:()=>Te,getFullRes:()=>Rw,getText:()=>Ys,head:()=>xw,isNetworkHealthy:()=>Lc,post:()=>Ve,postForm:()=>Xs,postText:()=>kc,put:()=>Oc});function Sw(){return global.caFileContent}function Ew(s,e){let t=[];s.on("data",r=>{t.push(r)}),s.on("end",()=>{e(null,Buffer.concat(t))})}function Iw(){return!gt.default.Request.prototype.proxy&&global.SuperagentProxy&&global.SuperagentProxy(gt.default),global.proxyUri}function yr(s,e=!1){let t=Sw();t&&s.ca(t);let r=!e&&Iw();r&&s.proxy(r)}async function im(s,e,t={},r=Jr,n=0){let i=gt.default.post(s).send(e).timeout(r).set(t);yr(i),n&&i.retry(n);try{return await i}catch(o){throw o.url=s,o.originalRequestTimeout=r,o.additionalSetHeaders=t,o}}async function Pc(s,e,t={},r=Jr,{isBinary:n=!1,skipProxy:i=!1}={}){let o=gt.default.get(s).query(e||{}).timeout(r).set(t);return n&&o.buffer(!0),yr(o,i),await o}var gt,Cc,nt,Jr,vw,Bt,Js,Ve,Xs,Ys,kc,Te,Rw,xw,Oc,_c,Lc,Dc,Ge=E(()=>{"use strict";gt=I(require("superagent"));$();nm();Cc=P("http-request"),nt=sm(),Jr=parseInt(process.env.DEFAULT_REQUEST_TIMEOUT||"0",10)||3e4,vw=6e4;Bt=(s,e,t)=>{let r=e.response;e.response instanceof gt.default.Response&&typeof r.toError=="function"&&(e=e.response.toError(),e.requestHeaders=r==null?void 0:r.header,e.responseHeaders=r==null?void 0:r.headers);let n=new Error("").stack;throw Cc.error(s,{...t,error:e,logErrorAndRethrowStack:n}),e};Js=nt(async(s,e={},t={},r=Jr)=>{try{let n=gt.default.delete(s).send(e).timeout(r).set(t);yr(n);let i=await n;return i.type==="text/plain"?i.text:i.body}catch(n){return Bt("failed to delete request",n,{url:s})}}),Ve=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{let i=await im(s,e,t,r,n);return i.type==="text/plain"?i.text:i.body}catch(i){return Bt("failed to post request",i,{url:s})}});Xs=nt(async(s,e,t,r={},n=Jr)=>{let i=gt.default.post(s).type("form").timeout(n).set(r);i.field(e),Object.entries(t).forEach(([o,a])=>{i.attach(o,a.buffer,a.fileName)}),yr(i);try{let o=await i;return o.type==="text/plain"?o.text:o.body}catch(o){return Bt("failed to post request",o,{url:s})}});Ys=nt(async(s,e,t)=>{try{return(await Pc(s,e,t)).text}catch(r){return Bt("failed to getText request",r,{url:s,query:e})}}),kc=nt(async({url:s,body:e,headers:t,timeout:r,retry:n})=>{try{return(await im(s,e,t,r,n)).text}catch(i){return Bt("failed to post request",i,{url:s})}}),Te=nt(async(s,e,t,r,n)=>{try{return(await Pc(s,e,t,r,n)).body}catch(i){return Bt("failed to get request",i,{url:s,query:e})}}),Rw=nt((s,e,t,r)=>Pc(s,e,t,r)),xw=nt(async s=>{let e=gt.default.head(s).timeout(Jr);yr(e);try{return await e}catch(t){return Bt("failed to head request",t,{url:s})}}),Oc=nt(async(s,e,t={},r=Jr)=>{let n=gt.default.put(s).send(e).timeout(r).set(t);yr(n);try{return(await n).body}catch(i){return Bt("failed to put request",i,{url:s})}}),_c=nt(async s=>{Cc.info("start to download",{url:s});let e=gt.default.get(s).set("User-Agent","Testim.io").timeout(vw).buffer(!0).parse(Ew);yr(e);try{let t=await e;return Cc.info("finished to download",{url:s}),t}catch(t){return Bt("failed to download",t,{url:s})}}),Lc=nt.isNetworkHealthy,Dc=nt.didNetworkConnectivityTestFail});function ht(){let s;return require.main?(require.main.filename.includes("/src")||require.main.filename.includes("\\src")?s=jt.resolve(__dirname,"../../"):s=jt.resolve(__dirname,""),s):process.cwd()}function Pi(s,e){return De(s)?e||jt.join(process.cwd(),s.replace(/^.*[\\/]/,"")):e||jt.basename(s)}function rt(){try{return require(`${__dirname}/package.json`).version}catch{return""}}function Fc(){try{return Sd.node}catch{return""}}async function cm(s,e,t=!0){let r=await it.promises.readdir(s,{withFileTypes:!0});await it.promises.mkdir(e,{recursive:t});for(let n of r){let i=jt.join(s,n.name),o=jt.join(e,n.name);n.isDirectory()?await cm(i,o):await it.promises.copyFile(i,o)}}async function ye(s){try{return await it.promises.access(s),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}var jt,om,am,it,Aw,$t,Je,ki,Nc,ot,Mc,lm=E(()=>{"use strict";jt=I(require("node:path"));fc();bi();om=I(require("unzip-stream")),am=I(require("p-retry")),it=require("node:fs"),Aw=3;$t=async s=>{let e=await Promise.resolve().then(()=>(Ge(),Ke));return(0,am.default)(()=>e.download(s),{retries:Aw,factor:1})},Je=async(s,e)=>{let t=await $t(s);return it.promises.writeFile(e,t.body)};ki=async(s,e)=>{let t=Pi(s,e);return De(s)?Je(s,t):it.promises.copyFile(s,t)},Nc=async s=>De(s)?$t(s):it.promises.readFile(s),ot=async(s,e)=>(0,it.createReadStream)(s).pipe(om.Extract({path:e})),Mc=s=>(0,it.statSync)(s).size/1e6});var Wt={};z(Wt,{APPIUM_SESSION_MESSAGE:()=>Wc,CLI_MODE:()=>K,MOBILE_APP_SOURCE:()=>Oi,MOBILE_RUN_SKIP_REASON:()=>$c,REGION_CONFIG:()=>Yr,X_HEADER_RUNNER_ID:()=>Vc,gridMessages:()=>yt,gridTypes:()=>_,mobileWeb:()=>Bc,runnerStatus:()=>Uc,runnerTestStatus:()=>fe,socketEventTypes:()=>Pt,stepResult:()=>Xr,test:()=>jc,testRunStatus:()=>Qs,testStatus:()=>Xe,timeoutMessages:()=>Ae});var Ae,Qs,Uc,fe,Xe,yt,Bc,jc,Pt,K,_,Xr,Oi,$c,Wc,Vc,Yr,ae=E(()=>{"use strict";Ae={GET_BROWSER_TIMEOUT_MSG:"get-browser-timeout",TEST_START_TIMEOUT_MSG:"test-start-timeout",TEST_COMPLETE_TIMEOUT_MSG:"test-complete-timeout",TEST_REACHED_CUSTOM_TIMEOUT_MSG:"test-reached-custom-timeout"},Qs={COMPLETED:"completed"},Uc={RUNNING:"RUNNING",SKIPPED:"SKIPPED",FINISHED:"FINISHED",ABORTED:"ABORTED",QUEUED:"QUEUED",TIMEOUT:"TIMEOUT"},fe={PASSED:"PASSED",FAILED:"FAILED",ABORTED:"ABORTED",SKIPPED:"SKIPPED",QUEUED:"QUEUED",PENDING:"PENDING"},Xe={DRAFT:"draft",EVALUATING:"evaluating",ACTIVE:"active",QUARANTINE:"quarantine"},yt={NOT_FOUND:"The specified grid is not available",UNKNOWN:"Test couldn't get browser - unknown error"},Bc={MOBILE_WEB_REMOTE_RUN_HEADER_SPACING:50},jc={HIDDEN_PARAM:"TST_HIDDEN_PARAM"},Pt={TEST_RESULT_CREATED:"test-result-created",TEST_RESULT_UPDATED:"test-result-updated",REMOTE_STEP_SAVED:"remote-step-saved"},K={EXTENSION:"extension",SELENIUM:"selenium",APPIUM:"appium"},_={TESTIM_ENTERPRISE:"testimEnterprise",TESTIM:"testim",TESTIM_PRIVATE:"testimPrivate",LAMBDATEST:"lambdaTest",TESTIM_LAMBDATEST:"testimLambdaTest",DEVICE_FARM:"testimDF",HYBRID:"testimHybrid",BROWSERSTACK:"browserstack",SAUCELABS:"saucelabs",TESTIM_HEADSPIN:"testimHeadspin",TESTIM_TDC:"testimTDC",TESTIM_TVC:"testimTVC",P_CLOUDY:"pcloudy"},Xr={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",KEEP_ALIVE_FAILED:"keep-alive-failed"},Oi={FROM_LIBRARY:"from-library",FROM_DEVICE:"from-device"},$c={APP_FROM_DEVICE:"app-from-device",VIRTUAL_BUILD:"virtual-build"},Wc={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"},Vc="X-Testim-Runner-ID",Yr={TTL:1e3*60*60*24,CACHE_FN_NAME:"setRegionConfig"}});function Zs(s,e){var t,r,n,i,o,a;return(t=s.browserstack)!=null&&t.browserName||(r=s.saucelabs)!=null&&r.browserName?[(n=s.browser)==null?void 0:n.toLowerCase()]:(i=s.testConfigNames)!=null&&i.length||(o=s.testConfigIds)!=null&&o.length||s.testPlan.length||s.testPlanIds.length||!s.browser?[...new Set(e.map(c=>{var l;return(l=c.runConfig)==null?void 0:l.browserValue}))]:[(a=s.browser)==null?void 0:a.toLowerCase()]}function Cw(){let{argv:s}=process;if(s.includes("--remoteRunId"))return{remoteRunId:s[s.indexOf("--remoteRunId")+1],projectId:s[s.indexOf("--project")+1],token:s[s.indexOf("--token")+1]}}var en,um,Ye,Pw,kw,Ow,_w,Lw,Gc,Hc,pm=E(()=>{"use strict";ae();en=s=>{var e,t;return Boolean(((e=s.testPlan)==null?void 0:e.length)||((t=s.testPlanIds)==null?void 0:t.length))},um=s=>Boolean(s.resultId&&s.source==="remote-run"),Ye=(s,e)=>s.testStatus===Xe.QUARANTINE&&!um(e)&&!e.runQuarantinedTests;Pw=s=>Boolean(s.loginMode),kw=s=>Boolean(s.tunnelOnlyMode),Ow=s=>Boolean(s.createPrefechedData),_w=s=>Boolean(s.installLazyDepsMode),Lw=s=>Boolean(s.agentMode),Gc=(s,e)=>{s.forEach((t,r)=>{e.has(t)&&(s[r]=`--${t}`)})},Hc=s=>{let e=[];return Object.entries(s).forEach(([t,r])=>{r&&e.push(`--${t}`,r)}),e}});function Li(s=0){return _i.default.duration(s).format("HH:mm:ss.SSS")}function qc(s=0){return _i.default.duration(s).asSeconds()}var _i,dm,zc,mm=E(()=>{"use strict";_i=I(require("dayjs")),dm=I(require("dayjs/plugin/duration"));_i.default.extend(dm.default);zc=s=>{let e=Math.floor(s.asMinutes()),t=s.asSeconds()%60||0;return e>0?`${e} min ${Math.floor(t)} sec`:`${Math.floor(t)} sec`}});var tn,Qr,Zt,fm,Zr,gm=E(()=>{"use strict";ae();tn=s=>!(!s||"fileName"in s),Qr=(s,e)=>{if(e===_.TESTIM_TVC)return!1;if(s){if(s.appMetadata&&"iOSSupportedTargetDevice"in s.appMetadata)return s.appMetadata.iOSSupportedTargetDevice==="virtual";if("fileName"in s)return s.fileName.endsWith(".app")}return!1},Zt=s=>{var e,t;return((e=s.projectData)==null?void 0:e.type)==="ios"||((t=s.projectData)==null?void 0:t.type)==="android"},fm=s=>s===_.TESTIM_TVC,Zr=(s,e)=>fm(e)||!s.flags.allowAppFromDeviceRuns.isEnabled()});function Kc(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 hm=E(()=>{"use strict"});var X={};z(X,{OSS:()=>es,TESTIM_BROWSER_DIR:()=>Vt,buildBasicHeader:()=>mc,calcPercentile:()=>Mi,copyDir:()=>cm,delay:()=>pe,doesPathExist:()=>ye,download:()=>$t,downloadAndSave:()=>Je,extractElementId:()=>Ne,formatTimeoutDuration:()=>zc,getArgsOnRemoteRunFailure:()=>Cw,getBrowserInfo:()=>Nw,getCdpAddressForHost:()=>wr,getCliLocation:()=>ht,getDuration:()=>Li,getDurationSec:()=>qc,getEnginesVersion:()=>Fc,getEnvironmentGitBranch:()=>Tr,getLinksFromUnescapeHTML:()=>nn,getLocalFileSizeInMB:()=>Mc,getMemorySnapshot:()=>Kc,getPlanType:()=>Ni,getRunConfigByBrowserName:()=>rn,getRunnerVersion:()=>rt,getSource:()=>ki,getSourceAsBuffer:()=>Nc,getSourcePath:()=>Pi,getTestUrl:()=>ze,getUniqBrowsers:()=>Zs,groupTestsByRetries:()=>Xc,guid:()=>re,hasTestPlanFlag:()=>en,isAgentMode:()=>Lw,isAppFromDevice:()=>tn,isAppFromDeviceDisabled:()=>Zr,isCreatePrefetchedDataMode:()=>Ow,isInstallLazyDepsMode:()=>_w,isLoginMode:()=>Pw,isMobileProject:()=>Zt,isPromise:()=>Rc,isQuarantineAndNotRemoteRun:()=>Ye,isRemoteRun:()=>um,isTestimVirtualGrid:()=>fm,isTunnelOnlyMode:()=>kw,isURL:()=>De,promiseAbort:()=>xc,promiseFromCallback:()=>Qt,promiseMap:()=>se,promiseTimeout:()=>le,removePropertyFromObject:()=>Di,replaceArgsWithNoDashes:()=>Gc,sanitizeNumberValue:()=>br,shouldBlockVirtualIosBuild:()=>Qr,spreadObjectToArgs:()=>Hc,unescapeHTML:()=>sn,unzipFile:()=>ot});function br(s,e){let t=Number(s);return Number.isNaN(t)||t<=0?e:t}function Nw(s){return s=s.toLowerCase(),Jc.find(e=>e.browserValue===s)}function rn(s,e,t){s=s==null?void 0:s.toLowerCase();let r=Jc.find(i=>i.browserName.toLowerCase()===s||s.includes(i.synonyms))||Jc[0],n=es.find(i=>i.osName==="Windows 10");return e&&(e.platform?n=es.find(i=>i.sl.platform===e.platform):e.platformName&&(n=es.find(i=>i.sl.platformName===e.platformName))),t&&(t.os_version?n=es.find(i=>i.bs.os_version===t.os_version):t.platform&&(n=es.find(i=>i.bs.platform===t.platform))),ts.merge(r,n)}function Tr(){return process.env.GIT_BRANCH||process.env.CIRCLE_BRANCH||process.env.TRAVIS_BRANCH||process.env.CI_BRANCH}function Di(s,e,t){for(let r in s)Object.hasOwn(s,r)&&(t(r,e)?delete s[r]:typeof s[r]=="object"&&Di(s[r],e,t))}function Ne(s){return s.ELEMENT||s[Jt]}function Ni(s){s||={};let e=Date.now(),t=s.expireAt||s.expireAT;return s.plan!=="free"?"pro":t?t<e?"free":"trial":"free"}function Xc(s=[]){return ts.chain(s).groupBy(e=>e.originalTestResultId||e.resultId).values().reduce((e,t)=>{if(!t)return e;if(t.length===1)return e.push(t[0]),e;let r=t.slice().sort((i,o)=>{let a=typeof i.retryCount=="number"?i.retryCount:1,c=typeof o.retryCount=="number"?o.retryCount:1;return a===c?i.startTime-o.startTime:(i.retryCount??0)-(o.retryCount??0)}),n=ts.cloneDeep(r.at(-1));return n&&(n.retryTestResults=r,e.push(n)),e},[]).compact().value()}function sn(s){return vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").documentElement.textContent}function nn(s){return[...vm.parseFromString(`<html><body>${s}</body></html>`,"text/html").getElementsByTagName("a")].map(t=>t.href).filter(Boolean)}async function wr(s,e){let t=await Promise.resolve().then(()=>(Ge(),Ke));try{return(await t.get(`http://${s}/json/version`,void 0,void 0,e)).webSocketDebuggerUrl}catch{throw new Error("unable to connect to devtools server")}}var bm,ts,Tm,wm,Dw,Vt,ym,es,Jc,Mi,vm,B=E(()=>{"use strict";bm=I(require("os")),ts=I(require("lodash")),Tm=I(require("path")),wm=require("linkedom");Hr();lm();pm();mm();fc();Ac();gm();hm();Dw=bm.homedir(),Vt=Tm.join(Dw,".testim-browser-profile"),ym="133",es=[{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"}}],Jc=[{browserName:"Chrome",bs:{browser:"Chrome",browser_version:ym},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:ym},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"}];Mi=(s,e)=>{if(s.length===0)return 0;if(typeof e!="number")throw new TypeError("p must be a number");if(s=[...s].sort((r,n)=>r-n),e<=0)return s[0];if(e>=100)return s.at(-1);let t=Math.ceil(s.length*(e/100))-1;return s[t]};vm=new wm.DOMParser});var Yc={};z(Yc,{$schema:()=>Mw,default:()=>$w,definitions:()=>Fw,properties:()=>jw,required:()=>Bw,type:()=>Uw});var Mw,Fw,Uw,Bw,jw,$w,Sm=E(()=>{Mw="http://json-schema.org/draft-07/schema#",Fw={request:{type:"object",required:["url"],additionalProperties:!1,properties:{url:{type:"string"},method:{type:"string",pattern:"^GET$|^HEAD$|^POST$|^PUT$|^DELETE$|^CONNECT$|^OPTIONS$|^TRACE$|^PATCH$"}}},header:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"}}},cookie:{type:"object",required:["name","value"],additionalProperties:!1,properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:"string",format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"}}},response:{type:"object",required:["status"],additionalProperties:!1,properties:{status:{type:"integer",minimum:100,exclusiveMaximum:600},headers:{type:"array",items:{$ref:"#/definitions/header"}},cookies:{type:"array",items:{$ref:"#/definitions/cookie"}},content:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}}},redirectResponse:{type:"object",required:["redirectUrl"],additionalProperties:!1,properties:{redirectUrl:{type:"string"}}},passthroughResponse:{type:"object",required:["passthrough"],additionalProperties:!1,properties:{passthrough:{type:"boolean",enum:[!0]}}},entry:{type:"object",required:["request","response"],additionalProperties:!1,properties:{request:{$ref:"#/definitions/request"},response:{oneOf:[{$ref:"#/definitions/response"},{$ref:"#/definitions/redirectResponse"},{$ref:"#/definitions/passthroughResponse"}]},maxHits:{type:"integer",minimum:1}}}},Uw="object",Bw=["entries"],jw={version:{type:"string",enum:["1.2","1.2.0"]},creator:{type:"string"},entries:{type:"array",items:{$ref:"#/definitions/entry"}}},$w={$schema:Mw,definitions:Fw,type:Uw,required:Bw,properties:jw}});async function Pm(){try{return await le(Fi.promises.readFile($i()).then(async s=>{let e=await Cm;return Gw(e,s)}),3e4)}catch{return{}}}function Gw(s,e){let t=e.slice(0,16),r=e.slice(16),n=Buffer.from(s),i=ss.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 kt(s,e,t=Ww,r=void 0){return async()=>{if(!Rm)return await s();let n=e;r&&(e+=JSON.stringify(r));let i=await Zc(e);if(i)return on.debug("cache hit:",{fnName:e}),i;if(on.debug("cache miss:",{fnName:e}),!xm)throw new Error(`Attempted to rebuild cache for ${n}. cache miss is not allowed with current run configuration`);let o=await s();return o&&await Hw(e,o,t),o}}async function Zc(s){let t=(await Wi)[s];if(!t)return;let{value:r,expiry:n}=t;if(!(n<Date.now())&&r)return r}async function Hw(s,e,t){if(Qc)throw on.error("calling set after waitForSave is not allowed",{key:s,ttl:t}),new Error("calling set after waitForSave is not allowed");try{let r=await Wi;r[s]={value:e,expiry:Date.now()+t},Am=new Promise(n=>{ji=n}),Vw(r)}catch{on.error("failed updating cache")}}async function ns(){let s=await Wi;Object.keys(s).forEach(e=>{delete s[e]})}function km(s){Rm=s}function qw(s=!0){xm=s}async function Om(){try{return Qc=!0,await Am}finally{Qc=!1}}function _m(s){Bi=s,Wi=Pm()}var Fi,Ui,ss,Em,on,Bi,Im,ji,Rm,xm,Qc,Am,Cm,Ww,$i,Wi,Vw,Lm,Dm,Ix,Nm,er=E(()=>{"use strict";Fi=I(require("fs")),Ui=I(require("path")),ss=I(require("crypto"));B();Em=require("lodash");$();on=P("local cache"),Bi=Ui.resolve(ht(),"testim-cache"),Rm=!0,xm=!0,Qc=!1,Am=new Promise(s=>{ji=s}),Cm=new Promise(s=>{Im=s}),Ww=1e3*60*60*3,$i=()=>Ui.resolve(Ui.resolve(Bi,"testim.cache"));Wi=Pm(),Vw=(0,Em.debounce)(async s=>{let e;try{let t=await Cm,r=ss.randomBytes(16),n=JSON.stringify(s),i=Buffer.from(t),o=ss.createCipheriv("aes-256-cbc",Buffer.concat([i,Buffer.alloc(32)],32),r),a=Buffer.concat([r,o.update(n),o.final()]);await ye(Bi)||await Fi.promises.mkdir(Bi,{recursive:!0}),await Fi.promises.writeFile($i(),a)}catch(t){on.error("failed saving cache",{err:t}),e=t}ji(e?{success:!1,error:e}:{success:!0})},200);Lm=Im,Dm=km.bind(void 0,!1),Ix=km.bind(void 0,!0),Nm=()=>qw(!1)});function Vi(){return{cliLocation:ht(),userInfo:is.userInfo(),platform:is.platform(),release:is.release()}}var is,el=E(()=>{"use strict";is=I(require("node:os"));B()});function zw(s){try{return Gi.resolve(Gi.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 tr(s){let e=zw(s);return require(e)}var Gi,an=E(()=>{"use strict";Gi=I(require("path"))});function Kw(s){let t=/EACCES[^']+'(.+)'/.exec(s);return t===null?!1:t[1]}function Jw(s){return/The "to" argument must be of type string./.exec(s)}function Bm(s,e,t){let r=Kw(s),n=Jw(s);return r||n?(Um.info("Failed to install package due to insufficient write access",{...Vi(),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.
@@ -8,14 +8,14 @@ Testim had missing write access to ${r||e}
8
8
 
9
9
  `),!0):!1}function rl(s){try{return tr(s)}catch{return!1}}function jm(s,e){return require(cn.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 Wm(s){let e=require(cn.join(s,"package.json"));if(!("exports"in e))return"";let t=$m(e);if(!t)throw new Ai(e.name);return t}async function qi(s,e,t){let r=cn.join(s,"npm-shrinkwrap.json"),n=cn.join(s,"npm-shrinkwrap-dummy.json"),i=!1;try{try{await ye(r)&&(await tl.promises.rename(r,n),i=!0)}catch{}return await Fm(`npm i ${e} --no-save --no-prune --prefer-offline --no-audit --progress=false`,{...t,cwd:s}).catch(o=>{throw Bm(o.stderr,s,e)?new Kr(`${s} Failed to install package: ${e} due to insufficient write access in directory`):o})}finally{if(i)try{await tl.promises.rename(n,r)}catch{}}}function sl(s,e,t,r,n=!0){return new Promise((i,o)=>{var h,g,y,T;let a=t?["--proxy",t]:[],c=t?{env:Object.assign(process.env,{HTTP_PROXY:t,HTTPS_PROXY:t})}:{},l="",m="",d=["--no-save","--no-package-lock","--no-prune","--no-audit","--progress=false"];n&&d.push("--prefer-offline");let u="npm";process.platform==="win32"&&(u="npm.cmd",c.shell=!0);let f=(0,Hi.spawn)(u,["i","--prefix",s,...d,...e,...a],c);(h=f.stderr)==null||h.pipe(process.stderr),(g=f.stdout)==null||g.pipe(process.stdout),(y=f.stdout)==null||y.on("data",v=>{l+=v}),(T=f.stderr)==null||T.on("data",v=>{m+=v}),f.on("close",v=>{var b,w;if(v){n&&sl(s,e,t,r,!1).then(i).catch(o);let S;try{let A=(b=/npm ERR! 404 {2}'(.+)' is not in the npm registry/gm.exec(m))==null?void 0:b[1],D=(w=/No matching version found for (\S+)@/gm.exec(m))==null?void 0:w[1];A||D?S=`404 Not Found - GET https://registry.npmjs.org/${D??A} - Not found`:Bm(m,s)?S=`insufficient write access in location ${s}`:S=`Npm Installation closed with exit code ${v} with error: ${m}`}catch(A){S=`Npm Install closed with exit code ${v}
10
10
  err: ${A}
11
- stdout: ${l} stderr: ${m}`}Um.info(`Npm Install closed with exit code ${v}`,{message:S,stderr:m}),o(new Ct(S))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function Vm(){try{return(await Fm("npm -v")).stdout.trim()}catch{return""}}var tl,cn,Mm,Hi,Fm,Um,os=E(()=>{"use strict";tl=I(require("fs")),cn=I(require("path"));B();Mm=require("util"),Hi=require("child_process");$();el();an();Y();Fm=(0,Mm.promisify)(Hi.exec),Um=P("cli-service")});var U,Hm,qm,zm,Xw,Yw,Qw,Gm,zi,il,O,de=E(()=>{"use strict";U=I(require("rox-node")),Hm=I(require("node-fetch")),qm=require("eventsource");$();B();oe();zm=P("FeatureFlagsService"),Xw=!We&&!0&&!_d,Yw=2e4,Qw=60*60*24,Gm=["labs","disabled","enabled"],zi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Gm)}getValue(){let e=super.getValue();return Gm.includes(e)?e:(zm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},il=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 zi("labs"),highSpeedMode:new zi,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,secrets:new U.default.Flag,chromeArgsDisableFeatures:new U.default.RoxString("")},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(!Xw)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Hm.default)(a,{...c,agent:o}),n=function(a){return new qm.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Qw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(kd,i),Yw).catch(o=>zm.error("failed to get feature flag status",o))}},O=new il});var Ym={};z(Ym,{install:()=>ev,isReady:()=>rv,start:()=>tv});var Km,Jm,Xm,al,ol,Zw,ev,tv,rv,Qm=E(()=>{"use strict";Km=I(require("fkill")),Jm=I(require("p-retry"));os();Ge();B();an();de();Xm="chromedriver",al=9515,ol=`http://localhost:${al}/wd/hub`,Zw=[`--port=${al}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],ev=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=De(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await qi(yt(),`${Xm} --detect_chromedriver_version ${e}`)},tv=async()=>{process.env.NODE_OPTIONS="",await(0,Km.default)(`:${al}`,{silent:!0}),await tr(Xm).start(Zw,!0)},rv=async({chromeBinaryLocation:s})=>{await(0,Jm.default)(async()=>{var n;let e=await Te(`${ol}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${ol}/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 Js(`${ol}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var un={};z(un,{getSessionPlayerFolder:()=>pl,prepareChromeDriver:()=>ln,prepareCustomExtension:()=>ll,prepareExtension:()=>ul,preparePlayer:()=>Sr});async function ll(s,e=!1){if(!s)return;if(De(s)){let n=as.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await sv(s)>cl&&!e)throw new C(Zm);return await Je(s,n),n}let t=as.resolve(s);if(!tf.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Mc(t)>cl&&!e)throw new C(Zm);return t}async function sv(s){let e=(Ge(),qe(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Ki.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function ul(s){Ki.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Pi(t)}));return kt(()=>se(e,({location:t,path:r})=>ki(t,r)),"prepareExtension",sf,e)()}async function ln(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Qm(),Ym));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 Kr||(Ki.error(a,{...s,...Vi(),error:(0,rf.serializeError)(o)}),console.log(`
11
+ stdout: ${l} stderr: ${m}`}Um.info(`Npm Install closed with exit code ${v}`,{message:S,stderr:m}),o(new Ct(S))}else i(l)}),setTimeout(()=>{try{f.kill()}finally{o(new ce)}},r)})}async function Vm(){try{return(await Fm("npm -v")).stdout.trim()}catch{return""}}var tl,cn,Mm,Hi,Fm,Um,os=E(()=>{"use strict";tl=I(require("fs")),cn=I(require("path"));B();Mm=require("util"),Hi=require("child_process");$();el();an();Y();Fm=(0,Mm.promisify)(Hi.exec),Um=P("cli-service")});var U,Hm,qm,zm,Xw,Yw,Qw,Gm,zi,il,O,de=E(()=>{"use strict";U=I(require("rox-node")),Hm=I(require("node-fetch")),qm=require("eventsource");$();B();oe();zm=P("FeatureFlagsService"),Xw=!We&&!0&&!_d,Yw=2e4,Qw=60*60*24,Gm=["labs","disabled","enabled"],zi=class extends U.default.RoxString{constructor(e="disabled"){super(e,Gm)}getValue(){let e=super.getValue();return Gm.includes(e)?e:(zm.warn('unexpected value for lab feature flag. Falling back to value "labs"',{featureFlagName:this.name,value:e}),"labs")}},il=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 zi("labs"),highSpeedMode:new zi,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,secrets:new U.default.Flag,chromeArgsDisableFeatures:new U.default.RoxString("")},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(!Xw)return;if(e){t=require("https-proxy-agent").HttpsProxyAgent;let o=e?new t(e):void 0;r=(a,c)=>(0,Hm.default)(a,{...c,agent:o}),n=function(a){return new qm.EventSource(a,{fetch:r})}}let i={fetchIntervalInSec:Qw,fetchFunction:r,eventSourceImpl:n};return le(U.default.setup(kd,i),Yw).catch(o=>zm.error("failed to get feature flag status",o))}},O=new il});var Ym={};z(Ym,{install:()=>ev,isReady:()=>rv,start:()=>tv});var Km,Jm,Xm,al,ol,Zw,ev,tv,rv,Qm=E(()=>{"use strict";Km=I(require("fkill")),Jm=I(require("p-retry"));os();Ge();B();an();de();Xm="chromedriver",al=9515,ol=`http://localhost:${al}/wd/hub`,Zw=[`--port=${al}`,"--url-base=/wd/hub","--disable-build-check","--whitelisted-ips=0.0.0.0","--log-level=OFF"],ev=async()=>{let s=O.flags.chromedriverCdnBinariesUrl.getValue(),e=De(s)?`--chromedriver_cdnbinariesurl=${s}`:"";await qi(ht(),`${Xm} --detect_chromedriver_version ${e}`)},tv=async()=>{process.env.NODE_OPTIONS="",await(0,Km.default)(`:${al}`,{silent:!0}),await tr(Xm).start(Zw,!0)},rv=async({chromeBinaryLocation:s})=>{await(0,Jm.default)(async()=>{var n;let e=await Te(`${ol}/status`);if(!((n=e==null?void 0:e.value)!=null&&n.ready))throw new Error("status failed");let t={...s&&{binary:s}},r=await Ve({url:`${ol}/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 Js(`${ol}/session/${r.sessionId}`)},{retries:99,factor:1,minTimeout:30})}});var un={};z(un,{getSessionPlayerFolder:()=>pl,prepareChromeDriver:()=>ln,prepareCustomExtension:()=>ll,prepareExtension:()=>ul,preparePlayer:()=>Sr});async function ll(s,e=!1){if(!s)return;if(De(s)){let n=as.join(process.cwd(),s.replace(/^.*[\\/]/,""));if(await sv(s)>cl&&!e)throw new C(Zm);return await Je(s,n),n}let t=as.resolve(s);if(!tf.existsSync(t))throw new C(`Failed to find custom extension in location: ${t}`);if(Mc(t)>cl&&!e)throw new C(Zm);return t}async function sv(s){let e=(Ge(),qe(Ke));try{let r=(await e.head(s)).headers["content-length"];return(r?parseInt(r,10):0)/1e6}catch(t){throw Ki.warn("failed to download custom extension",{err:t}),new C(`Failed to download custom extension from location: ${s}`)}}function ul(s){Ki.info("prepare extension",{locations:s});let e=s.map(t=>({location:t,path:Pi(t)}));return kt(()=>se(e,({location:t,path:r})=>ki(t,r)),"prepareExtension",sf,e)()}async function ln(s={},e={},t=!1){let n=require("ora")("Starting Driver").start(),i=await Promise.resolve().then(()=>(Qm(),Ym));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 Kr||(Ki.error(a,{...s,...Vi(),error:(0,rf.serializeError)(o)}),console.log(`
12
12
  1. If you don't have Chrome, please install it from https://www.google.com/chrome.
13
13
  2. If Chrome is installed, please verify it's binary directory:
14
14
  - installed where chromedriver expects it (see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver#requirements).
15
15
  - exists in your PATH environment variables.
16
16
  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").
17
- 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 nv(){let s=xt==="staging"?`${ft}/Staging-LATEST_VERSION`:`${ft}/sessionPlayer_LATEST_RELEASE`;return(await $t(s)).body.toString("utf8")}function iv(){return`${ft}/dev-sessionPlayer.zip`}async function ov(s,e){if(!De(s)||De(s)&&e||We)return s;let t=await nv();return`${s}-${t}${xt==="staging"?".zip":""}`}function pl(){let s=yt();return as.resolve(s,"testim-bin")}function av(){let s=pl();return as.resolve(s,"sessionPlayer.zip")}async function nf(s,e,t=!1){try{return await ki(s,e),await at(e,pl())}catch(r){if(t)throw r;return await nf(s,e,!0)}}async function Sr(s,e){Ki.info("prepare player",{location:s,canary:e});let t=av();return kt(async()=>{let r=xt==="development"?iv():await ov(s,e);return await nf(r,t),{}},"preparePlayer",sf,[s,e,t])()}var ef,tf,as,rf,Ki,sf,cl,Zm,pn=E(()=>{"use strict";ef=I(require("ms")),tf=I(require("node:fs")),as=I(require("node:path"));oe();er();rf=require("serialize-error");$();el();Y();B();Ki=P("prepare runner and testim start"),sf=(0,ef.default)("0.5 day"),cl=16,Zm=`The size of the custom extension is more than ${cl}MB`});function cv(){let s=dn.type().toLowerCase();return s==="darwin"?dn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?dn.arch()==="x64"?"win64":"win32":"linux"}async function Xi(){let s=cv(),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(mn,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]}/${mn}/${n[s]}.zip`,a=Ji.join(dl,n[s]),c=`${a}.zip`,l=Ji.join(a,i[s]);if(await ye(l))return l;if(!await ye(c)){let d=(0,ml.default)("Downloading Chromium").start();try{await of.promises.mkdir(dl),await Je(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw d.fail(f),new Error(f)}d.succeed()}let m=(0,ml.default)("Extracting Chromium").start();try{await at(c,dl)}catch(d){let u=`Failed to extract Chromium: ${d.message}`;throw m.fail(u),new Error(u)}return m.succeed(),l}var of,dn,Ji,ml,mn,dl,fl=E(()=>{"use strict";of=I(require("fs")),dn=I(require("os")),Ji=I(require("path")),ml=I(require("ora"));Y();B();mn="1000968",dl=Ji.join(Vt,`chrome-${mn}`)});async function lf(s,e){return Er=s,bl=e,await gl()}function uf(s,e){Er=e.projectId,bl=e.token,fn=e.userAccessKey,ct=s.token,hn=Tl(ct),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,af=e.publicIp,cf=e.initializedFromCache}function uv(s=Er,e=bl){return kt(()=>(gn.info("request to get cli token from server"),Ve({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",lv*10,{projectId:s,token:e})()}async function pv(){gn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${he()}/auth/refreshToken`,body:{token:ct,refreshToken:yn}});return ct=s.token,hn=Tl(ct),s.refreshToken&&(yn=s.refreshToken),ct}async function gl(){try{let s=await uv();return gn.info("successfully get cli token from server"),ct=s.token,hn=Tl(ct),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,ct}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."):(gn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Er}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Tl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Ot(){if(!hn)return gl();let s=O.flags.accessTokenExpiryMargin.getValue();if(hn<Date.now()+4*s)try{return await pv()}catch(e){return gn.error("failed to refresh token, executing fallback",e),gl()}return ct}function Yi(){return yn}function Ir(){return ct?{uid:require("jsonwebtoken").decode(ct).id,ngrokToken:hl,isNgrokWhitelisted:yl}:{}}async function Qi(){if(!fn||!Er)return;if(await wl({userAccessKey:fn,projectId:Er}))return fn;let e=`user access key "${fn}" is invalid for project "${Er}"`;throw new C(e)}function Zi(){return af}function eo(){return cf}var gn,ct,hn,yn,hl,yl,Er,bl,fn,af,cf,lv,lt=E(()=>{"use strict";oe();Ge();er();Y();$();ge();de();gn=P("testim-custom-token"),Er=null,bl=null,lv=5*60*1e3});function dv(s){if(s.protocol)return s.protocol;if([_.TESTIM_PRIVATE,_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.TESTIM_LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=pf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function mv(s){let e=pf.exec(s);return e==null?void 0:e[3]}function ro(s){var w,S,A,D,V,x,R,L,M,G,W;let e=s&&mv(s.host),t=s.port,r=s.path,n=s&&dv(s),i=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(S=s.external)==null?void 0:S.user,l=(A=s.external)==null?void 0:A.key,m=s.type,d=m===_.HYBRID?a&&((x=(V=(D=s.hybrid)==null?void 0:D.external)==null?void 0:V[s.hybrid.tunnel])==null?void 0:x.user):c,u=m===_.HYBRID?a&&((M=(L=(R=s.hybrid)==null?void 0:R.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:M.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(W=s.mobileTokens)==null?void 0:W.iosToken,v=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:m,name:f,provider:g,tunnelUser:d,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:v,isSupportGrid:b}}async function gv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw Qe.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(bt.UNKNOWN)}if(Qe.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw Qe.error("invalid response - get grid",{res:o}),new Error(bt.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,gf(n));let c=ro(o.grid);return fv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new nt(bt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(Qe.error("invalid code error response - get grid",{res:o}),new nt(bt.UNKNOWN))}function mf(s){return xl(s)}async function ff(s,e,t){let n=(t||await mf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return ro(n)}async function hv(s,e,t){let n=(t||await mf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return ro(n)}async function vl(s,e){let t=bn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete bn[s],!a){if(!r){Qe.warn("failed to find grid slot id",{projectId:e});return}Qe.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await El(o,e,r,n,i)}catch(c){Qe.error("failed to release slot",{projectId:e,err:c})}}}async function yv(s){let e=Object.values(bn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid){Qe.info("keep alive worker slots",{projectId:s,slots:e});try{await Sl(s,e)}catch(t){Qe.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}}function bv(s){df=global.setInterval(yv,1e4,s)}async function Tv(s){let e=Object.keys(bn);if(e.length){Qe.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>vl(Number(t),s))}catch(t){Qe.error("failed to release all slots",{err:t,projectId:s})}}}async function wv(s){await Tv(s),clearInterval(df)}function vv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Sv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>to.isEmpty(s.testobjectSauce)?to.isEmpty(s.saucelabs)?to.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=vv(t,s),c=Sv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:re()}}async function hf(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function yf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return gf(s);let l=t==null?void 0:t.companyId;if(a)return ff(l,a,e);if(c)return hv(l,c,e);if(en(s)||s.tunnelOnlyMode){Qe.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new nt("Missing host or grid configuration")}async function bf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:m,useChromeLauncher:d,company:u}=t,f=Boolean(m||d||l),h=u==null?void 0:u.companyId;return gv(o,h,r,s,t,()=>Rl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var to,Qe,bn,pf,df,fv,Tn,Tf,cs=E(()=>{"use strict";to=I(require("lodash"));ge();$();B();ae();Y();Qe=P("grid-service"),bn={},pf=/(^(https?):\/{2})?(.*)/,df=null;fv=(s,e,t,r,n,i)=>{bn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Tn={start:bv,end:wv};Tf=async(s={},e={},t={},r={},n={})=>{var h,g,y;let{company:{companyId:i}={}}=s,{gridId:o,type:a}=e,c=s.browser||t.browserValue,l=Boolean(s.tunnel),{maxRetries:m,currentRetry:d}=n;if(!o||!a||((a===_.TESTIM_LAMBDATEST||a===_.LAMBDATEST)&&await((h=r.enableIfNeeded)==null?void 0:h.call(r,e,i)),a!==_.HYBRID||!i||!c||!m||!d))return e;let u=await Il({companyId:i,gridId:o,maxRetries:m,currentRetry:d,browser:c,usingTunnel:l});Qe.info("handling hybrid grid",{response:u,companyId:i});let f=ro({...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,i)),f}});function vn(){return so||"master"}function wf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){so="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){so=s.branch||s;return}so=e?"master":void 0}var so,Al=E(()=>{"use strict";Y()});function If(s){We||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),Ef.identify(s))}function Tt(s,e){return ls("ci",s,e)}function ls(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:"runnerId"};Ef.track(Object.assign(r,{event:e,properties:t}))}var Sf,Ef,us=E(()=>{"use strict";oe();Sf=require("@segment/analytics-node"),Ef=new Sf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var Rf={};z(Rf,{isCi:()=>ps});var ps,no=E(()=>{"use strict";ps=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Af(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Cf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:xf(l,m),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},d);Tt("test-run-ci",y)}function Pf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let v=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:xf(m,d),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){Tt("test-run-ci-success",v);return}Tt("test-run-ci-fail",{...v,failureReason:n.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function kf(s){Tt("batch-run-ci",s)}var xf,Cl=E(()=>{"use strict";us();no();xf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ps&&e?"ci-with-user":ps?"ci":e?"cli-with-user":s});var Pl,ue,_f=E(()=>{"use strict";Pl=class{static colorString(e,t){return`${e}${t}${Pl.Reset}`}},ue=Pl;ue.Reset="\x1B[0m",ue.Bright="\x1B[1m",ue.Dim="\x1B[2m",ue.Underscore="\x1B[4m",ue.Blink="\x1B[5m",ue.Reverse="\x1B[7m",ue.Hidden="\x1B[8m",ue.FgBlack="\x1B[30m",ue.FgRed="\x1B[31m",ue.FgGreen="\x1B[32m",ue.FgYellow="\x1B[33m",ue.FgBlue="\x1B[34m",ue.FgMagenta="\x1B[35m",ue.FgCyan="\x1B[36m",ue.FgWhite="\x1B[37m",ue.FgGray="\x1B[90m",ue.BgBlack="\x1B[40m",ue.BgRed="\x1B[41m",ue.BgGreen="\x1B[42m",ue.BgYellow="\x1B[43m",ue.BgBlue="\x1B[44m",ue.BgMagenta="\x1B[45m",ue.BgCyan="\x1B[46m",ue.BgWhite="\x1B[47m",ue.BgGray="\x1B[100m"});var En,kl,Ev,Ol,Iv,io,oo,ao,co,lo,uo=E(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===fe.FAILED},kl=s=>{let{status:e}=s;return e===fe.ABORTED},Ev=s=>{let{status:e}=s;return e===fe.PASSED},Ol=s=>s.runnerStatus===Uc.SKIPPED,Iv=s=>s.testStatus===Xe.EVALUATING,io=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,oo=s=>Object.values(s).filter(e=>En(e)&&Iv(e)).length,ao=s=>Object.values(s).filter(En),co=s=>Object.values(s).filter(Ev),lo=s=>Object.values(s).filter(kl)});function xv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var _l,po,Rv,mo,Lf=E(()=>{"use strict";_l=I(require("lodash"));$();uo();po=P("debug-reporter"),Rv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],mo=class{constructor(e){this.options=e}onTestStarted(e,t){po.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,c=r.failedGetBrowserAttempts;po.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:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{..._l.default.omit(this.options,Rv),company:_l.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=xv(process.argv);po.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=co(e).length,a=Object.keys(e).length-o;po.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ll,_t,In=E(()=>{"use strict";ae();Ll=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===_.DEVICE_FARM}},_t=new Ll});var Nl={};z(Nl,{Reporter:()=>Av});var sr,Rn,Rr,fo,Df,Dl,Av,Ml=E(()=>{"use strict";sr=I(require("chalk")),Rn=I(require("lodash"));B();ae();In();uo();Rr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:fo}=Wt,Df="device",Dl=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: ${sr.default.underline(ze(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?fe.PASSED:fe.FAILED,n=`(${e.testId})`,i=Rr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Li(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Rr.error("Failed runs are:")),console.log(Rr.error(t.join(`
18
- \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ao(e),a=co(e),c=lo(e),l=a.length,m=c.length,d=o.length,u="",f="";if(_t.isTestStatusEnabled){let v=oo(e);u=` FAILED-EVALUATING: ${v}`,d-=v,f=` SKIPPED: ${io(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Rr[d?"error":"success"],T=`PASSED: ${l} FAILED: ${d}${u} ABORTED: ${m}${f} Duration: ${Li(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=Rn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Rn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Rn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Rn.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 c=u=>{u.forEach((f,h)=>{var v;let g=(v=f.testData)!=null&&v.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)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${d} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===fo.APPIUM?Df:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===fo.APPIUM?Df:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.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===fo.APPIUM?"device":"browser";if(n)console.log(Rr.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(Rr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===fo.APPIUM?"Appium":"Selenium";console.log(Rr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Av=Dl});var Bl={};z(Bl,{Reporter:()=>Lv});function Cv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Pv(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 kv(s){return`${s.visitedUrlsJson||""}`}async function Ov(s,e,t,r,n,i){function o(u){let f=ze(s,t,u.testId,u.resultId,r),h={$:{name:Cv(u),classname:n,time:qc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||kl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Ol(u)&&Ye(u,i)&&_t.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Pv(u),h["visited-urls-json"]=kv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:m(y),timestamp:c(e)};if(_t.isTestStatusEnabled){v.skipped=io(y,i);let b=oo(y);v.failures-=b,v["failure-evaluating"]=b}return{$:v,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(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 l(u){return Object.keys(u).length}function m(u){return ao(u).length+lo(u).length}let d={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Ul.Builder().buildObject(d)}catch(u){return _v(u)}}function _v(s){let e=new Ul.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 Ul,Nf,Fl,Lv,jl=E(()=>{"use strict";Ul=I(require("xml2js"));B();Nf=require("fs");In();uo();Fl=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 Ov(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Nf.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)}};Lv=Fl});var Mf={};z(Mf,{Reporter:()=>Dv});function ds(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 $l,Wl,Dv,Ff=E(()=>{"use strict";$();$l=P("team-city-reporter");Wl=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 ds(n)}onTestStarted(e,t,r,n){if(r){$l.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){$l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ds(t)}' details='${ds(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){$l.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='${ds(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ds(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ds(t)}']`)}},Dv=Wl});var Uf={};z(Uf,{Reporter:()=>Nv});var Vl,Nv,Bf=E(()=>{"use strict";Vl=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}}))}},Nv=Vl});function ho(s){let{platform:e}=process;e==="win32"?(0,go.exec)(`start chrome ${s}`):e==="darwin"?(0,go.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,go.exec)(`google-chrome ${s}`)}var go,Gl=E(()=>{"use strict";go=require("child_process")});var jf={};z(jf,{Reporter:()=>Mv});var Hl,Mv,$f=E(()=>{"use strict";B();Gl();Hl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return ho(t)}},Mv=Hl});var ql,Q,Lt=E(()=>{"use strict";Lf();ql=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 mo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Ml(),Nl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(jl(),Bl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ff(),Mf)),r.includes("console")&&Promise.resolve().then(()=>(Ml(),Nl)),r.includes("junit")&&Promise.resolve().then(()=>(jl(),Bl)),r.includes("json")&&Promise.resolve().then(()=>(Bf(),Uf)),r.includes("chrome")&&Promise.resolve().then(()=>($f(),jf))])).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 ql});async function zl(s,e,t){let r=ms[s];if(!r)return;let{slotId:n}=r;if(delete ms[s],!n){ut.warn("failed to find slot slot id",{companyId:e,workerId:s});return}ut.info("release slot id",{companyId:e,slotId:n});try{await Jl(e,t,n)}catch(i){ut.error("failed to release slot",{companyId:e,err:i})}}async function Fv(s,e){let t=Object.values(ms).filter(Boolean);if(t.length!==0){ut.info("keep alive worker slots",{companyId:s,slots:t});try{await Yl(s,e,t)}catch(r){ut.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}}function Uv(s,e){Wf=global.setInterval(()=>Fv(s,e),1e4)}async function Bv(s,e){let t=Object.keys(ms);if(t.length){ut.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>zl(Number(r),s,e))}catch(r){ut.error("failed to release all slots",{err:r,companyId:s})}}}async function jv(s,e){await Bv(s,e),clearInterval(Wf)}async function Gf(s,e,t){let r;try{r=await Kl(s,e)}catch(n){throw ut.error("failed to get slot",{companyId:s,err:n}),new Error(bt.UNKNOWN)}if(ut.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw ut.error("invalid response - get slot",{res:r}),new Error(bt.UNKNOWN);if(r.status==="success")return Vf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new nt(bt.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(ut.error("invalid code error response - get slot",{res:r}),new nt(bt.UNKNOWN))}async function Hf(s,e,t,r){let n=ms[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Vf(r,n),await Xl(s,e,n),ut.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var ut,ms,Wf,Vf,xn,fs=E(()=>{"use strict";ge();$();B();ae();Y();ut=P("slot-service"),ms={},Wf=null,Vf=(s,e)=>{ms[s]=e};xn={start:Uv,end:jv}});function zf(s,e=process){async function t(r){await le(se(qf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Cn.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(Cn.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",()=>{Cn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function gs(s){qf.push(s)}var Cn,qf,Pn=E(()=>{"use strict";$();B();Cn=P("process-handler"),qf=[]});var Yf={};z(Yf,{installAllLazyDependencies:()=>Gv,lazyRequire:()=>pt});async function pt(s,e={}){let t=rl(s);if(t)return t;let r;e.silent||(r=(0,Kf.default)(`Installing ${s} before first usage...`).start());try{let n=await Vv(s);return r&&r.succeed(),n}catch(n){Wv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Xf(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function Vv(s){return hs.has(s)||(hs.set(s,Jf(s)),hs.get(s).catch(()=>{hs.delete(s)})),hs.get(s)}async function Jf(s){let e=rl(s);if(e)return e;let t=Xf(s),r=`${s}@${t}`;return await qi(yt(),r),tr(s)}async function Gv(){let s=Object.keys(hc);for(let e of s)await Jf(e)}function Xf(s){let e=Object.entries(hc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Kf,Wv,hs,kn=E(()=>{"use strict";Kf=I(require("ora"));os();$();B();bi();an();Wv=P("lazy-require"),hs=new Map});var Qf,yo,Zf=E(()=>{"use strict";Qf=require("istanbul-lib-report"),yo=class extends Qf.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 eg,tg,rg,On,wt,sg,bo,Ql,ng,Hv,ig,og,qv,zv,ag,Kv,Jv,Xv,Yv,Qv,cg,lg=E(()=>{"use strict";eg=I(require("ora")),tg=I(require("dayjs")),rg=I(require("test-exclude")),On=I(require("fs")),wt=I(require("path")),sg=I(require("istanbul-reports")),bo=I(require("istanbul-lib-report"));ge();Y();B();$();kn();Zf();Ql=P("test-run-status"),ng=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Hv=s=>!!ng(s).search,ig=s=>s?ng(s).pathname.substring(1):"",og=(s,e)=>{let t=ig(e);return!new rg.default({relativePath:!1,include:s}).shouldInstrument(t)},qv=s=>s.substring(0,s.indexOf("?")),zv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await pt("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)},ag=(s,e)=>`${wt.resolve(s,ig(e))}.js`,Kv=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(og(r,o))return;let c=ag(e,o);await On.promises.mkdir(wt.parse(c).dir,{recursive:!0}),await On.promises.writeFile(c,i.sourcesContent[a])})})},Jv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Hv(e)&&(e=qv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Xv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=bo.createContext({dir:t,coverageMap:e,watermarks:bo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=ag(r,a);return On.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new yo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Jv}),sg.create(a,c).execute(o)}),i},Yv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await pt("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>og(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Qv=async(s,e)=>{let{mergeProcessCovs:r}=await pt("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await eu(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await _n(c,9e4);await se(l,async m=>{if(!i.has(m.url)){let d=m.text;m.sourceUrl&&(i.set(m.url,"TEMP"),d=await Zl(m.sourceUrl)),i.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},cg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,eg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=wt.resolve(s.codeCoverageReportPath||"./coverage"),o=wt.resolve(i,`.js/${(0,tg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([pt("istanbul-lib-coverage"),Qv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Ql.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),u={};await se(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=m.get(h),v=await zv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=v;let b=await Yv(s,{source:y,sourceMap:v,functions:g});d.merge(b)}),await Kv(s,o,u);let f=await Xv(s,d,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var ug={};z(ug,{SELENIUM_PERF_MARKS:()=>Pe,SeleniumPerfStats:()=>xr});var Pe,Zv,xr,ys=E(()=>{"use strict";B();Pe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Zv=["ALL",...Object.values(Pe)],xr=class{constructor(){this.marks=Object.fromEntries(Zv.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`,Mi(r,50)],[`${t}_P95`,Mi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var fg={};z(fg,{initServer:()=>rS,mapFilesToLocalDrive:()=>ru});function ru(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,To[t.id]?{screenshot:To[t.id]}:{})),Object.keys(wo).forEach(t=>{s.assets||={},s.assets[mg[t]]=wo[t]}),s.assets||={},s.assets.screenshots=Object.values(To)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function rS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await pt("multer"),n=typeof t=="string"?t:eS;await tu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let u=Ln.join(n,d.testResultId);try{await tu.promises.mkdir(u,{recursive:!0})}catch(f){return m(f,"")}return m(null,u)},filename(c,l,m){let{fileName:d}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Ln.extname(d);return m(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),o=(0,dg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(To[m.stepId]=c.file.path),m.testResultId&&tS.includes(m.subType)&&(wo[m.subType]||=[],wo[m.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(o);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var tu,pg,Ln,dg,eS,To,wo,mg,tS,su=E(()=>{"use strict";tu=I(require("fs")),pg=I(require("os")),Ln=I(require("path")),dg=I(require("express"));Y();kn();eS=Ln.join(pg.tmpdir(),"testim/rca/"),To={},wo={},mg={"test-log":"consoleLogs","har-file":"networkLogs"},tS=Object.keys(mg)});var nr,nu,vo,gg=E(()=>{"use strict";nr=I(require("lodash"));B();$();nu=P("override-test-data-builder"),vo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.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)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):nu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):nu.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}nu.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 nr.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(m=>this.generateTestUniqId(m)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}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 So(s,...e){if(!(!s||typeof s!="function"))try{return await s(...e)||{}}catch(t){throw Ze.warn("failed to run hook",{err:t}),new C(`failed to run hook promise ${t.message}`)}}var Ar,Ze,sS,nS,iS,oS,Eo,hg=E(()=>{"use strict";Ar=I(require("lodash"));B();ae();cs();fs();ge();Y();$();Lt();Pn();lg();ys();su();oe();de();gg();In();Ze=P("test-run-status"),sS=Tr(),nS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,iS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,oS=st();Eo=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 xr;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:vi||t.parallel||1,browser:i,gitBranch:sS,gitCommit:nS,gitRepoUrl:iS,runnerVersion:oS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:o,testStatus:d};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v},au({projectId:n,runId:i,testId:l,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 l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ro(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(m){Ze.error("failed to upload test data artifact (runner)",{err:m})}let c=Ar.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Cr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await So(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 Ze.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},Ze.info("on get grid info",{gridInfo:r.config.gridInfo})}reportTestStatus(e,t,r,n){let{name:i,testId:o,testStatus:a}=r,{resultId:c,success:l}=t;if(a===Xe.EVALUATING&&_t.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(l){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Kc();t.isOverThreshold&&Ze.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&&ru(o,Ze),o.resultUrl=ze(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 c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await So(this.options.afterTest,{...e,exportsGlobal:i,globalParameters:i},this.options.userData.loginData.token)}catch(a){Ze.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 Cr(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 Ze.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}=$c;return e&&(n=i),Qr(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 c=e.browser?rn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Zr(O,n)&&tn(a.nativeApp)&&!e.appId,m=Zt(e)&&(Qr(a.nativeApp,n)||l),d=Ye(a,e)||m,u={testId:a.testId,testOptimization:a.testOptimization,status:d?fe.SKIPPED:fe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Xe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...m&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...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:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await xn.end(r,t),e==="mongo"&&await Tn.end(t)}async executionStart(e,t,r,n,i){Ze.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:c,company:{companyId:l}={},slotService:m}=o;gs(()=>Promise.all([this.endKeepAlive(m,t,l),Io("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let d={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await So(o.beforeSuite,d),f=new vo(u,Ar.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 v=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var L;let D=b[A],V=(L=D.config)==null?void 0:L.testData,x=D.testId,R=await Ro(t,x,A,V,c.defaults);R&&(delete D.config.testData,D.config.testDataUrl=R)});let w=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),S=ou({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:w,intersections:o.intersections});return this.executionStartedPromise=S,S.catch(A=>Ze.error(A)),S};try{await v()}catch(b){Ze.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){Ar.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var m;let t=Xc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:d,testStatus:u}of t)d===fe.PASSED&&n++,d===fe.SKIPPED&&i++,d===fe.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await So(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Ze.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await cg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Io("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Ze.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await iu(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 cu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${ft}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:xt});return r||(aS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${ft}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function yg(s){let{chrome:e}=cu(s);return e}function xo(s){let e=xt==="staging"?`${ft}/staging-sessionPlayer`:`${ft}/sessionPlayer`;return s.canary?`${e}-master`:e}var aS,Dn=E(()=>{"use strict";oe();de();$();aS=P("runOptionsUtils")});function bs(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(lu).join("|")})`).exec(s))==null?void 0:n[0];return t||lu[Ed]||"usw2"}var lu,Tg,Ao=E(()=>{"use strict";oe();lu={"us-west-2":"usw2","eu-central-1":"euc1"},Tg=Object.fromEntries(Object.entries(lu).map(([s,e])=>[e,s]))});function wg(s,e){if(e){if(!mS.has(e)){Nn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var vg,Sg,Gt,Eg,Ig,Rg,Co,xg,Nn,cS,lS,Mn,uS,pS,dS,ne,mS,Po=E(()=>{"use strict";vg=I(require("ms")),Sg=I(require("p-retry")),Gt=I(require("node:os")),Eg=I(require("portfinder")),Ig=I(require("node:child_process"));B();Ge();ge();Rg=I(require("node:fs")),Co=I(require("node:fs/promises")),xg=require("node:path");Y();$();Dn();ae();de();B();Ao();Nn=P("lambdatestService"),cS="https://downloads.lambdatest.com/tunnel/v3",lS={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"},Mn=`${Gt.tmpdir()}/LT`,uS=`${Mn}/LT`,pS=(0,vg.default)("15m"),dS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.TESTIM_LAMBDATEST||e.type===_.LAMBDATEST||e.type===_.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=uu(t),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?pS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(uS))return;let t=lS[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${Mn}.zip`;await Je(`${cS}/${t}`,r),await at(r,Mn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ye(e))){try{await Co.access(e,Rg.constants.X_OK);return}catch{}try{await Co.chmod(e,"777")}catch(r){throw Nn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await pe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=re();let l=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...Hc(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)l=[...l,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,xg.join)(Mn,"LT")),ne.tunnel=Ig.spawn("./LT",l,{cwd:Mn});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,Sg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(m.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Nn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:m,stderrResult:d}),Nn.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,c){var S,A;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},m={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},d=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:wg(n,a==null?void 0:a.os)||wg(n,(S=o==null?void 0:o.lt)==null?void 0:S.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??dS,version:t==="safari"&&((A=o==null?void 0:o.lt)==null?void 0:A.safari_version)||l.version};if(c!==K.APPIUM&&c!==K.SELENIUM&&!f){let D=cu({canary:u});!h&&D[t]&&(d=[...d,D[t]]),h&&De(h)&&(d=[...d,h]),d.length||Nn.warn("No extension was loaded in LambdaTestService",{extUrls:D,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(d=[...d,g]);let T=bs(e.project||""),b={euc1:"eu"}[T],w=b?{region:b}:{};return{build:r,name:`${n} - ${i}`,...w,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:d,...m,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},mS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});function gS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Dg(s){return kg.readFileSync(s,{encoding:"base64"})}function Ng(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&De(s))&&s){let r=Dg(s);ws.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${mu(r)} current extension count: ${e.length}`),e.push(r)}}function Mg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,d=r||m,u=`--load-extension=${d}`;ws.info(`adding extension: testim unpacked , path: ${d}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=ko.basename(i));let c=ko.join(process.cwd(),a),l=Dg(c);ws.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${mu(l)} current extension count: ${e.length}`),e.push(l)}function hS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],m=[...Lg];e.headless&&m.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":pu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":pu.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(du(n)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&m.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}du(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>m.push(`--${T}`));try{let T=Oo();T.length&&T.forEach(v=>m.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=pu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&m.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&m.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Bc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Ng(r,l,o),a===K.EXTENSION&&Mg(e,l,m,i,o),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=m;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ne.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=d),s}function bS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Cg.join(","),"browser.helperApps.neverAsk.openFile":Cg.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 Ts(s){return`${s.width}x${s.height}`}function IS(s){let{platform:e}=s;if(!e)return Ts(Pg);let t=e.split(" ")[1];return e.startsWith("Windows")&&ES.has(t)?Ts(wS):e==="Linux"?Ts(TS):e.startsWith("macOS")?Ts(vS):Ts(e==="OS X El Capitan"||e==="OS X Yosemite"?SS:Pg)}function RS(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=IS(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,_g.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,dt.merge(i,n,r)}return dt.merge(n,r)}return{}}function xS(s){let{runnerOptions:e}=s;if(dt.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function AS(s){return s.perfecto?s.perfecto:{}}function CS(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 PS(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=mc(i,o)),a}function Oo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function _o(s){var A,D,V,x;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:m,testResultId:d,lambdatestService:u,mode:f}=s;if(o.mode==="local"){let R=[],L=[...Lg],M={};t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let G=Oo();G.length&&G.forEach(W=>L.push(`--disable-features=${W}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(G=>L.push(`--${G}`)),t.chromeBinaryLocation&&(M.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&Mg(t,R,L,null,u),Ng(a,R,u),{logLevel:Ag,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:R,...M},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:h,driverRequestRetries:g}=t,y=PS(t,o),T={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Ag,connectionRetryTimeout:h,connectionRetryCount:g,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!dt.isEmpty(y)&&{headers:y},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};du(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,T.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(T.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let v=Number(t.browserTimeout/1e3),b=t.browser||(i==null?void 0:i.browserValue),w={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:m};dt.merge(T.desiredCapabilities,RS(t,n,i),xS(w),AS(t),CS(t,b,v),u==null?void 0:u.getCapabilities(t,b,c,d,n,i,e,f));let S=null;switch(!t.ext&&!t.extensionPath&&((A=o.host)!=null&&A.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(b==="chrome"||b==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(S="/opt/testim-headless"),b){case"chrome":case"edge-chromium":T=yS(T,t,i,a,o,S,u,f);break;case"firefox":T=bS(T,t,u);break;case"safari":case"safari technology preview":T=gS(T,b);break;default:break}dt.merge(T.desiredCapabilities,t.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=q=>q[o.provider]||q[T.host]||q[R[T.host]],M=q=>{var ie,Ie;return L(q)||q[(ie=T.desiredCapabilities)==null?void 0:ie.browserName]||q[(Ie=T.desiredCapabilities)==null?void 0:Ie.version]||q||{}},G=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),W=M(M(G));Object.keys(W).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(W)}`),Object.assign(T.desiredCapabilities,W))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(T.desiredCapabilities&&!T.capabilities&&(fS(T),T.capabilities={alwaysMatch:T.desiredCapabilities,firstMatch:[{}]},delete T.desiredCapabilities),T.hostname=T.host,s.printFinalCaps){let R=(D=T.capabilities)==null?void 0:D.alwaysMatch,L=JSON.parse(JSON.stringify(T)),M=(V=L==null?void 0:L.capabilities)==null?void 0:V.alwaysMatch,G=q=>q.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(q=>{var ie,Ie;M!=null&&M[q]&&(M[q].extensions=(Ie=(ie=R==null?void 0:R[q])==null?void 0:ie.extensions)==null?void 0:Ie.map(G))}),M!=null&&M.loadExtension&&(M.loadExtension=(x=R==null?void 0:R.loadExtension)==null?void 0:x.map(G));let W=require("node:util");console.log(W.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return T}var kg,ko,Og,dt,_g,ws,Ag,pu,Lg,mu,du,fS,yS,Cg,Pg,TS,wS,vS,SS,ES,Lo=E(()=>{"use strict";kg=I(require("node:fs")),ko=I(require("node:path")),Og=I(require("node:crypto")),dt=I(require("lodash"));B();oe();$();de();ae();Po();_g=require("lodash"),ws=P("testim-desired-capabilities-builder"),Ag=wi?"debug":"silent",pu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Lg=["--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"],mu=(...s)=>Og.createHash("sha256").update(s.join("")).digest("hex"),du=s=>s.type===_.DEVICE_FARM||s.type===_.HYBRID&&s.provider==="devicefarm",fS=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=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};yS=dt.memoize(hS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(dt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return mu(o,a,c,r,l,i)}),Cg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Pg={width:1920,height:1080},TS={width:1920,height:1200},wS={width:2560,height:1600},vS={width:2360,height:1770},SS={width:2048,height:1536},ES=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function Ug(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 fu=E(()=>{"use strict"});function gu(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 c(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:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return gu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let m=!!n(s,u=>Number(i(u,"opacity"))===0),d=!!n(s,u=>i(u,"display")==="none");return!(m||d||!o(s)||c(s))}var Bg=E(()=>{"use strict"});var jg,$g,Ht,kS,OS,Do,Wg=E(()=>{"use strict";jg=I(require("promise-queue")),$g=I(require("webdriverio"));oe();$e();B();$();Hr();Bg();fu();ys();Ht=P("WebDriverApi"),kS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},OS={implicit:0,pageLoad:1,script:2},Do=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 Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),yc!==void 0&&(e=yc);let t=1/0;this.queue=new jg.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,c,l,m,d,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),F("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((d=(m=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:m[0])==null?void 0:d.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Pe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),F("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await $g.remote(e),this.logGridStatus(r)}),F("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Pe.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 c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.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){Ht.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(Pe.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,Pe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Pe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Pe.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(gu,{ELEMENT:e,[Jt]: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(Ug(e,this.isSafari(),Ht))})}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[OS[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(Ne(e)),await this.elementIdValue(Ne(e),t)}async getViewportSize(e){let t=await this.execute(kS);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(Ne(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 c;return(c=this.client)==null?void 0:c.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){Ht.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 Ht.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 ir={};z(ir,{getSessionPlayer:()=>Z,options:()=>yu});var No,yu,hu,Z,we=E(()=>{"use strict";No=require("path");$();yu={playerPath:void 0},Z=()=>{if(hu)return hu;let s=($e(),qe(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(pn(),qe(un)),t=e(),r=yu.playerPath?(0,No.resolve)(yu.playerPath,"src/background/sessionPlayerInit.ts"):(0,No.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),hu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(zd),n}});var Vg={};z(Vg,{doubleClick:()=>_S});var _S,Gg=E(()=>{"use strict";_S=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(v,b,w){return w>v&&w<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}},c=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},l=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},m=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},d=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>d(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=m();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 Fn={};z(Fn,{dispatchFocus:()=>LS});function LS(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 Un=E(()=>{"use strict"});var Jg={};z(Jg,{WebDriver:()=>Or});async function FS(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 NS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var vs,zg,Kg,Be,or,DS,Hg,NS,Pr,MS,qg,kr,Or,Bn=E(()=>{"use strict";vs=I(require("lodash"));B();$e();Lo();zg=I(require("p-retry")),Kg=I(require("ua-parser-js"));Hr();$();fu();Wg();Y();de();ys();Be=P("webdriver"),[or,DS]=[0,2],{extractElementId:Hg,getCdpAddressForHost:NS}=X,Pr=()=>(we(),qe(ir)).getSessionPlayer().codeSnippets,MS=()=>(we(),qe(ir)).getSessionPlayer().locatorBuilderUtils,qg=()=>(we(),qe(ir)).getSessionPlayer().utils,kr=()=>(we(),qe(ir)).getSessionPlayer().positionUtils;Or=class extends Do{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}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)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(r=>r!==t)}async init(t){var A,D,V,x,R,L,M,G;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:T,mode:v}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(D=(A=i==null?void 0:i.company)==null?void 0:A.activePlan)==null?void 0:D.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let b=_o({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:T,mode:v});b.desiredCapabilities&&delete b.desiredCapabilities.marionette,b.capabilities&&delete b.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let w=g?0:1500,S=g?()=>null:()=>this.executeJS("window.focus()");try{F("before initClient in webdriver.js init");let W=await this.initClient(b,a,f);F("after initResult before getCdpAddress in init"),this.cdpUrl=await FS(W),F("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(w),O.flags.dontFocusOnInit.isEnabled()||await S(),F("after focus and delay in webdriver.js init")}catch(W){let q=JSON.stringify(vs.omit(b,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:W,capabilitiesAsString:q});let ie=((R=(x=i==null?void 0:i.company)==null?void 0:x.activePlan)==null?void 0:R.plan)==="free";throw(L=W.stack)!=null&&L.includes("at startWebDriverSession")&&((M=W.message)!=null&&M.startsWith("Failed to create session"))&&((G=W.message)!=null&&G.includes("Timeout awaiting 'request'"))&&ie?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(W.message)?new zr(W.message):/capabilit(y|ies)/.test(W.message)?new Ri(W.message):/403 Forbidden/.test(W.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(W.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${W.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>vs.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,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[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,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Be.warn("failed to click on alert",{err:c}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Hg(r.value);return await this.switchToFrame({ELEMENT:n,[Jt]: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 xi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Pe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
17
+ 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 nv(){let s=xt==="staging"?`${mt}/Staging-LATEST_VERSION`:`${mt}/sessionPlayer_LATEST_RELEASE`;return(await $t(s)).body.toString("utf8")}function iv(){return`${mt}/dev-sessionPlayer.zip`}async function ov(s,e){if(!De(s)||De(s)&&e||We)return s;let t=await nv();return`${s}-${t}${xt==="staging"?".zip":""}`}function pl(){let s=ht();return as.resolve(s,"testim-bin")}function av(){let s=pl();return as.resolve(s,"sessionPlayer.zip")}async function nf(s,e,t=!1){try{return await ki(s,e),await ot(e,pl())}catch(r){if(t)throw r;return await nf(s,e,!0)}}async function Sr(s,e){Ki.info("prepare player",{location:s,canary:e});let t=av();return kt(async()=>{let r=xt==="development"?iv():await ov(s,e);return await nf(r,t),{}},"preparePlayer",sf,[s,e,t])()}var ef,tf,as,rf,Ki,sf,cl,Zm,pn=E(()=>{"use strict";ef=I(require("ms")),tf=I(require("node:fs")),as=I(require("node:path"));oe();er();rf=require("serialize-error");$();el();Y();B();Ki=P("prepare runner and testim start"),sf=(0,ef.default)("0.5 day"),cl=16,Zm=`The size of the custom extension is more than ${cl}MB`});function cv(){let s=dn.type().toLowerCase();return s==="darwin"?dn.arch()==="arm"?"mac_arm":"mac":s==="windows_nt"?dn.arch()==="x64"?"win64":"win32":"linux"}async function Xi(){let s=cv(),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(mn,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]}/${mn}/${n[s]}.zip`,a=Ji.join(dl,n[s]),c=`${a}.zip`,l=Ji.join(a,i[s]);if(await ye(l))return l;if(!await ye(c)){let d=(0,ml.default)("Downloading Chromium").start();try{await of.promises.mkdir(dl),await Je(o,c)}catch(u){let f=`Failed to download Chromium: ${u.message}`;throw d.fail(f),new Error(f)}d.succeed()}let m=(0,ml.default)("Extracting Chromium").start();try{await ot(c,dl)}catch(d){let u=`Failed to extract Chromium: ${d.message}`;throw m.fail(u),new Error(u)}return m.succeed(),l}var of,dn,Ji,ml,mn,dl,fl=E(()=>{"use strict";of=I(require("fs")),dn=I(require("os")),Ji=I(require("path")),ml=I(require("ora"));Y();B();mn="1000968",dl=Ji.join(Vt,`chrome-${mn}`)});async function lf(s,e){return Er=s,bl=e,await gl()}function uf(s,e){Er=e.projectId,bl=e.token,fn=e.userAccessKey,at=s.token,hn=Tl(at),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,af=e.publicIp,cf=e.initializedFromCache}function uv(s=Er,e=bl){return kt(()=>(gn.info("request to get cli token from server"),Ve({url:`${he()}/auth/token`,body:{projectId:s,token:e}})),"getTokenV3",lv*10,{projectId:s,token:e})()}async function pv(){gn.info("request to refresh JWT cli token from server");let s=await Ve({url:`${he()}/auth/refreshToken`,body:{token:at,refreshToken:yn}});return at=s.token,hn=Tl(at),s.refreshToken&&(yn=s.refreshToken),at}async function gl(){try{let s=await uv();return gn.info("successfully get cli token from server"),at=s.token,hn=Tl(at),yn=s.refreshToken,hl=s.ngrokToken,yl=s.isNgrokWhitelisted,at}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."):(gn.error(`While trying to retrieve CLI token. caught error: ${s}`,{projectId:Er}),new C(`While trying to retrieve CLI token, caught error: ${s}`))}}function Tl(s){return require("jsonwebtoken").decode(s).exp*1e3}async function Ot(){if(!hn)return gl();let s=O.flags.accessTokenExpiryMargin.getValue();if(hn<Date.now()+4*s)try{return await pv()}catch(e){return gn.error("failed to refresh token, executing fallback",e),gl()}return at}function Yi(){return yn}function Ir(){return at?{uid:require("jsonwebtoken").decode(at).id,ngrokToken:hl,isNgrokWhitelisted:yl}:{}}async function Qi(){if(!fn||!Er)return;if(await wl({userAccessKey:fn,projectId:Er}))return fn;let e=`user access key "${fn}" is invalid for project "${Er}"`;throw new C(e)}function Zi(){return af}function eo(){return cf}var gn,at,hn,yn,hl,yl,Er,bl,fn,af,cf,lv,ct=E(()=>{"use strict";oe();Ge();er();Y();$();ge();de();gn=P("testim-custom-token"),Er=null,bl=null,lv=5*60*1e3});function dv(s){if(s.protocol)return s.protocol;if([_.TESTIM_PRIVATE,_.TESTIM,_.BROWSERSTACK,_.SAUCELABS].includes(s.type)&&s.port===443)return"https";if([_.TESTIM_ENTERPRISE,_.TESTIM_LAMBDATEST,_.DEVICE_FARM].includes(s.type)){let e=pf.exec(s.host);return(e==null?void 0:e[2])||"https"}return""}function mv(s){let e=pf.exec(s);return e==null?void 0:e[3]}function ro(s){var w,S,A,D,V,x,R,L,M,G,W;let e=s&&mv(s.host),t=s.port,r=s.path,n=s&&dv(s),i=s.token,o=s.slotId,a=(w=s.hybrid)==null?void 0:w.tunnel,c=(S=s.external)==null?void 0:S.user,l=(A=s.external)==null?void 0:A.key,m=s.type,d=m===_.HYBRID?a&&((x=(V=(D=s.hybrid)==null?void 0:D.external)==null?void 0:V[s.hybrid.tunnel])==null?void 0:x.user):c,u=m===_.HYBRID?a&&((M=(L=(R=s.hybrid)==null?void 0:R.external)==null?void 0:L[s.hybrid.tunnel])==null?void 0:M.key):l,f=s.name,h=s&&(s._id||s.gridId),g=s.provider,y=(G=s.mobileTokens)==null?void 0:G.androidToken,T=(W=s.mobileTokens)==null?void 0:W.iosToken,v=s.apiUrl,b=s.isSupportGrid;return{host:e,port:t,path:r,protocol:n,accessToken:i,slotId:o,gridId:h,tunnel:a,user:c,key:l,type:m,name:f,provider:g,tunnelUser:d,tunnelKey:u,androidToken:y,iosToken:T,apiUrl:v,isSupportGrid:b}}async function gv(s,e,t,r,n,i){var a;let o;try{o=await i()}catch(c){throw lt.error("failed to get grid",{projectId:s,companyId:e,err:c}),new Error(yt.UNKNOWN)}if(lt.info("get grid info",{...o,projectId:s,companyId:e}),!o||!["success","error"].includes(o.status))throw lt.error("invalid response - get grid",{res:o}),new Error(yt.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,gf(n));let c=ro(o.grid);return fv(t,e,c.gridId,c.slotId,r,c.isSupportGrid),c}throw o.code==="not-found"?new st(yt.NOT_FOUND):o.code==="no-available-slot"?new Yt(`Failed to run test on ${r} - concurrency limit reached`):(lt.error("invalid code error response - get grid",{res:o}),new st(yt.UNKNOWN))}function mf(s){return xl(s)}async function ff(s,e,t){let n=(t||await mf(s)).find(i=>i._id===e);if(!n)throw new C(`Failed to find grid id: ${e}`);return ro(n)}async function hv(s,e,t){let n=(t||await mf(s)).find(i=>(i.name||"").toLowerCase()===e.toLowerCase());if(!n)throw new C(`Failed to find grid name: ${e}`);return ro(n)}async function vl(s,e){let t=bn[s];if(!t)return;let{slotId:r,gridId:n,browser:i,companyId:o,isSupportGrid:a}=t;if(delete bn[s],!a){if(!r){lt.warn("failed to find grid slot id",{projectId:e});return}lt.info("release slot id",{projectId:e,companyId:o,slotId:r,gridId:n,browser:i});try{await El(o,e,r,n,i)}catch(c){lt.error("failed to release slot",{projectId:e,err:c})}}}async function yv(s){let e=Object.values(bn).filter(Boolean);if(e.length!==0&&!e[0].isSupportGrid)try{await Sl(s,e)}catch(t){lt.error("failed to update grid keep alive",{err:t,slots:e,projectId:s})}}function bv(s){df=global.setInterval(yv,1e4,s)}async function Tv(s){let e=Object.keys(bn);if(e.length){lt.warn("not all slots released before end runner flow",{projectId:s});try{await se(e,t=>vl(Number(t),s))}catch(t){lt.error("failed to release all slots",{err:t,projectId:s})}}}async function wv(s){await Tv(s),clearInterval(df)}function vv(s,e){let{testobjectSauce:t,saucelabs:r}=e;if(s==="testobject")return t.testobjectApiKey;if(s==="saucelabs")return r.accessKey}function Sv(s,e){let{saucelabs:t}=e;if(s==="saucelabs")return t.username}function gf(s){let t=(()=>to.isEmpty(s.testobjectSauce)?to.isEmpty(s.saucelabs)?to.isEmpty(s.perfecto)?"hostAndPort":"perfecto":"saucelabs":"testobject")(),{host:r,port:n,path:i,protocol:o}=s,a=vv(t,s),c=Sv(t,s);return{host:r,port:n,path:i,protocol:o,type:t,user:c,key:a,gridId:re()}}async function hf(s,e){let t=s.company.companyId;return await ff(t,e.gridId,s.allGrids)}async function yf(s){let{allGrids:e,company:t,host:r,useLocalChromeDriver:n,localTmaUrl:i,useChromeLauncher:o,gridId:a,grid:c}=s;if(n||o||i)return{mode:"local"};if(r)return gf(s);let l=t==null?void 0:t.companyId;if(a)return ff(l,a,e);if(c)return hv(l,c,e);if(en(s)||s.tunnelOnlyMode){lt.info("skipping getting grid, as it is set on test plan",{companyId:l});return}throw new st("Missing host or grid configuration")}async function bf(s,e,t,r,n){let{host:i,project:o,grid:a,gridId:c,localTmaUrl:l,useLocalChromeDriver:m,useChromeLauncher:d,company:u}=t,f=Boolean(m||d||l),h=u==null?void 0:u.companyId;return gv(o,h,r,s,t,()=>Rl({projectId:o,companyId:h,browser:s,executionId:e,isRunningLocalMode:f,gridId:c,gridName:a,host:i,testResultId:n}))}var to,lt,bn,pf,df,fv,Tn,Tf,cs=E(()=>{"use strict";to=I(require("lodash"));ge();$();B();ae();Y();lt=P("grid-service"),bn={},pf=/(^(https?):\/{2})?(.*)/,df=null;fv=(s,e,t,r,n,i)=>{bn[s]={gridId:t,companyId:e,slotId:r,browser:n,isSupportGrid:i}};Tn={start:bv,end:wv};Tf=async(s={},e={},t={},r={},n={})=>{var g,y,T;let{company:{companyId:i}={},project:o}=s,{gridId:a,type:c}=e,l=s.browser||t.browserValue,m=Boolean(s.tunnel),{maxRetries:d,currentRetry:u}=n;if(!a||!c||((c===_.TESTIM_LAMBDATEST||c===_.LAMBDATEST)&&await((g=r.enableIfNeeded)==null?void 0:g.call(r,e,i,o)),c!==_.HYBRID||!i||!l||!d||!u))return e;let f=await Il({companyId:i,gridId:a,maxRetries:d,currentRetry:u,browser:l,usingTunnel:m});lt.info("handling hybrid grid",{response:f,companyId:i});let h=ro({...e,...f.connectionDetails,provider:f.provider});return f.provider!=="lambdatest"&&((y=r.disable)==null||y.call(r)),f.provider==="lambdatest"&&await((T=r.enableIfNeeded)==null?void 0:T.call(r,h,i,o)),h}});function vn(){return so||"master"}function wf(s="master",e="false"){if(typeof s!="string"&&(s!=null&&s.branch)&&s.branch==="master"){so="master";return}if(s!=null&&s.isArchived)throw new C(`Branch ${s.branch} is archived, run aborted.`);if(s){so=s.branch||s;return}so=e?"master":void 0}var so,Al=E(()=>{"use strict";Y()});function If(s){We||(s!=null&&s.userId||(s={anonymousId:"runnerId"}),Ef.identify(s))}function bt(s,e){return ls("ci",s,e)}function ls(s,e,t){if(We)return;let r=s?{userId:s}:{anonymousId:"runnerId"};Ef.track(Object.assign(r,{event:e,properties:t}))}var Sf,Ef,us=E(()=>{"use strict";oe();Sf=require("@segment/analytics-node"),Ef=new Sf.Analytics({writeKey:"sJOSIGKa5x5rJEGsaOlCjrgozAf7FnVY",flushAt:1})});var Rf={};z(Rf,{isCi:()=>ps});var ps,no=E(()=>{"use strict";ps=Boolean(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.BUILD_NUMBER||process.env.RUN_ID||!1)});function Af(s,e){return e!=null&&e.type&&(s[`${e.type}Mode`]=!0),s}function Cf({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:l,user:m,lightweightMode:d,isStartUp:u,projectType:f,appSource:h,gridType:g}){let y=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:n,companyId:i,companyName:o,projectName:a,companyPlan:c,source:xf(l,m),isStartUp:u,projectType:f,gridType:g,...["android","ios"].includes(f)&&h&&{appSource:h}},d);bt("test-run-ci",y)}function Pf({executionId:s,projectId:e,testId:t,resultId:r,result:n,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,source:m,user:d,lightweightMode:u,logger:f,isStartUp:h,projectType:g,appSource:y,gridType:T}){try{let v=Af({executionId:s,projectId:e,testId:t,resultId:r,ucid:i,companyId:o,companyName:a,projectName:c,companyPlan:l,mockNetworkEnabled:n.wasMockNetworkActivated,source:xf(m,d),isStartUp:h,projectType:g,gridType:T,...["android","ios"].includes(g)&&y&&{appSource:y}},u);if(n.success){bt("test-run-ci-success",v);return}bt("test-run-ci-fail",{...v,failureReason:n.failureReason})}catch(v){f.error("failed to update test end analytics",{err:v})}}function kf(s){bt("batch-run-ci",s)}var xf,Cl=E(()=>{"use strict";us();no();xf=(s,e)=>s!=="cli"&&s!=="cli-local"?s:ps&&e?"ci-with-user":ps?"ci":e?"cli-with-user":s});var Pl,ue,_f=E(()=>{"use strict";Pl=class{static colorString(e,t){return`${e}${t}${Pl.Reset}`}},ue=Pl;ue.Reset="\x1B[0m",ue.Bright="\x1B[1m",ue.Dim="\x1B[2m",ue.Underscore="\x1B[4m",ue.Blink="\x1B[5m",ue.Reverse="\x1B[7m",ue.Hidden="\x1B[8m",ue.FgBlack="\x1B[30m",ue.FgRed="\x1B[31m",ue.FgGreen="\x1B[32m",ue.FgYellow="\x1B[33m",ue.FgBlue="\x1B[34m",ue.FgMagenta="\x1B[35m",ue.FgCyan="\x1B[36m",ue.FgWhite="\x1B[37m",ue.FgGray="\x1B[90m",ue.BgBlack="\x1B[40m",ue.BgRed="\x1B[41m",ue.BgGreen="\x1B[42m",ue.BgYellow="\x1B[43m",ue.BgBlue="\x1B[44m",ue.BgMagenta="\x1B[45m",ue.BgCyan="\x1B[46m",ue.BgWhite="\x1B[47m",ue.BgGray="\x1B[100m"});var En,kl,Ev,Ol,Iv,io,oo,ao,co,lo,uo=E(()=>{"use strict";B();ae();En=s=>{let{status:e,mobile:t}=s;return t!=null&&t.isAppFromDevice||t!=null&&t.isAppForIosVirtualDevice?!1:e===fe.FAILED},kl=s=>{let{status:e}=s;return e===fe.ABORTED},Ev=s=>{let{status:e}=s;return e===fe.PASSED},Ol=s=>s.runnerStatus===Uc.SKIPPED,Iv=s=>s.testStatus===Xe.EVALUATING,io=(s,e)=>Object.values(s).filter(t=>{var r,n;return Ol(t)&&(Ye(t,e)||((r=t.mobile)==null?void 0:r.isAppFromDevice)||((n=t.mobile)==null?void 0:n.isAppForIosVirtualDevice))}).length,oo=s=>Object.values(s).filter(e=>En(e)&&Iv(e)).length,ao=s=>Object.values(s).filter(En),co=s=>Object.values(s).filter(Ev),lo=s=>Object.values(s).filter(kl)});function xv(s){let e=s.indexOf("--token");if(e!==-1)try{let t=s.slice();return t.splice(e,2),t}catch{}return s}var _l,po,Rv,mo,Lf=E(()=>{"use strict";_l=I(require("lodash"));$();uo();po=P("debug-reporter"),Rv=["allGrids","authData","gridData","perfecto","projectData","runParams","testobjectSauce","token","userData","userParamsData","awsAccessKeyId","awsSecretAccessKey"],mo=class{constructor(e){this.options=e}onTestStarted(e,t){po.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,c=r.failedGetBrowserAttempts;po.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:c,id:o,type:a},workerId:t})}get sanitizedOptionsForLogging(){return{..._l.default.omit(this.options,Rv),company:_l.default.pick(this.options.company,["companyId","name","planType"]),activePlan:this.options.company.activePlan}}onTestPlanStarted(e,t,r,n,i,o,a){let c=xv(process.argv);po.info("Test Plan Started",{executionId:i,testPlanName:n,isAnonymous:o,configName:a,options:this.sanitizedOptionsForLogging,args:c})}onTestPlanFinished(e,t,r,n,i){let o=co(e).length,a=Object.keys(e).length-o;po.info("Test Plan Finished",{executionId:n,testPlanName:t,isAnonymous:i,passed:o,failed:a,options:this.sanitizedOptionsForLogging,duration:r})}}});var Ll,_t,In=E(()=>{"use strict";ae();Ll=class{constructor(){this._planType="free"}setPlanType(e){this._planType=e}get isTestStatusEnabled(){return["pro","trial"].includes(this._planType)}shouldShowFreeGridRunWarning(e){return this._planType!=="pro"&&e===_.DEVICE_FARM}},_t=new Ll});var Nl={};z(Nl,{Reporter:()=>Av});var sr,Rn,Rr,fo,Df,Dl,Av,Ml=E(()=>{"use strict";sr=I(require("chalk")),Rn=I(require("lodash"));B();ae();In();uo();Rr={success:sr.default.green,warn:sr.default.yellow,error:sr.default.red},{CLI_MODE:fo}=Wt,Df="device",Dl=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: ${sr.default.underline(ze(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?fe.PASSED:fe.FAILED,n=`(${e.testId})`,i=Rr[e.success?"success":"error"];console.log(i(this.toWorkerIdPrefix(t),`Test "${e.name}" finished status: ${r} ${n} duration: ${Li(e.duration)}`))}printAllFailedTests(e){if(!e.length)return;let t=e.map(r=>{let n=ze(this.options.editorUrl,this.options.project,r.testId,r.resultId,this.branchToUse);return`${r.name} : ${n}`});console.log(Rr.error("Failed runs are:")),console.log(Rr.error(t.join(`
18
+ \r`)))}onTestPlanFinished(e,t,r,n,i){let o=ao(e),a=co(e),c=lo(e),l=a.length,m=c.length,d=o.length,u="",f="";if(_t.isTestStatusEnabled){let v=oo(e);u=` FAILED-EVALUATING: ${v}`,d-=v,f=` SKIPPED: ${io(e,this.options)}`}let h=this.buildTestPlanName(i,t),g,y=Rr[d?"error":"success"],T=`PASSED: ${l} FAILED: ${d}${u} ABORTED: ${m}${f} Duration: ${Li(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=Rn.isEmpty(this.options.suites)?"":`Suite: ${this.options.suites}`,n=Rn.isEmpty(this.options.label)?"":`Label: ${this.options.label}`,i=Rn.isEmpty(this.options.name)?"":`Name: ${this.options.name}`,o=Rn.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 c=u=>{u.forEach((f,h)=>{var v;let g=(v=f.testData)!=null&&v.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)})},l=a?`config '${a}'`:"default configs",m=this.options.sfdcCredential?` SfdcCredential: ${this.options.sfdcCredential}`:"",d=`${l}, Project: ${this.options.project}, Branch: ${this.branchToUse}${m}`;console.log(`Run${this.buildTestPlanName(o,n)} test plan with ${d} (${i})`),this.printWorkerDivider(),e.length>0&&(console.log("Before all:"),c(e)),console.log("Test list:"),c(t),r.length>0&&(console.log("After all:"),c(r)),this.printWorkerDivider()}onGetSlot(e,t){let r=this.options.grid||this.options.gridId,n=this.options.mode===fo.APPIUM?Df:t;r&&console.log(this.toWorkerIdPrefix(e),`Get ${sr.default.underline(n)} slot from ${sr.default.underline(r)}`)}onGetSession(e,t,r){let n=r===fo.APPIUM?Df:"browser";console.log(this.toWorkerIdPrefix(e),`Get ${n} to run ${sr.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===fo.APPIUM?"device":"browser";if(n)console.log(Rr.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(Rr.warn(this.toWorkerIdPrefix(e),"We are having issues starting ChromeDriver for you locally"));else if(this.options.host){let o=this.options.mode===fo.APPIUM?"Appium":"Selenium";console.log(Rr.warn(this.toWorkerIdPrefix(e),`We are having issues reaching your ${o} grid at ${this.options.host}:${this.options.port||4444}`))}}},Av=Dl});var Bl={};z(Bl,{Reporter:()=>Lv});function Cv(s){let e=s.testData||{},t=typeof e.total=="number"&&e.total!==1?` - ${e.index} / ${e.total} Data set`:"";return`${s.name}${t}`}function Pv(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 kv(s){return`${s.visitedUrlsJson||""}`}async function Ov(s,e,t,r,n,i){function o(u){let f=ze(s,t,u.testId,u.resultId,r),h={$:{name:Cv(u),classname:n,time:qc(u.duration),ownedBy:u.testOwnerName,ownerEmail:u.testOwnerEmail},"system-out":f};if(En(u)||kl(u)){let g=`Step Failed: ${u.failureReason||u.reason}`,y=En(u)?`${g} More info at: ${f}`:g;h.failure={$:{message:y}}}return Ol(u)&&Ye(u,i)&&_t.isTestStatusEnabled&&(h.skipped={}),i.urls&&(h["visited-urls-list"]=Pv(u),h["visited-urls-json"]=kv(u)),h}function a(u){let{results:f,testPlanName:h,configName:g}=u,y=f||{},v={name:(g&&h?`${h} with config '${g}'`:h)||"selenium run",tests:l(y),failures:m(y),timestamp:c(e)};if(_t.isTestStatusEnabled){v.skipped=io(y,i);let b=oo(y);v.failures-=b,v["failure-evaluating"]=b}return{$:v,testcase:Object.keys(y).map(b=>o(y[b]))}}function c(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 l(u){return Object.keys(u).length}function m(u){return ao(u).length+lo(u).length}let d={testsuites:{testsuite:e.map(u=>a(u))}};try{return new Ul.Builder().buildObject(d)}catch(u){return _v(u)}}function _v(s){let e=new Ul.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 Ul,Nf,Fl,Lv,jl=E(()=>{"use strict";Ul=I(require("xml2js"));B();Nf=require("fs");In();uo();Fl=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 Ov(this.options.editorUrl,e,r,this.branchToUse,this.classname,this.options);if(t)try{return await Nf.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)}};Lv=Fl});var Mf={};z(Mf,{Reporter:()=>Dv});function ds(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 $l,Wl,Dv,Ff=E(()=>{"use strict";$();$l=P("team-city-reporter");Wl=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 ds(n)}onTestStarted(e,t,r,n){if(r){$l.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){$l.debug("skip report test failed because is rerun");return}let a=this.getPrintName(e);console.log(`##teamcity[testFailed name='${a}' message='${ds(t)}' details='${ds(r)}' flowId='${o}']`)}onTestFinished(e,t,r){if(r){$l.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='${ds(r)}']`)}onTestPlanStarted(e,t,r,n){console.log(`##teamcity[testSuiteStarted name='${ds(n)}']`)}onTestPlanFinished(e,t){console.log(`##teamcity[testSuiteFinished name='${ds(t)}']`)}},Dv=Wl});var Uf={};z(Uf,{Reporter:()=>Nv});var Vl,Nv,Bf=E(()=>{"use strict";Vl=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}}))}},Nv=Vl});function ho(s){let{platform:e}=process;e==="win32"?(0,go.exec)(`start chrome ${s}`):e==="darwin"?(0,go.exec)(`open -a "Google Chrome" ${s}`):e==="linux"&&(0,go.exec)(`google-chrome ${s}`)}var go,Gl=E(()=>{"use strict";go=require("child_process")});var jf={};z(jf,{Reporter:()=>Mv});var Hl,Mv,$f=E(()=>{"use strict";B();Gl();Hl=class{constructor(e,t){this.options=e;this.branchToUse=t}onTestStarted(e){let t=ze(this.options.editorUrl,this.options.project,e.testId,e.resultId,this.branchToUse);return ho(t)}},Mv=Hl});var ql,Q,Lt=E(()=>{"use strict";Lf();ql=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 mo(e)),r===void 0||r.length===0){let{Reporter:n}=await Promise.resolve().then(()=>(Ml(),Nl));if(this.reporters.push(new n(e,t)),(e==null?void 0:e.reportFile)!==void 0){let{Reporter:i}=await Promise.resolve().then(()=>(jl(),Bl));this.reporters.push(new i(e,t))}}else(await Promise.all([r.includes("teamcity")&&Promise.resolve().then(()=>(Ff(),Mf)),r.includes("console")&&Promise.resolve().then(()=>(Ml(),Nl)),r.includes("junit")&&Promise.resolve().then(()=>(jl(),Bl)),r.includes("json")&&Promise.resolve().then(()=>(Bf(),Uf)),r.includes("chrome")&&Promise.resolve().then(()=>($f(),jf))])).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 ql});async function zl(s,e,t){let r=ms[s];if(!r)return;let{slotId:n}=r;if(delete ms[s],!n){Tt.warn("failed to find slot slot id",{companyId:e,workerId:s});return}Tt.info("release slot id",{companyId:e,slotId:n});try{await Jl(e,t,n)}catch(i){Tt.error("failed to release slot",{companyId:e,err:i})}}async function Fv(s,e){let t=Object.values(ms).filter(Boolean);if(t.length!==0)try{await Yl(s,e,t)}catch(r){Tt.error("failed to update slot keep alive",{err:r,slots:t,companyId:s})}}function Uv(s,e){Wf=global.setInterval(()=>Fv(s,e),1e4)}async function Bv(s,e){let t=Object.keys(ms);if(t.length){Tt.warn("not all slots released before end runner flow",{companyId:s});try{await se(t,r=>zl(Number(r),s,e))}catch(r){Tt.error("failed to release all slots",{err:r,companyId:s})}}}async function jv(s,e){await Bv(s,e),clearInterval(Wf)}async function Gf(s,e,t){let r;try{r=await Kl(s,e)}catch(n){throw Tt.error("failed to get slot",{companyId:s,err:n}),new Error(yt.UNKNOWN)}if(Tt.info("get slot info",{...r,companyId:s}),!r||!["success","error"].includes(r.status))throw Tt.error("invalid response - get slot",{res:r}),new Error(yt.UNKNOWN);if(r.status==="success")return Vf(t,{slotId:r.slotId}),r.slotId;throw r.code==="not-found"?new st(yt.NOT_FOUND):r.code==="no-available-slot"?new Yt("Failed to run test - concurrency limit reached"):(Tt.error("invalid code error response - get slot",{res:r}),new st(yt.UNKNOWN))}async function Hf(s,e,t,r){let n=ms[r];if(!n)throw new Error("slot not found");Object.assign(n,t),Vf(r,n),await Xl(s,e,n),Tt.info("update slot data on server",{companyId:s,projectId:e,slotData:t})}var Tt,ms,Wf,Vf,xn,fs=E(()=>{"use strict";ge();$();B();ae();Y();Tt=P("slot-service"),ms={},Wf=null,Vf=(s,e)=>{ms[s]=e};xn={start:Uv,end:jv}});function zf(s,e=process){async function t(r){await le(se(qf,async n=>n()),1e4).catch(()=>null),s(r)}e.on("uncaughtException",async r=>{Cn.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(Cn.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",()=>{Cn.error("Caught rejection handled")}),e.once("SIGTERM",()=>{let r="Runner aborted - SIGTERM event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("SIGINT",()=>{let r="Runner aborted - SIGINT event",n=new Error(r);throw Cn.error(r),t(n),n}),e.once("exit",r=>{s(r)})}function gs(s){qf.push(s)}var Cn,qf,Pn=E(()=>{"use strict";$();B();Cn=P("process-handler"),qf=[]});var Yf={};z(Yf,{installAllLazyDependencies:()=>Gv,lazyRequire:()=>ut});async function ut(s,e={}){let t=rl(s);if(t)return t;let r;e.silent||(r=(0,Kf.default)(`Installing ${s} before first usage...`).start());try{let n=await Vv(s);return r&&r.succeed(),n}catch(n){Wv.warn("failed to install dependency lazily",{dependency:s,err:n});let i=Xf(s),o=`${s}@${i}`,c=process.argv.includes("npx")?"":"-g ",l=`Installation of ${s} failed. This typically means you are running an out-of-date version of Node.js or NPM.Please manually install by running the following command: npm install ${c}${o}`;throw r&&r.fail(l),n}}async function Vv(s){return hs.has(s)||(hs.set(s,Jf(s)),hs.get(s).catch(()=>{hs.delete(s)})),hs.get(s)}async function Jf(s){let e=rl(s);if(e)return e;let t=Xf(s),r=`${s}@${t}`;return await qi(ht(),r),tr(s)}async function Gv(){let s=Object.keys(hc);for(let e of s)await Jf(e)}function Xf(s){let e=Object.entries(hc).find(([t])=>t===s);if(!e)throw new Error("The given package name is not lazyDependencies");return e[1]}var Kf,Wv,hs,kn=E(()=>{"use strict";Kf=I(require("ora"));os();$();B();bi();an();Wv=P("lazy-require"),hs=new Map});var Qf,yo,Zf=E(()=>{"use strict";Qf=require("istanbul-lib-report"),yo=class extends Qf.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 eg,tg,rg,On,wt,sg,bo,Ql,ng,Hv,ig,og,qv,zv,ag,Kv,Jv,Xv,Yv,Qv,cg,lg=E(()=>{"use strict";eg=I(require("ora")),tg=I(require("dayjs")),rg=I(require("test-exclude")),On=I(require("fs")),wt=I(require("path")),sg=I(require("istanbul-reports")),bo=I(require("istanbul-lib-report"));ge();Y();B();$();kn();Zf();Ql=P("test-run-status"),ng=s=>{try{return new URL(s)}catch{try{return new URL(`file://${s}`)}catch{return{}}}},Hv=s=>!!ng(s).search,ig=s=>s?ng(s).pathname.substring(1):"",og=(s,e)=>{let t=ig(e);return!new rg.default({relativePath:!1,include:s}).shouldInstrument(t)},qv=s=>s.substring(0,s.indexOf("?")),zv=async({source:s,sourceMapDir:e,sourceMapType:t})=>{let r=await ut("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)},ag=(s,e)=>`${wt.resolve(s,ig(e))}.js`,Kv=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(og(r,o))return;let c=ag(e,o);await On.promises.mkdir(wt.parse(c).dir,{recursive:!0}),await On.promises.writeFile(c,i.sourcesContent[a])})})},Jv={getPath(s){if(typeof s=="string")return s;let e=s.getQualifiedName();return s.isSummary()?e!==""?e+="/index.html":e="index.html":(Hv(e)&&(e=qv(e)),e+=".html"),e},relativePath(s,e){let t=this.getPath(e),r=wt.dirname(this.getPath(s));return wt.posix.relative(r,t)},assetPath(s,e){return this.relativePath(this.getPath(s),e)}},Xv=async(s,e,t,r)=>{let{codeCoverageReporter:n}=s,i={},o=bo.createContext({dir:t,coverageMap:e,watermarks:bo.getDefaultWatermarks(),sourceFinder:a=>{try{let c=ag(r,a);return On.readFileSync(c,"utf8")}catch(c){throw new Error(`Unable to lookup source: ${a} (${c.message})`)}}});return new yo({appendToObject:i}).execute(o),Array.isArray(n)&&n.forEach(a=>{let c={projectRoot:"/"};a==="html"&&(c={linkMapper:Jv}),sg.create(a,c).execute(o)}),i},Yv=async(s,{source:e,sourceMap:t,functions:r})=>{let{codeCoverageInclude:n}=s;if(!t||t.sourcemap.sources.length===0)return;let o=(await ut("v8-to-istanbul"))("FAKE_PATH",0,{source:e,sourceMap:t},a=>og(n,a));return await o.load(),o.applyCoverage(r),o.toIstanbul()},Qv=async(s,e)=>{let{mergeProcessCovs:r}=await ut("@bcoe/v8-coverage"),n={result:[]},i=new Map,a=(await eu(s,"testResult",`runId=${e}`)).data.docs;return await se(a.flatMap(c=>c.JSCoverageURLS||[]),async c=>{let l=await _n(c,9e4);await se(l,async m=>{if(!i.has(m.url)){let d=m.text;m.sourceUrl&&(i.set(m.url,"TEMP"),d=await Zl(m.sourceUrl)),i.set(m.url,{text:d,url:m.url,sourceMapType:m.sourceMapType,hash:m.hash})}delete m.text,n=r([n,{result:[m]}])})},{concurrency:20}),{covUrlMap:i,mergedCoverages:n}},cg=async(s,e,t,r)=>{if(!s.collectCodeCoverage)return;Ql.info("start js coverage process");let n=(0,eg.default)(`analyzing coverage for ${t} ${t===1?"test":"tests"}`).start(),i=wt.resolve(s.codeCoverageReportPath||"./coverage"),o=wt.resolve(i,`.js/${(0,tg.default)().format("DDMMYYYYHHmmss")}`),a=s.codeCoverageSourceMapPath?wt.resolve(s.codeCoverageSourceMapPath):void 0;try{let[c,{mergedCoverages:l,covUrlMap:m}]=await Promise.all([ut("istanbul-lib-coverage"),Qv(s.project,r)]);if(l.result.length===0){n.fail("Failed to report coverage information - js code coverage is empty");return}Ql.info("start js coverage merge and remap",{numOfFiles:m.size,numMergedCoverages:l.result.length});let d=c.createCoverageMap({}),u={};await se(l.result,async({url:h,functions:g})=>{let{text:y,sourceMapType:T}=m.get(h),v=await zv({sourceMapType:T,source:y,sourceMapDir:a});u[h]=v;let b=await Yv(s,{source:y,sourceMap:v,functions:g});d.merge(b)}),await Kv(s,o,u);let f=await Xv(s,d,i,o);return n.succeed(),f}catch(c){let l="Failed to report coverage information";c instanceof C?n.fail(`${l}, missing arg: ${c.message}`):n.fail(l),Ql.error(l,{err:c})}}});var ug={};z(ug,{SELENIUM_PERF_MARKS:()=>Pe,SeleniumPerfStats:()=>xr});var Pe,Zv,xr,ys=E(()=>{"use strict";B();Pe={GET_BROWSER:"GET_BROWSER",GET_HTML:"GET_HTML",GET_ELEMENT:"GET_ELEMENT",GET_SCREENSHOT:"GET_SCREENSHOT"},Zv=["ALL",...Object.values(Pe)],xr=class{constructor(){this.marks=Object.fromEntries(Zv.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`,Mi(r,50)],[`${t}_P95`,Mi(r,95)]]);return{seleniumPerfMarks:this.marks,seleniumStats:Object.fromEntries(e)}}}});var fg={};z(fg,{initServer:()=>rS,mapFilesToLocalDrive:()=>ru});function ru(s,e){try{s.failurePath=(s.failurePath||[]).map(t=>Object.assign(t,To[t.id]?{screenshot:To[t.id]}:{})),Object.keys(wo).forEach(t=>{s.assets||={},s.assets[mg[t]]=wo[t]}),s.assets||={},s.assets.screenshots=Object.values(To)}catch(t){e&&e.error("failed to map files to local drive",{err:t}),s.failurePath||=[],s.assets||={},s.assets.screenshots||=[]}}async function rS({agentPort:s,agentBind:e,saveRCALocally:t}){let r=await ut("multer"),n=typeof t=="string"?t:eS;await tu.promises.mkdir(n,{recursive:!0});let i=r({storage:r.diskStorage({async destination(c,l,m){let d=JSON.parse(c.body.metadata||"{}");if(!d.testResultId)return m(new Error("missing testResultId"),"");let u=Ln.join(n,d.testResultId);try{await tu.promises.mkdir(u,{recursive:!0})}catch(f){return m(f,"")}return m(null,u)},filename(c,l,m){let{fileName:d}=c.body,u=JSON.parse(c.body.metadata||"{}");if(!u.stepId&&!d)return m(new Error("missing stepId or fileName"),"");if(u.stepId){let f=Ln.extname(d);return m(null,`step_${u.stepId}_${u.stepName||""}${f}`.replace(/[/\\?%*:|"<>\s]/g,"-"))}return m(null,d)}})}),o=(0,dg.default)();o.disable("x-powered-by"),o.post("/",i.single("file"),(c,l)=>{let m=JSON.parse(c.body.metadata||"{}");m.stepId&&(To[m.stepId]=c.file.path),m.testResultId&&tS.includes(m.subType)&&(wo[m.subType]||=[],wo[m.subType].push(c.file.path)),l.sendStatus(200)}),o.use((c,l)=>l.status(404).send("Endpoint Not Found"));let{createServer:a}=await import("http");return await new Promise((c,l)=>{let m=a(o);m.listen(s,e),m.on("error",d),m.on("listening",()=>c(m.address()));function d(u){if(u.syscall!=="listen")return l(u);switch(u.code){case"EACCES":case"EPERM":return l(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return l(new C(`Port ${s} is already in use`));default:return l(u)}}})}var tu,pg,Ln,dg,eS,To,wo,mg,tS,su=E(()=>{"use strict";tu=I(require("fs")),pg=I(require("os")),Ln=I(require("path")),dg=I(require("express"));Y();kn();eS=Ln.join(pg.tmpdir(),"testim/rca/"),To={},wo={},mg={"test-log":"consoleLogs","har-file":"networkLogs"},tS=Object.keys(mg)});var nr,nu,vo,gg=E(()=>{"use strict";nr=I(require("lodash"));B();$();nu=P("override-test-data-builder"),vo=class{constructor(e,t,r){this.params=e;this.testInfoList=t;this.projectId=r}isObjectNotArray(e){return nr.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)&&!nr.isEmpty(e.overrideTestData)?(Object.keys(e.overrideTestData).forEach(r=>this.overrideSingleTest(r,e.overrideTestData[r])),delete e.overrideTestData):nu.error("invalid overrideTestData",{overrideTestData:e.overrideTestData,projectId:t})),this.isObjectNotArray(e)&&e.overrideAllTestsData!==void 0&&(nr.isObject(e.overrideAllTestsData)&&!nr.isEmpty(e.overrideAllTestsData)?(this.testInfoList.map(n=>n.name).forEach(n=>this.overrideSingleTest(n,e.overrideAllTestsData)),delete e.overrideAllTestsData):nu.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}nu.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 nr.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(m=>this.generateTestUniqId(m)),o=i.indexOf(n),a=i.lastIndexOf(n),c=r[o],l=this.createNewTestItems(c,t);return r.splice(o,a-o+1,...l)})}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 So(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 Ar,Qe,sS,nS,iS,oS,Eo,hg=E(()=>{"use strict";Ar=I(require("lodash"));B();ae();cs();fs();ge();Y();$();Lt();Pn();lg();ys();su();oe();de();gg();In();Qe=P("test-run-status"),sS=Tr(),nS=process.env.GIT_COMMIT||process.env.CIRCLE_SHA1||process.env.TRAVIS_COMMIT,iS=process.env.GIT_URL||process.env.CIRCLE_REPOSITORY_URL,oS=rt();Eo=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 xr;var a,c,l,m;this.options.runParams||={},this.fileUserParamsData=this.options.userParamsData;let i=Zs(t,e),o=t.lightweightMode?t.lightweightMode.type:t.mode;this.execConfig={parallel:vi||t.parallel||1,browser:i,gitBranch:sS,gitCommit:nS,gitRepoUrl:iS,runnerVersion:oS,gridHost:t.host||((a=t.gridData)==null?void 0:a.host),testimBranch:n,canaryMode:t.canary,source:t.source,schedulerId:t.schedulerId,testPlanId:r,testPlans:t.testPlan,testLabels:t.label,testSuites:[...new Set(e.flatMap(d=>d.testSuites))],testNames:t.name,testIds:t.testId,testConfigs:t.testConfigNames,testConfigIds:t.testConfigIds,port:t.port,browserTimeout:t.browserTimeout,timeout:t.timeout,newBrowserWaitTimeout:t.newBrowserWaitTimeout,tunnel:t.tunnel,tunnelPort:t.tunnelPort,tunnelHostHeader:t.tunnelHostHeader,runnerMode:o,gridId:t.gridId||((c=t.gridData)==null?void 0:c.gridId),gridName:t.grid||((l=t.gridData)==null?void 0:l.name),gridType:(m=t.gridData)==null?void 0:m.type,retentionDays:t.retentionDays,codeCoverageReportPath:t.codeCoverageReportPath,collectCodeCoverage:t.codeCoverageUrlFilter||t.collectCodeCoverage,sessionType:"codeless"},this.testRunStatus=this.calcTestRunStatus()}waitForExecutionStartedFinished(){return this.executionStartedPromise}getTestResult(e){return this.testRunStatus[e]}async addRetryTestResult({newResultId:e,originalTestResultId:t,previousTestResultId:r,projectId:n,executionId:i,retryCount:o=1}){let a=this.testRunStatus[t]||{},{config:c,testId:l,name:m,testStatus:d,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v}=a,b={originalTestResultId:t,previousTestResultId:r,config:Ar.cloneDeep(c),testId:l,status:"QUEUED",name:m,resultId:e,retryCount:o,testStatus:d};return this.testRunStatus[e]={...b,testCreatorName:u,testCreatorEmail:f,testOwnerName:h,testOwnerEmail:g,testLabels:y,testSuites:T,allLabels:v},au({projectId:n,runId:i,testId:l,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 l;let{project:n,remoteRunId:i,projectData:o}=this.options;if((l=this.options.lightweightMode)!=null&&l.onlyTestIdsNoSuite)return this.executionStartedPromise;let a="";try{a=await Ro(n,e.testId,e.resultId,e.config.testData,o.defaults)||""}catch(m){Qe.error("failed to upload test data artifact (runner)",{err:m})}let c=Ar.cloneDeep(e.config);return delete c.testData,c.testDataUrl=a,await this.executionStartedPromise,Cr(n,t,e.testId,e.resultId,"RUNNING",{startTime:e.startTime,config:c,remoteRunId:i,testRetryKey:r})}async testStartReport(e,t,r){if(Ye(e,this.options))return;let n=this.exportsGlobal;try{let i=await So(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:c,success:l}=t;if(a===Xe.EVALUATING&&_t.isTestStatusEnabled){Q.onTestIgnored(e,r,`test in ${Xe.EVALUATING} status`);return}if(l){Q.onTestPassed(i);return}Q.onTestFailed(r,r.failureReason,ze(this.options.editorUrl,this.options.project,o,c,this.branchToUse),o,n,c)}calcResultText(e){return e.success?fe.PASSED:fe.FAILED}onTestIgnored(e,t){let r=this.getTestResult(t);Q.onTestIgnored(e,r,`test in ${Xe.QUARANTINE}`)}monitorMemoryUsage(e){let t=Kc();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&&ru(o,Qe),o.resultUrl=ze(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 c={...this.exportsGlobal,...t.exportsGlobal};return this.exportsGlobal=c,o}async testEndReport(e,t,r,n){var o;let i=r.exportsGlobal;try{try{await So(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 Cr(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}=$c;return e&&(n=i),Qr(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 c=e.browser?rn(e.browser,e.saucelabs,e.browserstack):a.runConfig,l=Zr(O,n)&&tn(a.nativeApp)&&!e.appId,m=Zt(e)&&(Qr(a.nativeApp,n)||l),d=Ye(a,e)||m,u={testId:a.testId,testOptimization:a.testOptimization,status:d?fe.SKIPPED:fe.QUEUED,name:a.name,resultId:a.resultId,testStatus:a.testStatus||Xe.DRAFT,testCreatorName:a.creatorName,testCreatorEmail:a.creatorEmail,testOwnerName:a.testOwnerName,testOwnerEmail:a.testOwnerEmail,testLabels:a.testLabels,testSuites:a.testSuites,allLabels:a.allLabels,...m&&{reason:this.getMobileRunSkippedReason(l,a.nativeApp,n)},config:{...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:c.browserValue.toLowerCase()}};return[a.resultId,u]});return Object.fromEntries(i)}async endKeepAlive(e,t,r){e==="redis"&&await xn.end(r,t),e==="mongo"&&await Tn.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:c,company:{companyId:l}={},slotService:m}=o;gs(()=>Promise.all([this.endKeepAlive(m,t,l),Io("ABORTED",e,t,!1,void 0,a,{gridName:this.options.grid})])),this.startTime=r||Date.now();let d={projectId:t,executionId:e,...O.flags.testNamesToBeforeSuiteHook.isEnabled()&&{testNames:i}},u=await So(o.beforeSuite,d),f=new vo(u,Ar.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 v=async()=>{let b=Ar.cloneDeep(this.testRunStatus);await se(Object.keys(b),async A=>{var L;let D=b[A],V=(L=D.config)==null?void 0:L.testData,x=D.testId,R=await Ro(t,x,A,V,c.defaults);R&&(delete D.config.testData,D.config.testDataUrl=R)});let w=Boolean(o.useLocalChromeDriver||o.useChromeLauncher),S=ou({executionId:e,projectId:t,labels:n||[],startTime:r,executions:b,config:this.execConfig,resultLabels:o.resultLabels,remoteRunId:o.remoteRunId,localRunUserId:o.user,isLocalRun:w,intersections:o.intersections});return this.executionStartedPromise=S,S.catch(A=>Qe.error(A)),S};try{await v()}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){Ar.chain(e).keys().each(t=>{let r=t;this.seleniumPerfStats.marks[r]&&(this.seleniumPerfStats.marks[r]=[...this.seleniumPerfStats.marks[r],...e[r]])}).value()}async executionEnd(e){var m;let t=Xc(this.testRunStatus),r=t.length,n=0,i=0,o=0;for(let{status:d,testStatus:u}of t)d===fe.PASSED&&n++,d===fe.SKIPPED&&i++,d===fe.FAILED&&u===Xe.EVALUATING&&o++;let{seleniumPerfMarks:a,...c}=this.seleniumPerfStats.getStats();try{await So(this.options.afterSuite,{exportsGlobal:this.exportsGlobal,tests:t,total:r,passed:n,skipped:i})}catch(d){console.log("check your callback handler on afterSuite Hook for syntax or exception errors"),Qe.warn("error while running afterSuite Hook",{err:d,projectId:this.options.projectData.projectId,executionId:this.options.executionId})}let l=await cg(this.options,this.branchToUse,r,e);if(Object.assign(c,{coverageSummary:l}),!((m=this.options.lightweightMode)!=null&&m.onlyTestIdsNoSuite))try{return await Io("FINISHED",e,this.options.project,r===n+i+o,{tmsSuppressReporting:this.options.tmsSuppressReporting,tmsRunId:this.options.tmsRunId,tmsCustomFields:this.options.tmsCustomFields},this.options.remoteRunId,c)}catch(d){throw Qe.error("Failed to update suite finished",{err:d}),d}}async markAllQueuedTests(e,t,r,n){let i=Object.keys(this.testRunStatus).filter(o=>this.getTestResult(o).status==="QUEUED");await iu(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 cu(s){var i;let e=s.canary?"-master.zip":".zip",t=`${mt}/testim-headless${e}`,r=O.flags.testimHeadlessExtensionDownloadUrl.getValue({companyId:(i=s.company)==null?void 0:i.companyId,projectId:s.project,runnerEnvironment:xt});return r||(aS.warn("testimHeadlessExtensionDownloadUrl flag is not set, defaulting to MV3 extension",{resultId:s.resultId,executionId:s.executionId,projectId:s.project}),r=`${mt}/testim-headless.zip`),!(s.ext||s.extensionPath)&&r&&(t=r,s.testimHeadlessExtensionDownloadUrl=r),{chrome:t,"edge-chromium":t}}function yg(s){let{chrome:e}=cu(s);return e}function xo(s){let e=xt==="staging"?`${mt}/staging-sessionPlayer`:`${mt}/sessionPlayer`;return s.canary?`${e}-master`:e}var aS,Dn=E(()=>{"use strict";oe();de();$();aS=P("runOptionsUtils")});function bs(s){var n;let t=(n=new RegExp(`^\\b(${Object.values(lu).join("|")})`).exec(s))==null?void 0:n[0];return t||lu[Ed]||"usw2"}var lu,Tg,Ao=E(()=>{"use strict";oe();lu={"us-west-2":"usw2","eu-central-1":"euc1"},Tg=Object.fromEntries(Object.entries(lu).map(([s,e])=>[e,s]))});function wg(s,e){if(e){if(!mS.has(e)){Nn.warn(`OS ${e} is not supported by LT`,{testResultId:s});return}return e}}var vg,Sg,Gt,Eg,Ig,Rg,Co,xg,Nn,cS,lS,Mn,uS,pS,dS,ne,mS,Po=E(()=>{"use strict";vg=I(require("ms")),Sg=I(require("p-retry")),Gt=I(require("node:os")),Eg=I(require("portfinder")),Ig=I(require("node:child_process"));B();Ge();ge();Rg=I(require("node:fs")),Co=I(require("node:fs/promises")),xg=require("node:path");Y();$();Dn();ae();de();B();Ao();Nn=P("lambdatestService"),cS="https://downloads.lambdatest.com/tunnel/v3",lS={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"},Mn=`${Gt.tmpdir()}/LT`,uS=`${Mn}/LT`,pS=(0,vg.default)("15m"),dS="2560x1440",ne=class{constructor(){this.isActive=!1}static isLambdatestGrid(e){return e.type===_.TESTIM_LAMBDATEST||e.type===_.LAMBDATEST||e.type===_.HYBRID&&e.provider==="lambdatest"}isLambdatestRun(){return this.isActive}async enableIfNeeded(e,t,r){ne.isLambdatestGrid(e)&&(ne.lambdatestConfigPromise||=uu(t,r),ne.lambdatestConfig=await ne.lambdatestConfigPromise,this.isActive=!0)}disable(){this.isActive=!1}get getSessionTimeout(){return this.isActive?pS:null}get getSessionRetries(){return this.isActive?1:null}static async prepareTunnel(){if(await ye(uS))return;let t=lS[Gt.platform()+Gt.arch()];if(!t)throw new Error(`tunnel on ${Gt.platform()+Gt.arch()} platform is not supported.`);let r=`${Mn}.zip`;await Je(`${cS}/${t}`,r),await ot(r,Mn)}static async chmodLtTunnel(e){if(!(Gt.platform()==="win32"||!await ye(e))){try{await Co.access(e,Rg.constants.X_OK);return}catch{}try{await Co.chmod(e,"777")}catch(r){throw Nn.error("Failed to make LT tunnel executable",{e:r}),r}}}static async delay(e){await pe(e)}static async connectTunnel(e){if(e.externalLambdatestTunnelId){ne.tunnelName=e.externalLambdatestTunnelId;return}await this.prepareTunnel();let t=await Eg.getPortPromise(),{gridData:r={},gridUsername:n,gridPassword:i,externalLambdatestNTLMTunnelUsername:o,externalLambdatestNTLMTunnelPassword:a}=e,c=global.proxyUri;ne.tunnelName=re();let l=["--tunnelName",ne.tunnelName,"--infoAPIPort",String(t)];if(O.flags.enableLambdaTestTunnelNTLM.isEnabled())if(l=[...l,"--ntlm"],o&&a)l=[...l,"--ntlm-username",o,"--ntlm-password",a];else{let u=JSON.parse(O.flags.addCustomLTtunnelNTLMOptions.getValue());u&&(l=[...l,...Hc(u)])}if(O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()&&(l=[...l,"--skip-upgrade"]),e.externalLambdatestUseWss&&(l=[...l,"--mode","ws"]),e.externalLambdatestDisableAutomationTunneling&&(l=[...l,"--bypassHosts","run.testim.io,services.testim.io,api.coralogix.com,conf.rollout.io,statestore.rollout.io,push.rollout.io,analytic.rollout.io"]),r.tunnelUser&&r.tunnelKey)l=[...l,"--user",r.tunnelUser,"--key",r.tunnelKey];else if(n&&i)l=[...l,"--user",n,"--key",i];else throw new C("tunnel requires username and password");if(c)try{let u=new URL(c);l=[...l,"--proxy-host",u.hostname],u.port&&(l=[...l,"--proxy-port",u.port]),u.username&&u.password&&(l=[...l,"--proxy-user",u.username,"--proxy-pass",u.password])}catch{throw new C("proxy url is invalid")}e.externalLambdatestMitm&&(l=[...l,"--mitm"]),await ne.delay(3e3),await ne.chmodLtTunnel((0,xg.join)(Mn,"LT")),ne.tunnel=Ig.spawn("./LT",l,{cwd:Mn});let m="",d="";ne.tunnel.stdout.on("data",u=>{m+=u.toString()}),ne.tunnel.stderr.on("data",u=>{d+=u.toString()});try{let u=await(0,Sg.default)(()=>Te(`http://127.0.0.1:${t}/api/v1.0/info`,{},{},void 0,{skipProxy:!0}),{onFailedAttempt:f=>{if(m.includes("Invalid Credentials"))throw Object.assign(f,{isInvalidCredsForLT:!0})},retries:30,minTimeout:2e3});Nn.info("LT tunnel info",u)}catch(u){throw Object.assign(u,{stdoutResult:m,stderrResult:d}),Nn.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,c){var S,A;if(!this.isActive)return{};let l=ne.lambdatestConfig.CAPABILITIES[t]||{},m={...ne.tunnelName&&{tunnel:!0,tunnelName:ne.tunnelName}},d=[],{canary:u,ext:f,extensionPath:h,installCustomExtension:g}=e,y={platform:wg(n,a==null?void 0:a.os)||wg(n,(S=o==null?void 0:o.lt)==null?void 0:S.platform)||l.platform||ne.lambdatestConfig.PLATFORM,resolution:ne.lambdatestConfig.RESOLUTION??dS,version:t==="safari"&&((A=o==null?void 0:o.lt)==null?void 0:A.safari_version)||l.version};if(c!==K.APPIUM&&c!==K.SELENIUM&&!f){let D=cu({canary:u});!h&&D[t]&&(d=[...d,D[t]]),h&&De(h)&&(d=[...d,h]),d.length||Nn.warn("No extension was loaded in LambdaTestService",{extUrls:D,extensionPath:h})}O.flags.enableFixForCustomExtensionForLT.isEnabled()&&g&&De(g)&&(d=[...d,g]);let T=bs(e.project||""),b={euc1:"eu"}[T],w=b?{region:b}:{};return{build:r,name:`${n} - ${i}`,...w,selenium_version:ne.lambdatestConfig.SELENIUM_VERSION,timezone:ne.lambdatestConfig.TIMEZONE,...l,...y,loadExtension:d,...m,console:!0,queueTimeout:300,network:O.flags.LTNetworkCapabilities.isEnabled(),ntlm:O.flags.enableLambdaTestTunnelNTLM.isEnabled(),skipBinaryUpgrade:O.flags.enableLambdaTestTunnelSkipUpgrade.isEnabled()}}},mS=new Set(["Linux","Windows 10","Windows 11","macOS Sonoma","macOS Ventura","macOS Monterey","macOS Catalina","macOS Big Sur"])});function gS(s,e){let t={browserName:"safari",...e==="safari technology preview"&&{"safari.options":{technologyPreview:!0}}};return Object.assign(s.desiredCapabilities,t),s}function Dg(s){return kg.readFileSync(s,{encoding:"base64"})}function Ng(s,e,t){if(!(t!=null&&t.isLambdatestRun()&&De(s))&&s){let r=Dg(s);ws.info(`adding extension: custom, path: ${s} length: ${r.length} hash: ${mu(r)} current extension count: ${e.length}`),e.push(r)}}function Mg(s,e,t,r,n){if(n!=null&&n.isLambdatestRun())return;let i=s.testimHeadlessExtensionDownloadUrl;if((s.ext||r)&&!i){let m=typeof s.ext=="string"?s.ext:`${__dirname}/..`,d=r||m,u=`--load-extension=${d}`;ws.info(`adding extension: testim unpacked , path: ${d}`),t.push(u);return}let a=`testim-headless${s.canary?"-master.zip":".zip"}`;!s.extensionPath&&i&&(a=ko.basename(i));let c=ko.join(process.cwd(),a),l=Dg(c);ws.info(`adding extension: testim zipped, path: ${c} length: ${l.length} hash: ${mu(l)} current extension count: ${e.length}`),e.push(l)}function hS(s,e,t,r,n,i,o,a){var g,y;let c=t.seleniumName||t.browserValue,l=[],m=[...Lg];e.headless&&m.push("--headless");let d={prefs:{"profile.default_content_setting_values.popups":pu.CONTENT_SETTING_ALLOW,"profile.default_content_setting_values.automatic_downloads":pu.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(du(n)){let T=O.flags.DFAcceptInsecureOrigins.getValue();typeof T=="string"&&m.push(`--unsafely-treat-insecure-origin-as-secure=${T}`),d.prefs["download.default_directory"]="C:\\Users\\testnode",s.desiredCapabilities.version=O.flags.DFBrowserVersion.getValue(),s.desiredCapabilities["aws:maxDurationSecs"]=2400,s.desiredCapabilities["aws:idleTimeoutSecs"]=60}du(n)&&c==="MicrosoftEdge"&&(s.desiredCapabilities["ms:edgeChromium"]=!0),e.chromeExtraPrefs&&Object.assign(d.prefs,e.chromeExtraPrefs),e.chromeExtraArgs&&e.chromeExtraArgs.forEach(T=>m.push(`--${T}`));try{let T=Oo();T.length&&T.forEach(v=>m.push(`--disable-features=${v}`))}catch{}e.chromeBlockLocation&&(d.prefs["profile.default_content_setting_values.geolocation"]=pu.CONTENT_SETTING_BLOCK),e.chromeUserDataDir&&m.push(`--user-data-dir=${e.chromeUserDataDir}`),(y=(g=e.projectData)==null?void 0:g.defaults)!=null&&y.disableChromiumGpu&&m.push("--disable-gpu"),Object.assign(s.desiredCapabilities,{browserName:c});function u(){t.mobileEmulation&&(d.mobileEmulation={deviceMetrics:{width:t.mobileEmulation.device.width,height:t.mobileEmulation.device.height+Bc.MOBILE_WEB_REMOTE_RUN_HEADER_SPACING,pixelRatio:t.mobileEmulation.device.deviceScaleFactor},userAgent:t.mobileEmulation.userAgent})}u(),Ng(r,l,o),a===K.EXTENSION&&Mg(e,l,m,i,o),l.length>0&&(d.extensions=l),e.disableCookiesSameSiteNoneRequiresSecure&&(d.localState={"browser.enabled_labs_experiments":["cookies-without-same-site-must-be-secure@2"]}),d.args=m;let f={MicrosoftEdge:"edgeOptions",chrome:"chromeOptions"}[c],h={MicrosoftEdge:"ms",chrome:"goog"}[c];return ne.isLambdatestGrid(n)&&delete d.w3c,e.oldCapabilities&&n.type!=="testimEnterprise"&&!(o!=null&&o.isLambdatestRun())&&(s.desiredCapabilities[f]=d),(e.w3cCapabilities||n.type==="testimEnterprise")&&(s.desiredCapabilities[`${h}:${f}`]=d),s}function bS(s,e,t){let r={"pdfjs.disabled":!0};return O.flags.autoSaveDownloadFileFireFox.isEnabled()&&Object.assign(r,{"browser.helperApps.neverAsk.saveToDisk":Cg.join(","),"browser.helperApps.neverAsk.openFile":Cg.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 Ts(s){return`${s.width}x${s.height}`}function IS(s){let{platform:e}=s;if(!e)return Ts(Pg);let t=e.split(" ")[1];return e.startsWith("Windows")&&ES.has(t)?Ts(wS):e==="Linux"?Ts(TS):e.startsWith("macOS")?Ts(vS):Ts(e==="OS X El Capitan"||e==="OS X Yosemite"?SS:Pg)}function RS(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=IS(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,_g.cloneDeep)(t.sl);return delete i.screenResolution,t.browserValue!=="safari"&&delete i.safari_version,pt.merge(i,n,r)}return pt.merge(n,r)}return{}}function xS(s){let{runnerOptions:e}=s;if(pt.isEmpty(e.browserstack))return{};let{projectData:t,testRunConfig:r,testId:n,testName:i,executionId:o,executionName:a}=s,c={buildName:`${a} - ${o}`,sessionName:`${i} - ${n}`,projectName:`${t.name} - ${t.projectId}`,...e.browserstack};return r&&r.browserValue==="safari"&&r.bs.safari_version&&(c.os_version=r.bs.safari_version,r.bs.safari_version==="10"&&Object.assign(c,{"safari.options":{technologyPreview:!0}})),c}function AS(s){return s.perfecto?s.perfecto:{}}function CS(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 PS(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=mc(i,o)),a}function Oo(){return(O.flags.chromeArgsDisableFeatures.getValue()||"").split(",").filter(s=>s.trim().length)}function _o(s){var A,D,V,x;let{overrideConfiguration:e,browserOptions:t,testId:r,testName:n,testRunConfig:i,gridInfo:o,customExtensionLocalLocation:a,executionId:c,executionName:l,projectData:m,testResultId:d,lambdatestService:u,mode:f}=s;if(o.mode==="local"){let R=[],L=[...Lg],M={};t.headless&&L.push("--headless"),t.silentDebuggerExtensionApi&&L.push("--silent-debugger-extension-api"),t.remoteDebuggingPort!==void 0&&L.push(`--remote-debugging-port=${t.remoteDebuggingPort}`);try{let G=Oo();G.length&&G.forEach(W=>L.push(`--disable-features=${W}`))}catch{}return t.chromeExtraArgs&&t.chromeExtraArgs.forEach(G=>L.push(`--${G}`)),t.chromeBinaryLocation&&(M.binary=t.chromeBinaryLocation),f!==K.SELENIUM&&Mg(t,R,L,null,u),Ng(a,R,u),{logLevel:Ag,capabilities:{alwaysMatch:{"goog:chromeOptions":{args:L,extensions:R,...M},browserName:"chrome"},firstMatch:[{}]},path:"/wd/hub",hostname:"localhost",port:9515}}let{driverRequestTimeout:h,driverRequestRetries:g}=t,y=PS(t,o),T={hostname:o.host,host:o.host,port:o.port||4444,path:o.path||"/wd/hub",protocol:o.protocol||"http",logLevel:Ag,connectionRetryTimeout:h,connectionRetryCount:g,getSessionTimeout:Math.max(u.getSessionTimeout,t.getSessionTimeout),getSessionRetries:u.getSessionRetries||t.getSessionRetries,deprecationWarnings:!1,desiredCapabilities:{acceptSslCerts:!0,unexpectedAlertBehaviour:"accept"},...!pt.isEmpty(y)&&{headers:y},...t.proxyForGrid&&{agent:new global.ProxyAgent(global.proxyUri)}};du(o)&&(t.oldCapabilities=!1,t.w3cCapabilities=!0,T.desiredCapabilities={unexpectedAlertBehaviour:"accept"}),t.disableNativeEvents&&(T.desiredCapabilities.nativeEvents=!1),o.user&&o.key&&(o.type==="saucelabs"&&(t.saucelabs||={},t.saucelabs.username||=o.user,t.saucelabs.accessKey||=o.key),o.type==="browserstack"&&(t.browserstack||={},t.browserstack["browserstack.user"]||=o.user,t.browserstack["browserstack.key"]||=o.key)),o.key&&o.type==="perfecto"&&(t.perfecto.securityToken=o.key);let v=Number(t.browserTimeout/1e3),b=t.browser||(i==null?void 0:i.browserValue),w={runnerOptions:t,testId:r,testName:n,testRunConfig:i,executionId:c,executionName:l,projectData:m};pt.merge(T.desiredCapabilities,RS(t,n,i),xS(w),AS(t),CS(t,b,v),u==null?void 0:u.getCapabilities(t,b,c,d,n,i,e,f));let S=null;switch(!t.ext&&!t.extensionPath&&((A=o.host)!=null&&A.endsWith(".testim.io"))&&!t.canary&&f===K.EXTENSION&&(b==="chrome"||b==="edge-chromium"&&O.flags.sendExtensionOnEdgeNonLinux.isEnabled())&&(S="/opt/testim-headless"),b){case"chrome":case"edge-chromium":T=yS(T,t,i,a,o,S,u,f);break;case"firefox":T=bS(T,t,u);break;case"safari":case"safari technology preview":T=gS(T,b);break;default:break}pt.merge(T.desiredCapabilities,t.seleniumCapsFileContent);try{let R={"hub.lambdatest.com":"lambdatest",[O.flags.publicGridURL.getValue()]:"testim","testgrid-devicefarm.us-west-2.amazonaws.com":"devicefarm"},L=q=>q[o.provider]||q[T.host]||q[R[T.host]],M=q=>{var ie,Ie;return L(q)||q[(ie=T.desiredCapabilities)==null?void 0:ie.browserName]||q[(Ie=T.desiredCapabilities)==null?void 0:Ie.version]||q||{}},G=JSON.parse(O.flags.addCustomCapabilities.getValue()||"{}"),W=M(M(G));Object.keys(W).length&&(ws.info(`Adding custom capabilities: ${JSON.stringify(W)}`),Object.assign(T.desiredCapabilities,W))}catch(R){ws.error("Failed to load custom capabilities",{error:R,customCapabilities:O.flags.addCustomCapabilities.getValue()})}if(T.desiredCapabilities&&!T.capabilities&&(fS(T),T.capabilities={alwaysMatch:T.desiredCapabilities,firstMatch:[{}]},delete T.desiredCapabilities),T.hostname=T.host,s.printFinalCaps){let R=(D=T.capabilities)==null?void 0:D.alwaysMatch,L=JSON.parse(JSON.stringify(T)),M=(V=L==null?void 0:L.capabilities)==null?void 0:V.alwaysMatch,G=q=>q.substring(0,80);["goog:chromeOptions","ms:edgeOptions"].forEach(q=>{var ie,Ie;M!=null&&M[q]&&(M[q].extensions=(Ie=(ie=R==null?void 0:R[q])==null?void 0:ie.extensions)==null?void 0:Ie.map(G))}),M!=null&&M.loadExtension&&(M.loadExtension=(x=R==null?void 0:R.loadExtension)==null?void 0:x.map(G));let W=require("node:util");console.log(W.inspect(L,{showHidden:!1,depth:null,colors:!0}))}return T}var kg,ko,Og,pt,_g,ws,Ag,pu,Lg,mu,du,fS,yS,Cg,Pg,TS,wS,vS,SS,ES,Lo=E(()=>{"use strict";kg=I(require("node:fs")),ko=I(require("node:path")),Og=I(require("node:crypto")),pt=I(require("lodash"));B();oe();$();de();ae();Po();_g=require("lodash"),ws=P("testim-desired-capabilities-builder"),Ag=wi?"debug":"silent",pu={CONTENT_SETTING_DEFAULT:0,CONTENT_SETTING_ALLOW:1,CONTENT_SETTING_BLOCK:2,CONTENT_SETTING_ASK:3},Lg=["--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"],mu=(...s)=>Og.createHash("sha256").update(s.join("")).digest("hex"),du=s=>s.type===_.DEVICE_FARM||s.type===_.HYBRID&&s.provider==="devicefarm",fS=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=O.flags.unsupportedCapsFields.getValue();let n=JSON.parse(t);if(!Array.isArray(n))return;n.forEach(i=>{delete e[i]})}catch{ws.error('Fail to parse "unsupportedCapsFields" flag',{unsupportedCapsFields:t})}};yS=pt.memoize(hS,(s,e,t,r,n,i)=>{let o=JSON.stringify(s.desiredCapabilities),a=JSON.stringify(pt.omit(e,"runParams")),c=JSON.stringify(t),l=JSON.stringify(n.type);return mu(o,a,c,r,l,i)}),Cg=["application/force-download","application/pdf","application/x-pdf","application/acrobat","applications/vnd.pdf","text/pdf","text/x-pdf","application/vnd.cups-pdf"];Pg={width:1920,height:1080},TS={width:1920,height:1200},wS={width:2560,height:1600},vS={width:2360,height:1770},SS={width:2048,height:1536},ES=new Set(["7","8","8.1","10","11"])});function Ue(s){var e,t,r,n,i,o,a,c;return((e=s.message)==null?void 0:e.match(/Command not found/))||s.message==="HTTP method not allowed"||((t=s.message)==null?void 0:t.toLowerCase())==="unknown error"||((r=s.message)==null?void 0:r.match(/Unknown timeout type/))||s.name==="unknown command"||((n=s.message)==null?void 0:n.match(/did not match a known command/))||((i=s.message)==null?void 0:i.match(/Server returned HTTP response code: 405 for URL/))||((o=s.seleniumStack)==null?void 0:o.message)==="The arguments passed to a command are either invalid or malformed."||((a=s.message)==null?void 0:a.match(/Invalid timeout type specified: ms/))||((c=s.message)==null?void 0:c.match(/\.\w* is not a function/))}function Ug(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 fu=E(()=>{"use strict"});function gu(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 c(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:c(f))}function l(u){var f;return u?(f=u.parentNode)!=null&&f.host?!0:l(u.parentNode):!1}if(!s||!l(s)&&!document.contains(s))return!1;switch(s.tagName.toUpperCase()){case"BODY":return!0;case"SCRIPT":case"NOSCRIPT":return!1;case"OPTGROUP":case"OPTION":{let f=r(s,h=>h.tagName.toUpperCase()==="SELECT");return gu(f)}case"INPUT":if(s.type==="hidden")return!1;break;default:break}if(i(s,"visibility")!=="visible")return!1;let m=!!n(s,u=>Number(i(u,"opacity"))===0),d=!!n(s,u=>i(u,"display")==="none");return!(m||d||!o(s)||c(s))}var Bg=E(()=>{"use strict"});var jg,$g,Ht,kS,OS,Do,Wg=E(()=>{"use strict";jg=I(require("promise-queue")),$g=I(require("webdriverio"));oe();$e();B();$();Hr();Bg();fu();ys();Ht=P("WebDriverApi"),kS=function(){return{screenWidth:Math.floor(window.innerWidth||0),screenHeight:Math.floor(window.innerHeight||0)}},OS={implicit:0,pageLoad:1,script:2},Do=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 Ht.warn("error from selenium",{err:e,testResultId:n,testName:r,crashingFunc:i}),e}initQueueRequests(){let e=1/0;this.isAndroid()&&(e=1),yc!==void 0&&(e=yc);let t=1/0;this.queue=new jg.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,c,l,m,d,u,f;this.testName=t,this.testResultId=r,e.deprecationWarnings=!1,this.initQueueRequests(),F("right before addToQueue");let n=((o=e.capabilities.alwaysMatch)==null?void 0:o.loadExtension)||((a=e.capabilities.alwaysMatch)==null?void 0:a.loadExt)||((d=(m=(l=(c=e.capabilities.alwaysMatch)==null?void 0:c["goog:chromeOptions"])==null?void 0:l.extensions)==null?void 0:m[0])==null?void 0:d.slice(0,80)),i=(u=this.seleniumPerfStats)==null?void 0:u.markStart(Pe.GET_BROWSER);try{await this.addToQueue(async()=>{Ht.info("requesting browser",{testResultId:r,testName:t,extUrl:n}),F("before this.client.init"),e.headers||={},e.headers["Test-Result-Id"]=r??"",this.client=await $g.remote(e),this.logGridStatus(r)}),F("after client init")}finally{(f=this.seleniumPerfStats)==null||f.markEnd(i,Pe.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 c of a.slots||[])if(((o=c==null?void 0:c.session)==null?void 0:o.sessionId)===t){r=a,n=c;break}}catch(a){if(a.message==="unknown error"){Ht.info("grid status is not supported by the grid",{testResultId:e});return}Ht.error("failed to get grid status",{error:a,testResultId:e});return}r&&typeof r=="object"&&"slots"in r&&(r==null||delete r.slots),Ht.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){Ht.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(Pe.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,Pe.GET_SCREENSHOT)}}async takeElementScreenshot(e){let t=this.seleniumPerfStats.markStart(Pe.GET_SCREENSHOT);try{return await this.addToQueue(()=>this.client.takeElementScreenshot(Ne(e)))}finally{this.seleniumPerfStats.markEnd(t,Pe.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(gu,{ELEMENT:e,[Jt]: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(Ug(e,this.isSafari(),Ht))})}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[OS[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(Ne(e)),await this.elementIdValue(Ne(e),t)}async getViewportSize(e){let t=await this.execute(kS);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(Ne(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 c;return(c=this.client)==null?void 0:c.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){Ht.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 Ht.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 ir={};z(ir,{getSessionPlayer:()=>Z,options:()=>yu});var No,yu,hu,Z,we=E(()=>{"use strict";No=require("path");$();yu={playerPath:void 0},Z=()=>{if(hu)return hu;let s=($e(),qe(je));s.log("getSessionPlayerRequire start");let{getSessionPlayerFolder:e}=(pn(),qe(un)),t=e(),r=yu.playerPath?(0,No.resolve)(yu.playerPath,"src/background/sessionPlayerInit.ts"):(0,No.join)(t,"sessionPlayer.js"),n=require(r);return s.log("getSessionPlayerRequire end"),hu=n,process.env.LOGGER_CONSOLE&&process.env.DEBUG&&n.setLoggerFormatter&&n.setLoggerFormatter(zd),n}});var Vg={};z(Vg,{doubleClick:()=>_S});var _S,Gg=E(()=>{"use strict";_S=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(v,b,w){return w>v&&w<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}},c=function(u,f,h){if(!window.PointerEvent)return;let g=a(f,h);return new window.PointerEvent(u,g)},l=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},m=function(){var f;let u=document.activeElement;for(;(f=u.shadowRoot)!=null&&f.activeElement;)u=u.shadowRoot.activeElement;return u},d=function(u){let f=o(u),h=u.event;return t.includes(h)?c(h,f.x,f.y):l(h,f.x,f.y)};try{n.map(f=>d(f)).filter(Boolean).forEach(f=>r.dispatchEvent(f));let u=m();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 Fn={};z(Fn,{dispatchFocus:()=>LS});function LS(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 Un=E(()=>{"use strict"});var Jg={};z(Jg,{WebDriver:()=>Or});async function FS(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 NS(r):void 0}catch(r){Be.info("Error getting cdpAddress",r);return}}var vs,zg,Kg,Be,or,DS,Hg,NS,Pr,MS,qg,kr,Or,Bn=E(()=>{"use strict";vs=I(require("lodash"));B();$e();Lo();zg=I(require("p-retry")),Kg=I(require("ua-parser-js"));Hr();$();fu();Wg();Y();de();ys();Be=P("webdriver"),[or,DS]=[0,2],{extractElementId:Hg,getCdpAddressForHost:NS}=X,Pr=()=>(we(),qe(ir)).getSessionPlayer().codeSnippets,MS=()=>(we(),qe(ir)).getSessionPlayer().locatorBuilderUtils,qg=()=>(we(),qe(ir)).getSessionPlayer().utils,kr=()=>(we(),qe(ir)).getSessionPlayer().positionUtils;Or=class extends Do{constructor(){super(...arguments);this.started=!1;this.keepAliveTimer=null;this._isAlive=!1;this._keepAliveRequests=[];this.browserClosedCallbacks=[];this.browserClosedFailedKeepAlives=0;this.keepAliveFailedCallbacks=[];this.generalKeepAliveFailures=0;this.ignoreHiddenTagsText=!1;this.browserAndOS=null;this.stopKeepAliveInterval=()=>{this.keepAliveTimer&&(this.unregisterToClosedBrowser(this.stopKeepAliveInterval),clearInterval(this.keepAliveTimer),this.keepAliveTimer=null)}}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)}registerToKeepAliveFailed(t){this.keepAliveFailedCallbacks.push(t)}unregisterToKeepAliveFailed(t){this.keepAliveFailedCallbacks=this.keepAliveFailedCallbacks.filter(r=>r!==t)}async init(t){var A,D,V,x,R,L,M,G;let{projectData:r,overrideConfiguration:n,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,seleniumPerfStats:h,fastInit:g,lambdatestService:y,printFinalCaps:T,mode:v}=t;this.browserClosedFailedKeepAlives=0,this.ignoreHiddenTagsText=Boolean((V=(D=(A=i==null?void 0:i.company)==null?void 0:A.activePlan)==null?void 0:D.premiumFeatures)==null?void 0:V.ignoreHiddenTagsText),this.browserClosedCallbacks=[];let b=_o({projectData:r,browserOptions:i,testId:o,testName:a,testRunConfig:c,gridInfo:l,customExtensionLocalLocation:m,executionId:d,executionName:u,testResultId:f,lambdatestService:y,overrideConfiguration:n,printFinalCaps:T,mode:v});b.desiredCapabilities&&delete b.desiredCapabilities.marionette,b.capabilities&&delete b.capabilities.alwaysMatch.marionette,this.initUnsupportedActions(y==null?void 0:y.isLambdatestRun()),this.browserAndOS=null,this.seleniumPerfStats=h;let w=g?0:1500,S=g?()=>null:()=>this.executeJS("window.focus()");try{F("before initClient in webdriver.js init");let W=await this.initClient(b,a,f);F("after initResult before getCdpAddress in init"),this.cdpUrl=await FS(W),F("after getCdpAddress in webdriver.js init"),Be.info(`init new session testName: ${a}`,{sessionId:this.getSessionId(),testResultId:f}),await pe(w),O.flags.dontFocusOnInit.isEnabled()||await S(),F("after focus and delay in webdriver.js init")}catch(W){let q=JSON.stringify(vs.omit(b,"extensions","capabilities.extensions","capabilities.capabilities.extensions","capabilities.alwaysMatch.goog:chromeOptions.extensions"));Be.error("failed to init webdriver",{err:W,capabilitiesAsString:q});let ie=((R=(x=i==null?void 0:i.company)==null?void 0:x.activePlan)==null?void 0:R.plan)==="free";throw(L=W.stack)!=null&&L.includes("at startWebDriverSession")&&((M=W.message)!=null&&M.startsWith("Failed to create session"))&&((G=W.message)!=null&&G.includes("Timeout awaiting 'request'"))&&ie?new Error("Our free grids are in full capacity, please try again or upgrade to our Professional plan"):/Invalid username or password/.test(W.message)?new zr(W.message):/capabilit(y|ies)/.test(W.message)?new Ri(W.message):/403 Forbidden/.test(W.message)?new Error("Grid Access Denied"):/Browser_Version not supported/.test(W.message)?new Error("Browser or Browser version not supported"):new Error(`Failed to init client driver: ${W.message}`)}}initUnsupportedActions(t){t&&this.unsupportedActions.add("move")}isAlive(){return this._isAlive}maxKeepAliveGap(){let t=i=>vs.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,c)=>{let l=this._keepAliveRequests.find(m=>m.id===c);l&&(l[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,this.generalKeepAliveFailures=0}catch(a){if(n("error",o),a.name==="unexpected alert open"){this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures=0,Be.warn("close unexpected alert open"),await this.alertAccept().catch(c=>Be.warn("failed to click on alert",{err:c}));return}if(Be.warn("err while getting testim status",{err:a,testResultId:this.testResultId}),this._isAlive=!1,this.isClosedBrowserError(a)){this.browserClosedFailedKeepAlives++;let c=3;Be.warn("browser was closed",{err:a,testResultId:this.testResultId,counter:this.browserClosedFailedKeepAlives,threshold:c,numOfCallbacks:this.browserClosedCallbacks.length}),this.browserClosedFailedKeepAlives>=c&&this.handleThresholdBasedError(this.browserClosedCallbacks,a)}else this.generalKeepAliveFailures++,this.browserClosedFailedKeepAlives=0,this.generalKeepAliveFailures>=3&&this.handleThresholdBasedError(this.keepAliveFailedCallbacks,a)}};this.keepAliveTimer=setInterval(t,1e4),this.registerToClosedBrowser(this.stopKeepAliveInterval)}handleThresholdBasedError(t,r){t.forEach(n=>{try{n(r)}catch{}})}async switchToLocatedFrame(t){let r=await this.getElement(t),n=Hg(r.value);return await this.switchToFrame({ELEMENT:n,[Jt]: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 xi:r}}async getElement(t){var i;let r=this.seleniumPerfStats.markStart(Pe.GET_ELEMENT);if(typeof t=="string"||typeof t=="number")try{return await this.getElementBySelector(`[testim_dom_element_id='${t}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}if(((i=t==null?void 0:t.shadowPath)==null?void 0:i.length)||O.flags.runGetElementCodeInAut.isEnabled()&&this.isSafari())try{return await this.execute(`
19
19
  var fn = ${Pr().getLocatedElementCode};
20
20
  return fn.apply(null, arguments);
21
21
  `,t)}finally{this.seleniumPerfStats.markEnd(r,Pe.GET_ELEMENT)}try{return await this.getElementBySelector(`[testim_dom_element_id='${t==null?void 0:t.testimId}']`)}finally{this.seleniumPerfStats.markEnd(r,Pe.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 c=getLocatedElement(a);if(!c)throw new Error("could not find dynamic parent");c.setAttribute(i,o)}await this.executeJS(`
@@ -209,8 +209,8 @@ Testim had missing write access to ${r||e}
209
209
  injectCode(params, args, incomingParams, context, code);
210
210
  });
211
211
  })();
212
- `,u=[],f=new Zg.Worker(d,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};mt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?mt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):mt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{mt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ce))throw h;return mt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function WS(s){try{await Xg.promises.rm(s,{recursive:!0,force:!0})}catch(e){mt.warn("failed to remove install npm packages folder",{err:e})}}function eh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Es(s,e,t,r,n,i){let o=eh(n,e,s,t),{data:a}=await VS(o,r,i);return a}async function Is(s,e,t,r,n,i,o,a,c,l){var g;let m=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),d=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(m){let T=Wm(y.testimPackageLocalLocation);return[y.paramName,Ss.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=eh(o,n,e,i);if(l){let y=await _n(l);y&&(c=y)}Buffer.isBuffer(c)&&(mt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(mt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await $S(u,t,r,s,d,a,c),nodeVersion:process.version}}async function VS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=th(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Ss.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await sl(o,r,a,t),mt.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(d=>{let u=jm(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${u}`,packageLocalLocation:Ss.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(m){throw mt.warn("npm package install failed",{transactionId:s,err:m}),m}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&mt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function th(){return Ss.join(Yg.tmpdir(),"/testim_local_packages")}function GS(){let s=th();return WS(s)}var Xg,Yg,Ss,Qg,Zg,mt,Rs=E(()=>{"use strict";Xg=I(require("fs")),Yg=I(require("os")),Ss=I(require("path"));B();os();Qg=I(require("data-uri-to-buffer")),Zg=require("worker_threads");Y();$();ge();os();de();mt=P("cli-service");GS().catch(s=>mt.warn("failed to clean local package folder",{err:s}))});var ar={};z(ar,{run:()=>qS});function HS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var qS,rh=E(()=>{"use strict";Rs();Y();de();qS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:u}=e.data;try{let f=await Is(r,n,i,o,a,c,l,m,d,u);return f&&HS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ce?new Error("Timeout while running action"):f}}});var Su={};z(Su,{run:()=>zS});var zS,sh=E(()=>{"use strict";Rs();Y();zS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await Es(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof Ct)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function ih(s,e,t,r){try{return await Eu(s,e,t,r)}catch{Mo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function JS(s,e,t,r,n){return Mo.info("finished to run remote step",{stepId:t,sessionId:n}),await ih(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function nh(s,e,t,r,n){return Mo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await ih(s,e,t,{status:"completed",success:!1,failureReason:r})}async function oh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;Mo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=KS[o];if(!l)return await nh(n,r,c,`Failed to find step type ${o}`,a);try{let m=await l.run(e,t,i);return await JS(n,r,c,m,a)}catch(m){return await nh(n,r,c,m.message,a)}}var Mo,KS,ah=E(()=>{"use strict";rh();ge();sh();$();Mo=P("step-playback"),KS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Su}});var lh={};z(lh,{preloadTests:()=>Wn});async function Wn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await kt(async()=>{let t=await se(s.testId,r=>Vn({...e,testId:r}),{concurrency:2});return ch.keyBy(t,"testData.id")},"loadTests",YS,[e,s.testId])()}var ch,YS,Fo=E(()=>{"use strict";ch=I(require("lodash"));er();ge();B();YS=1e3*60*60*10});var Iu,uh,_r,QS,Ru,vt,Uo=E(()=>{"use strict";B();lt();Iu=I(require("ws")),uh=require("events");$();oe();_r=P("socket-service"),QS=5e3,Ru=class extends uh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){_r.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),QS)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){_r.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(xd);return Ot().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Iu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return _r.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{_r.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Iu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{_r.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){_r.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){_r.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},vt=new Ru});var dh,xu,ZS,eE,tE,ph,Bo,xs,Au=E(()=>{"use strict";dh=I(require("p-retry")),xu=I(require("socket.io-client"));oe();B();$();ZS=50,eE=10,tE=5e3,ph=10*1e3,Bo=P("base socket service"),xs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Bo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Bo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===eE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=ZS)throw new Error(`Can't connect to Testim Servers.
213
- Action required: Please allow opening a websockets connection to ${he()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Bo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:ph,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he()}/${t}`,this._socket=xu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:ph,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he()}/${t}`,this._socket=xu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,dh.default)(()=>le(n(),tE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var mh={};z(mh,{remoteStepServiceSocketIO:()=>rE});var Cu,rE,fh=E(()=>{"use strict";Au();Cu=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},rE=new Cu});var gh={};z(gh,{remoteStepService:()=>As});var Pu,Gn,ku,As,jo=E(()=>{"use strict";Uo();ae();de();({REMOTE_STEP_SAVED:Pu}=Pt),ku=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Gn=(await Promise.resolve().then(()=>(fh(),mh))).remoteStepServiceSocketIO,Gn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Pu]):Gn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Pu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Gn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Pu]),Promise.resolve()):Gn.unlistenToRemoteStep(e)}},As=new ku});var Ou,Lr,hh=E(()=>{"use strict";Au();Ou=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Lr=new Ou});var bh={};z(bh,{testResultService:()=>Dt});var yh,_u,Dt,$o=E(()=>{"use strict";yh=require("events");Uo();ae();de();hh();_u=class extends yh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Lr.init(e),Lr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]):Lr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]);return}await Lr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Lr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Lr.getSocket()}},Dt=new _u});var wh,vh,Sh,Ee,sE,Eh,Th,nE,Wo,Ih=E(()=>{"use strict";wh=I(require("lodash"));B();oe();$e();us();lt();ge();ah();vh=I(require("p-retry")),Sh=require("node:url");$();Fo();ys();ae();jo();$o();ge();Ee=P("test-run-handler"),sE=3,Eh=20*1e3,Th=s=>JSON.stringify(s).length<Eh,nE="Test couldn't be started",Wo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new xr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?rn(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return tn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Qr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Oi.FROM_DEVICE:Oi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Vn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Ot(),refreshToken:Yi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Ld(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Qi()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Th(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Ee.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Eh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Wn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Th(e))return;let r=async()=>{try{return await Nu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ee.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Du(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===nE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){F("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{F("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};F("before Runtime.evaluate"),await(0,vh.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),F("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return F("after Runtime.evaluate"),l.value}catch(o){throw Ee.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Sh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Dr(a,c,m,l);n(d),r||setTimeout(o,3e3)}catch(d){Ee.error("failed to check if done",{err:d}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Dt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Dr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Ee.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Ee.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(i){throw Ee.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Dt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Dt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=wh.debounce(async()=>{try{await Dt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ee.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Dr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Ee.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Ee.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Ee.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Dt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Lu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ee.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Dt.off("socket-connected",e)}}listenToRemoteStep(e){As.listenToRemoteStep(this.testResultId,t=>{oh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:sE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Vo,Rh=E(()=>{"use strict";Ih();Vo=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Wo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Ah(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Uu({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Mu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Fu(s,e){let t=s.mode===K.EXTENSION?Nr:Hn,r=xh.difference(Zs(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var xh,Nr,Hn,Go=E(()=>{"use strict";xh=I(require("lodash"));B();us();ge();Y();ae();Nr=["edge-chromium","chrome"],Hn=[...Nr,"firefox","safari","safari technology preview"]});var iE,oE,aE,qn,Bu=E(()=>{"use strict";cs();fs();$();iE=P("worker-utils"),oE=async(s,e,t)=>{e&&await vl(s,t)},aE=async(s,e,t)=>{await zl(s,e,t)},qn=async(s,e,t,r,n,i)=>{iE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await oE(s,e,t),n==="redis"&&await aE(s,r,t)}}});function pE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,_h,zo,Ko,Lh,St,Ch,Ph,kh,Oh,Mr,cE,ju,lE,qt,uE,Ho,dE,Nt,zn=E(()=>{"use strict";qo=I(require("ms")),_h=I(require("lodash")),zo=I(require("p-retry")),Ko=I(require("dayjs")),Lh=I(require("dayjs/plugin/duration"));B();$e();cs();fs();ge();$();Bu();Lt();Po();de();jo();$o();lt();Ge();ae();Y();Ko.default.extend(Lh.default);St=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ch,TEST_START_TIMEOUT_MSG:Ph,TEST_COMPLETE_TIMEOUT_MSG:kh,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Oh}=Ae,{SETUP_TIMEOUT:Mr,NETWORK_ERROR:cE,GRID_ERROR:ju,BROWSER_CLOSED:lE,SELENIUM_ERROR:qt,UNKNOWN_ERROR:uE,MOBILE_SESSION_ERROR:Ho}=Xr;dE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Nt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await bf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new qs(!0)}async getBrowserOnce(e,t,r,n){throw new qs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),St.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Zr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=br(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=br(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(0,qo.default)("1m")}getSessionTimeout(){if(Zt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,zo.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(Gf(o,a,this.id),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Yt?St.info("could not get grid slot due to concurrency issue",r):St.error("error getting grid slot",{error:e,...r}),await pe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{F("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);F("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,zo.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{let u=await Tf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,F("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,d,u),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return F("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),d||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===K.APPIUM?"device":"browser";throw St.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(u instanceof At)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-m)),u}},{retries:c-1,minTimeout:0,factor:1}),F("after getBrowserOnce retries")}catch(o){throw await qn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[At,zr].some(a=>o instanceof a)?o:o instanceof nt?new hr(o,ju):new hr(o,qt)}return n}async runTest(e,t,r){var m;F("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Zt(this.options)&&this.handleMobileTest(e);if(o)return o;F("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Ot(),await this.runTestOnce(e,l)}finally{await qn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var L,M;if(Ye(g,this.options)||Zr(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof hr,w=v(Ph),S=y&&(v(kh)||w&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,V=S&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!b&&!S,R=!g.success&&(x||V||D);try{let G=e.retryKey;g.testRetryKey=G;let W=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,R,W),await this.runTestCleanup(),R){if(V&&await e.startNewTimeoutRetry(),D){St.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(M=this.options.projectData)==null?void 0:M.projectId,ie=e.testResultId,Ie=e.testId;await Jo(q,ie,Ie,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return x&&!D&&!V&&await e.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(R)}t(this.id,...r);return}catch(G){if(G instanceof Xt)return;St.error("failed to process test result",{error:G}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
212
+ `,u=[],f=new Zg.Worker(d,{eval:!0});try{return await le(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};dt.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?dt.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:o}):dt.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{dt.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),i)}catch(h){if(!(h instanceof ce))throw h;return dt.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function WS(s){try{await Xg.promises.rm(s,{recursive:!0,force:!0})}catch(e){dt.warn("failed to remove install npm packages folder",{err:e})}}function eh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function Es(s,e,t,r,n,i){let o=eh(n,e,s,t),{data:a}=await VS(o,r,i);return a}async function Is(s,e,t,r,n,i,o,a,c,l){var g;let m=r.computePackagePathFromPackageJsonExports||O.flags.computePackagePathFromPackageJsonExports.isEnabled(),d=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(m){let T=Wm(y.testimPackageLocalLocation);return[y.paramName,Ss.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=eh(o,n,e,i);if(l){let y=await _n(l);y&&(c=y)}Buffer.isBuffer(c)&&(dt.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:c}),c=c.toString());let f="data:,";return c==="data:"&&(dt.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:c}),c=f),{...await $S(u,t,r,s,d,a,c),nodeVersion:process.version}}async function VS(s,e,t){let r=e.map(l=>`${l.packageName}@${l.packageVersion}`),n=th(),o=O.flags.reuseCliPkgInstallFolder.isEnabled()?n:Ss.join(n,`/${s}`),a=global.proxyUri;async function c(){let l="";try{if(l=await sl(o,r,a,t),dt.info("npm package install finished",{transactionId:s,output:l,timeout:t}),Number(l.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(d=>{let u=jm(o,d.packageName);return{...d,packageFullName:`${d.packageName}@${u}`,packageLocalLocation:Ss.resolve(o,"node_modules",d.packageName)}}),installFolder:o}}catch(m){throw dt.warn("npm package install failed",{transactionId:s,err:m}),m}}try{return await le(c(),t)}catch(l){throw l instanceof ce&&dt.warn("timeout to install package",{packages:r,transactionId:s,err:l,timeout:t}),l}}function th(){return Ss.join(Yg.tmpdir(),"/testim_local_packages")}function GS(){let s=th();return WS(s)}var Xg,Yg,Ss,Qg,Zg,dt,Rs=E(()=>{"use strict";Xg=I(require("fs")),Yg=I(require("os")),Ss=I(require("path"));B();os();Qg=I(require("data-uri-to-buffer")),Zg=require("worker_threads");Y();$();ge();os();de();dt=P("cli-service");GS().catch(s=>dt.warn("failed to clean local package folder",{err:s}))});var ar={};z(ar,{run:()=>qS});function HS(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=O.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var qS,rh=E(()=>{"use strict";Rs();Y();de();qS=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:i,context:o,testResultId:a,retryIndex:c,stepResultId:l,runTimeout:m,fileDataUrl:d,s3filepath:u}=e.data;try{let f=await Is(r,n,i,o,a,c,l,m,d,u);return f&&HS({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ce?new Error("Timeout while running action"):f}}});var Su={};z(Su,{run:()=>zS});var zS,sh=E(()=>{"use strict";Rs();Y();zS=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:i,packageData:o,timeout:a}=e.data;try{return{data:await Es(t,r,n,o,i,a),success:!0}}catch(c){if(c instanceof Ct)return{success:!1,code:"invalid-node-package",message:c.message};if(c instanceof ce)return{success:!1,code:"timeout"};throw c}}});async function ih(s,e,t,r){try{return await Eu(s,e,t,r)}catch{Mo.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function JS(s,e,t,r,n){return Mo.info("finished to run remote step",{stepId:t,sessionId:n}),await ih(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function nh(s,e,t,r,n){return Mo.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await ih(s,e,t,{status:"completed",success:!1,failureReason:r})}async function oh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:i}=s,o=t.type,a=e.getSessionId(),c=t.id;Mo.info("start play remote step",{stepType:o,stepId:c,sessionId:a});let l=KS[o];if(!l)return await nh(n,r,c,`Failed to find step type ${o}`,a);try{let m=await l.run(e,t,i);return await JS(n,r,c,m,a)}catch(m){return await nh(n,r,c,m.message,a)}}var Mo,KS,ah=E(()=>{"use strict";rh();ge();sh();$();Mo=P("step-playback"),KS={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":Su}});var lh={};z(lh,{preloadTests:()=>Wn});async function Wn(s){if(!Array.isArray(s.testId)||!s.testId.length)return{};let e={branch:s.branch,projectId:s.project};return await kt(async()=>{let t=await se(s.testId,r=>Vn({...e,testId:r}),{concurrency:2});return ch.keyBy(t,"testData.id")},"loadTests",YS,[e,s.testId])()}var ch,YS,Fo=E(()=>{"use strict";ch=I(require("lodash"));er();ge();B();YS=1e3*60*60*10});var Iu,uh,_r,QS,Ru,vt,Uo=E(()=>{"use strict";B();ct();Iu=I(require("ws")),uh=require("events");$();oe();_r=P("socket-service"),QS=5e3,Ru=class extends uh.EventEmitter{constructor(){super(...arguments);this.clientId=re();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){_r.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),QS)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){_r.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(xd);return Ot().then(n=>new Promise(i=>{let o={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Iu.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,o),this.ws.on("open",()=>{var a;return _r.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),i()}),this.ws.on("close",a=>{_r.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Iu.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{_r.info("websocket error",{event:a})}),this.ws.on("message",a=>{let c=this.parseEvent(a);c!=null&&c.type&&this.emit(c.type,c.data)})}))}sendMessage(t){if(!this.ws){_r.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){_r.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let i=o=>{r(o)&&(n(o),this.removeListener(t,i))};this.on(t,i)}listenTo(t,r,n,i){function o(c){n(c)&&i(c)}(Array.isArray(r)?r:[r]).forEach(c=>{this.listeners[`${t}:${c}`]||=[];let l=o.bind(this);this.listeners[`${t}:${c}`].push(l),this.on(c,l)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,i=!1){return new Promise(o=>{let a=re(),c={query:r,id:a,type:n,fullDocument:i};this.listenOnce("add-filter:done",l=>l.id===a,o),this.sendMessage({type:"add-filter",filter:c}),this.filterMap[t]=c})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let i=this.listeners[`${t}:${n}`];i&&(delete this.listeners[`${t}:${n}`],i.forEach(o=>this.removeListener(n,o)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let i=Array.isArray(r)?r:[r];this.removeListeners(t,i),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},vt=new Ru});var dh,xu,ZS,eE,tE,ph,Bo,xs,Au=E(()=>{"use strict";dh=I(require("p-retry")),xu=I(require("socket.io-client"));oe();B();$();ZS=50,eE=10,tE=5e3,ph=10*1e3,Bo=P("base socket service"),xs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Bo.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Bo.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===eE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=ZS)throw new Error(`Can't connect to Testim Servers.
213
+ Action required: Please allow opening a websockets connection to ${he()} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Bo.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:ph,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${he()}/${t}`,this._socket=xu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:ph,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${he()}/${t}`,this._socket=xu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((i,o)=>{this._socket.emit(e,t,a=>a!=null&&a.success?i():(r[e]=t,o(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,dh.default)(()=>le(n(),tE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Bo.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var mh={};z(mh,{remoteStepServiceSocketIO:()=>rE});var Cu,rE,fh=E(()=>{"use strict";Au();Cu=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},rE=new Cu});var gh={};z(gh,{remoteStepService:()=>As});var Pu,Gn,ku,As,jo=E(()=>{"use strict";Uo();ae();de();({REMOTE_STEP_SAVED:Pu}=Pt),ku=class{async init(e){O.flags.useNewWSCLI.isEnabled()||(Gn=(await Promise.resolve().then(()=>(fh(),mh))).remoteStepServiceSocketIO,Gn.init(e))}joinToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Pu]):Gn.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Pu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Gn.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return O.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Pu]),Promise.resolve()):Gn.unlistenToRemoteStep(e)}},As=new ku});var Ou,Lr,hh=E(()=>{"use strict";Au();Ou=class extends xs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=i=>{i.resultId===t&&i.testId===r&&n(i.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Lr=new Ou});var bh={};z(bh,{testResultService:()=>Dt});var yh,_u,Dt,$o=E(()=>{"use strict";yh=require("events");Uo();ae();de();hh();_u=class extends yh.EventEmitter{init(e){if(O.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Lr.init(e),Lr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return O.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]):Lr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(O.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED]);return}await Lr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(O.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Pt.TEST_RESULT_UPDATED,Pt.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Lr.listenToTestResult(e,t,r)}getSocket(){if(!O.flags.useNewWSCLI.isEnabled())return Lr.getSocket()}},Dt=new _u});var wh,vh,Sh,Ee,sE,Eh,Th,nE,Wo,Ih=E(()=>{"use strict";wh=I(require("lodash"));B();oe();$e();us();ct();ge();ah();vh=I(require("p-retry")),Sh=require("node:url");$();Fo();ys();ae();jo();$o();ge();Ee=P("test-run-handler"),sE=3,Eh=20*1e3,Th=s=>JSON.stringify(s).length<Eh,nE="Test couldn't be started",Wo=class{constructor(e,t,r,n,i,o){this._executionId=e;this._executionName=t;this._options=n;this._branch=i;this._testRunStatus=o;this.seleniumPerfStats=new xr;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this.testInfraIssueRetryCount=2;this.isRerunOnTestStartTimeOutError=!1;this.clearTestResultFinished=Promise.resolve(void 0);var c,l;this._testStatus=r.testStatus,this._testId=r.testId,this._testOptimization=r.testOptimization,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(c=r.overrideTestConfig)==null?void 0:c.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((l=r.runConfig)!=null&&l.isMobileWeb)&&n.browser;this._runConfig=a?rn(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get nativeApp(){return this._nativeApp}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,i,o,a;return this.isAppFromDevice?null:r?(i=(n=r.gridData)==null?void 0:n[e])==null?void 0:i[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(o=this._nativeApp.gridData)==null?void 0:o[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return tn(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Qr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?Oi.FROM_DEVICE:Oi.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${he()}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async isTestRecordedWithEnhancedMode(){return(await Vn({projectId:this._options.project,testId:this.testId,branch:this.branch})).domMode==="enhanced"}async getRunRequestParams(){var r,n;let t={tokenV3:await Ot(),refreshToken:Yi(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:Ld(),remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await Qi()};if(this._options.disableMockNetwork&&bt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let i=this.runData,o=Th(i);Object.assign(t.lightweightMode,{isRunDataSentInUrl:o});let a=JSON.stringify(i).length,c=this.testId;o?(Object.assign(t,{runData:i}),Ee.info(`Run data sent as URL param, test id: ${c} run data length: ${a}`)):Ee.warn(`Run data is too big to be sent as a URL param. Test id: ${c}, run data size: ${a} (limit: ${Eh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let i=await Wn(this._options);Object.assign(t,{preloadedTest:i[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Ee.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testOptimization(){return this._testOptimization}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var i;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((i=this._options.lightweightMode)!=null&&i.disableResults&&!t&&Th(e))return;let r=async()=>{try{return await Nu(this._options.project,this._testId,this._testResultId,e)}catch(o){return Ee.error("failed to upload run data artifact (runner)",{err:o}),""}},n=async()=>{let o=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),Du(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:o,runData:o?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}isRerunOnInfraError(e){return(this.isSeleniumHubNoMatchSessionError(e)||e===nE||this.isRerunOnTestStartTimeOutError)&&this.testInfraIssueRetryCount}setReRunOnTestStartTimeOutError(e){this.isRerunOnTestStartTimeOutError=e}decreaseInfraErrorRetry(){this.testInfraIssueRetryCount--}get retryOnInfraErrors(){return Boolean(this.testInfraIssueRetryCount)}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){F("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=new Set(["Testim Editor","Tricentis Testim Editor","Service Worker chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia/background/background.js"]),{targetId:n}=t.find(o=>(o.type==="background_page"||o.type==="service_worker")&&r.has(o.title))||{},{targetId:i}=t.find(o=>o.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!i)throw new Error("AUT target not found");try{F("before Target.attachToTarget");let[o,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:c}=o||{};F("before Runtime.evaluate"),await(0,vh.default)(async()=>{let{result:m}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},c);if(!m.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),F("after wait for runTestimTest function");let{result:l}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},c);if(l.subtype==="error")throw new Error(l.description);return F("after Runtime.evaluate"),l.value}catch(o){throw Ee.error("error running test using CDP",{err:o}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new Sh.URL(e)}catch{return}let{username:n,password:i}=r;if(n||i)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=i=>{if(!r){if(this.isRetryKeyMismatch(i)){Ee.warn(`ignoring result update for on started due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(i.status)&&(i.resultId=this.testResultId,i.status==="completed"&&!this.isRerunOnInfraError(i.reason)&&(Ee.info("setting _wasCompletedOnStartedCheck to true",{testResult:i,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=i),r=!0,t(i))}};if(this._options.disableSockets){let i=Date.now()+e,o=async()=>{if(Date.now()>i)return;let{testId:a,testResultId:c,branch:l,_options:{project:m}}=this;try{let d=await Dr(a,c,m,l);n(d),r||setTimeout(o,3e3)}catch(d){Ee.error("failed to check if done",{err:d}),setTimeout(o,3e3)}};setTimeout(o,3e3)}else Dt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let i=await Dr(e,t,r,n),o=["running","completed"];if(o.includes(i.status))return Ee.info(`get status: ${i.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),i;throw Ee.error(`test not start test status: ${i.status} (expected [${o.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}catch(i){throw Ee.error("failed to get test result after test start timeout",{err:i,testId:e,testResultId:t,branch:n}),new Error(Ae.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Dt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Ee.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Dt.listenToTestResult(this._testResultId,this._testId,o=>{if(this.isRetryKeyMismatch(o)){Ee.warn(`ignoring result update for on completed due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}o.status==="completed"&&(o.resultId=this._testResultId,r(o))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),i=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=wh.debounce(async()=>{try{await Dt.joinToTestResult(this._testResultId,this.testId)}catch(o){Ee.error("failed joining to test result updates after socket reconnected",{error:o})}try{let o=await Dr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(o)?(Ee.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(o==null?void 0:o.status)==="completed"?(Ee.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),o.resultId=this._testResultId,r(o),!0):!1}catch(o){return Ee.warn("Error while trying to check status on socket connect",o),!1}},n,{maxWait:i}),!this._options.disableSockets)Dt.on("socket-connected",e);else{let o=()=>{setTimeout(async()=>{try{let{isComplete:a}=await Lu(this._testResultId,this._options.project,this.retryKey);a?await e()||(Ee.warn("onConnected returned false even though isComplete was true"),o()):o()}catch(a){Ee.error("failed to check is complete",{err:a}),o()}},3e3)};o()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Dt.off("socket-connected",e)}}listenToRemoteStep(e){As.listenToRemoteStep(this.testResultId,t=>{oh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:sE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=re(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Vo,Rh=E(()=>{"use strict";Ih();Vo=class{constructor(e,t,r,n,i,o){this.pendingAppUploads=new Map;let a=new Set(r.map(c=>{var l;return(l=c.nativeApp)==null?void 0:l.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(c=>{this.pendingAppUploads.set(c,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(c=>new Wo(e,t,c,n,i,o))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});async function Ah(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await Uu({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Mu(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function Fu(s,e){let t=s.mode===K.EXTENSION?Nr:Hn,r=xh.difference(Zs(s,e),t);if(r.length>0)throw bt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var xh,Nr,Hn,Go=E(()=>{"use strict";xh=I(require("lodash"));B();us();ge();Y();ae();Nr=["edge-chromium","chrome"],Hn=[...Nr,"firefox","safari","safari technology preview"]});var iE,oE,aE,qn,Bu=E(()=>{"use strict";cs();fs();$();iE=P("worker-utils"),oE=async(s,e,t)=>{e&&await vl(s,t)},aE=async(s,e,t)=>{await zl(s,e,t)},qn=async(s,e,t,r,n,i)=>{iE.info("releasing player",{hasPlayer:Boolean(i)});try{await(i==null?void 0:i.onDone())}finally{n==="mongo"&&await oE(s,e,t),n==="redis"&&await aE(s,r,t)}}});function pE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var qo,_h,zo,Ko,Lh,St,Ch,Ph,kh,Oh,Mr,cE,ju,lE,qt,uE,Ho,dE,Nt,zn=E(()=>{"use strict";qo=I(require("ms")),_h=I(require("lodash")),zo=I(require("p-retry")),Ko=I(require("dayjs")),Lh=I(require("dayjs/plugin/duration"));B();$e();cs();fs();ge();$();Bu();Lt();Po();de();jo();$o();ct();Ge();ae();Y();Ko.default.extend(Lh.default);St=P("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Ch,TEST_START_TIMEOUT_MSG:Ph,TEST_COMPLETE_TIMEOUT_MSG:kh,TEST_REACHED_CUSTOM_TIMEOUT_MSG:Oh}=Ae,{SETUP_TIMEOUT:Mr,NETWORK_ERROR:cE,GRID_ERROR:ju,BROWSER_CLOSED:lE,SELENIUM_ERROR:qt,UNKNOWN_ERROR:uE,MOBILE_SESSION_ERROR:Ho}=Xr;dE=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],Nt=class{constructor(e,t,r,n,i,o,a,c,l=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=i;this.onTestCompleted=o;this.onGridSlot=a;this.onTestIgnored=c;this.releaseSlotOnTestFinished=l;this.lambdatestService=new ne;this.id=0;this.uniqueId="";this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}async getGridSlot(e,t){let r=await bf(e,t.executionId,this.options,this.id,t.testResultId);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Q.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new qs(!0)}async getBrowserOnce(e,t,r,n){throw new qs(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),St.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId(),executionId:e.executionId}),await e.clearTestResult()}handleQuarantine(e){if(!Ye({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,testOptimization:e.testOptimization};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,i;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Zr(O,(i=this.options.gridData)==null?void 0:i.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let o={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:fe.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,o),o}}calculateMobileTestTimeout(e){let t=O.flags.increaseTDCRequestTimeout.isEnabled(),r=e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN,n=br(O.flags.appiumConnectionRequestTimeout.getValue(),(0,qo.default)("2m")),i=br(O.flags.appiumConnectionRetryCount.getValue(),1),o=n*i;return e===_.BROWSERSTACK||t&&r?o+(0,qo.default)("10m"):o+(0,qo.default)("1m")}getSessionTimeout(){if(Zt(this.options)){let t=this.options.gridData.type,r=this.calculateMobileTestTimeout(t);return Math.max(r,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,zo.default)(async()=>{let n=Date.now();try{return await le(this.getSlotOnce(e),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(i){return t++,await this.handleGetSlotError(i,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,zo.default)(async()=>{var n,i;let r=Date.now();try{let o=(n=this.options.company)==null?void 0:n.companyId,a=(i=this.options.projectData)==null?void 0:i.projectId;return await le(Gf(o,a,this.id),this.options.getBrowserTimeout,Ae.GET_BROWSER_TIMEOUT_MSG)}catch(o){return e++,await this.handleGetSlotError(o,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Yt?St.info("could not get grid slot due to concurrency issue",r):St.error("error getting grid slot",{error:e,...r}),await pe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var i;let r=(i=this.userData)==null?void 0:i.projectId,n;try{F("before getSlotOnce retries");let{failedAttemptsCount:o,gridInfo:a={}}=await this.handleGetSlot(e);F("before getBrowserOnce retries");let c=this.options.getBrowserRetries-o;if(!c)throw new Error("No free browser slots in desired grid");let l=0;n=await(0,zo.default)(async()=>{let m=Date.now(),d=this.initPlayer(e);try{let u=await Tf(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:c,currentRetry:l+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=l,F("before getBrowserOnce");let f=await le(this.getBrowserOnce(e,t,d,u),this.getSessionTimeout(),Ae.GET_BROWSER_TIMEOUT_MSG);return F("after getBrowserOnce"),Q.onGetBrowserSuccess(this.id,r),d||f}catch(u){let f={...a,failedGetBrowserAttempts:l,id:this.options.gridData.gridId},h=this.options.mode===K.APPIUM?"device":"browser";throw St.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Q.onGetBrowserFailure(this.id,r,++l),d.onDone(),!(u instanceof At)&&this.options.mode!==K.APPIUM&&await pe(this.options.getBrowserTimeout-(Date.now()-m)),u}},{retries:c-1,minTimeout:0,factor:1}),F("after getBrowserOnce retries")}catch(o){throw await qn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[At,zr].some(a=>o instanceof a)?o:o instanceof st?new hr(o,ju):new hr(o,qt)}return n}async runTest(e,t,r){var m;F("inside runTest");let n=(m=this.userData)==null?void 0:m.projectId,i=this.handleQuarantine(e);if(i)return i;let o=Zt(this.options)&&this.handleMobileTest(e);if(o)return o;F("before runTest onTestStarted");let a=e.getAppSource,c=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=c.config.baseUrl;let l=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Ot(),await this.runTestOnce(e,l)}finally{await qn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,l)}}async runTestCleanup(){}async onQueueCompleted(){}run(e,t,...r){var f,h;let n=async(g,y)=>{var L,M;if(Ye(g,this.options)||Zr(O,(L=this.options.gridData)==null?void 0:L.type)&&e.isAppFromDevice&&!this.options.appId||e.isAppForIosVirtualDevice){t(this.id,...r);return}let T=e.sessionId;e.setReRunOnTestStartTimeOutError(!1);let v=G=>y==null?void 0:y.message.includes(G),b=y&&y instanceof hr,w=v(Ph),S=y&&(v(kh)||w&&!e.retryOnInfraErrors),D=(!!g.reason&&e.isSeleniumHubNoMatchSessionError(g.reason)||w)&&e.retryOnInfraErrors,V=S&&e.hasMoreTimeoutRetries(),x=e.hasMoreRetries()&&!b&&!S,R=!g.success&&(x||V||D);try{let G=e.retryKey;g.testRetryKey=G;let W=e.getAppSource;if(await this.onTestCompleted(this.id,this.testId,g,T,R,W),await this.runTestCleanup(),R){if(V&&await e.startNewTimeoutRetry(),D){St.info(`retry test id: ${this.testId} name: ${this.testName} again due to infrastructure issues`,{testId:e.testId,retryReason:g.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId,err:y});let q=(M=this.options.projectData)==null?void 0:M.projectId,ie=e.testResultId,Ie=e.testId;await Jo(q,ie,Ie,{show:!1}),e.decreaseInfraErrorRetry(),e.decreaseRetryCount(),e.setReRunOnTestStartTimeOutError(!0),await e.startNewRetry()}return x&&!D&&!V&&await e.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:S,testRetryKey:G,totalRetries:e._totalRetryCount}),this.testResultId=e.testResultId,await u(R)}t(this.id,...r);return}catch(G){if(G instanceof Xt)return;St.error("failed to process test result",{error:G}),t(this.id,...r);return}},i=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
214
214
  Please make sure the CLI has stable access to the internet. ${Dc()?"(Internal: network connectivity test failed)":""}`,o=g=>{let{DEVICE_OS_VERSION_TOO_LOW:y,APP_NOT_EXIST_ON_DEVICE:T,APP_NEVER_STARTED:v,TIMEOUT_ERROR:b,SAUCELABS_APP_IS_NOT_INSTALLED:w}=Wc,S=g instanceof Error?g.message:g;if(S.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),S.includes(Ch)||S.includes(b))return{errorType:Mr,reason:"timeout while getting device"};if(S.includes(Oh)){if(!this.testRunTimeout)return{errorType:Mr,reason:"Test timeout reached!"};let A=Ko.default.duration({milliseconds:this.testRunTimeout});return{errorType:Mr,reason:`Test timeout reached (timeout: ${zc(A)})`}}return S.includes(T)||S.includes(w)?{errorType:Ho,reason:"app doesn't exist on device"}:S.includes(v)?{errorType:Ho,reason:"app never started, check app permission or app activity"}:S.includes(y)?{errorType:Ho,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Ho,reason:S}},a=(g,y)=>{let T=this.options.mode===K.APPIUM?"device":"browser";if(!y&&O.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:cE,reason:i()};let v=g instanceof Error?g.message:g;if(v.includes(Ch))return{errorType:Mr,reason:`Test couldn't get ${T}`};if(v.includes(Ph))return{errorType:Mr,reason:"Test couldn't be started"};if(v.includes(Oh)){if(!this.testRunTimeout)return{errorType:Mr,reason:"Test timeout reached: test is too long"};let b=Ko.default.duration({milliseconds:this.testRunTimeout}),w=Math.floor(b.asMinutes()),S=b.asSeconds(),A=w>0?` ${w} min`:"",D=S>0?` ${S} sec`:"";return{errorType:Mr,reason:`Test timeout reached (timeout:${A}${D}): test is too long`}}if(g instanceof hr&&g.type){if(g.type===ju)return{errorType:ju,reason:`Test couldn't get ${T} from grid - ${g.message}`};if(g.type===qt)return{errorType:qt,reason:`Failed to create new session - ${g.message}`}}return"type"in g&&g.type===lE?{errorType:qt,reason:`Session terminated, this is often caused to connection
215
215
  problems between the Testim CLI and the grid running the test. Please check your network connection.`}:"type"in g&&g.type==="KEEP_ALIVE_FAILED"?{errorType:qt,reason:"Test terminated due to repeated keep alive failures. The browser may have become unresponsive or the test environment may be unstable."}:/SeleniumError: connect ECONNREFUSED/.test(g.message)||/Couldn't connect to selenium server/.test(g.message)?{errorType:qt,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(g.message)?{errorType:qt,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(g.message)?{errorType:qt,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(g.message)?{errorType:qt,reason:`Session could not be created, please check that the ${T} you requested is supported in your plan`}:{errorType:uE,reason:v}},c=async g=>{var w;let y=await Lc();!y&&O.flags.warnOnBadNetwork.isEnabled()&&console.warn(i()),St.warn("error on run",{err:g});let T=(w=this.userData)==null?void 0:w.projectId,{errorType:v,reason:b}=this.options.mode===K.APPIUM?o(g):a(g,y);Jo(T,this.testResultId,this.testId,{status:Qs.COMPLETED,success:!1,reason:b,errorType:v,testRetryKey:e.retryKey,setupStepResult:{status:Qs.COMPLETED,success:!1,reason:b,errorType:v}},e.remoteRunId),await n(pE(this.testId,this.testName,this.testResultId,b),g)},l=async g=>{var w;let y=this.testId,T=this.testResultId,v=(w=this.userData)==null?void 0:w.projectId,b=this.branch;if(!y||!T||!v||!b)return St.warn("Test failed. Not enough data to recover results via API",{err:g}),c(g);try{let S=await Dr(y,T,v,b);if(St.warn("Test failed. Got results via API",{err:g,testResult:_h.default.omit(S,dE),resultId:T}),S&&S.status===Qs.COMPLETED&&!g.message.includes(kh))return await n(S);throw g}catch(S){return S!==g&&St.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:v,branch:b,err:S}),c(g)}},m=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableResults)&&(this.options.useChromeLauncher||this.options.mode===K.SELENIUM),d=this.options.disableSockets||((h=this.options.lightweightMode)==null?void 0:h.disableRemoteStep),u=async g=>{try{await Promise.all([!d&&As.joinToRemoteStep(this.testResultId),!m&&Dt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==K.APPIUM&&e.validateRunConfig();let y=await this.runTest(e,this.customExtensionLocalLocation,g);await n(y),F("After onRunComplete"),t(this.id,...r)}catch(y){await l(y),t(this.id,...r)}finally{d||As.unlistenToRemoteStep(this.testResultId)}};return this.testId=e.testId,this.testName=e.testName,this.testResultId=e.testResultId,this.overrideTestConfigId=e.overrideTestConfigId,this.testRunConfig=e.runConfig,this.branch=e.branch,u()}}});var Nh,Dh,Cs,$u=E(()=>{"use strict";B();Nh=I(require("p-retry"));B();$();Y();Dh=P("window-utils"),Cs=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(i,o){let a=document.elementFromPoint(i,o);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(i){let o=i.message.includes("method IWebBrowser2::Navigate2() failed");if(i.seleniumStack&&o&&n>0)return Dh.warn("selenium navigation failed. retrying to navigate",{err:i}),await pe(1500),r(n-1);throw!i.seleniumStack&&o&&Dh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:i}),i}};return Promise.race([r(),pe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),pe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,i=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),o=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:i,width:o}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await pe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&!r.href.startsWith("res://ieframe.dll/http_404.htm")&&!r.href.startsWith("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")}if(!(await this.driver.executeJS(e)).value)throw new At("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,Nh.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}}});var Wu,Ps,Vu=E(()=>{"use strict";$();Wu=P("cookies-utils"),Ps=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw Wu.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw Wu.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw Wu.error("failed to remove cookie",{err:t}),t}}}});var Gu,Xo,Mh=E(()=>{"use strict";Gu=I(require("p-retry")),Xo=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[i,o]=await(0,Gu.default)(n,{retries:e,minTimeout:t,factor:1}),a=o?o.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),i=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[o,a]=await(0,Gu.default)(i,{retries:t,minTimeout:r,factor:1}),c=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(c.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Fh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let i=s.offset||{top:0,left:0};if(i.top*=r,i.left*=r,!s.elementRect)return mE.warn("missing elementRect",Bh.omit(s,"image")),{};let{elementRect:o}=s,a=await Yo.Jimp.fromBuffer(Buffer.from(n[1],"base64")),c=o.left*r+i.left*r,l=o.top*r+i.top*r,m=o.width*r,d=o.height*r;c<0&&(m+=c,m=Math.max(m,0),c=0),l<0&&(d+=l,d=Math.max(d,0),l=0);let u=a.bitmap.width,f=a.bitmap.height;if(c+m>u&&(m=u-c),l+d>f&&(d=f-l),d<=0||m<=0)throw new Hu("height or width is equal or lower than zero");return{elementImage:await a.crop({x:c,y:l,w:m,h:d}).getBase64(jh)}}async function fE(s,e){let t=new Yo.Jimp({width:s.width,height:s.height});for(let n of e){let i=n.image.match(/^data:[^;]*;base64,(.*)$/),o=await Yo.Jimp.fromBuffer(Buffer.from(i[1],"base64"));t.composite(o,n.position.left,n.position.top)}return await t.getBase64(jh)}function gE(s,e){return fE(s,e)}async function hE(){}async function yE(s){function e(i){let o=s[i];return typeof o=="string"&&o.startsWith("data")}async function t(i){let o=await hE(s[i]);return{key:i,url:o}}let r=await se(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(i=>[i.key,i.url]));return Object.assign(s,n)}function Uh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var Bh,Yo,mE,jh,Hu,Qo,$h=E(()=>{"use strict";Bh=I(require("lodash"));B();Yo=require("jimp");$();mE=P("image-capture-utils"),jh="image/png",Hu=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Qo=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await Fh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Uh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return yE({screenImage:t.image,absoluteScreenHighlight:Uh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>pe(250),i=Boolean(e);async function o(u,f){i?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Fh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await o(h.scrollPos,h.cropData);f.push(g)}return f}function c(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,v=Array.from({length:Math.ceil(h/g)},(w,S)=>({scrollX:Math.min(S*g,h-g),cropX:S*g-Math.min(S*g,h-g),cropW:g-(S*g-Math.min(S*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(w,S)=>({scrollY:Math.min(S*T,y-T),cropY:S*T-Math.min(S*T,y-T),cropH:T-(S*T-Math.min(S*T,y-T))}));return v.flatMap(w=>b.map(S=>({scrollPos:{x:w.scrollX,y:S.scrollY},cropData:{top:S.cropY,left:w.cropX,width:w.cropW,height:S.cropH}})))}async function l(u,f){let h=await t.getCurrentScrollPosition(),g=c(u,f),y=await a(g);return await t.scrollToPosition(h),gE(u,y)}let[m,d]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await l(m,d)}}});var Wh,Vh,Zo,ea,Gh=E(()=>{"use strict";Wh=I(require("p-retry")),Vh=I(require("semver"));B();$();$u();Mh();$h();we();Zo=P("tab-service"),ea=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Zo.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,i={}){let o=await this.getTabDetails(t,e,i),a=re();function c(l){return i.checkForMainTab?o.isMainTab:!o.isMainTab||o.isMainTab==="unknown"?!l.getMainTabInfo(e):o.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:o.url,title:o.title,favIconUrl:o.favIconUrl,order:r,from:this.getTabInfo(e,o.openerTabId),isMain:c(this),openerStepId:n},a}async addTab(e,t,r,n,i={}){let o=await this.buildTabInfo(e,t,r,n,i),a=new Cs(t,this.driver);this._utils[o]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Qo(t,a,new Xo(t,this.driver,{takeScreenshots:i.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(o=>r[o]).filter(o=>!o.isMain);if(n.length===1)return this._utils[n[0].infoId];let i=Object.keys(e).map(o=>e[o]).filter(o=>this.isSameTab(e,t,o));return i.length>0?this._utils[i[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(i=>i===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:i}=Z(),o=i.urlBreaker(e.url||e.currentUrl),a=i.urlBreaker(t.url||t.currentUrl),c=n(o),l=n(a),m=r.map(d=>i.urlBreaker(d)).map(d=>n(d)).filter(d=>d===c);return c===l&&m.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Z();if(n){let l=this.getAllTabInfos(e),m=Object.keys(l).map(d=>l[d]);return n.isSameTab(m,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let i=this.getAllTabInfos(e),o=Object.keys(i).map(l=>i[l].url);if(this.exactUrlMatch(t,r,o))return!0;let a=l=>`${l.domain}/${l.path.join("/")}`;if(this.singleExactMatchForParts(t,r,o,a))return!0;let c=l=>`${l.domain}/${l.path.join("/")}#${l.hash}`;return!!(this.singleExactMatchForParts(t,r,o,c)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(i=>i.value));try{let[i,o,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:i,url:o,isMainTab:a}}catch(i){Zo.error("failed to get url or title",{err:i})}}catch(n){Zo.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await pe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(o=>r[o].openerStepId===t))return;if(this.pendingTabs[e]){Zo.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let i=await this.waitForTabToOpen(e);await this.addNewTab(e,i,this.pendingTabs[e]),this.addFrameHandler(i),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,Wh.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=Vh.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(i=>i.type==="locate"&&!i.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var c,l;let{tabMatcher:r,commonConstants:n}=Z();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((c=t.useCurrentTab)!=null&&c.call(t)){let m=await this.driver.getCurrentTabId();if(m)return m;let d=this.getMainTabId(e);if(d)return d;throw new Error("Current tab not found")}let i=(l=t.tabInfo)==null?void 0:l.openerStepId;await this.waitToPendingTabs(e,i),await this.tryToAddTab(e);let o=this.getAllTabIds(e).map(m=>({...this.getTabInfo(e,m),tabId:m})).filter(m=>!m.isClosed),a=r.matchTabs(t,o);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(m){let d=["no such window","no window found","the window could not be found"];if(m.message&&d.some(u=>m.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw m}}}});var qu,ta,zu=E(()=>{"use strict";qu=class{select(){return console.log(`
216
216
  internal error - cant use port selector in selenium!!!!
@@ -401,21 +401,21 @@ Please make sure the CLI has stable access to the internet. ${Dc()?"(Internal: n
401
401
  `;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 ba.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let i="The element is not editable",o="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",c="element not interactable",l="element is not pointer- or keyboard interactable",m="invalid element state: Element is not currently interactable and may not be manipulated",d="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",f=n?n.message:"";if(f===m||f.startsWith(d)||f.startsWith(i)||f.startsWith(o)||f.startsWith(a)||f.includes(u)||f.includes(c)||f.includes(l)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ba.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Ne(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=O.flags.overrideAzureStorageUrl.isEnabled(),n=O.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:i,context:o,step:a,stepActionUtils:c,driver:l}=this,m=await i.utils.addTokenToFileUrls(o.project.id,a.fileUrls,c.testimServicesApi,r,ba);if(m.length===0)throw new Error("No files urls to upload");if(n&&(m=await Promise.all(m.map(async({name:u,url:f})=>{let h=await $t(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),l.isSafari()||l.isFirefox()||l.isEdgeChromium()){await this.driver.executeJS(`
402
402
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
403
403
  const downloadAndUploadFile = ${BE()};
404
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,m);return}let d=await Dy(m,this.uploadFile);await this.uploadFilesAndForceVisibility(d,t)}}});var wa,va,Fy=E(()=>{"use strict";wa=require("url");me();va=class extends H{async updateBaseUrl(e){let t=new wa.URL(e),r=new wa.URL(this.context.recordedBaseUrl),n=new wa.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 Sa,Uy=E(()=>{"use strict";me();B();Sa=class extends H{async performAction(){await pe(this.step.durationMS||0)}}});var Ea,By=E(()=>{"use strict";me();Ea=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Zn,jy=E(()=>{"use strict";me();Zn=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ia,$y=E(()=>{"use strict";me();Ia=class extends H{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Wy,Ju,Xu,Vy=E(()=>{"use strict";Wy=I(require("@applitools/spec-driver-webdriverio"));bi();we();Ju=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=vd["@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:Wy.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}},Xu=new Ju});var Hy,Gy,ei,qy=E(()=>{"use strict";Hy=I(require("lodash"));me();$();Vy();Gy=P("pixel-validation-step-action"),ei=class extends H{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,c=await Xu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Hy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Gy.error("Applitools SDK step failed",{err:f,info:f.info}),m={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Xu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var Os,Yu=E(()=>{"use strict";Rs();Y();ua();Os=class extends cr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await Is(i,o,a,d,c,l,m,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,zy=E(()=>{"use strict";Yu();lr=class extends Os{isFailedResult(e){return e===!1}}});var Ra,Ky=E(()=>{"use strict";Yu();Ra=class extends Os{isFailedResult(e){return!e}}});var xa,Jy=E(()=>{"use strict";Rs();me();Y();xa=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await Es(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Ct?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Ur,Xy=E(()=>{"use strict";me();Ur=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Yy=E(()=>{"use strict";me();be=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,Qy=E(()=>{"use strict";me();Aa=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ca,Zy=E(()=>{"use strict";me();Ca=class extends H{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function jE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Pa(s,e){jE($E,e),e.registerLocateStepActionUtils(Jn.getUtils(s))}var $E,Qu=E(()=>{"use strict";Jh();Qh();ay();cy();uy();my();hy();yy();by();Ty();Sy();Ey();Iy();Ay();ky();My();Fy();Uy();By();jy();$y();qy();zy();Ky();Jy();Xy();Yy();Qy();Zy();$E={locate:Jn,scroll:ia,mouse:oa,submit:fa,text:ca,"special-key":pa,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":ks,"skip-code-step":ks,"element-code-step":ks,"evaluate-expression":aa,"text-validation":Yn,"wait-for-text-validation":Yn,"select-option":ma,"drop-file":ya,"input-file":Ta,hover:ga,navigation:va,wheel:ha,sleep:Sa,refresh:Ea,"keyboard-shortcut-step":da,"api-validation":Zn,"api-action":Zn,"api-code-step":zt,"extract-text":Ia,"simple-ui-verification":ei,"wait-for-simple-ui-verification":ei,"cli-validation-download-file":Ur,"cli-wait-for-download-file":Ur,"network-validation-step":Ur,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ra,"node-package":xa,"email-code-step":zt,"cli-email-code-step":lr,"sfdc-internal-test-step":Ca,"sfdc-recorded-step":Aa,"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":Ur,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var eb,WE,_s,Zu=E(()=>{"use strict";eb=["simple-ui-verification","wait-for-simple-ui-verification"],WE=[...eb,"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"],_s=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=WE.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 eb.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 rb={};z(rb,{SeleniumTestPlayer:()=>ti});var tb,VE,ti,ep=E(()=>{"use strict";B();tb=require("@applitools/eyes-sdk-core");Bn();Y();$();Vu();Gh();zu();sa();zh();Ku();we();Qu();Zu();oe();VE=P("SeleniumTestPlayer"),ti=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new _s(na());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new Or;let m=new ra(this.driver);this.stepActionFactory=new l(m),Pa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new ea(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=qh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ps(this.driver),FrameLocator:d,portSelector:ta,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:tb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){VE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=[new URL(rt||gr).hostname].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var rp={};z(rp,{WorkerSelenium:()=>tp});function HE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>F(`Got event ${t}`))}var ka,GE,tp,sp=E(()=>{"use strict";B();$e();zn();$();Lt();Fo();ae();$u();Y();ep();we();lt();ka=P("worker-selenium"),GE=1e9,tp=class extends Nt{initPlayer(t){return new ti(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){F("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Cs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),F("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),F("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,GE),await this.windowUtils.validatePageIsAvailable(),F("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof At||m||d?new At(`Page '${c}' is not available`):(ka.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:Zi(),initializedFromCache:eo()}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),HE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await Wn(this.options))[this.testId]);let m=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(ka.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&&(ka.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(),F("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),F("right after super.runTestOnce in workerSelenium");let u=await m();return F("right after runSeleniumTest"),u}catch(u){throw ka.error("failed to run test once",{err:u}),u}}}});var sb,nb,He,qE,zE,np,Et,Oa=E(()=>{"use strict";sb=I(require("ora")),nb=require("jimp");oe();Ge();ge();$();ae();we();de();He=P("mobile-grid-service"),qE="https://tdc.tricentis-cloud.com",zE="https://ui.headspin.io",np=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||bc}/${wc}/devices`:t===_.TESTIM_TDC?`${r||Tc}/${wc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ys(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let m=await si({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=m==null?void 0:m[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let m=e.pCloudy_DeviceFullName.split("_");return`${m[0]} ${m[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:m}={},company:{companyId:d=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=Z();y=v(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,m,d,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Cr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),m=Buffer.from(c,"base64"),d=await nb.Jimp.fromBuffer(m),u=d.bitmap.width,f=d.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,m){let[d,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,m),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Vs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?zE:qE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Cr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await op({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 ri({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/(Nd*60))+1)*60*1e3,Math.max(Dd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,sb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await ip({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),m.gridAppId}catch(m){throw l.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={}}=t,{gridId:u="",type:f=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:d,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:d,projectType:T});v&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!v&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!v&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var m,d;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Vs}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${vc}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?bc:Tc}/${vc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Md}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await kc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(d=(m=JSON.parse(h).result)==null?void 0:m.files)==null?void 0:d.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},Et=new np});function ib({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!KE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function JE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function XE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function YE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),m=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),d=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:XE(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n},...d&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function _a(s){return"id"in s?s.id:s.packageName}function QE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function ZE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=QE(n,t.gridData.type));let d=()=>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":d(),...r&&{"appium:bundleId":_a(r)},...n&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":_a(r),"appium:appActivity":r.activity??".*"},...n&&c};default:throw Error(`unsupported mobile project ${s}`)}}function jr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:_a(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`]:_a(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function ob({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=YE(o.type,i,n);return ZE({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Da({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 Na({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Sc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Sc:".*")}function eI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function tI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...La(s,Ls)}}function ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function rI(s){return ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function sI(s){return ab(s,e=>!e.startsWith("browserstack."))}function cb(s){return!s||!lb(s)?"2.0.0":s}function lb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function ub({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),m=c||l;if(t){let d=lb(t);return!d&&m?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):d}return m}function La(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function nI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:m}=n,d=(a==null?void 0:a.mobile)||{},{type:u}=i,f=eI(i,s),h=await si({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:w})=>{var S;return((S=d.staticAllocation)==null?void 0:S.deviceUdid)===w}),y=(g==null?void 0:g.osVersion)??Da({osVersion:l,mobileConfig:d}),T=(g==null?void 0:g.name)??Na({deviceName:m,mobileConfig:d,projectType:s,gridType:u}),v=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":v,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Da({osVersion:c,mobileConfig:m}),y=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Fd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=tI(b)),t="",jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ls}})}function oI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=i,u=Da({osVersion:c,mobileConfig:m}),f=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h=(0,Br.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ub({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},v={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:cb(g.appiumVersion??"stable"),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...La(h,Ls),"sauce:options":{...T,...v,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:s,sessionCaps:b,appiumPrefix:Ls,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return jr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function aI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:m}=i,d=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Da({osVersion:l,mobileConfig:d}),h=Na({deviceName:m,mobileConfig:d,projectType:e,gridType:u}),g=rI(i.browserstack),y=(0,Br.omit)(sI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},v=O.flags.enableAppium2BrowserStack.isEnabled();if(v||ub({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let w={...T,userName:o.user,accessKey:o.key,appiumVersion:v?"2.0.1":cb(g.appiumVersion),debug:!0,networkLogs:!0},S={"appium:platformVersion":f,"appium:deviceName":h,...La(y,Ls),"bstack:options":{...w,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:e,sessionCaps:S,appiumPrefix:Ls,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...La(g,"browserstack.")};return jr({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function cI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return ob(s);if(_.TESTIM_TVC===s.gridInfo.type)return await nI(s);if(_.P_CLOUDY===s.gridInfo.type)return iI(s);if(_.SAUCELABS===s.gridInfo.type)return oI(s);if(_.BROWSERSTACK===s.gridInfo.type)return aI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function lI(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Et.getGridConnection(e),c=await cI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=lI(r,i==null?void 0:i.mobile);if(!(0,Br.isEmpty)(T)){let v=Object.entries(T).map(([b,w])=>w.split(",").map(S=>S===".*"||S==="="?"":`${b}:${S}`).join(",")).join(" ").trim();c[`${y}:selector`]=v}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,m=O.flags.increaseTDCRequestTimeout.isEnabled(),d=0,u=(0,ap.default)("2m"),f=(0,ap.default)("12m"),h=br(O.flags.appiumConnectionRetryCount.getValue(),d),g=br(O.flags.appiumConnectionRequestTimeout.getValue(),u);return m&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),JE({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),d=await Et.getGridDirectConnection(t,m),f=ob({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(f["appium:udid"]=m),{...d,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=jr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function fb(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 ap,Br,Ls,KE,cp=E(()=>{"use strict";ap=I(require("ms"));de();ae();Oa();Br=require("lodash");B();oe();ge();Ls="appium:",KE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var Ma,hb=E(()=>{"use strict";Ma=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 Fa,yb=E(()=>{"use strict";B();Fa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var lp,Ua,bb=E(()=>{"use strict";$();lp=P("mobile-frame-locator-mock"),Ua=class{foundFrameCallback(){return lp.info("foundFrameCallback-mock invoked"),{}}locate(){return lp.info("locate-mock invoked"),{}}async findFrame(){return lp.info("findFrame-mock invoked"),{}}}});var uI,wb,Tb,Ds,up=E(()=>{"use strict";uI=I(require("webdriverio")),wb=require("@applitools/eyes-sdk-core");hb();zu();$();yb();Ku();we();Qu();bb();Zu();Tb=P("appium-test-player"),Ds=class{constructor(e,t,r,n=uI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=Z(),d=new Fa(this.driver);this.stepActionFactory=new l(d),Pa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new _s(na()),this.sessionPlayer=new a(e,{tabService:new Ma,cookieUtils:void 0,FrameLocator:Ua,portSelector:ta,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Tb.info("appium session deleted",{...i}))}catch(o){Tb.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 pI(s){return await Te(`${s}/api/status`)}async function vb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Sb(s){if((await pI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Eb=E(()=>{"use strict";Ge()});var Ib={};z(Ib,{WorkerLocalTma:()=>fp});var $r,pp,dp,mp,fp,Rb=E(()=>{"use strict";Ge();cp();zn();B();$();Lt();up();we();Eb();Oa();$r=P("worker-appium"),pp=class extends Error{},dp=class extends Error{},mp=class extends Error{},fp=class extends Nt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ds(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 S;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await Sb(o);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:A}=await Et.getMobileAppDataByAppId({appId:f,projectId:l,token:m});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:v,version:b},w]=await Promise.all([this.getAppStateFromDevice(o,a,T),vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if($r.info("device status and app state",{deviceStatus:w,appInstalled:v,version:b,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&y&&(await this.installApp(o,a,y),$r.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:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},D=mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),V={capabilities:{udid:a,...D}};$r.info("requesting new appium session from TMA",{tmaSessionSettings:V,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,V,g);this.sessionData=x;let R=await d.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),$r.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(A){throw $r.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new mp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await $t(n);await Xs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new dp(l,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new pp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw $r.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw $r.error("failed to run test once",{err:l}),l}}}});var Ab={};z(Ab,{WorkerAppium:()=>gp});var xb,Wr,gp,Cb=E(()=>{"use strict";B();cp();xb=require("linkedom");zn();$();Lt();up();we();Oa();ae();fs();Wr=P("worker-appium"),gp=class extends Nt{initPlayer(t){return new Ds(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await Et.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),m=o==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,executionName:t.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:d,appPath:l,androidActivityWait:m,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Et.lockDevice(i,this.options.deviceUdid),h=await db(f)):h=await pb({...f,shouldRunInEnhancedMode:a}),Wr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:fb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await Et.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Wr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Wr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Wr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Hf(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Wr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let m;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:v,port:b,path:w}=await Et.getHeadSpinDeviceConnection(this.options.gridData,y);m=`${T}://${v}:${b}${w}`}else m=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(m,this.activeSession.sessionId,xb.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((v,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:v,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Wr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),l,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw Wr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ba,Pb=E(()=>{"use strict";B();Bn();Y();Ba=class{constructor(e){this.id=e;this.driver=new Or}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function kb(){let s=await Promise.any(dI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var dI,ja,$a=E(()=>{"use strict";Ge();dI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];ja=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Ob,Wa,_b=E(()=>{"use strict";Ob=I(require("ws"));B();$a();Wa=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=ja({timeout:e}),r=new Ob.default(this._cdpUrl,t),n=Qt(o=>{r.once("open",o)}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ga,hp,Va,Lb=E(()=>{"use strict";B();Ga=I(require("chrome-launcher"));Lo();_b();Pn();hp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Wa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}=e,d=_o({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}),u=[...((h=d.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=d.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ga.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await Ga.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 wr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),gs(()=>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}},Va=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new hp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var yp={};z(yp,{WorkerExtension:()=>ni});function mI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Db(s){return mI(s)?s:new Error(s)}var et,ni,Ha=E(()=>{"use strict";$e();Y();zn();B();$();Lt();ae();Pb();Lb();lt();et=P("worker-ext"),ni=class extends Nt{initPlayer(){return this.options.useChromeLauncher?new Va(this.id):new Ba(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw et.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Zi(),initializedFromCache:eo(),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;F("WorkerExtension runTestOnce");let o=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(m.cdpTestRunner),d,Ae.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return et.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let f=await m.url(d);return u.driverUrlFinished=!0,f}catch(f){throw et.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:d,urlLength:d.length}),f}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(F("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.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(y){throw et.warn("failed to run test via CDP",{err:y}),y}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let v=function(w){e.onCompletedCleanup(),et.warn("on browser closed error detected",{err:w,testResultId:r,executionId:n,testId:i}),d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),w.type=Xr.BROWSER_CLOSED,T.abort(w)},b=function(w){d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),et.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:n,testId:i}),w.type=Xr.KEEP_ALIVE_FAILED,T.abort(w)};var f=v,h=b;let y=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ce))throw w;et.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let T=new AbortController;d.registerToClosedBrowser(v),d.registerToKeepAliveFailed(b);try{let w=le(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),S=await xc(w,T.signal);d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(V){et.error("Could not update the grid about the test status",{err:V})}d.isAlive()||(et.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let A=d.maxKeepAliveGap();return A>=3e4&&(et.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=A),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw et.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:n,testId:i}),Db(w)}finally{d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b)}}catch(y){throw et.warn("failed to start url",{err:y}),Db(y)}};t.driver.start();try{return await super.runTestOnce(e,t),F("WorkerExtension super.runTestOnce"),await l()}catch(m){throw et.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Tp={};z(Tp,{WorkerExtensionSingleBrowser:()=>bp});var fI,gI,bp,wp=E(()=>{"use strict";$e();B();$();Bu();Lt();Ha();fI=P("base-worker"),gI=500,bp=class extends ni{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await qn(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()&&(fI.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;F("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 pe(gI)}}});var vp,qa,Nb=E(()=>{"use strict";Bn();oe();$e();Cl();lt();wu();Y();$();ae();Rh();Go();vp=P("worker-manager"),qa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(sp(),rp))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerLocalTma:(await Promise.resolve().then(()=>(Cb(),Ab))).WorkerAppium;default:return jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension}else switch(r){case(Nr.find(n=>n===r)&&jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser;case Nr.find(n=>n===r):return(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension;case Hn.find(n=>n===r):return(await Promise.resolve().then(()=>(sp(),rp))).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 F("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{F("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,m=0,d=(u,f)=>new Promise(h=>{var ie,Ie,It,Gr,k,N,j,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vo(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",v=(Ie=i.company)==null?void 0:Ie.companyId,b=(It=i.company)==null?void 0:It.name,w=i.source||"cli",S=i.user,A=(Gr=i.company)==null?void 0:Gr.planType,D=(k=i.company)==null?void 0:k.isStartUp,V=(N=i.projectData)==null?void 0:N.name,x=(j=i.projectData)==null?void 0:j.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(_e,Rt,ve,uc,li,pc)=>(m++,Cf({executionId:r,projectId:g,testId:Rt,resultId:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,isStartUp:D,projectType:x,appSource:pc,gridType:L}),t.testStartAndReport(_e,r,ve,uc,li)),G=async(_e,Rt,ve,uc,li,pc)=>{var gd,hd,yd;m--;let tt={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(tt.gridName=i.grid||((gd=i.gridData)==null?void 0:gd.name),tt.gridType=(hd=i.gridData)==null?void 0:hd.type,tt.gridProvider=(yd=i.gridData)==null?void 0:yd.provider):i.localTmaUrl?(tt.gridName="local-tma-from-options",tt.gridType="local-tma"):i.useLocalChromeDriver?(tt.gridName="local-chrome-driver-from-options",tt.gridType="local-chrome"):i.useChromeLauncher?(tt.gridName="chrome-launcher-from-options",tt.gridType="local-chrome"):i.browserstack?tt.gridName="browserstack-from-options":i.saucelabs&&(tt.gridName="saucelabs-from-options"),await t.testEndAndReport(_e,ve,r,uc,li,tt).catch(JT=>vp.error("testEndAndReport threw an error",{err:JT})),li)return;this.combinedTestResults[ve.resultId]=ve,Pf({executionId:r,projectId:g,testId:Rt,resultId:ve.resultId,result:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,logger:vp,isStartUp:D,projectType:x,appSource:pc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},W=(_e,Rt)=>{this.combinedTestResults[Rt.resultId]=Rt,t.onTestIgnored(_e,Rt.resultId),m--,(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},q=(_e,Rt)=>t.onGridSlot(_e,Rt);for(i.userData={loginData:{...Ir(),refreshToken:Yi(),authData:Ir(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},F("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,G,q,W)});try{let u=await Ot(),f=await Qi(),h=await d(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new Xt;return h}catch(u){throw vp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var ii,Mb,za,Sp,Ep,Vr,Ip=E(()=>{"use strict";ii=I(require("lodash"));B();$();oe();ae();$e();cs();Al();Cl();ge();Mb=require("uuid");_f();B();Lt();hg();Y();Nb();de();Go();({CLI_MODE:za}=Wt),Sp=P("test-plan-runner"),Ep=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Ep._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},m=new qa(this.customExtensionLocalLocation),d=async()=>{let g=i.beforeParallel||1,y=!0,T=await m.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=vi||i.parallel,y=!1;F("right before this.workerManager.runTests");let T=await m.runTests(t,c,o,a,i,n,g,y);F("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await m.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};kf({executionId:o,projectId:i.project}),F("right before runBeforeTests");try{return await d(),F("right before runTestPlanTests"),await u(),F("right after runTestPlanTests"),await f(),l}catch(g){if(Sp.error("error running test plan",{err:g}),g instanceof Xt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,v,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===za.SELENIUM){let[{getSessionPlayer:w},{makeSDK:S}]=await Promise.all([Promise.resolve().then(()=>(we(),ir)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=w();await A.closeBatch(o,S);return}let g;try{if(!((b=(v=(T=i.company)==null?void 0:T.activePlan)==null?void 0:v.premiumFeatures)!=null&&b.applitools)||(g=await Cp(i.project),ii.default.isEmpty(g)||!o))return;let{runKey:w,url:S}=g,A=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),D=1e4;await le(A.closeBatches({settings:{batchIds:[o],serverUrl:S,apiKey:w}}),D)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,w,S;let l=re(),m=n.project;Jd(l),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new Eo(d,n,o,a),f=ii.default.chain(d).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?[]:d.map(A=>A.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,i,g);F("before testListInfoPromise");let T=await y;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),F("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return F("before executionEnd"),await u.executionEnd(l),F("after executionEnd"),{results:v,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ue.colorString(ue.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Rp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await xp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Sp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(m){return ii.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async m=>{let d=await oi(o,e.testPlan,[m],t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})}),await se(e.testPlan,async m=>{let d=await oi(o,[m],e.testPlanIds,t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})})):a=await oi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==za.APPIUM&&await Fu(e,r(l)),await se(c,async m=>{var h;let d=m.testPlanId;n[d]={};let u={...e};u.baseUrl||=m.startUrl,u.appId||=((h=m.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await hf(e,m);let f=u.overrideExecutionName||m.name;return await se(l[d],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,d,t);Q.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let T=Object.keys(n[d]).map(S=>({executionId:S,status:Mu(n[d][S])})),v=Object.keys(n[d]).map(S=>n[d][S]).reduce((S,A)=>Object.assign(S,A),{}),b=Mu(v);Object.assign(i,v);let w=b?T[0].executionId:T.find(S=>!S.status).executionId;return await Ap(o,d,{success:b,executions:T,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var c;Sp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),F("before getSuite");let r=await Ah(e,t);if(F("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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;F("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===za.APPIUM&&(a=await ri({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(d=>{"nativeApp"in d&&(d.nativeApp=a)}),e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==za.APPIUM&&await Fu(e,l),F("right before runTestPlan");let m=await this.runTestPlan([],l,[],e,i,null,t,o);return F("right after runTestPlan"),await Q.onTestPlanFinished(m.results,i,this.startTime,m.executionId,o),m})}async run(e){let t=vn(),r=[];await this.reportTestRunnerStarted(e.project,e),en(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ii.default.flattenDeep(r);return F("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),F("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Vr=Ep;Vr._id=(0,Mb.v4)()});var Ce={};z(Ce,{addTestRetry:()=>au,clearTestResult:()=>Du,deleteCloudflareTunnel:()=>Mp,fetchLambdatestConfig:()=>uu,fixGridAppIDStructure:()=>op,forceUpdateCloudflareTunnelRoutes:()=>Np,getAllGrids:()=>xl,getAppDetails:()=>ri,getApplitoolsIntegrationData:()=>Cp,getBrowserStackSessionMetaData:()=>RI,getCloudflareTunnel:()=>Dp,getEditorUrl:()=>SI,getGridSlot:()=>Rl,getHybridGridProvider:()=>Il,getLabFeaturesByProjectId:()=>vu,getMobileDevicesFromGrid:()=>si,getRealData:()=>eu,getS3Artifact:()=>_n,getS3ArtifactText:()=>Zl,getSuiteTestList:()=>Uu,getTestPlan:()=>vI,getTestPlanTestList:()=>oi,getTestResults:()=>Dr,getUsageForCurrentBillingPeriod:()=>_p,initializeUserWithAuth:()=>Lp,isTestResultCompleted:()=>Lu,keepAliveCompanySlots:()=>Yl,keepAliveGrid:()=>Sl,loadSfdcCredential:()=>Op,loadTest:()=>Vn,releaseCompanySlot:()=>Jl,releaseGridSlot:()=>El,reportExecutionFinished:()=>Io,reportExecutionStarted:()=>ou,reportRunnerFinished:()=>xp,reportRunnerStarted:()=>Rp,requestCompanySlot:()=>Kl,saveRemoteStep:()=>Eu,saveTestPlanResult:()=>Ap,updateCompanySlot:()=>Xl,updateExecutionTests:()=>iu,updateRemoteRunFailure:()=>Fp,updateTestDataArtifact:()=>Ro,updateTestResult:()=>Jo,updateTestStatus:()=>Cr,uploadAppToGrid:()=>ip,uploadRunDataArtifact:()=>Nu,validateUserAccessKey:()=>wl});async function Ns(){let s=await Ot();if(!s)throw new Error("Failed to get token from server");return{[Vc]:Vr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Ns(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function TI(s,e,t,r={},n=void 0){let i=await Ns(),o={...r,...i};return await Xs(`${he()}${s||""}`,e,t,o,n)}async function ai(s,e){let t=await Ns();return await Oc(`${he()}${s||""}`,e,t)}async function Ub(s,e){let t=await Ns();return await Js(`${he()}${s||""}`,e,t)}async function wI(s,e){let t=await Ns();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function ke(s,e,t,r){let n=await Ns();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function _n(s,e){return(0,ee.default)(()=>ke(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Zl(s){return(0,ee.default)(()=>wI(`/storage${s}`))}async function Rp(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function xp(s){return await Ub("/test-runner",{projectId:s})}async function vI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>ke("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Op({branch:s,projectId:e}){let t=await(0,ee.default)(()=>ke(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Vn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>ke(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function Ap(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Cr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ai("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:hI,...i}),{retries:o,factor:1})}function iu(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ai("/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 ou({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:m}){let{isCi:d}=await Promise.resolve().then(()=>(no(),Rf));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:m,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function Io(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ai("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function oi(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Uu({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}}),{retries:te,factor:1})}async function ri({appId:s,projectId:e}){try{return await(0,ee.default)(()=>ke(`/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 _p(s){try{return await(0,ee.default)(()=>ke(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Mt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Lu(s,e,t){return(0,ee.default)(()=>ke(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Dr(s,e,t,r){return(0,ee.default)(()=>ke(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function Sl(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function El(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Il(s){return Re({url:"/grid/hybrid/provider",body:s})}function Rl(s){return(0,ee.default)(()=>ke("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Lp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m}){var d,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Mt.error("error initializing info from server",f),(d=f.message)!=null&&d.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(Pp.default[y](Pp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Mt.error("Error parsing error message from server",f)}throw f}}async function SI(){if(rt)return{editorUrl:rt};try{return await(0,ee.default)(()=>ke("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Mt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function xl(s){return(0,ee.default)(()=>ke("/grid",{companyId:s}),{retries:te,factor:1})}function eu(s,e,t){return(0,ee.default)(()=>ke(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Jo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Du(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Eu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function EI(s){return s.startsWith("/")?s:`/${s}`}function II(s,e,t){let r=EI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Bb(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=II(c,bI,s),m=Buffer.from(Fb.gzip(r,{level:3})),d={file:{fileName:a,buffer:m}};return await(0,ee.default)(()=>TI(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function au({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Cp(s){try{return await ke(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Mt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Dp(s,e){try{return await ai("/tunnel",{companyId:s,routes:e})}catch(t){return Mt.warn("could'nt get tunnel.",{err:t}),{}}}async function Np(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}async function Mp(s,e){try{return await Ub(`/tunnel/${e}`,{companyId:s})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}function Fp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function si({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${yI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>ke(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Mt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function ip({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function op(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Kl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Jl(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Xl(s,e,t){return(0,ee.default)(()=>ai("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Yl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function RI(s,e){return await Te(`${Vs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function wl(s){try{return await ke("/v2/project/validateUserAccessKey",s),!0}catch(e){return Mt.error("error validating user access key",{error:e}),!1}}var Pp,ur,Fb,ee,kp,hI,Mt,te,yI,bI,uu,vu,Nu,Ro,ge=E(()=>{"use strict";Pp=I(require("chalk")),ur=I(require("lodash")),Fb=I(require("pako"));B();oe();ae();Ge();lt();ee=I(require("p-retry")),kp=I(require("object-hash"));Y();$();Ip();hI=st(),Mt=P("testim service api"),te=3,yI="/grid",bI="test-result-artifacts";uu=async s=>(0,ee.default)(()=>ke("/grid/lt/config",{companyId:s}),{retries:te,factor:1}),vu=async s=>(0,ee.default)(()=>ke(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Nu=ur.memoize(async(s,e,t,r)=>{if(!ur.isEmpty(r))return await Bb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`),Ro=ur.memoize(async(s,e,t,r,n)=>!r||ur.isEmpty(r)?void 0:await Bb(s,e,t,JSON.stringify((()=>{let o=ur.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:jc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`)});function Ka(){return st()}var Up=E(()=>{"use strict";B()});function CI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(ir)).getSessionPlayer()}catch{}})}function PI(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(Bp.default[i](Bp.default[n](r.text)))})}function kI(s,e){let{serviceUrl:t}=s;Gs(t),kt(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:t})(),Ut.setRegion(Tg[bs(e)])}async function ci(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,m=Boolean(n==null?void 0:n.general),d=Boolean(i||o),u=m?AI:xI,f=Ka(),h=Fc(),g=await Vm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!d)try{y=await kb()}catch(b){jb.error("failed to get public ip",b)}let T=!0;F("before initializeUserWithAuth");let v=await kt(async()=>(CI(a),T=!1,await Lp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:d,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:m,localGrid:d,gridId:c,grid:l,publicIp:y})();return PI(v),kI(v.clientConfig,e),s.publicIps=[v.clientPublicIp],F("after initializeUserWithAuth"),y&&v.clientPublicIp&&v.clientPublicIp!==y&&(jb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:v.clientPublicIp}),s.publicIps.push(y)),uf(v.authData,{projectId:e,token:t,userAccessKey:r,publicIp:v.clientPublicIp,initializedFromCache:T}),v}var Bp,jb,xI,AI,$b=E(()=>{"use strict";Bp=I(require("chalk"));$e();ge();er();lt();$a();ae();$();de();Up();B();os();oe();Ao();jb=P("initializeUserWithAuth"),xI=1e3*60*5,AI=1e3*60*60*10});async function Gb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Xi():s.chromeBinaryLocation,e=ln({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==K.EXTENSION&&await Sr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await ul(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await ll(s.installCustomExtension,n)}return await e,t}async function Hb(s){var o;OI.info("prepare MockNetwork",{location:s});let e=await Nc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Wb*1e6)throw new Error(`${jp} exceeded ${Wb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${jp} cannot be parsed.${Ja.EOL}${a}`)}let n=new Vb.default;if(!n.validate(Yc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Ja.EOL);throw new Error(`${jp} is malformed.${Ja.EOL}${a}`)}return r.entries}var Ja,Vb,Wb,jp,OI,$p=E(()=>{"use strict";Ja=I(require("node:os"));B();Sm();pn();Vb=I(require("ajv"));ae();fl();$();$b();Wb=1,jp="JSON file supplied to --mock-network-pattern",OI=P("prepare runner")});function Xb(s){return s.start&&ls(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Yb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=xo(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 Qb=E(()=>{"use strict";Dn();us();Y()});var Ms,Hp,Zb=E(()=>{"use strict";Ms="SECRETS",Hp={get secretsKey(){return Ms},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ms}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ms]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ms):JSON.stringify(s).includes(Ms)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ms}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let m=l[1];o[c]=e[m]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let m=l[1];o[a]=e[m]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Xp={};z(Xp,{doLogin:()=>Jp,getProjectId:()=>FI,getToken:()=>UI});async function FI(){return rT("projectId")}async function UI(){return rT("token")}function tT(s,e){return Promise.race([s,pe(e).then(()=>{throw new ce("timeout")})])}async function BI(){let s=(await import("express")).default(),e=async function(){return tT(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(),Ce)),{editorUrl:n}=await r();ho(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${rt||gr}`)}return await e}async function Jp({overwriteExisting:s=!0,projects:e=null}={}){let t=qp.homedir(),r=zp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await tT(BI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await eT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(m=>({title:m.name,value:m}))});i.token=l.project.ci.token,i.projectId=l.project.id,await eT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function eT(s,e){await Kp.promises.writeFile(s,Ya.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function rT(s){let e=qp.homedir(),t=zp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ya.parse((await Kp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var qp,zp,Ya,Kp,Qa=E(()=>{"use strict";qp=I(require("os")),zp=I(require("path")),Ya=I(require("yaml"));B();Kp=require("fs");Y();Gl();oe()});var pT={};z(pT,{process:()=>KI,program:()=>p});var Qp,aT,Za,cT,Kt,Fe,lT,jI,Me,ed,$I,WI,nT,uT,VI,Zp,ec,td,Yp,Ft,iT,GI,HI,p,qI,zI,oT,KI,rd=E(()=>{"use strict";Qp=I(require("ms")),aT=I(require("chalk")),Za=I(require("node:fs")),cT=I(require("node:url")),Kt=I(require("lodash")),Fe=I(require("node:path"));B();Dn();Qb();er();lT=require("commander");ae();Y();Hr();B();de();Zb();Go();Ao();oe();jI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),ed=new lT.Command,$I=s=>s.split(","),WI=(s,e)=>!s||s.length===0?e:s,nT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],uT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function m(g){return g.includes("--high-speed")}function d(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")}ed.help(g=>g.split(`
404
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,m);return}let d=await Dy(m,this.uploadFile);await this.uploadFilesAndForceVisibility(d,t)}}});var wa,va,Fy=E(()=>{"use strict";wa=require("url");me();va=class extends H{async updateBaseUrl(e){let t=new wa.URL(e),r=new wa.URL(this.context.recordedBaseUrl),n=new wa.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 Sa,Uy=E(()=>{"use strict";me();B();Sa=class extends H{async performAction(){await pe(this.step.durationMS||0)}}});var Ea,By=E(()=>{"use strict";me();Ea=class extends H{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Zn,jy=E(()=>{"use strict";me();Zn=class extends H{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let i=await this.driver.executeCodeAsync(r,t,e);return(i==null?void 0:i.value)||{}}catch(i){throw(n=i==null?void 0:i.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):i}}runApiInBg(e){let{apiCall:t}=this.sessionPlayerInit;return t(e)}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},i=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),o=i.result||{},a={method:t.method,status:o.status,url:t.url};return i.success?o.status===0?{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:o,resultInfo:a,shouldRetry:!1,success:!0}:{result:o,resultInfo:a,shouldRetry:!1,success:!1,reason:o.error||e.error.REQUEST_TIMED_OUT,errorType:o.exception?void 0:o.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ia,$y=E(()=>{"use strict";me();Ia=class extends H{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var Wy,Ju,Xu,Vy=E(()=>{"use strict";Wy=I(require("@applitools/spec-driver-webdriverio"));bi();we();Ju=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=vd["@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:Wy.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}},Xu=new Ju});var Hy,Gy,ei,qy=E(()=>{"use strict";Hy=I(require("lodash"));me();$();Vy();Gy=P("pixel-validation-step-action"),ei=class extends H{async performAction(){var d,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:i}=this.context;this.runContext=this.context.getRunContext(void 0);let o=((d=this.runContext.incomingParams)==null?void 0:d.final)||{},a=((u=r.batch)==null?void 0:u.id)||i,c=await Xu.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),l=this.getTarget()||{},m;try{let f=await c.openEyes({driver:this.driver.client,config:r,logger:n}),g={region:this.step.action==="element"&&l.seleniumElement||void 0,fully:this.step.action==="stitched"};Hy.isPlainObject(o.applitoolsStepSettings)&&(Object.assign(g,o.applitoolsStepSettings),Gy.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:o.applitoolsStepSettings})),await f.check({settings:g}),m={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){Gy.error("Applitools SDK step failed",{err:f,info:f.info}),m={isApplitoolsSdkResult:!0,success:!1,err:f}}return await Xu.handleApplitoolsSdkResult(this.context,m,this.step)}}});var Os,Yu=E(()=>{"use strict";Rs();Y();ua();Os=class extends cr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:i="",id:o=""}=e,{incomingParams:a,testResultId:c,retryIndex:l,stepResultId:m}=t,d={config:t.config,data:t.data},u=t.data.timeToPlayStep,f=await Is(i,o,a,d,c,l,m,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ce?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var lr,zy=E(()=>{"use strict";Yu();lr=class extends Os{isFailedResult(e){return e===!1}}});var Ra,Ky=E(()=>{"use strict";Yu();Ra=class extends Os{isFailedResult(e){return!e}}});var xa,Jy=E(()=>{"use strict";Rs();me();Y();xa=class extends H{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:i,timeToPlayBeforeExec:o}=this.context;try{return{data:await Es(e,r,n,t,i,o),success:!0}}catch(a){return a instanceof Ct?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ce?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Ur,Xy=E(()=>{"use strict";me();Ur=class extends H{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var be,Yy=E(()=>{"use strict";me();be=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let i=this.context.sfdcTestActions;if(i===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,i,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Aa,Qy=E(()=>{"use strict";me();Aa=class extends H{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((i,o)=>this.context.playback.sfdcAddLog(i,o)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(i){return{success:!1,reason:i.reason||i.message,exception:i,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ca,Zy=E(()=>{"use strict";me();Ca=class extends H{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function jE(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Pa(s,e){jE($E,e),e.registerLocateStepActionUtils(Jn.getUtils(s))}var $E,Qu=E(()=>{"use strict";Jh();Qh();ay();cy();uy();my();hy();yy();by();Ty();Sy();Ey();Iy();Ay();ky();My();Fy();Uy();By();jy();$y();qy();zy();Ky();Jy();Xy();Yy();Qy();Zy();$E={locate:Jn,scroll:ia,mouse:oa,submit:fa,text:ca,"special-key":pa,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":ks,"skip-code-step":ks,"element-code-step":ks,"evaluate-expression":aa,"text-validation":Yn,"wait-for-text-validation":Yn,"select-option":ma,"drop-file":ya,"input-file":Ta,hover:ga,navigation:va,wheel:ha,sleep:Sa,refresh:Ea,"keyboard-shortcut-step":da,"api-validation":Zn,"api-action":Zn,"api-code-step":zt,"extract-text":Ia,"simple-ui-verification":ei,"wait-for-simple-ui-verification":ei,"cli-validation-download-file":Ur,"cli-wait-for-download-file":Ur,"network-validation-step":Ur,"cli-validation-code-step":lr,"cli-wait-for-code-step":lr,"cli-action-code-step":lr,"cli-api-code-step":lr,"cli-condition-step":Ra,"node-package":xa,"email-code-step":zt,"cli-email-code-step":lr,"sfdc-internal-test-step":Ca,"sfdc-recorded-step":Aa,"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":Ur,"sfdc-step-flow-screen-completion":be,"sfdc-step-sobjectverifyoptions":be}});var eb,WE,_s,Zu=E(()=>{"use strict";eb=["simple-ui-verification","wait-for-simple-ui-verification"],WE=[...eb,"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"],_s=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=WE.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 eb.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 rb={};z(rb,{SeleniumTestPlayer:()=>ti});var tb,VE,ti,ep=E(()=>{"use strict";B();tb=require("@applitools/eyes-sdk-core");Bn();Y();$();Vu();Gh();zu();sa();zh();Ku();we();Qu();Zu();oe();VE=P("SeleniumTestPlayer"),ti=class{constructor(e,t,r,n,i=void 0,o=void 0){this.id=e;this.playbackTimeoutCalculator=new _s(na());let{SessionPlayer:a,commonConstants:c,StepActionFactory:l}=Z();this.driver=n??new Or;let m=new ra(this.driver);this.stepActionFactory=new l(m),Pa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new ea(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let d=qh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new Ps(this.driver),FrameLocator:d,portSelector:ta,LocateElementPlayer:null,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:tb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await le((r=this.driver)==null?void 0:r.end(),t)}catch(i){i instanceof ce&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){VE.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),i=[new URL(tt||gr).hostname].concat(r);for(let o of n.reverse()){await this.tabService.addNewTab(this.id,o,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,o);if(i.some(c=>a.url.includes(c))){this.tabService.removeTabInfo(this.id,o);continue}await this.sessionPlayer.addPlaybackFrameHandler(o,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let o=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,o);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var rp={};z(rp,{WorkerSelenium:()=>tp});function HE(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>F(`Got event ${t}`))}var ka,GE,tp,sp=E(()=>{"use strict";B();$e();zn();$();Lt();Fo();ae();$u();Y();ep();we();ct();ka=P("worker-selenium"),GE=1e9,tp=class extends Nt{initPlayer(t){return new ti(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){F("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:o}=n;this.windowUtils=new Cs(this.id,o),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,c=t.baseUrl;try{let l=this.options.useLocalChromeDriver;await o.init({projectData:this.options.projectData,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:i,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:l,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.SELENIUM}),F("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:l}),F("in WorkerSelenium after addTab"),l||await this.windowUtils.navigate(c,GE),await this.windowUtils.validatePageIsAvailable(),F("in WorkerSelenium after navigate")}catch(l){let m=l.message&&(l.message.startsWith("Malformed URL")||l.message.includes("Reached error page: about:neterror"))&&a==="firefox",d=l.message&&l.message==="invalid argument";throw l instanceof At||m||d?new At(`Page '${c}' is not available`):(ka.error("failed to navigate to page",{baseUrl:c,err:l,whitelistedPublicIp:Zi(),initializedFromCache:eo()}),l)}}async runTestOnce(t,r){var d;let{manifestVersion:n,localAssetService:i}=Z(),{driver:o,sessionPlayer:a}=r,c=n||"runner";Q.onWaitToTestComplete(this.id),HE(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===K.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),i.initialize({serverUrl:this.options.localRCASaver});let l=null;(d=this.options.lightweightMode)!=null&&d.preloadTests&&(l=(await Wn(this.options))[this.testId]);let m=async()=>le(new Promise((u,f)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:l}).catch(f)}),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ce&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await i.drain(),u.stepsResults=null,u.resultId=this.testResultId,o.isAlive()||(ka.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&&(ka.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(),F("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),F("right after super.runTestOnce in workerSelenium");let u=await m();return F("right after runSeleniumTest"),u}catch(u){throw ka.error("failed to run test once",{err:u}),u}}}});var sb,nb,He,qE,zE,np,Et,Oa=E(()=>{"use strict";sb=I(require("ora")),nb=require("jimp");oe();Ge();ge();$();ae();we();de();He=P("mobile-grid-service"),qE="https://tdc.tricentis-cloud.com",zE="https://ui.headspin.io",np=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||bc}/${wc}/devices`:t===_.TESTIM_TDC?`${r||Tc}/${wc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),i=this.buildRequestBody(e,t);try{await Ve({url:r,headers:n,body:i})}catch(o){throw He.debug(`error while locking device ${t}`,{error:o}),o.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):o}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let i=await Te(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(i,e.accessToken)}catch(i){throw He.error("error while getting automation config for device",{error:i,deviceId:t}),i}}async getPCloudyAuthToken(e,t,r){let n=await Ys(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,i=new URL(n);return{hostname:i.hostname,port:Number(i.port),protocol:i.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:i,gridId:o}){var a,c,l;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let m=await si({projectId:r,projectType:n,companyId:i,gridId:o,selectors:`device_id:${e.udid}`});return((a=m==null?void 0:m[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((c=e.mobile)==null?void 0:c.version.split("-")[0])||((l=e.desired)==null?void 0:l.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let m=e.pCloudy_DeviceFullName.split("_");return`${m[0]} ${m[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n,i=!1){let{executionId:o,testId:a,testResultId:c}=e,{project:l,projectData:{type:m}={},company:{companyId:d=""}={},gridData:{gridId:u="",type:f=""}={}}=n,h=t.capabilities,g=h.platformName,y;if(f===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:v}=Z();y=v(t.capabilities,i)}else y=await this.getDeviceFromAppiumCapabilities(h,t,r,g,f,l,m,d,u,i);let T=await this.buildRemoteResultLink(n.gridData,t.sessionId,h);return await Cr(l,o,a,c,"RUNNING",{device:y,...T&&{remoteResultLink:T}}),He.info("device details updated on testResult",{testResultId:c,executionId:o,testId:a,device:y,remoteResultLink:T,gridType:f}),y}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n,i){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),a=Number(o[0]),c=Number(o[1]);return{scaleFactor:e.pixelRatio,width:a,height:c}}try{let{AppiumApi:o}=Z(),a=new o(t,r.sessionId,null,i),[c,l]=await Promise.all([a.getScreenshot(),a.getDeviceSize()]),m=Buffer.from(c,"base64"),d=await nb.Jimp.fromBuffer(m),u=d.bitmap.width,f=d.bitmap.height;return{scaleFactor:u/l.width,width:u,height:f}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,i,o,a,c,l,m){let[d,u]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n,m),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:i,projectId:o,projectType:a,companyId:c,gridId:l})]),f=this.getOsVersion(e,i);return{name:u??"",model:e.deviceModel,udid:e.udid,osVersion:f,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Vs}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?zE:qE}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e,t){let n=(await Te(`${e}/api/devices`)).find(i=>i.udid===t);if(!n)throw new Error(`device ${t} not found`);return{udid:n.udid,name:n.name,model:n.model,height:n.height,width:n.width,geo:"local",osVersion:n.osVersion,osType:n.deviceType.toLowerCase(),scaleFactor:n.scaleFactor??0,isVirtual:n.virtual??!1,minApiVersion:n.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:i,testResultId:o}=r,{project:a,localTmaUrl:c}=t,l=await this.getTmaDeviceDetails(c,e);return await Cr(a,n,i,o,"RUNNING",{device:l}),He.info("device details updated on testResult",{testResultId:o,executionId:n,testId:i,device:l}),l}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,i=t.mobileApp,o=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:i,gridHost:e.host});return o?(O.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:o,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await op({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 ri({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/(Nd*60))+1)*60*1e3,Math.max(Dd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:i}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[i].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let c=r||t.mobileApp,l=(0,sb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let m=await ip({projectId:e,gridId:n,app:c,timeout:this.calculateUploadRequestTimeOut(c.fileSize)});return l.succeed(`app uploaded successfully to ${a}`),m.gridAppId}catch(m){throw l.fail(`failed to upload app to ${a}`),He.error(`failed to upload app to ${a}`,{error:m,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:i,mobileAppId:o}){let a=t.get(o);if(a!=null&&a.isUploaded)return a.uploadedAppId;let c=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:i});return t.set(o,{isUploaded:!0,uploadedAppId:c}),c}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",i,{executionId:o,testResultId:a}=e,{appId:c="",project:l,authData:{token:m=""}={},gridData:d={}}=t,{gridId:u="",type:f=""}=d;if(!c&&e.isAppFromDevice)return n;if(c){He.info("getting appData by appId",{appId:c,projectId:l,testResultId:a,executionId:o});let T=await this.getMobileAppDataByAppId({appId:c,projectId:l,token:m});n=T.appUrl,i=T.mobileApp,e.nativeApp=i}else He.info("no appId setting appPath from app associated with the test",{projectId:l,testResultId:a,executionId:o}),n=e.downloadableAppPublicLink||"";let h=c||e.mobileApp.appId,g=await this.getGridAppId({projectId:l,gridData:d,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,v=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:d,projectType:T});v&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=g),!v&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:l,testResultId:a,executionId:o,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),!v&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:l,testResultId:a,executionId:o})}return!g&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:l,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var m,d;let{accessToken:n,user:i,host:o,key:a,type:c,apiUrl:l}=t;if(c===_.BROWSERSTACK){let u=`${Vs}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(c===_.SAUCELABS){let u=`https://${o==null?void 0:o.replace("ondemand","api")}/v1/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:i,key:a})).items.some(h=>h.id===e)}if(c===_.TESTIM_HEADSPIN||c===_.TESTIM_TDC){let u=`${l}/${vc}/apps`;return l||(u=`${c===_.TESTIM_HEADSPIN?bc:Tc}/${vc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(c===_.TESTIM_TVC){let u=`${Md}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(c===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(o,i,a),f=`https://${o}/api/drive`,h=await kc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(d=(m=JSON.parse(h).result)==null?void 0:m.files)==null?void 0:d.some(y=>y.file===e)}throw new Error(`grid type ${c} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let i={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await Te(e,void 0,i)}},Et=new np});function ib({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!KE.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function JE({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function XE(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,i=[{executionId:t},{testResultId:r}];return e&&i.push({testName:e}),n&&i.push({customTag:n}),i}function YE(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:i}=e,o=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,c=o?"tdc":"headspin",l=a&&O.flags.enableBatchHeadSpin.isEnabled(),m=o&&(O.flags.enableBatchTDC.isEnabled()||O.flags.headSpinTdcEnableFlagCapability.isEnabled()),d=O.flags.increaseTDCRequestTimeout.isEnabled();return{[`${c}:capture.video`]:!0,...O.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${c}:capture.network`]:!1},...i&&{[`${c}:controlLock`]:!0},[`${c}:retryNewSessionFailure`]:!1,[`${c}:sessionTags`]:XE(t),[`${c}:enableBatch`]:l||m,...!r&&{"appium:noReset":n},...d&&{[`${c}:newCommandTimeout`]:600,"appium:newCommandTimeout":600}}}function _a(s){return"id"in s?s.id:s.packageName}function QE(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function ZE({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:i}){let{fullReset:o,setNoReset:a}=t,c={"appium:app":n},l=n==null?void 0:n.startsWith("http");n&&!l&&(c=QE(n,t.gridData.type));let d=()=>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":d(),...r&&{"appium:bundleId":_a(r)},...n&&c};case"android":return{...e,platformName:"Android","appium:fullReset":!!o,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...i&&{"appium:appWaitActivity":`${i}, *`},...r&&{"appium:appPackage":_a(r),"appium:appActivity":r.activity??".*"},...n&&c};default:throw Error(`unsupported mobile project ${s}`)}}function jr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:i="",shouldRunInEnhancedMode:o}){switch(s){case"ios":return{platformName:"iOS",[`${i}autoAcceptAlerts`]:!0,[`${i}automationName`]:o?"WaldoTestim":"XCUITest",[`${i}fullReset`]:!0,...t&&{[`${i}bundleId`]:_a(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`]:_a(t),[`${i}appActivity`]:t.activity??".*"},...r&&{[`${i}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function ob({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:i,gridInfo:o,shouldRunInEnhancedMode:a}){let c=YE(o.type,i,n);return ZE({projectType:s,sessionCaps:c,options:i,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:a})}function Da({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 Na({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:i}=e,o=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?o?n.deviceUdid:n.deviceName:i!=null&&i.deviceNameRegex?t==="android"&&i.deviceNameRegex===".*"&&o?Sc:i.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":o?t==="ios"?"apple":Sc:".*")}function eI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function tI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...La(s,Ls)}}function ab(s,e,t){return s?Object.entries(s).reduce((r,[n,i])=>{if(e(n)){if(!t)return r[n]=i,r;let o=n.replace(t,"");r[o]=i}return r},{}):{}}function rI(s){return ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function sI(s){return ab(s,e=>!e.startsWith("browserstack."))}function cb(s){return!s||!lb(s)?"2.0.0":s}function lb(s){return s.split(".")[0]==="2"||s.includes("appium2")||["latest","stable"].includes(s)}function ub({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,i=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,o=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&i.test(s),c=e==="android"&&(n.test(s)||a),l=e==="ios"&&o.test(s),m=c||l;if(t){let d=lb(t);return!d&&m?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):d}return m}function La(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let i=`${e}${r}`;t[i]=n}),t}async function nI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a,shouldRunInEnhancedMode:c}){let{osVersion:l,deviceName:m}=n,d=(a==null?void 0:a.mobile)||{},{type:u}=i,f=eI(i,s),h=await si({gridId:i.gridId,projectType:s,projectId:n.project,companyId:n.company.companyId}),g=h==null?void 0:h.find(({udid:w})=>{var S;return((S=d.staticAllocation)==null?void 0:S.deviceUdid)===w}),y=(g==null?void 0:g.osVersion)??Da({osVersion:l,mobileConfig:d}),T=(g==null?void 0:g.name)??Na({deviceName:m,mobileConfig:d,projectType:s,gridType:u}),v=ze(n.editorUrl,n.project,o.testId,o.testResultId,o.branch),b={device:T,os_version:y,"waldo:displayName":`${o.testName}-${o.executionId}-${o.testResultId}`,"waldo:externalUrl":v,...c&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:f}};return jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,shouldRunInEnhancedMode:c})}function iI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{user:d,key:u,type:f}=i,h=O.flags.enableAppium2pCloudy.isEnabled(),g=Da({osVersion:c,mobileConfig:m}),y=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),v={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:d,pCloudy_ApiKey:u,pCloudy_Individual:o.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...v,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Fd),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=tI(b)),t="",jr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Ls}})}function oI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:i,sessionTags:o,testRunConfig:a}){let{osVersion:c,deviceName:l}=n,m=(a==null?void 0:a.mobile)||{},{type:d}=i,u=Da({osVersion:c,mobileConfig:m}),f=Na({deviceName:l,mobileConfig:m,projectType:s,gridType:d}),h=(0,Br.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],ub({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},v={user:i.user,key:i.key,name:o.testResultId,build:o.executionId,appiumVersion:cb(g.appiumVersion??"stable"),deviceName:f,tags:Object.values(o)},b={"appium:platformVersion":u,"appium:deviceName":f,...La(h,Ls),"sauce:options":{...T,...v,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:s,sessionCaps:b,appiumPrefix:Ls,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":i.user,"saucelabs.key":i.key,platformVersion:u,deviceName:f,tags:Object.values(o),name:o.testResultId,build:o.executionId,...h,...g};return jr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function aI({projectData:s,projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,options:i,gridInfo:o,sessionTags:a,testRunConfig:c}){let{osVersion:l,deviceName:m}=i,d=(c==null?void 0:c.mobile)||{},{type:u}=o,f=Da({osVersion:l,mobileConfig:d}),h=Na({deviceName:m,mobileConfig:d,projectType:e,gridType:u}),g=rI(i.browserstack),y=(0,Br.omit)(sI(i.browserstack),["automationName","platformName","project","build","name"]),T={buildName:`${a.executionName} - ${a.executionId}`,projectName:`${s.name} - ${s.projectId}`,sessionName:`${a.testName} - ${a.testId}`},v=O.flags.enableAppium2BrowserStack.isEnabled();if(v||ub({osVersion:y.platformVersion||f,projectType:e,isBrowserStack:!0,appiumVersion:g.appiumVersion})){let w={...T,userName:o.user,accessKey:o.key,appiumVersion:v?"2.0.1":cb(g.appiumVersion),debug:!0,networkLogs:!0},S={"appium:platformVersion":f,"appium:deviceName":h,...La(y,Ls),"bstack:options":{...w,...(0,Br.omit)(g,"appiumVersion")}};return jr({projectType:e,sessionCaps:S,appiumPrefix:Ls,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}let b={...T,os_version:y.platformVersion||f,device:y.deviceName||h,realDevice:!0,buildTags:Object.values(a).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...y,...La(g,"browserstack.")};return jr({projectType:e,sessionCaps:b,nativeAppMetadata:t,appPath:r,androidActivityWait:n})}async function cI(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return ob(s);if(_.TESTIM_TVC===s.gridInfo.type)return await nI(s);if(_.P_CLOUDY===s.gridInfo.type)return iI(s);if(_.SAUCELABS===s.gridInfo.type)return oI(s);if(_.BROWSERSTACK===s.gridInfo.type)return aI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function lI(s,e){var l,m;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:i,osVersion:o,deviceUdid:a}=s,c={};return n==="dynamic"&&(!i&&((l=r==null?void 0:r.selector)!=null&&l.manufacturer)&&(c.manufacturer=r.selector.manufacturer),!o&&((m=r==null?void 0:r.selector)!=null&&m.osVersion)&&(c.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(c.device_id=t.deviceUdid),i&&(c.manufacturer=i),o&&(c.os_version=o),a&&(c.device_id=a,delete c.os_version,delete c.manufacturer),c}async function pb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:i}=s,{selectedGrid:o}=(i==null?void 0:i.mobile)||{};if(i!=null&&i.mobile&&(o==null?void 0:o.type)!==e.type)throw Error(`selected grid type ${o.type} is not equal to grid type ${e.type}`);ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Et.getGridConnection(e),c=await cI(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let y=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",T=lI(r,i==null?void 0:i.mobile);if(!(0,Br.isEmpty)(T)){let v=Object.entries(T).map(([b,w])=>w.split(",").map(S=>S===".*"||S==="="?"":`${b}:${S}`).join(",")).join(" ").trim();c[`${y}:selector`]=v}}let l=e.type===_.TESTIM_TVC?{alwaysMatch:c}:c,m=O.flags.increaseTDCRequestTimeout.isEnabled(),d=0,u=(0,ap.default)("2m"),f=(0,ap.default)("12m"),h=br(O.flags.appiumConnectionRetryCount.getValue(),d),g=br(O.flags.appiumConnectionRequestTimeout.getValue(),u);return m&&g<f&&(g=f),{...a,desiredCapabilities:c,connectionRetryTimeout:g,capabilities:l,connectionRetryCount:h,logLevel:r.appiumLogLevel}}async function db(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:i,androidActivityWait:o,sessionTags:a,testRunConfig:c}=s,{deviceUdid:l}=n;ib({nativeAppMetadata:r,appPath:i,gridInfo:t}),JE({deviceUdid:l,gridInfo:t,testRunConfig:c});let m=l||((g=(h=c.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),d=await Et.getGridDirectConnection(t,m),f=ob({projectType:e,nativeAppMetadata:r,appPath:i,androidActivityWait:o,options:n,sessionTags:a,testRunConfig:c,gridInfo:t});return m&&(f["appium:udid"]=m),{...d,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function mb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,o=jr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete o.app,o}function fb(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 ap,Br,Ls,KE,cp=E(()=>{"use strict";ap=I(require("ms"));de();ae();Oa();Br=require("lodash");B();oe();ge();Ls="appium:",KE=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var Ma,hb=E(()=>{"use strict";Ma=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 Fa,yb=E(()=>{"use strict";B();Fa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=sn;this.getLinksFromUnescapeHTML=nn}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var lp,Ua,bb=E(()=>{"use strict";$();lp=P("mobile-frame-locator-mock"),Ua=class{foundFrameCallback(){return lp.info("foundFrameCallback-mock invoked"),{}}locate(){return lp.info("locate-mock invoked"),{}}async findFrame(){return lp.info("findFrame-mock invoked"),{}}}});var uI,wb,Tb,Ds,up=E(()=>{"use strict";uI=I(require("webdriverio")),wb=require("@applitools/eyes-sdk-core");hb();zu();$();yb();Ku();we();Qu();bb();Zu();Tb=P("appium-test-player"),Ds=class{constructor(e,t,r,n=uI,i=void 0,o=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:c,StepActionFactory:l,MobileLocateElementPlayer:m}=Z(),d=new Fa(this.driver);this.stepActionFactory=new l(d),Pa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new _s(na()),this.sessionPlayer=new a(e,{tabService:new Ma,cookieUtils:void 0,FrameLocator:Ua,portSelector:ta,LocateElementPlayer:m,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=i,this.sessionPlayer.playbackManager.previousTestResultId=o,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(c.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,i={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Tb.info("appium session deleted",{...i}))}catch(o){Tb.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 pI(s){return await Te(`${s}/api/status`)}async function vb(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Sb(s){if((await pI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Eb=E(()=>{"use strict";Ge()});var Ib={};z(Ib,{WorkerLocalTma:()=>fp});var $r,pp,dp,mp,fp,Rb=E(()=>{"use strict";Ge();cp();zn();B();$();Lt();up();we();Eb();Oa();$r=P("worker-appium"),pp=class extends Error{},dp=class extends Error{},mp=class extends Error{},fp=class extends Nt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Ds(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 S;if(Q.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:o,deviceUdid:a,projectData:c}=this.options;await Sb(o);let{project:l,authData:{token:m=""}={}}=this.options,{driver:d}=n,u=c.type,f=this.options.appId;if(f){let{mobileApp:A}=await Et.getMobileAppDataByAppId({appId:f,projectId:l,token:m});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:v,version:b},w]=await Promise.all([this.getAppStateFromDevice(o,a,T),vb(o,a)]).catch(A=>{throw this.handleDeviceNotFoundError(A),A});if($r.info("device status and app state",{deviceStatus:w,appInstalled:v,version:b,executionId:this.executionId,testResultId:this.testResultId}),!v&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!v&&y&&(await this.installApp(o,a,y),$r.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:`${(S=this.options.projectData)==null?void 0:S.name}-${this.options.project}`},D=mb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:A,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig}),V={capabilities:{udid:a,...D}};$r.info("requesting new appium session from TMA",{tmaSessionSettings:V,executionId:this.executionId,testResultId:this.testResultId});let x=await this.requestNewAppiumSessionFromTma(o,V,g);this.sessionData=x;let R=await d.attach({sessionId:x.sessionId,capabilities:D,options:{capabilities:D}});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),$r.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:R.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:R.capabilities})}catch(A){throw $r.error("failed to start application",{err:A}),A}}async requestNewAppiumSessionFromTma(t,r,n){var i,o;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),c={name:n.name,version:n.version};return{...a,appInfo:c,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message;throw a.status===500&&typeof c=="string"&&c.startsWith("Failed to create driver session")?new mp(c):a}}async getAppStateFromDevice(t,r,n){let i=this.options.projectData.type==="ios"?"bundles":"apps",o=`${this.baseDevicePath(t,r)}/${i}`,c=(await Te(o)).find(l=>"id"in l?l.id===n:l.packageName===n);return c?{appInstalled:!0,version:c.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var i,o;try{let a=await $t(n);await Xs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let c=(o=(i=a.response)==null?void 0:i.body)==null?void 0:o.message,l="Failed to install app";throw c&&(l=`${l}: ${c}`),new dp(l,{cause:a})}}handleDeviceNotFoundError(t){var n,i;let r=(i=(n=t.response)==null?void 0:n.body)==null?void 0:i.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new pp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:i}=Z(),{sessionPlayer:o}=r,a=n||"runner";Q.onWaitToTestComplete(this.id),o.playbackManager.executionId=t.executionId,o.playbackManager.executionName=t.executionName,o.playbackManager.appiumSessionData={...this.sessionData,device:this.device,nativeApp:t.nativeApp},await this.initAndGetAppiumAPI(r),i.initialize({serverUrl:this.options.localRCASaver});let c=async()=>{try{let l=await new Promise((d,u)=>{o.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:d,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await i.drain(),l.stepsResults=null,l.resultId=this.testResultId,{...l,...t.seleniumPerfStats.getStats()}}catch(l){throw $r.error("error while running appium tests",{err:l}),l}};try{return await super.runTestOnce(t,r),await c()}catch(l){throw $r.error("failed to run test once",{err:l}),l}}}});var Ab={};z(Ab,{WorkerAppium:()=>gp});var xb,Wr,gp,Cb=E(()=>{"use strict";B();cp();xb=require("linkedom");zn();$();Lt();up();we();Oa();ae();fs();Wr=P("worker-appium"),gp=class extends Nt{initPlayer(t){return new Ds(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,i){let o=this.options.projectData.type,a=(o==="android"||o==="ios")&&await t.isTestRecordedWithEnhancedMode();if(i.type!==_.TESTIM_TVC&&a)throw Error("The provided test(s) were authored in Enhanced Mode and can run only on VMG!");Q.onGetSession(this.id,this.testName,t.runMode);let{driver:c}=n,l=await Et.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),m=o==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let u={testName:this.testName,executionId:this.executionId,executionName:t.executionName,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},f={projectData:this.options.projectData,projectType:o,nativeAppMetadata:d,appPath:l,androidActivityWait:m,sessionTags:u,gridInfo:i,options:this.options,testRunConfig:this.testRunConfig,shouldRunInEnhancedMode:a},h;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await Et.lockDevice(i,this.options.deviceUdid),h=await db(f)):h=await pb({...f,shouldRunInEnhancedMode:a}),Wr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:u,nativeAppMetadata:d,capabilities:fb(h)}),h.headers={"User-Agent":this.getUserAgentString()};let g=this.getServerAddressFromGrid();this.activeSession=await c.remote(h),this.device=await Et.updateDeviceOnRemoteTestResult(t,this.activeSession,g,this.options,a);let y=`${g}/session/${this.activeSession.sessionId}`;this.updateSlotData(y),Wr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(u){throw Wr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:u}),u}}startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await t.getOrientation()}catch(i){Wr.error("failed to keep appium session alive",{err:i}),r!=null&&r.AppiumSessionTerminatedError&&i instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&Hf(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Wr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:i}=this.options.gridData;return i===_.TESTIM_HEADSPIN||i===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:i===_.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(){let{protocol:t,hostname:r,port:n,path:i}=this.activeSession.options;if(t&&r&&n&&i)return`${t}://${r}:${n}${i}`}async runTestOnce(t,r){var f,h,g;let{manifestVersion:n,AppiumApi:i,localAssetService:o}=Z(),{sessionPlayer:a}=r,c=n||"runner",l=this.options.timeout;Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let m;if(this.options.skipLoadBalancer){let y=this.options.deviceUdid||((f=this.testRunConfig.mobile)==null?void 0:f.staticAllocation.deviceUdid),{protocol:T,hostname:v,port:b,path:w}=await Et.getHeadSpinDeviceConnection(this.options.gridData,y);m=`${T}://${v}:${b}${w}`}else m=this.getDirectAddressConnection()||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(h=this.options.company)==null?void 0:h.companyId,device:this.device,nativeApp:t.nativeApp},a.playbackManager.appiumApi=new i(m,this.activeSession.sessionId,xb.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((v,b)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:c,resolve:v,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(b)});return this.stopKeepAlive(),await o.drain(),y.stepsResults=null,y.resultId=this.testResultId,{...y,...t.seleniumPerfStats.getStats()}}catch(y){throw Wr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:y}),this.stopKeepAlive(),y}};try{return await super.runTestOnce(t,r),await le(u(),l,Ae.TEST_REACHED_CUSTOM_TIMEOUT_MSG)}catch(y){throw Wr.error("failed to run test once",{err:y}),y}}getUserAgentString(){return"Testim/CI-Branch:test"}}});var Ba,Pb=E(()=>{"use strict";B();Bn();Y();Ba=class{constructor(e){this.id=e;this.driver=new Or}async onDone(){try{await le(this.driver.end(),12e4)}catch(t){t instanceof ce&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});async function kb(){let s=await Promise.any(dI.map(async e=>{try{return await Te(e)}catch{return null}}));return s==null?void 0:s.ip}var dI,ja,$a=E(()=>{"use strict";Ge();dI=["https://api.ipify.org?format=json","https://ipinfo.io/json","https://api.my-ip.io/ip.json"];ja=({timeout:s})=>({timeout:s,...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}})});var Ob,Wa,_b=E(()=>{"use strict";Ob=I(require("ws"));B();$a();Wa=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=ja({timeout:e}),r=new Ob.default(this._cdpUrl,t),n=Qt(o=>{r.once("open",o)}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return r.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([n,i]).then(()=>r),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let i=this._lastWsId++,o=new Promise((c,l)=>{this._cdpCallbacks.set(i,{resolve:c,reject:l})}),a={method:e,params:t,id:i};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),o}}});var Ga,hp,Va,Lb=E(()=>{"use strict";B();Ga=I(require("chrome-launcher"));Lo();_b();Pn();hp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Wa}async init(e){var h,g,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}=e,d=_o({browserOptions:t,testName:r,testRunConfig:n,gridInfo:i,customExtensionLocalLocation:o,executionId:a,testResultId:c,printFinalCaps:l,mode:m}),u=[...((h=d.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(g=d.capabilities)==null?void 0:g.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ga.Launcher.defaultFlags().filter(v=>v!=="--disable-extensions")];this.chrome=await Ga.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 wr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(f),gs(()=>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}},Va=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new hp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var yp={};z(yp,{WorkerExtension:()=>ni});function mI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Db(s){return mI(s)?s:new Error(s)}var Ze,ni,Ha=E(()=>{"use strict";$e();Y();zn();B();$();Lt();ae();Pb();Lb();ct();Ze=P("worker-ext"),ni=class extends Nt{initPlayer(){return this.options.useChromeLauncher?new Va(this.id):new Ba(this.id)}async _getBrowserOnce(e,t,r,n){var o;let{driver:i}=r;try{return await i.init({projectData:this.options.projectData,overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testId:e.testId,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,executionName:e.executionName,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(o=this.options.lightweightMode)==null?void 0:o.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:K.EXTENSION})}catch(a){throw Ze.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Zi(),initializedFromCache:eo(),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;F("WorkerExtension runTestOnce");let o=async m=>{let d=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await le(e.runTestUsingCDP(m.cdpTestRunner),d,Ae.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ce))throw u;return Ze.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(m,d,u)=>{try{let f=await m.url(d);return u.driverUrlFinished=!0,f}catch(f){throw Ze.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:i,url:d,urlLength:d.length}),f}},c=async m=>{let d=await e.onStarted(this.options.testStartTimeout);return m.testRunHandlerOnStartedHadFinished=!0,d},l=async()=>{var g;if(F("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.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(y){throw Ze.warn("failed to run test via CDP",{err:y}),y}}let{driver:d}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let v=function(w){e.onCompletedCleanup(),Ze.warn("on browser closed error detected",{err:w,testResultId:r,executionId:n,testId:i}),d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),w.type=Xr.BROWSER_CLOSED,T.abort(w)},b=function(w){d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b),Ze.warn("on keep alive failed error detected",{err:w,testResultId:r,executionId:n,testId:i}),w.type=Xr.KEEP_ALIVE_FAILED,T.abort(w)};var f=v,h=b;let y=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await le(Promise.all([a(t.driver,y,u),c(u)]),this.options.testStartTimeout,Ae.TEST_START_TIMEOUT_MSG)}catch(w){if(!(w instanceof ce))throw w;Ze.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:i,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let T=new AbortController;d.registerToClosedBrowser(v),d.registerToKeepAliveFailed(b);try{let w=le(e.onCompleted(),this.testRunTimeout,Ae.TEST_COMPLETE_TIMEOUT_MSG),S=await xc(w,T.signal);d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b);try{await this.updateTestStatusOnGrid(d,Boolean(S.success),S.reason)}catch(V){Ze.error("Could not update the grid about the test status",{err:V})}d.isAlive()||(Ze.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.gridIssues="could not validate grid is alive");let A=d.maxKeepAliveGap();return A>=3e4&&(Ze.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),S.keepAliveIssue=A),{...S,...e.seleniumPerfStats.getStats()}}catch(w){throw Ze.warn("timeout wait until test completed",{err:w,testResultId:r,executionId:n,testId:i}),Db(w)}finally{d.unregisterToClosedBrowser(v),d.unregisterToKeepAliveFailed(b)}}catch(y){throw Ze.warn("failed to start url",{err:y}),Db(y)}};t.driver.start();try{return await super.runTestOnce(e,t),F("WorkerExtension super.runTestOnce"),await l()}catch(m){throw Ze.error("failed to run test",{err:m,testId:e.testId,resultId:e.testResultId}),m}}}});var Tp={};z(Tp,{WorkerExtensionSingleBrowser:()=>bp});var fI,gI,bp,wp=E(()=>{"use strict";$e();B();$();Bu();Lt();Ha();fI=P("base-worker"),gI=500,bp=class extends ni{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await qn(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()&&(fI.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;F("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 pe(gI)}}});var vp,qa,Nb=E(()=>{"use strict";Bn();oe();$e();Cl();ct();wu();Y();$();ae();Rh();Go();vp=P("worker-manager"),qa=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],i=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,i),i.id=t,i.uniqueId=n,i.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case K.SELENIUM:return(await Promise.resolve().then(()=>(sp(),rp))).WorkerSelenium;case K.APPIUM:return t?(await Promise.resolve().then(()=>(Rb(),Ib))).WorkerLocalTma:(await Promise.resolve().then(()=>(Cb(),Ab))).WorkerAppium;default:return jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension}else switch(r){case(Nr.find(n=>n===r)&&jn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(wp(),Tp))).WorkerExtensionSingleBrowser;case Nr.find(n=>n===r):return(await Promise.resolve().then(()=>(Ha(),yp))).WorkerExtension;case Hn.find(n=>n===r):return(await Promise.resolve().then(()=>(sp(),rp))).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 F("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{F("after new Worker",r.mode)}}async runTests(e,t,r,n,i,o,a,c){if(e&&e.length===0)return;let l=!1,m=0,d=(u,f)=>new Promise(h=>{var ie,Ie,It,Gr,k,N,j,J;let g=i.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vo(r,n,e,i,o,t),this.combinedTestResults={};let T=((ie=i.company)==null?void 0:ie.ucid)||"",v=(Ie=i.company)==null?void 0:Ie.companyId,b=(It=i.company)==null?void 0:It.name,w=i.source||"cli",S=i.user,A=(Gr=i.company)==null?void 0:Gr.planType,D=(k=i.company)==null?void 0:k.isStartUp,V=(N=i.projectData)==null?void 0:N.name,x=(j=i.projectData)==null?void 0:j.type,R=i.lightweightMode,L=(J=i.gridData)==null?void 0:J.type,M=(_e,Rt,ve,uc,li,pc)=>(m++,Cf({executionId:r,projectId:g,testId:Rt,resultId:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,isStartUp:D,projectType:x,appSource:pc,gridType:L}),t.testStartAndReport(_e,r,ve,uc,li)),G=async(_e,Rt,ve,uc,li,pc)=>{var gd,hd,yd;m--;let et={...(R==null?void 0:R.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...i.host&&{gridHost:i.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),i.grid||i.gridId?(et.gridName=i.grid||((gd=i.gridData)==null?void 0:gd.name),et.gridType=(hd=i.gridData)==null?void 0:hd.type,et.gridProvider=(yd=i.gridData)==null?void 0:yd.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(_e,ve,r,uc,li,et).catch(JT=>vp.error("testEndAndReport threw an error",{err:JT})),li)return;this.combinedTestResults[ve.resultId]=ve,Pf({executionId:r,projectId:g,testId:Rt,resultId:ve.resultId,result:ve,ucid:T,companyId:v,companyName:b,projectName:V,companyPlan:A,source:w,user:S,lightweightMode:R,logger:vp,isStartUp:D,projectType:x,appSource:pc}),c&&!ve.success&&(this.executionQueue.stop(),l=!0),(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},W=(_e,Rt)=>{this.combinedTestResults[Rt.resultId]=Rt,t.onTestIgnored(_e,Rt.resultId),m--,(Object.keys(this.combinedTestResults).length===y||l&&m===0)&&h(this.combinedTestResults)},q=(_e,Rt)=>t.onGridSlot(_e,Rt);for(i.userData={loginData:{...Ir(),refreshToken:Yi(),authData:Ir(),token:u,userAccessKey:f},projectId:i.project,company:i.company,servicesUrl:he()},F("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(i,this.customExtensionLocalLocation,r,M,G,q,W)});try{let u=await Ot(),f=await Qi(),h=await d(u,f);if(this.workers.size>0&&this.workers.clear(),l)throw new Xt;return h}catch(u){throw vp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var ii,Mb,za,Sp,Ep,Vr,Ip=E(()=>{"use strict";ii=I(require("lodash"));B();$();oe();ae();$e();cs();Al();Cl();ge();Mb=require("uuid");_f();B();Lt();hg();Y();Nb();de();Go();({CLI_MODE:za}=Wt),Sp=P("test-plan-runner"),Ep=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}static get id(){return Ep._id}async runTestAllPhases(e,t,r,n,i,o,a,c){let l={},m=new qa(this.customExtensionLocalLocation),d=async()=>{let g=i.beforeParallel||1,y=!0,T=await m.runTests(e,c,o,a,i,n,g,y);Object.assign(l,T)},u=async()=>{let g=vi||i.parallel,y=!1;F("right before this.workerManager.runTests");let T=await m.runTests(t,c,o,a,i,n,g,y);F("right after this.workerManager.runTests"),Object.assign(l,T)},f=async()=>{let g=i.afterParallel||1,y=!1,T=await m.runTests(r,c,o,a,i,n,g,y);Object.assign(l,T)};kf({executionId:o,projectId:i.project}),F("right before runBeforeTests");try{return await d(),F("right before runTestPlanTests"),await u(),F("right after runTestPlanTests"),await f(),l}catch(g){if(Sp.error("error running test plan",{err:g}),g instanceof Xt)return c.markAllQueuedTests(o,fe.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,v,b;if((y=i.lightweightMode)!=null&&y.disablePixelValidation)return;if(i.mode===za.SELENIUM){let[{getSessionPlayer:w},{makeSDK:S}]=await Promise.all([Promise.resolve().then(()=>(we(),ir)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:A}=w();await A.closeBatch(o,S);return}let g;try{if(!((b=(v=(T=i.company)==null?void 0:T.activePlan)==null?void 0:v.premiumFeatures)!=null&&b.applitools)||(g=await Cp(i.project),ii.default.isEmpty(g)||!o))return;let{runKey:w,url:S}=g,A=require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}),D=1e4;await le(A.closeBatches({settings:{batchIds:[o],serverUrl:S,apiKey:w}}),D)}catch{}}}async runTestPlan(e,t,r,n,i,o,a,c){var b,w,S;let l=re(),m=n.project;Jd(l),e.forEach(A=>Object.assign(A,{isBeforeTestPlan:!0})),r.forEach(A=>Object.assign(A,{isAfterTestPlan:!0}));let d=[...e,...t,...r],u=new Eo(d,n,o,a),f=ii.default.chain(d).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?[]:d.map(A=>A.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(l,m,this.startTime,i,g);F("before testListInfoPromise");let T=await y;(S=n.lightweightMode)!=null&&S.onlyTestIdsNoSuite||Q.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,i,l,c,h),F("before runTestAllPhases");let v=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,l,i||"All Tests",u);return F("before executionEnd"),await u.executionEnd(l),F("after executionEnd"),{results:v,executionId:l,testPlanName:i,configName:h}}isJsonString(e){try{JSON.parse(e)}catch{return!1}return!0}handleReportFailure(e,t){try{e.text?t=e.text:t=JSON.stringify(e)}catch{}console.error(ue.colorString(ue.FgMagenta,t)),process.exit(-1)}async reportTestRunnerStarted(e,t){try{return await Rp(e,t.testOptimization)}catch(r){return this.handleReportFailure(r,"Failed Report: Test Runner Started")}}async reportTestRunnerFinished(e){try{return await xp(e)}catch(t){return this.handleReportFailure(t,"Failed Report: Test Runner Finished")}}async runTestPlans(e,t){Sp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(m){return ii.default.flattenDeep(Object.values(m)).reduce((d,u)=>d.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},i={},o=e.project,a={testPlans:[],testPlansData:{}};O.flags.enableTestPlanAggregation.isEnabled()?(await se(e.testPlanIds,async m=>{let d=await oi(o,e.testPlan,[m],t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})}),await se(e.testPlan,async m=>{let d=await oi(o,[m],e.testPlanIds,t,e.intersections);d.testPlans.forEach(u=>{a.testPlans.push(u);let f=u._id;a.testPlansData[f]=d.testPlansData[f]})})):a=await oi(o,e.testPlan,e.testPlanIds,t,e.intersections);let c=a.testPlans,l=a.testPlansData;if(!c||c.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!l||Object.keys(l).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==za.APPIUM&&await Fu(e,r(l)),await se(c,async m=>{var h;let d=m.testPlanId;n[d]={};let u={...e};u.baseUrl||=m.startUrl,u.appId||=((h=m.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=m.gridId,e.grid&&delete u.gridId,u.gridData=await hf(e,m);let f=u.overrideExecutionName||m.name;return await se(l[d],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,d,t);Q.onTestPlanFinished(y.results,m.name,this.startTime,y.executionId,!1),n[d][y.executionId]=y.results;let T=Object.keys(n[d]).map(S=>({executionId:S,status:Mu(n[d][S])})),v=Object.keys(n[d]).map(S=>n[d][S]).reduce((S,A)=>Object.assign(S,A),{}),b=Mu(v);Object.assign(i,v);let w=b?T[0].executionId:T.find(S=>!S.status).executionId;return await Ap(o,d,{success:b,executions:T,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var c;Sp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),F("before getSuite");let r=await Ah(e,t);if(F("after getSuite"),!((c=r==null?void 0:r.tests[0])!=null&&c.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;F("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===za.APPIUM&&(a=await ri({appId:e.appId,projectId:e.project})),await se(r.tests,async l=>{if(a&&l.forEach(d=>{"nativeApp"in d&&(d.nativeApp=a)}),e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==za.APPIUM&&await Fu(e,l),F("right before runTestPlan");let m=await this.runTestPlan([],l,[],e,i,null,t,o);return F("right after runTestPlan"),await Q.onTestPlanFinished(m.results,i,this.startTime,m.executionId,o),m})}async run(e){let t=vn(),r=[];await this.reportTestRunnerStarted(e.project,e),en(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t),await this.reportTestRunnerFinished(e.project);let n=ii.default.flattenDeep(r);return F("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),F("right after onAllTestPlansFinished"),n.map(i=>i.results).reduce((i,o)=>Object.assign(i,o),{})}},Vr=Ep;Vr._id=(0,Mb.v4)()});var Ce={};z(Ce,{addTestRetry:()=>au,clearTestResult:()=>Du,deleteCloudflareTunnel:()=>Mp,fetchLambdatestConfig:()=>uu,fixGridAppIDStructure:()=>op,forceUpdateCloudflareTunnelRoutes:()=>Np,getAllGrids:()=>xl,getAppDetails:()=>ri,getApplitoolsIntegrationData:()=>Cp,getBrowserStackSessionMetaData:()=>RI,getCloudflareTunnel:()=>Dp,getEditorUrl:()=>SI,getGridSlot:()=>Rl,getHybridGridProvider:()=>Il,getLabFeaturesByProjectId:()=>vu,getMobileDevicesFromGrid:()=>si,getRealData:()=>eu,getS3Artifact:()=>_n,getS3ArtifactText:()=>Zl,getSuiteTestList:()=>Uu,getTestPlan:()=>vI,getTestPlanTestList:()=>oi,getTestResults:()=>Dr,getUsageForCurrentBillingPeriod:()=>_p,initializeUserWithAuth:()=>Lp,isTestResultCompleted:()=>Lu,keepAliveCompanySlots:()=>Yl,keepAliveGrid:()=>Sl,loadSfdcCredential:()=>Op,loadTest:()=>Vn,releaseCompanySlot:()=>Jl,releaseGridSlot:()=>El,reportExecutionFinished:()=>Io,reportExecutionStarted:()=>ou,reportRunnerFinished:()=>xp,reportRunnerStarted:()=>Rp,requestCompanySlot:()=>Kl,saveRemoteStep:()=>Eu,saveTestPlanResult:()=>Ap,updateCompanySlot:()=>Xl,updateExecutionTests:()=>iu,updateRemoteRunFailure:()=>Fp,updateTestDataArtifact:()=>Ro,updateTestResult:()=>Jo,updateTestStatus:()=>Cr,uploadAppToGrid:()=>ip,uploadRunDataArtifact:()=>Nu,validateUserAccessKey:()=>wl});async function Ns(){let s=await Ot();if(!s)throw new Error("Failed to get token from server");return{[Vc]:Vr.id,Authorization:`Bearer ${s}`}}async function Re({url:s,body:e,headers:t={},timeout:r,retry:n}){let i=await Ns(),o={...t,...i};return Ve({url:`${he()}${s||""}`,body:e,headers:o,timeout:r,retry:n})}async function TI(s,e,t,r={},n=void 0){let i=await Ns(),o={...r,...i};return await Xs(`${he()}${s||""}`,e,t,o,n)}async function ai(s,e){let t=await Ns();return await Oc(`${he()}${s||""}`,e,t)}async function Ub(s,e){let t=await Ns();return await Js(`${he()}${s||""}`,e,t)}async function wI(s,e){let t=await Ns();return await Ys(`${he()}${s||""}`,e||void 0,t)}async function ke(s,e,t,r){let n=await Ns();return await Te(`${he()}${s||""}`,e||void 0,n,r,t)}function _n(s,e){return(0,ee.default)(()=>ke(`/storage${s}`,null,{isBinary:!0},e),{retries:te,factor:1})}function Zl(s){return(0,ee.default)(()=>wI(`/storage${s}`))}async function Rp(s,e){return await Re({url:"/test-runner",body:{projectId:s,testOptimization:e}})}async function xp(s){return await Ub("/test-runner",{projectId:s})}async function vI(s,e){let t=n=>n===null?[]:typeof n=="string"&&JSON.parse(n)||n;return(await(0,ee.default)(()=>ke("/testPlan",{projectId:s,name:e.join(",")}),{retries:te,factor:1})).map(({testConfigIds:n,beforeAllLabels:i,testLabels:o,afterAllLabels:a,...c})=>Object.assign(c,{testConfigIds:t(n),beforeAllLabels:t(i),testLabels:t(o),afterAllLabels:t(a)}))}async function Op({branch:s,projectId:e}){let t=await(0,ee.default)(()=>ke(`/branch/branchData/${encodeURIComponent(s)}`,{projectId:e}),{retries:te,factor:1});return t==null?void 0:t.sfdcCredential}function Vn({testId:s,branch:e,projectId:t,skipSharedSteps:r=!1,useBranchMap:n=!0}){return(0,ee.default)(()=>ke(`/test/${s}`,{projectId:t,branch:e,skipSharedSteps:r,useBranchMap:n}),{retries:te,factor:1})}function Ap(s,e,t){return(0,ee.default)(()=>Re({url:"/testPlan/result",body:{projectId:s,testPlanId:e,result:t}}),{retries:te,factor:1})}function Cr(s,e,t,r,n,i,o=te){return(0,ee.default)(()=>ai("/result/run/test",{runId:e,testId:t,resultId:r,status:n,projectId:s,runnerVersion:hI,...i}),{retries:o,factor:1})}function iu(s,e,t,r,n,i,o,a){return(0,ee.default)(()=>ai("/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 ou({executionId:s,projectId:e,labels:t,startTime:r,executions:n,config:i,resultLabels:o,remoteRunId:a,localRunUserId:c,isLocalRun:l,intersections:m}){let{isCi:d}=await Promise.resolve().then(()=>(no(),Rf));return Re({timeout:9e4,url:"/result/run",body:{runId:s,projectId:e,labels:t,startTime:r,execution:n,status:"RUNNING",config:i,resultLabels:o,remoteRunId:a,intersections:m,metadata:{isCiRun:d,localRunUserId:c,isLocalRun:l}},retry:3})}function Io(s,e,t,r,n={},i=void 0,o=void 0){let a=Date.now();return(0,ee.default)(()=>ai("/result/run",{runId:e,projectId:t,endTime:a,status:s,success:r,tmsOptions:n,remoteRunId:i,resultExtraData:o}),{retries:te,factor:1})}async function oi(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/testPlan/list",body:{projectId:s,names:e,planIds:t,branch:r,intersections:n},timeout:12e4}),{retries:te,factor:1})}function Uu({projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}){return(0,ee.default)(()=>Re({url:"/suite/v2/list",body:{projectId:s,labels:e,testIds:t,testNames:r,testConfigNames:n,suiteNames:i,suiteIds:o,branch:a,rerunFailedByRunId:c,testConfigIds:l,intersections:m}}),{retries:te,factor:1})}async function ri({appId:s,projectId:e}){try{return await(0,ee.default)(()=>ke(`/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 _p(s){try{return await(0,ee.default)(()=>ke(`/plan/project/${s}/usage-current-billing-period`),{retries:te,factor:1})}catch(e){Mt.error("failed getting usage for current billing period",{projectId:s,error:e});return}}function Lu(s,e,t){return(0,ee.default)(()=>ke(`/result/${s}/isComplete`,{projectId:e,testRetryKey:t}),{retries:te,factor:1})}function Dr(s,e,t,r){return(0,ee.default)(()=>ke(`/test/v2/${s}/result/${e}`,{projectId:t,branch:r}),{retries:te,factor:1})}function Sl(s,e){return Re({url:`/grid/keep-alive?reqId=${re()}`,body:{projectId:s,slots:e},timeout:1e4})}function El(s,e,t,r,n){return Re({url:`/grid/release?reqId=${re()}`,body:{companyId:s,projectId:e,slotId:t,gridId:r,browser:n}})}function Il(s){return Re({url:"/grid/hybrid/provider",body:s})}function Rl(s){return(0,ee.default)(()=>ke("/grid/grid-slot",{...s,reqId:re()}),{retries:te,factor:1})}async function Lp({projectId:s,token:e,branchName:t,lightweightMode:r,localGrid:n,publicIp:i,gridId:o,grid:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m}){var d,u;try{return await(0,ee.default)(()=>Ve({url:`${he()}/executions/initialize`,body:{projectId:s,token:e,branchName:t||"master",lightweightMode:r,localGrid:n,publicIp:i,gridId:o,gridName:a,clientCliVersion:c,clientNodeVersion:l,clientNpmVersion:m},timeout:6e4}),{retries:te,factor:1})}catch(f){if(Mt.error("error initializing info from server",f),(d=f.message)!=null&&d.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(Pp.default[y](Pp.default[g](h.clientMessage.text))),h.exitCode&&process.exit(h.exitCode)}catch{Mt.error("Error parsing error message from server",f)}throw f}}async function SI(){if(tt)return{editorUrl:tt};try{return await(0,ee.default)(()=>ke("/system-info/editor-url"),{retries:te,onFailedAttempt:s=>{if(s.attemptNumber>=te)throw s},factor:1})}catch(s){return Mt.error("cannot retrieve editor-url from server",{err:s}),{editorUrl:"https://app.testim.io"}}}function xl(s){return(0,ee.default)(()=>ke("/grid",{companyId:s}),{retries:te,factor:1})}function eu(s,e,t){return(0,ee.default)(()=>ke(`/real-data/${e}?${t}&projectId=${s}`),{retries:te,factor:1})}function Jo(s,e,t,r,n){return(0,ee.default)(()=>Re({url:"/result/test",body:{projectId:s,resultId:e,testId:t,testResult:r,remoteRunId:n}}),{retries:te,factor:1})}function Du(s,e,t,r){return(0,ee.default)(()=>Re({url:"/result/test/clear",body:{projectId:s,resultId:e,testId:t,testResult:r}}),{retries:te,factor:1})}function Eu(s,e,t,r){return(0,ee.default)(()=>Re({url:"/remoteStep",body:{projectId:s,resultId:e,stepId:t,remoteStep:r}}),{retries:te,factor:1})}function EI(s){return s.startsWith("/")?s:`/${s}`}function II(s,e,t){let r=EI(s);return t&&(r=`/${t}${r}`),e&&(r=`/${e}${r}`),r}async function Bb(s,e,t,r,n,i="application/octet-stream"){let o=null;i==="application/json"&&(o=".json");let a=`${n}_${re()}${o||""}`,c=`${e}/${t}/${a}`,l=II(c,bI,s),m=Buffer.from(Fb.gzip(r,{level:3})),d={file:{fileName:a,buffer:m}};return await(0,ee.default)(()=>TI(`/storage${l}`,{},d,{"X-Asset-Encoding":"gzip"}),{retries:te,factor:1}),l}function au({projectId:s,runId:e,testId:t,newResultId:r,originalTestResultId:n,previousTestResultId:i,testResult:o}){return(0,ee.default)(()=>Re({url:"/result/test/retry",body:{projectId:s,newResultId:r,originalTestResultId:n,previousTestResultId:i,testId:t,runId:e,testResult:o}}),{retries:te,factor:1})}async function Cp(s){try{return await ke(`/integration/applitools/v3/connected?projectId=${s}`)}catch(e){return Mt.warn("could'nt get applitools integration data.",{err:e}),{}}}async function Dp(s,e){try{return await ai("/tunnel",{companyId:s,routes:e})}catch(t){return Mt.warn("could'nt get tunnel.",{err:t}),{}}}async function Np(s,e){try{return await Re({url:`/tunnel/${e}`,body:{companyId:s}})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}async function Mp(s,e){try{return await Ub(`/tunnel/${e}`,{companyId:s})}catch(t){Mt.warn("could'nt get tunnel.",{err:t});return}}function Fp(s){return Ve({url:`${he()}/result/remoteRunFailure`,body:s})}async function si({projectId:s,projectType:e,gridId:t,companyId:r,selectors:n}){let i=`${yI}/mobileDevices/${t}/${r}?projectType=${e}`;i=n?`${i}&selectors=${encodeURIComponent(n)}`:i;try{return await(0,ee.default)(()=>ke(i,{projectId:s}),{retries:te,factor:1})}catch(o){return Mt.warn("could'nt get devices from headspin grid.",{err:o}),null}}async function ip({projectId:s,gridId:e,app:t,timeout:r}){return(0,ee.default)(()=>Re({url:`/mobile-app/app/upload-to-grid?projectId=${s}&gridId=${e}`,body:t,timeout:r}),{retries:te,factor:1})}async function op(s){return(0,ee.default)(()=>Re({url:"/mobile-app/app/fix-grid-app-id",body:s}),{retries:te,factor:1})}async function Kl(s,e){return(0,ee.default)(()=>Re({url:"/slot-management/request-slot",body:{companyId:s,projectId:e}}),{retries:te,factor:1})}async function Jl(s,e,t){return(0,ee.default)(()=>Re({url:"/slot-management/release-slot",body:{companyId:s,projectId:e,slotId:t}}),{retries:te,factor:1})}async function Xl(s,e,t){return(0,ee.default)(()=>ai("/slot-management/update-slot",{slotId:t.slotId,companyId:s,projectId:e,slot:t}),{retries:te,factor:1})}function Yl(s,e,t){return Re({url:`/slot-management/keep-alive?reqId=${re()}`,body:{slots:t,companyId:s,projectId:e},timeout:1e4})}async function RI(s,e){return await Te(`${Vs}/sessions/${s}`,void 0,{Authorization:`Basic ${Buffer.from(`${e.user}:${e.key}`).toString("base64")}`})}async function wl(s){try{return await ke("/v2/project/validateUserAccessKey",s),!0}catch(e){return Mt.error("error validating user access key",{error:e}),!1}}var Pp,ur,Fb,ee,kp,hI,Mt,te,yI,bI,uu,vu,Nu,Ro,ge=E(()=>{"use strict";Pp=I(require("chalk")),ur=I(require("lodash")),Fb=I(require("pako"));B();oe();ae();Ge();ct();ee=I(require("p-retry")),kp=I(require("object-hash"));Y();$();Ip();hI=rt(),Mt=P("testim service api"),te=3,yI="/grid",bI="test-result-artifacts";uu=async(s,e)=>(0,ee.default)(()=>ke("/grid/lt/config",{companyId:s,...e&&{projectId:e}}),{retries:te,factor:1}),vu=async s=>(0,ee.default)(()=>ke(`/labFeature/v2/project/${s}`),{retries:te,factor:1});Nu=ur.memoize(async(s,e,t,r)=>{if(!ur.isEmpty(r))return await Bb(s,e,t,JSON.stringify(r),"test-run-data","application/json")},(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`),Ro=ur.memoize(async(s,e,t,r,n)=>!r||ur.isEmpty(r)?void 0:await Bb(s,e,t,JSON.stringify((()=>{let o=ur.clone(r);if(n!=null&&n.hiddenParams){let a=n.hiddenParams||[];(Array.isArray(a)?a:Object.keys(a)).forEach(l=>{o[l]&&Object.assign(o,{[l]:jc.HIDDEN_PARAM})})}return o})()),"test-test-data","application/json"),(s,e,t,r)=>`${(0,kp.default)(r)}:${e}:${t}`)});function Ka(){return rt()}var Up=E(()=>{"use strict";B()});function CI(s){K.EXTENSION!==s&&process.nextTick(()=>{try{(we(),qe(ir)).getSessionPlayer()}catch{}})}function PI(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(Bp.default[i](Bp.default[n](r.text)))})}function kI(s,e){let{serviceUrl:t}=s;Gs(t),kt(async()=>s,Yr.CACHE_FN_NAME,Yr.TTL,{serviceUrl:t})(),Ut.setRegion(Tg[bs(e)])}async function ci(s){let{project:e,token:t,userAccessKey:r,lightweightMode:n,useLocalChromeDriver:i,useChromeLauncher:o,mode:a,gridId:c,grid:l}=s,m=Boolean(n==null?void 0:n.general),d=Boolean(i||o),u=m?AI:xI,f=Ka(),h=Fc(),g=await Vm(),y=null;if(O.flags.getPublicIpFrom3rdPartyServices.isEnabled()&&!d)try{y=await kb()}catch(b){jb.error("failed to get public ip",b)}let T=!0;F("before initializeUserWithAuth");let v=await kt(async()=>(CI(a),T=!1,await Lp({projectId:e,token:t,branchName:s.branch,lightweightMode:n,localGrid:d,publicIp:y,gridId:c,grid:l,clientCliVersion:f,clientNodeVersion:h,clientNpmVersion:g})),"initializeUserWithAuth",u,{project:e,token:t,branchName:s.branch,lightweightModeGeneral:m,localGrid:d,gridId:c,grid:l,publicIp:y})();return PI(v),kI(v.clientConfig,e),s.publicIps=[v.clientPublicIp],F("after initializeUserWithAuth"),y&&v.clientPublicIp&&v.clientPublicIp!==y&&(jb.error("public ip mismatch",{publicIpFromExternalService:y,publicIpFromServices:v.clientPublicIp}),s.publicIps.push(y)),uf(v.authData,{projectId:e,token:t,userAccessKey:r,publicIp:v.clientPublicIp,initializedFromCache:T}),v}var Bp,jb,xI,AI,$b=E(()=>{"use strict";Bp=I(require("chalk"));$e();ge();er();ct();$a();ae();$();de();Up();B();os();oe();Ao();jb=P("initializeUserWithAuth"),xI=1e3*60*5,AI=1e3*60*60*10});async function Gb(s){var r;let e=Promise.resolve();s.useLocalChromeDriver&&(s.chromeBinaryLocation=s.downloadBrowser?await Xi():s.chromeBinaryLocation,e=ln({projectId:s.project,userId:s.user},{chromeBinaryLocation:s.chromeBinaryLocation},Boolean((r=s.lightweightMode)==null?void 0:r.general)),s.useLocalChromeDriver=!0),!s.playerRequirePath&&s.mode!==K.EXTENSION&&await Sr(s.playerLocation,s.canary),s.mode!==K.SELENIUM&&s.mode!==K.APPIUM&&!s.ext&&await ul(s.extensionLocation);let t;if(s.installCustomExtension){let n=Boolean(s.useLocalChromeDriver||s.useChromeLauncher);t=await ll(s.installCustomExtension,n)}return await e,t}async function Hb(s){var o;OI.info("prepare MockNetwork",{location:s});let e=await Nc(s),t=Buffer.isBuffer(e)?e:e.body;if(t.byteLength>Wb*1e6)throw new Error(`${jp} exceeded ${Wb}MB`);let r;try{r=JSON.parse(t.toString("utf-8"))}catch(a){throw new Error(`${jp} cannot be parsed.${Ja.EOL}${a}`)}let n=new Vb.default;if(!n.validate(Yc,r)){let a=(o=n.errors)==null?void 0:o.map((c,l)=>`${++l}) ${c.dataPath} ${c.message}`).join(Ja.EOL);throw new Error(`${jp} is malformed.${Ja.EOL}${a}`)}return r.entries}var Ja,Vb,Wb,jp,OI,$p=E(()=>{"use strict";Ja=I(require("node:os"));B();Sm();pn();Vb=I(require("ajv"));ae();fl();$();$b();Wb=1,jp="JSON file supplied to --mock-network-pattern",OI=P("prepare runner")});function Xb(s){return s.start&&ls(null,"cli-start-command",{downloadBrowser:Boolean(s.downloadBrowser)}),!!(s.startV2||s.start||s.agent)}async function Yb(s){let e=!!s.start;if(Number.isNaN(s.agentPort))throw new C("Agent port is not number");let t=xo(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 Qb=E(()=>{"use strict";Dn();us();Y()});var Ms,Hp,Zb=E(()=>{"use strict";Ms="SECRETS",Hp={get secretsKey(){return Ms},get proxySecrets(){return new Proxy({},{get(s,e){return`${Ms}.${e}`}})},injectProxySecretsStoreToGlobal(){Object.assign(globalThis,{[Ms]:this.proxySecrets})},containsSecrets(s){return typeof s=="string"?s.includes(Ms):JSON.stringify(s).includes(Ms)},extractSecretKeysFromCode(s){let e=new Set,r=(typeof s=="string"?s:JSON.stringify(s)).match(new RegExp(`${Ms}\\.\\w+`,"g"));return r==null||r.map(n=>{let i=n.split(".")[1];i&&e.add(i)}),e},replaceValuesWithDecryptedSecrets({testData:s,secretsRecord:e}){let r=this.secretsKey.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${r}\\.(\\w+)$`),i=o=>{Array.isArray(o)?o.forEach((a,c)=>{if(typeof a=="string"){let l=a.match(n);if(l){let m=l[1];o[c]=e[m]??a}}else typeof a=="object"&&a!==null&&i(a)}):o&&typeof o=="object"&&Object.entries(o).forEach(([a,c])=>{if(typeof c=="string"){let l=c.match(n);if(l){let m=l[1];o[a]=e[m]??c}}else typeof c=="object"&&c!==null&&i(c)})};i(s)}}});var Xp={};z(Xp,{doLogin:()=>Jp,getProjectId:()=>FI,getToken:()=>UI});async function FI(){return rT("projectId")}async function UI(){return rT("token")}function tT(s,e){return Promise.race([s,pe(e).then(()=>{throw new ce("timeout")})])}async function BI(){let s=(await import("express")).default(),e=async function(){return tT(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(),Ce)),{editorUrl:n}=await r();ho(`${n}/#/new-test`)}catch{console.log(`Unable to open Testim automatically - please manually go to ${tt||gr}`)}return await e}async function Jp({overwriteExisting:s=!0,projects:e=null}={}){let t=qp.homedir(),r=zp.join(t,".testim");if(await ye(r)&&!s)return;let i={},[{default:o},{default:a}]=await Promise.all([import("prompts"),import("ora")]),c=a("Getting credentials from Tricentis Testim extension ...").start();if(e||(e=await tT(BI(),62e3).catch(()=>null)),e!=null&&e.token){i.token=e.token,i.projectId=e.projectId,c.succeed(),await eT(r,i);return}if(e!=null&&e.length){c.succeed();let l=e.length===1?{project:e[0]}:await o({type:"select",name:"project",message:"There are multiple projects associated with your user account. Please select the project you would like to connect to:",choices:e.map(m=>({title:m.name,value:m}))});i.token=l.project.ci.token,i.projectId=l.project.id,await eT(r,i);return}c.fail(),console.log("Error getting credentials - please pass `--token` and `--project` to the CLI or try again")}async function eT(s,e){await Kp.promises.writeFile(s,Ya.stringify(e)),console.log(`Testim credentials saved in '${s}'`)}async function rT(s){let e=qp.homedir(),t=zp.join(e,".testim"),r=await ye(t),n={};if(r)try{n=Ya.parse((await Kp.promises.readFile(t)).toString())}catch{}return n||={},n[s]}var qp,zp,Ya,Kp,Qa=E(()=>{"use strict";qp=I(require("os")),zp=I(require("path")),Ya=I(require("yaml"));B();Kp=require("fs");Y();Gl();oe()});var pT={};z(pT,{process:()=>KI,program:()=>p});var Qp,aT,Za,cT,Kt,Fe,lT,jI,Me,ed,$I,WI,nT,uT,VI,Zp,ec,td,Yp,Ft,iT,GI,HI,p,qI,zI,oT,KI,rd=E(()=>{"use strict";Qp=I(require("ms")),aT=I(require("chalk")),Za=I(require("node:fs")),cT=I(require("node:url")),Kt=I(require("lodash")),Fe=I(require("node:path"));B();Dn();Qb();er();lT=require("commander");ae();Y();Hr();B();de();Zb();Go();Ao();oe();jI=s=>s.replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),Me=(s,e)=>(e.push(s),e),ed=new lT.Command,$I=s=>s.split(","),WI=(s,e)=>!s||s.length===0?e:s,nT=["enable-heavy-ad-intervention","heavy-ad-privacy-mitigations","use-fake-device-for-media-stream","use-fake-ui-for-media-stream","proxy-server"],uT=()=>{function s(g){return g.includes("-h, --help")}function e(g){return g.includes("--params [params-json-string]")}function t(g){return g.includes("--ext")||g.includes("--extension-path")||g.includes("--headless-extension-download-path")}function r(g){return g.includes("--player-path")||g.includes("--player-require-path")}function n(g){return g.includes("--executionId")||g.includes("--source")||g.includes("--resultId")||g.includes("--remoteRunId")||g.includes("--schedulerId")}function i(g){return g.includes("--get-browser-timeout")||g.includes("--get-browser-retries")||g.includes("--get-session-timeout")||g.includes("--get-session-retries")||g.includes("--driver-request-timeout")||g.includes("--driver-request-retries")}function o(g){return g.includes("--user")}function a(g){return g.includes("shouldMonitorPerformance")}function c(g){return g.includes("--save-rca-locally")}function l(g){return g.includes("--exit-code-ignore-failing-tests")}function m(g){return g.includes("--high-speed")}function d(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")}ed.help(g=>g.split(`
405
405
  `).filter(T=>!t(T)&&!e(T)&&!s(T)&&!r(T)&&!n(T)&&!a(T)&&!o(T)&&!i(T)&&!c(T)&&!l(T)&&!m(T)&&!d(T)&&!u(T)&&!f(T)&&!h(T)).join(`
406
406
  `))},VI=(s,e)=>{let t=e?`Please use ${e} instead.`:"";console.log(aT.default.yellow(`
407
407
  WARNING: ${s} is deprecated. ${t}
408
- `))},Zp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:ec,argv:td,exit:Yp,cwd:Ft}=global.process,iT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services-eu.dev.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services-eu.staging.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services-eu.prod.testim.io"}}},GI=async s=>{let e=bs(s),t=await Zc(Yr.CACHE_FN_NAME);if(t&&t.region===e){Gs(t.servicesUrl);return}let n=(iT[xt]||iT.production)[e]||{servicesUrl:"https://services.testim.io"};ec.SERVICES_HOST||Gs(n.servicesUrl)},HI=new Set(["trace","debug","info","warn","error","silent"]);Gc(td,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));ed.description("Testim.io CLI").option("-h --help","output usage information",uT).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",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).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",$I).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",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).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",Me,[]).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(ec.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,Qp.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,Qp.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: ${Zp.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).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("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").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",Me,[]).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)",Me,[]).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)",Me,[]).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(td);p=ed.opts(),qI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},zI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},oT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=Za.readFileSync(s);(r=Hp)!=null&&r.containsSecrets(t.toString())&&Hp.injectProxySecretsStoreToGlobal()},KI=async()=>{var T,v,b,w,S,A,D,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!td.slice(2).length)throw uT(),new qr;if(p.version){let x="Testim CLI Version: ";ec.npm_package_version&&(console.log(x,ec.npm_package_version),Yp(0));let R=st();R&&(console.log(x,R),Yp(0)),console.log("Could not find version, please check the package.json manually"),Yp(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Dm(),p.clearFileCache&&ns();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let x=Fe.resolve(n);_m(x)}if(p.usePrefechedData&&Nm(),p.playerRequirePath){let x=Fe.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",x);let R=Fe.join(x,"tsconfig.node.json"),M=require("ts-node").register({project:R,ignore:[/node_modules/,new RegExp(`^${Kt.escapeRegExp(Fe.relative(Ft(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:M.config.options.paths,baseUrl:M.config.options.baseUrl}),(we(),qe(ir)).options.playerPath=x;let W=require("node:module"),q=W.prototype.require;W.prototype.require=function(Ie){return Ie==="rox-alias"?q.call(this,"rox-node"):Ie==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Za.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(Xb(p))return Yb(p);try{let x={};p.configFile?(oT(p.configFile),x=require(Fe.join(Ft(),p.configFile)).config):p.optionsFile&&(x=require(Fe.join(Ft(),p.optionsFile))),x&&typeof x.then=="function"&&(x=await x),Object.keys(x).forEach(R=>{let L=jI(R);p[L]=WI(p[L],x[R])})}catch(x){throw x.message=`Unable to read options file: ${x.message}`,x}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)||((v=p.testConfigId)==null?void 0:v.length),o=((b=p.testPlan)==null?void 0:b.length)||((w=p.testPlanId)==null?void 0:w.length),a=((S=p.suite)==null?void 0:S.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Fe.join(Ft(),p.seleniumCapsFile))}catch(x){throw new C(`Failed to parse selenium caps file file error: ${x.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(Fe.join(Ft(),p.chromeExtraPrefs))}catch(x){throw new C(`Failed to read/open chrome extra prefs file error: ${x.message}`)}if(p.chromeExtraArgs){let x=p.chromeExtraArgs.split(",");for(let R of x){let[L]=R.split("=");nT.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(R),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(nT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&oT(p.paramsFile),s={...s,...require(Fe.join(Ft(),p.paramsFile))}}catch(x){throw new C(`Failed to read/open params file error: ${x.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(x){throw new C(`Failed to parse params string error: ${x.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&&(qI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let x=require(Fe.join(Ft(),p.sauceOptions)),R=x.platformName&&["ios","android"].includes(x.platformName.toLowerCase());if(x.browserName){let M=x.browserName.toLowerCase();switch(M){case"microsoftedge":p.browser="edge";break;default:p.browser=M}}p.browser==="edge"&&parseFloat(x.version)>=79&&(p.browser="edge-chromium");let L=parseFloat(x.version)<50&&!["dev","beta"].includes(x.version);if(!R&&p.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...x}}catch(x){throw new C(`Failed to parse saucelabs options file error: ${x.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&&(zI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let x=require(Fe.join(Ft(),p.browserstackOptions)),R=x.platform&&["mac","android"].includes(x.platform.toLowerCase());if(x.browserName&&(p.browser=x.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(x.browser_version)>=79&&(p.browser="edge-chromium"),!R&&parseFloat(x.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...x}}catch(x){throw new C(`Failed to parse browserstack options file error: ${x.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let x=require(Fe.join(Ft(),p.perfectoOptions)),R={location:"US East",securityToken:p.perfectoToken};p.perfecto={...R,...x}}catch(x){throw new C(`Failed to parse perfecto options file error: ${x.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let x=require(Fe.join(Ft(),p.testobjectOptions)),R={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...R,...x}}catch(x){throw new C(`Failed to parse test object options file error: ${x.message}`)}let c={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=c,!p.project){let R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getProjectId();if(R)p.project=R;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}GI(p.project),O.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 m=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 R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getToken();if(R)p.token=R;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 d=x=>x<=0||!Number.isInteger(x);if(d(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(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(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(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![K.EXTENSION,K.SELENIUM,K.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Nr,...Hn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!HI.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((V=p.host)!=null&&V.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=cT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(R=>R.trim()).filter(Boolean);let x=p.resultLabel.filter(R=>R.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Tr()&&p.resultLabel.unshift(Tr()),x.length)throw new C("A result label cannot exceed 250 characters")}let f=xo(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&&!Kt.inRange(Kt.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&&Kt.difference(p.codeCoverageReporter,Zp).length){let x=Kt.difference(p.codeCoverageReporter,Zp);throw new C(`invalid --code-coverage-reporter parameters ${x.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(x=>Boolean(p[x]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&y.length){let x=y.length>1?"are":"is";throw new C(`${y.map(R=>g[R]).join(" and ")} ${x} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let x=Za.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(x)}catch(x){throw new C(`failed to parse field file error: ${x.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&&(VI("--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 x={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"},R=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...x,...R}}catch(x){throw new C(`failed to parse lightweightMode settings error: ${x.message}`)}else p.turboMode&&![K.APPIUM,K.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&&[K.APPIUM,K.SELENIUM].includes(p.mode)&&console.warn(`
409
- 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"?Tr():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:m,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 sd,JI,Fs,dT,mT,nd,fT,gT=E(()=>{"use strict";B();Y();$();kn();sd=P("testimNgrok"),JI=".whitelisted-ngrok.testim.io",Fs="",mT=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}${JI}`);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 pt("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(sd.info("replace https to http"),Fs=i.replace("https://","http://")):Fs=i,s.tunnelDiagnostics&&nd(),s.baseUrl=Fs},nd=async(s=!0)=>{try{let t=(await pt("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Fs);console.log("ngrok stats",n),sd.info("ngrok stats",{tunnel:n})}catch(e){sd.error("error collecting ngrok stats",{err:e})}s&&(dT=setTimeout(()=>nd(),1e4))},fT=async s=>{if(!Fs)return;clearTimeout(dT),s.tunnelDiagnostics&&await nd(!1),await(await pt("ngrok")).disconnect(Fs)}});var pr,od,hT,YI,QI,id,tc,sc,rc,ZI,yT,bT,TT=E(()=>{"use strict";pr=I(require("os")),od=I(require("fs")),hT=I(require("child_process"));B();ge();YI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",QI={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"}},id=pr.tmpdir(),tc=`${id}/cloudflared`,sc=null,rc=null,ZI=async()=>{if(await ye(tc))return;let e=QI[pr.platform()+pr.arch()];if(!e)throw new Error(`tunnel on ${pr.platform()+pr.arch()} platform is not supported.`);let t=e.extract?id+e.path:tc;await Je(`${YI}/${e.path}`,t),e.extract&&await at(t,id),await od.promises.chmod(tc,"755")},yT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Dp(s.company.companyId,t),ZI()]);sc=r._id,rc=hT.spawn(tc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Np(s.company.companyId,sc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await od.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},bT=async s=>{let e=[];return sc&&e.push(Mp(s.company.companyId,sc)),rc&&e.push(new Promise((t,r)=>{rc.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),rc.kill()})),await Promise.all(e)}});var ad={};z(ad,{connect:()=>ic,disconnect:()=>oc,serveTunneling:()=>rR});var nc,wT,vT,tR,ic,oc,rR,cd=E(()=>{"use strict";gT();Pn();TT();lt();nc=I(require("ora"));$();ae();Po();wT=P("tunnel"),vT=s=>{var e;return[_.TESTIM_LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},tR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},ic=async s=>{if(!s.tunnel)return;let e=Ir(),t;try{vT(s)?(t=(0,nc.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):tR(s)?(t=(0,nc.default)("Starting testim cloudflare tunnel...").start(),await yT(s)):(t=(0,nc.default)("Starting testim ngrok tunnel...").start(),await mT(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."),wT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
408
+ `))},Zp=["clover","html","json-summary","json","lcov","lcovonly","teamcity","text-lcov","text-summary","text"],{env:ec,argv:td,exit:Yp,cwd:Ft}=global.process,iT={development:{usw2:{servicesUrl:"https://services.dev.testim.io"},euc1:{servicesUrl:"https://services-eu.dev.testim.io"}},staging:{usw2:{servicesUrl:"https://services.staging.testim.io"},euc1:{servicesUrl:"https://services-eu.staging.testim.io"}},production:{usw2:{servicesUrl:"https://services.testim.io"},euc1:{servicesUrl:"https://services-eu.prod.testim.io"}}},GI=async s=>{let e=bs(s),t=await Zc(Yr.CACHE_FN_NAME);if(t&&t.region===e){Gs(t.servicesUrl);return}let n=(iT[xt]||iT.production)[e]||{servicesUrl:"https://services.testim.io"};ec.SERVICES_HOST||Gs(n.servicesUrl)},HI=new Set(["trace","debug","info","warn","error","silent"]);Gc(td,new Set(["run","connect","agent","tunneld","start","init","install-lazy-deps"]));ed.description("Testim.io CLI").option("-h --help","output usage information",uT).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",Me,[]).option("--test-config-id [test-config-id]","test config ID to override for all tests in current execution",Me,[]).option("--params-file [params-file.json | params-file.js]","").option("--params [params-json-string]","").option("-t, --testId [test-id]","test ID to run",Me,[]).option("--test-id [test-id]","test ID to run",Me,[]).option("-l, --label [label]","labels to search test by",Me,[]).option("-n, --name [test-name]","test name to run",Me,[]).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",$I).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",Me,[]).option("--test-plan-id [test-plan-id]","test plan to run",Me,[]).option("--suite [suite-name]","suite to run",Me,[]).option("--suite-id [suite-id]","suite ID to run",Me,[]).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",Me,[]).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(ec.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,Qp.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,Qp.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: ${Zp.join("/")}`,Me,[]).option("--code-coverage-include [pattern]","set selecting files for coverage (default src/**)",Me,[]).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("--sealights-test-stage [sealights-test-stage]","SeaLight Test Stage Name").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",Me,[]).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)",Me,[]).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)",Me,[]).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(td);p=ed.opts(),qI=()=>{p.grid||p.gridId||(p.host||(p.host="ondemand.saucelabs.com"),p.port||(p.port=80))},zI=()=>{p.grid||p.gridId||(p.host||(p.host="hub-cloud.browserstack.com"),p.port||(p.port=80))},oT=s=>{var r;if(!O.flags.secrets.isEnabled({projectId:p.project}))return;let t=Za.readFileSync(s);(r=Hp)!=null&&r.containsSecrets(t.toString())&&Hp.injectProxySecretsStoreToGlobal()},KI=async()=>{var T,v,b,w,S,A,D,V;p.inspect&&require("node:inspector").open(p.inspect);let s={},e={},t=[],r={};if(!td.slice(2).length)throw uT(),new qr;if(p.version){let x="Testim CLI Version: ";ec.npm_package_version&&(console.log(x,ec.npm_package_version),Yp(0));let R=rt();R&&(console.log(x,R),Yp(0)),console.log("Could not find version, please check the package.json manually"),Yp(0)}if(p.installLazyDeps)return{installLazyDepsMode:!0};p.disableFileCache&&Dm(),p.clearFileCache&&ns();let n=p.fileCacheLocation||p.usePrefechedData||p.createPrefechedData;if(n){let x=Fe.resolve(n);_m(x)}if(p.usePrefechedData&&Nm(),p.playerRequirePath){let x=Fe.resolve(p.playerRequirePath);console.log("Using Local Clickim for Player Require Path =",x);let R=Fe.join(x,"tsconfig.node.json"),M=require("ts-node").register({project:R,ignore:[/node_modules/,new RegExp(`^${Kt.escapeRegExp(Fe.relative(Ft(),__dirname))}`)],transpileOnly:!0});require("tsconfig-paths").register({paths:M.config.options.paths,baseUrl:M.config.options.baseUrl}),(we(),qe(ir)).options.playerPath=x;let W=require("node:module"),q=W.prototype.require;W.prototype.require=function(Ie){return Ie==="rox-alias"?q.call(this,"rox-node"):Ie==="canvas"?{}:q.apply(this,arguments)}}if(p.caFile&&(global.caFileContent=Za.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(Xb(p))return Yb(p);try{let x={};p.configFile?(oT(p.configFile),x=require(Fe.join(Ft(),p.configFile)).config):p.optionsFile&&(x=require(Fe.join(Ft(),p.optionsFile))),x&&typeof x.then=="function"&&(x=await x),Object.keys(x).forEach(R=>{let L=jI(R);p[L]=WI(p[L],x[R])})}catch(x){throw x.message=`Unable to read options file: ${x.message}`,x}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)||((v=p.testConfigId)==null?void 0:v.length),o=((b=p.testPlan)==null?void 0:b.length)||((w=p.testPlanId)==null?void 0:w.length),a=((S=p.suite)==null?void 0:S.length)||((A=p.suiteId)==null?void 0:A.length);if(p.seleniumCapsFile)try{r=require(Fe.join(Ft(),p.seleniumCapsFile))}catch(x){throw new C(`Failed to parse selenium caps file file error: ${x.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(Fe.join(Ft(),p.chromeExtraPrefs))}catch(x){throw new C(`Failed to read/open chrome extra prefs file error: ${x.message}`)}if(p.chromeExtraArgs){let x=p.chromeExtraArgs.split(",");for(let R of x){let[L]=R.split("=");nT.includes(L)||p.useLocalChromeDriver||p.useChromeLauncher?(t.push(R),L==="proxy-server"&&t.push("proxy-bypass-list=*.testim.io;*.coralogix.com;*.rollout.io")):console.warn(`Ignoring an unsupported chrome arg (${L}), allowed values: ${JSON.stringify(nT)}`)}}if(p.paramsFile)try{p.paramsFile.endsWith("js")&&oT(p.paramsFile),s={...s,...require(Fe.join(Ft(),p.paramsFile))}}catch(x){throw new C(`Failed to read/open params file error: ${x.message}`)}if(p.params)try{s={...s,...JSON.parse(p.params)}}catch(x){throw new C(`Failed to parse params string error: ${x.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&&(qI(),p.saucelabs={},p.saucelabs.username=p.sauceUser,p.saucelabs.accessKey=p.sauceKey),p.sauceOptions)try{let x=require(Fe.join(Ft(),p.sauceOptions)),R=x.platformName&&["ios","android"].includes(x.platformName.toLowerCase());if(x.browserName){let M=x.browserName.toLowerCase();switch(M){case"microsoftedge":p.browser="edge";break;default:p.browser=M}}p.browser==="edge"&&parseFloat(x.version)>=79&&(p.browser="edge-chromium");let L=parseFloat(x.version)<50&&!["dev","beta"].includes(x.version);if(!R&&p.browser==="chrome"&&L)throw new C("The minimum chrome supported version is 50.0");p.saucelabs={...p.saucelabs,...x}}catch(x){throw new C(`Failed to parse saucelabs options file error: ${x.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&&(zI(),p.browserstack={},p.browserstack["browserstack.user"]=p.browserstackUser,p.browserstack["browserstack.key"]=p.browserstackKey),p.browserstackOptions)try{let x=require(Fe.join(Ft(),p.browserstackOptions)),R=x.platform&&["mac","android"].includes(x.platform.toLowerCase());if(x.browserName&&(p.browser=x.browserName.toLowerCase()),p.browser==="edge"&&parseFloat(x.browser_version)>=79&&(p.browser="edge-chromium"),!R&&parseFloat(x.browser_version)<50&&p.browser==="chrome")throw new C("The minimum chrome supported version is 50.0");p.browserstack={...p.browserstack,...x}}catch(x){throw new C(`Failed to parse browserstack options file error: ${x.message}`)}if(p.perfecto={},p.perfectoToken&&(p.perfecto.securityToken=p.perfectoToken),p.perfectoOptions)try{let x=require(Fe.join(Ft(),p.perfectoOptions)),R={location:"US East",securityToken:p.perfectoToken};p.perfecto={...R,...x}}catch(x){throw new C(`Failed to parse perfecto options file error: ${x.message}`)}if(p.testobjectSauce={},p.testobjectKey&&(p.testobjectSauce.testobjectApiKey=p.testobjectKey),p.testobjectOptions)try{let x=require(Fe.join(Ft(),p.testobjectOptions)),R={testobjectApiKey:p.testobjectKey};p.testobjectSauce={...R,...x}}catch(x){throw new C(`Failed to parse test object options file error: ${x.message}`)}let c={seaLights:{buildSessionId:p.sealightsBuildSessionId,labId:p.sealightsLabId,testStage:p.sealightsTestStage}};if(p.testOptimization=c,!p.project){let R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getProjectId();if(R)p.project=R;else throw new C("missing project-id info, either --login to provide new credentials or use --project <project-id>")}GI(p.project),O.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 m=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 R=await(await Promise.resolve().then(()=>(Qa(),Xp))).getToken();if(R)p.token=R;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 d=x=>x<=0||!Number.isInteger(x);if(d(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(d(p.browserTimeout))throw new C("get browser timeout could not be a negative number, --browser-timeout <get-browser-timeout>");if(d(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(d(p.timeout))throw new C("test run timeout could not be a negative number, --timeout <run-timeout>");if(d(p.beforeParallel))throw new C("before-parallel could not be a negative number or not number, --before-parallel <number-of-tests>");if(d(p.parallel))throw new C("parallel could not be a negative number or not number, --parallel <number-of-tests>");if(d(p.afterParallel))throw new C("after-parallel could not be a negative number or not number, --after-parallel <number-of-tests>");if(p.mode&&![K.EXTENSION,K.SELENIUM,K.APPIUM].includes(p.mode))throw new C(`runner mode <${p.mode}> is not supported`);if(p.browser&&![...Nr,...Hn].includes(p.browser))throw new C(`browser ${p.browser} is not supported`);if(p.mode!==K.SELENIUM&&p.disableNativeEvents)throw new C("--disable-native-events is only applicable in selenium mode");if(p.appiumLogLevel||(p.appiumLogLevel="silent"),!HI.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((V=p.host)!=null&&V.includes("/")&&(/^(f|ht)tps?:\/\//i.test(p.host)||(p.host=`http://${p.host}`),p.host=cT.parse(p.host).hostname),p.resultLabel.length){p.resultLabel=p.resultLabel.map(R=>R.trim()).filter(Boolean);let x=p.resultLabel.filter(R=>R.length>=250).filter(Boolean);if(p.branch==="auto-detect"&&p.resultLabel.includes("auto-detect-branch")&&Tr()&&p.resultLabel.unshift(Tr()),x.length)throw new C("A result label cannot exceed 250 characters")}let f=xo(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&&!Kt.inRange(Kt.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&&Kt.difference(p.codeCoverageReporter,Zp).length){let x=Kt.difference(p.codeCoverageReporter,Zp);throw new C(`invalid --code-coverage-reporter parameters ${x.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(x=>Boolean(p[x]));if([K.APPIUM,K.SELENIUM].includes(p.mode)&&y.length){let x=y.length>1?"are":"is";throw new C(`${y.map(R=>g[R]).join(" and ")} ${x} only applicable in extension mode`)}if((p.useChromeLauncher||p.useLocalChromeDriver)&&(p.browser="chrome"),p.tmsFieldFile)try{let x=Za.readFileSync(p.tmsFieldFile);p.tmsCustomFields=JSON.parse(x)}catch(x){throw new C(`failed to parse field file error: ${x.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&&(VI("--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 x={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"},R=typeof p.lightweightMode=="string"?JSON.parse(p.lightweightMode):{};p.lightweightMode={...x,...R}}catch(x){throw new C(`failed to parse lightweightMode settings error: ${x.message}`)}else p.turboMode&&![K.APPIUM,K.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&&[K.APPIUM,K.SELENIUM].includes(p.mode)&&console.warn(`
409
+ 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"?Tr():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:m,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 sd,JI,Fs,dT,mT,nd,fT,gT=E(()=>{"use strict";B();Y();$();kn();sd=P("testimNgrok"),JI=".whitelisted-ngrok.testim.io",Fs="",mT=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}${JI}`);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 ut("ngrok")).connect(r);s.tunnelUseHttpAddress&&i.startsWith("https://")?(sd.info("replace https to http"),Fs=i.replace("https://","http://")):Fs=i,s.tunnelDiagnostics&&nd(),s.baseUrl=Fs},nd=async(s=!0)=>{try{let t=(await ut("ngrok")).getApi(),{tunnels:r}=await t.listTunnels(),n=r.find(i=>i.public_url===Fs);console.log("ngrok stats",n),sd.info("ngrok stats",{tunnel:n})}catch(e){sd.error("error collecting ngrok stats",{err:e})}s&&(dT=setTimeout(()=>nd(),1e4))},fT=async s=>{if(!Fs)return;clearTimeout(dT),s.tunnelDiagnostics&&await nd(!1),await(await ut("ngrok")).disconnect(Fs)}});var pr,od,hT,YI,QI,id,tc,sc,rc,ZI,yT,bT,TT=E(()=>{"use strict";pr=I(require("os")),od=I(require("fs")),hT=I(require("child_process"));B();ge();YI="https://github.com/cloudflare/cloudflared/releases/download/2024.1.5/",QI={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"}},id=pr.tmpdir(),tc=`${id}/cloudflared`,sc=null,rc=null,ZI=async()=>{if(await ye(tc))return;let e=QI[pr.platform()+pr.arch()];if(!e)throw new Error(`tunnel on ${pr.platform()+pr.arch()} platform is not supported.`);let t=e.extract?id+e.path:tc;await Je(`${YI}/${e.path}`,t),e.extract&&await ot(t,id),await od.promises.chmod(tc,"755")},yT=async s=>{let e=s.baseUrl||`http://localhost:${s.tunnelPort||80}`,t="tunnelRoutes"in s&&s.tunnelRoutes||[e],[r]=await Promise.all([Dp(s.company.companyId,t),ZI()]);sc=r._id,rc=hT.spawn(tc,["tunnel","--no-autoupdate","run","--token",r.token],{stdio:"inherit"}),await Np(s.company.companyId,sc),"tunnelRoutesOutput"in s&&s.tunnelRoutesOutput&&await od.promises.writeFile(s.tunnelRoutesOutput,JSON.stringify(r.routesMapping,null,2)),s.baseUrl=`${s.tunnelUseHttpAddress?"http":"https"}://${r.routesMapping[e]}`},bT=async s=>{let e=[];return sc&&e.push(Mp(s.company.companyId,sc)),rc&&e.push(new Promise((t,r)=>{rc.on("close",n=>{n&&r(new Error(`tunnel process exited with code ${n}`)),t()}),rc.kill()})),await Promise.all(e)}});var ad={};z(ad,{connect:()=>ic,disconnect:()=>oc,serveTunneling:()=>rR});var nc,wT,vT,tR,ic,oc,rR,cd=E(()=>{"use strict";gT();Pn();TT();ct();nc=I(require("ora"));$();ae();Po();wT=P("tunnel"),vT=s=>{var e;return[_.TESTIM_LAMBDATEST,_.HYBRID].includes((e=s.gridData)==null?void 0:e.type)&&s.gridData.tunnel==="lambdatest"},tR=s=>{var e;return s.tunnelRoutes||((e=s.gridData)==null?void 0:e.type)===_.HYBRID&&s.gridData.tunnel==="cloudflare"},ic=async s=>{if(!s.tunnel)return;let e=Ir(),t;try{vT(s)?(t=(0,nc.default)("Starting testim lambdatest tunnel...").start(),await ne.connectTunnel(s)):tR(s)?(t=(0,nc.default)("Starting testim cloudflare tunnel...").start(),await yT(s)):(t=(0,nc.default)("Starting testim ngrok tunnel...").start(),await mT(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."),wT.error("Failed to open tunnel",{err:r}),t==null||t.fail(n),new Error(r.isInvalidCredsForLT?`${n}
410
410
  ${r.stdoutResult}`:n)}},oc=async s=>{if(s.tunnel)try{vT(s)?await ne.disconnectTunnel(s):"tunnelRoutes"in s?await bT(s):await fT(s)}catch(e){let t="catch error - failed to close tunnel";throw wT.error(t,{err:e}),new Error(t)}},rR=async(s,e=new Promise(()=>{}))=>(await ic(s),gs(()=>oc(s)),await e)});var RT={};z(RT,{init:()=>RR,run:()=>vR});async function nR(s){let e=s.project,t=await _p(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"),ls(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Hs}function oR(s,e){var i,o,a,c,l,m,d,u,f,h,g,y,T;let t=Ni(e.activePlan),r=s.parallel;if(t==="free"&&r>ET)throw new C(`The free plan allows only ${ET} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let v=(i=s.projectData)!=null&&i.type?iR[s.projectData.type]:void 0,b=(o=e.activePlan)!=null&&o.premiumFeatures.parallelism&&v?(a=e.activePlan)==null?void 0:a.premiumFeatures.parallelism[v]:0;b&&r>b&&(console.warn(`It looks like your command used more parallel processing than your plan supports (${r} vs. ${b}).
411
411
  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 w=(l=(c=e.activePlan)==null?void 0:c.premiumFeatures)==null?void 0:l.tunnel;if(s.tunnel&&!w)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 S=(d=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:d.runInTurboMode;s.lightweightMode&&!S&&(console.warn(`
412
- Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===_.TESTIM_TVC){let v=e.tvcLicense.expireAt||1;if(Date.now()>v&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===_.TESTIM_TDC){let v=e.tdcLicense.expireAt||1;if(Date.now()>v)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let v=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>v)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${v}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let v=e.tvcLicense,b=e.tdcLicense;if(v!=null&&v.isPaid||b!=null&&b.isPaid)return;let w=e==null?void 0:e.createdAt;if(new Date(w)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function aR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await nR(s)}catch(t){if([C,Hs].some(r=>t instanceof r))throw t;ld.error("could not validate cli account",{err:t})}}function cR(s){let e=Ir();return If({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function lR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(jo(),gh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($o(),bh));r.init(s)}}function uR(s,e){let{branch:t,autoDetect:r}=s;if(wf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function pR(s,e){let{id:t,type:r}=e,i=IT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=vn();i&&(s.sfdcCredential=await Op({projectId:t,branch:o}))}function dR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ni(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ST?ST:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),_t.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function mR(s,e){s.editorUrl=rt||e}function fR(s,e){s.allGrids=e}function gR(s,e){s.authData=e}function hR(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function yR(s){var e;s.gridData=await yf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function bR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function TR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Hb(s.overrideMappingFile))}async function wR(s,e){F("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await aR(s),F("in runRunner before tunnel.connect"),await ic(s),F("in runRunner after tunnel.connect");let a=await new Vr(e).run(s);return F("before tunnel.disconnect"),await oc(s),await IR(s.slotService,t,s.company.companyId),F("after tunnel.disconnect and gridService.keepAlive.end"),a}function SR(s){var e;_t.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
412
+ Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((u=s.gridData)==null?void 0:u.type)===_.TESTIM_TVC){let v=e.tvcLicense.expireAt||1;if(Date.now()>v&&!e.churnedByL2C)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let b=Number((h=(f=e.plan.premiumFeatures)==null?void 0:f.parallelism)==null?void 0:h.mobile);if(r>b)throw new C(`Your license allows only ${b} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((g=s.gridData)==null?void 0:g.type)===_.TESTIM_TDC){let v=e.tdcLicense.expireAt||1;if(Date.now()>v)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(n){let v=(T=(y=e.activePlan)==null?void 0:y.premiumFeatures)==null?void 0:T.resultRetention;if(n>v)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${v}). Run aborted`)}if(Zt(s)){if(O.flags.removeMobileTrialRestrictions.isEnabled())return;let v=e.tvcLicense,b=e.tdcLicense;if(v!=null&&v.isPaid||b!=null&&b.isPaid)return;let w=e==null?void 0:e.createdAt;if(new Date(w)<new Date(O.flags.applyMobileRestrictionFromDate.getValue()))return;s.timeout>=6e5&&(s.timeout=6e5,console.warn("Mobile Trial projects are limited to 10 minutes of execution time. The timeout has been reduced to 10 minutes."));let A=s.retries;A&&A>=1&&(s.retries=0,console.warn("Mobile Trial projects are not allowed to have test retries."))}}async function aR(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await nR(s)}catch(t){if([C,Hs].some(r=>t instanceof r))throw t;ld.error("could not validate cli account",{err:t})}}function cR(s){let e=Ir();return If({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function lR(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(O.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(jo(),gh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($o(),bh));r.init(s)}}function uR(s,e){let{branch:t,autoDetect:r}=s;if(wf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function pR(s,e){let{id:t,type:r}=e,i=IT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&O.flags.sfdcHybridCompany.isEnabled(),o=vn();i&&(s.sfdcCredential=await Op({projectId:t,branch:o}))}function dR(s,e){let{id:t,name:r,activePlan:n={}}=e,i=Boolean(n.isPoc),o=Boolean(n.isStartUp),a=Ni(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<ST?ST:s.newBrowserWaitTimeout),O.setCompanyId(t),O.setIsPOC(i),O.setIsStartUp(o),O.setPlanType(a),_t.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:i,isStartUp:o,activePlan:n}}function mR(s,e){s.editorUrl=tt||e}function fR(s,e){s.allGrids=e}function gR(s,e){s.authData=e}function hR(s,e){let{id:t,name:r,type:n,defaults:i}=e;O.setProjectId(t),O.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:i}}async function yR(s){var e;s.gridData=await yf(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function bR(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}async function TR(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(bt("user-override-file",t),s.mockNetworkRules=await Hb(s.overrideMappingFile))}async function wR(s,e){F("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:i}=s;r||(s.source=n||i?"cli-local":"cli"),await aR(s),F("in runRunner before tunnel.connect"),await ic(s),F("in runRunner after tunnel.connect");let a=await new Vr(e).run(s);return F("before tunnel.disconnect"),await oc(s),await IR(s.slotService,t,s.company.companyId),F("after tunnel.disconnect and gridService.keepAlive.end"),a}function SR(s){var e;_t.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
413
413
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
414
414
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m
415
415
  `)}function ER(s,e,t){s==="redis"&&xn.start(t,e),s==="mongo"&&Tn.start(e)}async function IR(s,e,t){s==="redis"&&await xn.end(t,e),s==="mongo"&&await Tn.end(e)}async function RR(s){var h,g,y,T,v,b;F("start runner init");let{project:e,lightweightMode:t,useChromeLauncher:r,mode:n,disableSockets:i}=s,o=lR(e,{disableResults:i||Boolean((t==null?void 0:t.disableResults)&&(r||n===K.SELENIUM)),disableRemoteStep:i||Boolean(t==null?void 0:t.disableRemoteStep)});o.catch(()=>{});let{authData:a,companyByProjectId:c,projectById:l,branchName:m,allGrids:d,clientConfig:u}=await ci(s);if(c.disabled)throw new C("The company is disabled.");if(l.disabled)throw new C("The project is disabled.");if(s.printGrids){let w=d.sort((S,A)=>S.type.localeCompare(A.type));console.table(w.reduce((S,A)=>{class D{constructor(R,L){this.Type=R,this.Browsers=L}}let V=Object.entries(A.browsers||{"N/A":""}).map(x=>x.join(":")).join(", ");return S[A.name]=new D(A.type,V),S},{})),process.exit(0)}if(await o,F("after featureFlagsReady and socketConnected"),mR(s,u.editorUrl),dR(s,c),hR(s,l),bR(s,l),uR(s,m),fR(s,d),gR(s,a),await pR(s,l),await yR(s),oR(s,c),(h=s.extensionLocation)!=null&&h.length||(s.extensionLocation=[yg(s)]),O.flags.clearRunnerFileCache.isEnabled())try{await ns(),ld.info("runner file cache cleared")}catch(w){ld.error("failed to clear runner file cache",{err:w})}(g=s.lightweightMode)!=null&&g.disableLabs||await jn.loadLabFeatures(l.id,c.activePlan),((y=s.lightweightMode)==null?void 0:y.type)==="turboMode"&&(O.flags.highSpeedMode.getValue()==="disabled"||s.company.planType==="free")&&delete s.lightweightMode,((T=s.lightweightMode)==null?void 0:T.type)==="turboMode"&&console.log(`
416
- Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),ER(s.slotService,e,c.id),cR(e),await TR(s),SR(s);let f=vn();await Q.setOptions(s,f),(b=(v=s.testOptimization)==null?void 0:v.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==sR&&ls(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var IT,ST,ET,sR,ld,iR,vR,xT=E(()=>{"use strict";IT=I(require("lodash"));B();cd();$e();cs();fs();us();Al();ge();lt();er();$();Lt();oe();ae();Y();Ip();Uo();wu();de();In();$p();Dn();ST=30*60*1e3,ET=1,sR="Testim Automation",ld=P("runner");iR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};vR=wR});function AT(s){s.get("/",(e,t)=>{let r=ud();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ka()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Jp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var CT=E(()=>{"use strict";Qa();pd();Up()});var dd,PT,Us,ac,kT=E(()=>{"use strict";dd=I(require("chalk"));Rs();PT=require("express");$();Y();Us=P("cli-router"),ac=(0,PT.Router)();ac.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let d={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m,nodePackageParams:n.nodePackageParams};try{let u=await Is(t,r,n,i,o,a,c,l,m);u.success||(console.log(dd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...d})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...d}),console.log(dd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});ac.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let l=await Es(t,r,n,i,o,a);Us.info("installed packages successfully",c),e.status(200).json({success:!0,data:l})}catch(l){if(l instanceof Ct){Us.error("failed to install node packages",{err:l,...c}),e.status(200).json({success:!1,code:"invalid-node-package",message:l.message});return}if(l instanceof ce){Us.error("timeout installing node package",{err:l,...c}),e.status(200).json({success:!1,code:"timeout"});return}Us.error("failed to install node packages",{err:l,...c}),e.status(500).json({success:!1,code:"internal-error"})}})});var OT=E(()=>{"use strict";kT()});var NT={};z(NT,{orchestrateRoutes:()=>xR});function xR(s){let e=(0,LT.default)();e.disable("x-powered-by"),s(e),e.use(md.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,DT.default)()),e.use(md.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:We||Id?"*":["http://localhost:3000","https://app.testim.io","https://app.staging.testim.io","https://app-eu.staging.testim.io","https://app.dev.testim.io","https://app-eu.dev.testim.io","https://app-eu.prod.testim.io","https://playground.testim.io","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,_T.default)(r)),AT(e),e.use("/cliJs",ac),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var _T,LT,md,DT,MT=E(()=>{"use strict";_T=I(require("cors")),LT=I(require("express")),md=I(require("body-parser")),DT=I(require("compression"));CT();OT();oe()});var UT={};z(UT,{init:()=>AR});async function AR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(MT(),NT));return new Promise((i,o)=>{let a=()=>{};t&&(lf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=FT.createServer(c);l.listen(s,e),l.on("error",m),l.on("listening",d);function m(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function d(){let{port:u}=l.address();console.log(`Running on port: ${u}`),CR()}})}async function CR(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var FT,BT=E(()=>{"use strict";FT=I(require("http"));lt();Y()});var qT={};z(qT,{getStartedWithStart:()=>ud,runAgentMode:()=>_R});async function _R(s){var r;let e;if(await Sr(s.playerLocation,s.canary),s.startTestimBrowser){await NR();try{e=await DR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(BT(),UT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(ep(),qe(rb)))},6e3),t.init(s)}function ud(){return GT}function jT(s){try{return process.kill(s,0)}catch{return!1}}async function LR(s,e,t){let r=dr.join(Vt,`chrome-${mn}-process`),n=3e3,i=()=>{Oe.rmSync(r,{recursive:!0}),console.log(`
416
+ Turbo mode will ignore step delays. Test artifacts like screenshots and logs will only be saved for failed runs. For more information see our docs: https://help.testim.io/docs/turbo-mode`),ER(s.slotService,e,c.id),cR(e),await TR(s),SR(s);let f=vn();await Q.setOptions(s,f),(b=(v=s.testOptimization)==null?void 0:v.seaLights)!=null&&b.testStage&&s.testOptimization.seaLights.testStage!==sR&&ls(a.uid,"cli-sealights_stage_changed",{testStage:s.testOptimization.seaLights.testStage,projectId:e})}var IT,ST,ET,sR,ld,iR,vR,xT=E(()=>{"use strict";IT=I(require("lodash"));B();cd();$e();cs();fs();us();Al();ge();ct();er();$();Lt();oe();ae();Y();Ip();Uo();wu();de();In();$p();Dn();ST=30*60*1e3,ET=1,sR="Testim Automation",ld=P("runner");iR={desktopWeb:"web",mobileWeb:"web",android:"mobile",ios:"mobile",sfdc:"sfdc"};vR=wR});function AT(s){s.get("/",(e,t)=>{let r=ud();return t.status(200).json({success:!0,isTestimAgent:!0,startMode:r})}),s.get("/version",(e,t)=>{t.status(200).json({node:process.version,app:Ka()})}),s.get("/loginInfo",(e,t)=>{try{let r=JSON.parse(Buffer.from(e.query.info,"base64").toString());Jp({overwriteExisting:!1,projects:r}),t.status(200).end()}catch{t.status(400).end()}})}var CT=E(()=>{"use strict";Qa();pd();Up()});var dd,PT,Us,ac,kT=E(()=>{"use strict";dd=I(require("chalk"));Rs();PT=require("express");$();Y();Us=P("cli-router"),ac=(0,PT.Router)();ac.post("/run",async(s,e)=>{let{code:t,stepId:r,incomingParams:n,context:i,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m}=s.body;if(typeof t!="string"||!r||!n||!i||!o||typeof a!="number"||!c||typeof l!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let d={stepId:r,testResultId:o,retryIndex:a,stepResultId:c,timeout:l,fileDataUrl:m,nodePackageParams:n.nodePackageParams};try{let u=await Is(t,r,n,i,o,a,c,l,m);u.success||(console.log(dd.default.red(u.result.resultValue)),Us.error("CLI Action Failure",{message:u.result.resultValue,...d})),e.status(200).json({success:!0,data:u})}catch(u){Us.error("failed to run cli code",{err:u,...d}),console.log(dd.default.red("failed to run cli code",u)),e.status(500).json({success:!1,code:"internal-error"})}});ac.post("/install",async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,packageData:i,stepResultId:o,timeout:a}=s.body;if(!t||typeof i!="object"||!r||typeof n!="number"||!o||typeof a!="number"){e.status(400).json({success:!1,code:"invalid-params"});return}let c={stepId:t,testResultId:r,retryIndex:n,stepResultId:o,timeout:a,packageData:i};try{let l=await Es(t,r,n,i,o,a);Us.info("installed packages successfully",c),e.status(200).json({success:!0,data:l})}catch(l){if(l instanceof Ct){Us.error("failed to install node packages",{err:l,...c}),e.status(200).json({success:!1,code:"invalid-node-package",message:l.message});return}if(l instanceof ce){Us.error("timeout installing node package",{err:l,...c}),e.status(200).json({success:!1,code:"timeout"});return}Us.error("failed to install node packages",{err:l,...c}),e.status(500).json({success:!1,code:"internal-error"})}})});var OT=E(()=>{"use strict";kT()});var NT={};z(NT,{orchestrateRoutes:()=>xR});function xR(s){let e=(0,LT.default)();e.disable("x-powered-by"),s(e),e.use(md.default.urlencoded({extended:!1,limit:"50mb"})),e.use((0,DT.default)()),e.use(md.default.json({limit:"50mb"}));let r={methods:["GET","PUT","POST","DELETE","OPTIONS"],allowedHeaders:["Content-Type","Authorization"],credentials:!0,maxAge:86400,origin:We||Id?"*":["http://localhost:3000","https://app.testim.io","https://app.staging.testim.io","https://app-eu.staging.testim.io","https://app.dev.testim.io","https://app-eu.dev.testim.io","https://app-eu.prod.testim.io","https://playground.testim.io","chrome-extension://pebeiooilphfmbohdbhbomomkkoghoia","https://tta-crm.tricentis.com"]};return e.use("*",(0,_T.default)(r)),AT(e),e.use("/cliJs",ac),e.use((n,i)=>{i.status(404).send("Endpoint Not Found")}),e}var _T,LT,md,DT,MT=E(()=>{"use strict";_T=I(require("cors")),LT=I(require("express")),md=I(require("body-parser")),DT=I(require("compression"));CT();OT();oe()});var UT={};z(UT,{init:()=>AR});async function AR({agentPort:s,agentBind:e,project:t,token:r}){let{orchestrateRoutes:n}=await Promise.resolve().then(()=>(MT(),NT));return new Promise((i,o)=>{let a=()=>{};t&&(lf(t,r),a=u=>{u.use((f,h,g)=>{Object.assign(f,{project:t}),g()})});let c=n(a),l=FT.createServer(c);l.listen(s,e),l.on("error",m),l.on("listening",d);function m(u){if(u.syscall!=="listen")return o(u);switch(u.code){case"EACCES":case"EPERM":return o(new C(`Port ${s} requires elevated privileges`));case"EADDRINUSE":return o(new C(`Port ${s} is already in use, is another Testim instance running?`));default:return o(u)}}function d(){let{port:u}=l.address();console.log(`Running on port: ${u}`),CR()}})}async function CR(){await require("prompts")({name:"",type:"text",message:'Type the word "stop" or Press Ctrl + C.',validate:t=>t.toUpperCase().trim()==="STOP"}),console.log("Exiting Testim CLI"),process.exit(0)}var FT,BT=E(()=>{"use strict";FT=I(require("http"));ct();Y()});var qT={};z(qT,{getStartedWithStart:()=>ud,runAgentMode:()=>_R});async function _R(s){var r;let e;if(await Sr(s.playerLocation,s.canary),s.startTestimBrowser){await NR();try{e=await DR(s)}catch(n){throw(r=n==null?void 0:n.message)!=null&&r.includes("user data directory is already in use")?new C('Please close all chrome browsers that were opened with "testim start" and try again'):n}}let t=await Promise.resolve().then(()=>(BT(),UT));return e!=null&&e.webdriverApi&&setTimeout(()=>{setTimeout(()=>(ep(),qe(rb)))},6e3),t.init(s)}function ud(){return GT}function jT(s){try{return process.kill(s,0)}catch{return!1}}async function LR(s,e,t){let r=dr.join(Vt,`chrome-${mn}-process`),n=3e3,i=()=>{Oe.rmSync(r,{recursive:!0}),console.log(`
417
417
 
418
- Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Oe.readFileSync(r));if(jT(f.pid)){let h=()=>jT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Xi();await ye(Bs)||await Oe.promises.mkdir(Bs,{recursive:!0});let c=[...HT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...lc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},m=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",rt||gr).href,d=await lc.launch({chromeFlags:c,startingUrl:m,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:d.port,pid:d.pid,cdpUrl:await wr(`localhost:${d.port}`)};return Oe.writeFileSync(r,JSON.stringify(u)),d.process.once("exit",i),d.process.once("close",i),{webdriverApi:u}}async function DR(s){let e=`${ft}/testim-full-master.zip`,t=dr.basename(e),r=dr.join(Vt,t),n=dr.join(Vt,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Oe.promises.stat(r);i=Date.now()-kR>f.mtimeMs}if(await Oe.promises.mkdir(Vt,{recursive:!0}),i){let f=(0,WT.default)("Downloading Testim Editor").start();await Je(e,r);try{await at(r,n)}catch{await Oe.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await at(r,n)}catch{throw await Oe.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Oe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Oe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await LR(s,o,n);await ln({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=HT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Bn(),qe(Jg)),{SeleniumPerfStats:l}=(ys(),qe(ug)),m=new c;m.seleniumPerfStats=new l;let d=await m.initClient(a);GT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":rt||gr}?startMode=true`;await m.url(u),Object.assign(m,{initialUrl:u});try{m.cdpUrl=await wr(d.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:m}}function HT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Oo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:PR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function NR(){if(await ye(cc))try{let{webSocketDebuggerUrl:s}=await MR();await FR(s),await Oe.promises.unlink(cc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Oe.promises.unlink(cc)}}async function MR(){let s=await Oe.promises.readFile(cc,{encoding:"utf8"}),[e,t]=s.split(`
418
+ Browser session ended`),process.exit(0)};if(await ye(r)){let f=JSON.parse(Oe.readFileSync(r));if(jT(f.pid)){let h=()=>jT(f.pid)?setTimeout(h,n):i();return h(),{webdriverApi:f}}}let o=await Xi();await ye(Bs)||await Oe.promises.mkdir(Bs,{recursive:!0});let c=[...HT(Bs,e,t,o).desiredCapabilities.chromeOptions.args,...lc.Launcher.defaultFlags().filter(f=>!["--disable-extensions","--disable-component-extensions-with-background-pages"].includes(f))],l={GOOGLE_API_KEY:"AIzaSyCkfPOPZXDKNn8hhgu3JrA62wIgC93d44k",GOOGLE_DEFAULT_CLIENT_ID:"811574891467.apps.googleusercontent.com",GOOGLE_DEFAULT_CLIENT_SECRET:"kdloedMFGdGla2P1zacGjAQh"},m=s.extensionPath?"http://localhost:3000/app/":new URL("?startMode=true",tt||gr).href,d=await lc.launch({chromeFlags:c,startingUrl:m,ignoreDefaultFlags:!0,userDataDir:Bs,chromePath:o,envVars:l}),u={port:d.port,pid:d.pid,cdpUrl:await wr(`localhost:${d.port}`)};return Oe.writeFileSync(r,JSON.stringify(u)),d.process.once("exit",i),d.process.once("close",i),{webdriverApi:u}}async function DR(s){let e=`${mt}/testim-full-master.zip`,t=dr.basename(e),r=dr.join(Vt,t),n=dr.join(Vt,`${t}__unzipped__`),i=!(s.ext||s.extensionPath);if(i&&await ye(r)){let f=await Oe.promises.stat(r);i=Date.now()-kR>f.mtimeMs}if(await Oe.promises.mkdir(Vt,{recursive:!0}),i){let f=(0,WT.default)("Downloading Testim Editor").start();await Je(e,r);try{await ot(r,n)}catch{await Oe.promises.rm(r,{recursive:!0,force:!0}),await Je(e,r);try{await ot(r,n)}catch{throw await Oe.promises.rm(r,{recursive:!0,force:!0}),f.fail("Failed to download Testim Editor"),new Error("Failed to download Testim Editor")}}finally{s.downloadBrowser||await Oe.promises.rm(n,{recursive:!0,force:!0})}f.succeed()}let o=s.extensionPath?null:(await Oe.promises.readFile(s.ext||r)).toString("base64");if(s.downloadBrowser)return await LR(s,o,n);await ln({projectId:s.project},{chromeBinaryLocation:s.chromeBinaryLocations});let a=HT(Bs,o,s.extensionPath,s.chromeBinaryLocations),{WebDriver:c}=(Bn(),qe(Jg)),{SeleniumPerfStats:l}=(ys(),qe(ug)),m=new c;m.seleniumPerfStats=new l;let d=await m.initClient(a);GT=!0;let u=`${s.extensionPath?"http://localhost:3000/app/":tt||gr}?startMode=true`;await m.url(u),Object.assign(m,{initialUrl:u});try{m.cdpUrl=await wr(d.value["goog:chromeOptions"].debuggerAddress)}catch{}return{webdriverApi:m}}function HT(s,e,t,r){let n=e?[e]:[],i=[`--user-data-dir=${s}`,"--log-level=OFF","--silent-debugger-extension-api","--no-first-run"];t&&i.push(`--load-extension=${t}`);try{let o=Oo();o.length&&o.forEach(a=>i.push(`--disable-features=${a}`))}catch{}return{logLevel:PR,desiredCapabilities:{chromeOptions:{args:i,extensions:n,binary:r},browserName:"chrome"},host:"localhost",port:9515}}async function NR(){if(await ye(cc))try{let{webSocketDebuggerUrl:s}=await MR();await FR(s),await Oe.promises.unlink(cc)}catch(s){s&&s.message==="unable to connect to devtools http server"&&await Oe.promises.unlink(cc)}}async function MR(){let s=await Oe.promises.readFile(cc,{encoding:"utf8"}),[e,t]=s.split(`
419
419
  `).map(i=>i.trim()),r=Number.parseInt(e,10);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("invalid port number");if(!t.startsWith("/devtools/browser/"))throw new Error("invalid devtools browser url");let n=await wr(`localhost:${r}`,500);if(!n.endsWith(t))throw new Error("invariant webSocketDebuggerUrl miss match");return{port:r,webSocketDebuggerUrl:n}}async function FR(s,e=100){let t=await UR(s,e);return Qt(r=>{t.send(JSON.stringify({id:0,method:"Browser.close"}),r)})}async function UR(s,e=100){let t=ja({timeout:e}),r=new VT.default(s,t),n=Qt(o=>{r.once("open",o)}).then(()=>{r.removeAllListeners()}),i=Qt(o=>{r.once("error",o)}).catch(()=>{r.close(),r.removeAllListeners()});return Promise.race([n,i]).then(()=>r)}var $T,WT,VT,Oe,dr,lc,PR,kR,Bs,OR,cc,GT,pd=E(()=>{"use strict";$T=I(require("ms")),WT=I(require("ora")),VT=I(require("ws")),Oe=I(require("node:fs")),dr=I(require("node:path")),lc=I(require("chrome-launcher"));oe();pn();Y();fl();B();Lo();$a();PR=wi?"verbose":"silent",kR=(0,$T.default)("1h"),Bs=dr.join(Vt,"profile"),OR="DevToolsActivePort",cc=dr.join(Bs,OR);GT=!1});var $N=require("source-map-support/register");var yi=I(require("os")),$s=I(require("url")),Ws=I(require("http")),dc=I(require("https")),pi=I(require("form-data")),di=class{constructor(){this.onloadstart=null;this.onprogress=null;this.onabort=null;this.onerror=null;this.onload=null;this.ontimeout=null;this.onloadend=null;this._listeners={}}addEventListener(e,t){e=e.toLowerCase(),this._listeners[e]||=[],this._listeners[e].push(t)}removeEventListener(e,t){let r;e=e.toLowerCase(),this._listeners[e]&&(r=this._listeners[e].indexOf(t),r!==-1&&this._listeners[e].splice(r,1))}dispatchEvent(e){var n;e.currentTarget=this,e.target=this;let t=e.type,r=this._listeners[t]||[];for(let i of r)i==null||i.call(this,e);(n=this[`on${t}`])==null||n.call(this,e)}},mi=class extends di{constructor(t){super();this._request=t;this._contentType=null;this._body=null}_reset(){this._contentType=null,this._body=null}_setData(t){if(t!=null)if(typeof t=="string")t.length!==0&&(this._contentType="text/plain;charset=UTF-8"),this._body=Buffer.from(t,"utf8");else if(Buffer.isBuffer(t))this._body=t;else if(t instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=new Uint8Array(t);for(let i=0;i<t.byteLength;i++)r[i]=n[i];this._body=r}else if("buffer"in t&&t.buffer instanceof ArrayBuffer){let r=Buffer.alloc(t.byteLength),n=t.byteOffset,i=new Uint8Array(t.buffer);for(let o=0;o<t.byteLength;o++)r[o]=i[o+n];this._body=r}else if(typeof t=="object"&&t instanceof pi.default)this._body=null;else throw new Error(`Unsupported send() data ${t}`)}_finalizeHeaders(t,r){this._contentType&&!("content-type"in r)&&(t["Content-Type"]=this._contentType),this._body&&(t["Content-Length"]=this._body.length.toString())}_startUpload(t){this._body&&t.write(this._body),t.end()}},js=class{constructor(e){this.type=e;this.target=null;this.currentTarget=null;this.lengthComputable=!1;this.loaded=0;this.total=0;this.bubbles=!1;this.cancelable=!1}},fi=class extends Error{},gi=class extends Error{},hi=class extends Error{},mr=class extends Error{},xe=class extends di{constructor(t){super();this.UNSENT=0;this.OPENED=1;this.HEADERS_RECEIVED=2;this.LOADING=3;this.DONE=4;this.nodejsHttpAgent=Ws.globalAgent;this.nodejsHttpsAgent=dc.globalAgent;this.nodejsBaseUrl=null;this._restrictedMethods={CONNECT:!0,TRACE:!0,TRACK:!0};this._restrictedHeaders={"accept-charset":!0,"accept-encoding":!0,"access-control-request-headers":!0,"access-control-request-method":!0,connection:!0,"content-length":!0,cookie:!0,cookie2:!0,date:!0,dnt:!0,expect:!0,host:!0,"keep-alive":!0,origin:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,via:!0};this._privateHeaders={"set-cookie":!1,"set-cookie2":!1};this._userAgent=`Mozilla/5.0 (${yi.type()} ${yi.arch()}) node.js/${process.versions.node} v8/${process.versions.v8}`;this.onreadystatechange=null;this.readyState=xe.UNSENT;this.response=null;this.responseText="";this.responseType="";this.status=0;this.statusText="";this.timeout=0;this.upload=new mi(this);this._method=null;this._url=null;this._sync=!1;this._headers=null;this._loweredHeaders=null;this._mimeOverride=null;this._request=null;this._response=null;this._responseParts=null;this._responseHeaders=null;this._aborting=null;this._error=null;this._loadedBytes=0;this._totalBytes=0;this._lengthComputable=!1;this._anonymous=t==null?void 0:t.anon}static nodejsSet(t){xe.prototype.nodejsSet(t)}nodejsSet(t){if("httpAgent"in t&&(this.nodejsHttpAgent=t.httpAgent),"httpsAgent"in t&&(this.nodejsHttpsAgent=t.httpsAgent),"baseUrl"in t){let r=t.baseUrl;if(r!==null&&!$s.parse(r,!1,!0).protocol)throw new fi("baseUrl must be an absolute URL");this.nodejsBaseUrl=r}}open(t,r,n){if(t=t.toUpperCase(),t in this._restrictedMethods)throw new hi(`HTTP method ${t} is not allowed in XHR`);let i=this._parseUrl(r);n===void 0&&(n=!0),this._method=t,this._url=i,this._sync=!n,this._headers={},this._loweredHeaders={},this._mimeOverride=null,this._setReadyState(xe.OPENED),this._request=null,this._response=null,this.status=0,this.statusText="",this._responseParts=[],this._responseHeaders=null,this._loadedBytes=0,this._totalBytes=0,this._lengthComputable=!1}setRequestHeader(t,r){if(this.readyState!==xe.OPENED)throw new mr("XHR readyState must be OPENED");let n=t.toLowerCase();this._restrictedHeaders[n]||n.startsWith("sec-")||n.startsWith("proxy-")||(r=r.toString(),n in this._loweredHeaders?(t=this._loweredHeaders[n],this._headers[t]=`${this._headers[t]}, ${r}`):(this._loweredHeaders[n]=t,this._headers[t]=r))}send(t){if(this.readyState!==xe.OPENED)throw new mr("XHR readyState must be OPENED");if(this._request)throw new mr("send() already called");switch(this._url.protocol){case"file:":this._sendFile();break;case"http:":case"https:":this._sendHttp(t);break;default:throw new gi(`XHR request to ${this._url.href} failed: unsupported protocol '${this._url.protocol}'. Please use supported protocols like HTTP, HTTPS, or file.`)}}abort(){this._request&&(this._request.abort(),this._setError(),this._dispatchProgress("abort"),this._dispatchProgress("loadend"))}getResponseHeader(t){var n;let r=t.toLowerCase();return((n=this._responseHeaders)==null?void 0:n[r])||null}getAllResponseHeaders(){return this._responseHeaders?Object.entries(this._responseHeaders).map(([t,r])=>`${t}: ${r}`).join(`\r
420
420
  `):""}overrideMimeType(t){if([xe.LOADING,xe.DONE].includes(this.readyState))throw new mr("overrideMimeType() not allowed in LOADING or DONE");this._mimeOverride=t.toLowerCase()}_setReadyState(t){this.readyState=t;let r=new js("readystatechange");this.dispatchEvent(r)}_sendFile(){throw this._url.method!=="GET"?new gi("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:"?Ws:dc).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 pi.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 pi.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=Ws.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(xe.HEADERS_RECEIVED)}_onHttpResponseData(t,r){if(this._response===t)return this._responseParts.push(r),this._loadedBytes+=r.length,this.readyState!==xe.LOADING&&this._setReadyState(xe.LOADING),this._dispatchProgress("progress")}_onHttpResponseEnd(t){if(this._response===t)return this._parseResponse(),this._request=null,this._response=null,this._setReadyState(xe.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(xe.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_onHttpTimeout(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend")}_onHttpRequestError(t){if(this._request===t)return this._setError(),t.abort(),this._setReadyState(xe.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}_dispatchProgress(t){let r=new js(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:$s.resolve(this.nodejsBaseUrl,t),a=$s.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"}},Le=xe;Le.SyntaxError=fi,Le.ProgressEvent=js,Le.SecurityError=hi,Le.XMLHttpRequest=xe,Le.InvalidStateError=mr,Le.XMLHttpRequestUpload=mi,Le.UNSENT=0,Le.OPENED=1,Le.HEADERS_RECEIVED=2,Le.LOADING=3,Le.DONE=4;Object.assign(global,{xhr2:Le,XMLHttpRequest:Le});var zT=I(require("semver"));$e();$p();er();pn();var fd=I(require("chalk")),KT=require("node:events");ae();Pn();Y();ae();no();$();var qb=I(require("os")),Wp=I(require("path")),Vp=I(require("chalk")),Xa=require("fs");oe();function zb(s){var e,t,r;if(!((e=s==null?void 0:s.message)!=null&&e.includes("SIGINT")))try{let n=qb.homedir();(0,Xa.mkdirSync)(Wp.resolve(n,".testim_logs"),{recursive:!0});let i=Wp.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}`),Pd&&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(Vp.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(Vp.default.red("change require('ts-node/register/transpile-only'); to require('ts-node/register'); for better errors"))),(0,Xa.writeFileSync)(i,`${s}
421
421
  ${s==null?void 0:s.stack}